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);
313 btrfs_free_path(path);
314 btrfs_end_transaction(trans, root);
318 struct async_extent {
323 unsigned long nr_pages;
325 struct list_head list;
330 struct btrfs_root *root;
331 struct page *locked_page;
334 struct list_head extents;
335 struct btrfs_work work;
338 static noinline int add_async_extent(struct async_cow *cow,
339 u64 start, u64 ram_size,
342 unsigned long nr_pages,
345 struct async_extent *async_extent;
347 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
348 BUG_ON(!async_extent); /* -ENOMEM */
349 async_extent->start = start;
350 async_extent->ram_size = ram_size;
351 async_extent->compressed_size = compressed_size;
352 async_extent->pages = pages;
353 async_extent->nr_pages = nr_pages;
354 async_extent->compress_type = compress_type;
355 list_add_tail(&async_extent->list, &cow->extents);
359 static inline int inode_need_compress(struct inode *inode)
361 struct btrfs_root *root = BTRFS_I(inode)->root;
364 if (btrfs_test_opt(root, FORCE_COMPRESS))
366 /* bad compression ratios */
367 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
369 if (btrfs_test_opt(root, COMPRESS) ||
370 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
371 BTRFS_I(inode)->force_compress)
377 * we create compressed extents in two phases. The first
378 * phase compresses a range of pages that have already been
379 * locked (both pages and state bits are locked).
381 * This is done inside an ordered work queue, and the compression
382 * is spread across many cpus. The actual IO submission is step
383 * two, and the ordered work queue takes care of making sure that
384 * happens in the same order things were put onto the queue by
385 * writepages and friends.
387 * If this code finds it can't get good compression, it puts an
388 * entry onto the work queue to write the uncompressed bytes. This
389 * makes sure that both compressed inodes and uncompressed inodes
390 * are written in the same order that the flusher thread sent them
393 static noinline void compress_file_range(struct inode *inode,
394 struct page *locked_page,
396 struct async_cow *async_cow,
399 struct btrfs_root *root = BTRFS_I(inode)->root;
401 u64 blocksize = root->sectorsize;
403 u64 isize = i_size_read(inode);
405 struct page **pages = NULL;
406 unsigned long nr_pages;
407 unsigned long nr_pages_ret = 0;
408 unsigned long total_compressed = 0;
409 unsigned long total_in = 0;
410 unsigned long max_compressed = 128 * 1024;
411 unsigned long max_uncompressed = 128 * 1024;
414 int compress_type = root->fs_info->compress_type;
417 /* if this is a small write inside eof, kick off a defrag */
418 if ((end - start + 1) < 16 * 1024 &&
419 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
420 btrfs_add_inode_defrag(NULL, inode);
422 actual_end = min_t(u64, isize, end + 1);
425 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
426 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
429 * we don't want to send crud past the end of i_size through
430 * compression, that's just a waste of CPU time. So, if the
431 * end of the file is before the start of our current
432 * requested range of bytes, we bail out to the uncompressed
433 * cleanup code that can deal with all of this.
435 * It isn't really the fastest way to fix things, but this is a
436 * very uncommon corner.
438 if (actual_end <= start)
439 goto cleanup_and_bail_uncompressed;
441 total_compressed = actual_end - start;
444 * skip compression for a small file range(<=blocksize) that
445 * isn't an inline extent, since it dosen't save disk space at all.
447 if (total_compressed <= blocksize &&
448 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
449 goto cleanup_and_bail_uncompressed;
451 /* we want to make sure that amount of ram required to uncompress
452 * an extent is reasonable, so we limit the total size in ram
453 * of a compressed extent to 128k. This is a crucial number
454 * because it also controls how easily we can spread reads across
455 * cpus for decompression.
457 * We also want to make sure the amount of IO required to do
458 * a random read is reasonably small, so we limit the size of
459 * a compressed extent to 128k.
461 total_compressed = min(total_compressed, max_uncompressed);
462 num_bytes = ALIGN(end - start + 1, blocksize);
463 num_bytes = max(blocksize, num_bytes);
468 * we do compression for mount -o compress and when the
469 * inode has not been flagged as nocompress. This flag can
470 * change at any time if we discover bad compression ratios.
472 if (inode_need_compress(inode)) {
474 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
476 /* just bail out to the uncompressed code */
480 if (BTRFS_I(inode)->force_compress)
481 compress_type = BTRFS_I(inode)->force_compress;
484 * we need to call clear_page_dirty_for_io on each
485 * page in the range. Otherwise applications with the file
486 * mmap'd can wander in and change the page contents while
487 * we are compressing them.
489 * If the compression fails for any reason, we set the pages
490 * dirty again later on.
492 extent_range_clear_dirty_for_io(inode, start, end);
494 ret = btrfs_compress_pages(compress_type,
495 inode->i_mapping, start,
496 total_compressed, pages,
497 nr_pages, &nr_pages_ret,
503 unsigned long offset = total_compressed &
504 (PAGE_CACHE_SIZE - 1);
505 struct page *page = pages[nr_pages_ret - 1];
508 /* zero the tail end of the last page, we might be
509 * sending it down to disk
512 kaddr = kmap_atomic(page);
513 memset(kaddr + offset, 0,
514 PAGE_CACHE_SIZE - offset);
515 kunmap_atomic(kaddr);
522 /* lets try to make an inline extent */
523 if (ret || total_in < (actual_end - start)) {
524 /* we didn't compress the entire range, try
525 * to make an uncompressed inline extent.
527 ret = cow_file_range_inline(root, inode, start, end,
530 /* try making a compressed inline extent */
531 ret = cow_file_range_inline(root, inode, start, end,
533 compress_type, pages);
536 unsigned long clear_flags = EXTENT_DELALLOC |
538 unsigned long page_error_op;
540 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
541 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
544 * inline extent creation worked or returned error,
545 * we don't need to create any more async work items.
546 * Unlock and free up our temp pages.
548 extent_clear_unlock_delalloc(inode, start, end, NULL,
549 clear_flags, PAGE_UNLOCK |
560 * we aren't doing an inline extent round the compressed size
561 * up to a block size boundary so the allocator does sane
564 total_compressed = ALIGN(total_compressed, blocksize);
567 * one last check to make sure the compression is really a
568 * win, compare the page count read with the blocks on disk
570 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
571 if (total_compressed >= total_in) {
574 num_bytes = total_in;
577 if (!will_compress && pages) {
579 * the compression code ran but failed to make things smaller,
580 * free any pages it allocated and our page pointer array
582 for (i = 0; i < nr_pages_ret; i++) {
583 WARN_ON(pages[i]->mapping);
584 page_cache_release(pages[i]);
588 total_compressed = 0;
591 /* flag the file so we don't compress in the future */
592 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
593 !(BTRFS_I(inode)->force_compress)) {
594 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
600 /* the async work queues will take care of doing actual
601 * allocation on disk for these compressed pages,
602 * and will submit them to the elevator.
604 add_async_extent(async_cow, start, num_bytes,
605 total_compressed, pages, nr_pages_ret,
608 if (start + num_bytes < end) {
615 cleanup_and_bail_uncompressed:
617 * No compression, but we still need to write the pages in
618 * the file we've been given so far. redirty the locked
619 * page if it corresponds to our extent and set things up
620 * for the async work queue to run cow_file_range to do
621 * the normal delalloc dance
623 if (page_offset(locked_page) >= start &&
624 page_offset(locked_page) <= end) {
625 __set_page_dirty_nobuffers(locked_page);
626 /* unlocked later on in the async handlers */
629 extent_range_redirty_for_io(inode, start, end);
630 add_async_extent(async_cow, start, end - start + 1,
631 0, NULL, 0, BTRFS_COMPRESS_NONE);
638 for (i = 0; i < nr_pages_ret; i++) {
639 WARN_ON(pages[i]->mapping);
640 page_cache_release(pages[i]);
645 static void free_async_extent_pages(struct async_extent *async_extent)
649 if (!async_extent->pages)
652 for (i = 0; i < async_extent->nr_pages; i++) {
653 WARN_ON(async_extent->pages[i]->mapping);
654 page_cache_release(async_extent->pages[i]);
656 kfree(async_extent->pages);
657 async_extent->nr_pages = 0;
658 async_extent->pages = NULL;
662 * phase two of compressed writeback. This is the ordered portion
663 * of the code, which only gets called in the order the work was
664 * queued. We walk all the async extents created by compress_file_range
665 * and send them down to the disk.
667 static noinline void submit_compressed_extents(struct inode *inode,
668 struct async_cow *async_cow)
670 struct async_extent *async_extent;
672 struct btrfs_key ins;
673 struct extent_map *em;
674 struct btrfs_root *root = BTRFS_I(inode)->root;
675 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
676 struct extent_io_tree *io_tree;
680 while (!list_empty(&async_cow->extents)) {
681 async_extent = list_entry(async_cow->extents.next,
682 struct async_extent, list);
683 list_del(&async_extent->list);
685 io_tree = &BTRFS_I(inode)->io_tree;
688 /* did the compression code fall back to uncompressed IO? */
689 if (!async_extent->pages) {
690 int page_started = 0;
691 unsigned long nr_written = 0;
693 lock_extent(io_tree, async_extent->start,
694 async_extent->start +
695 async_extent->ram_size - 1);
697 /* allocate blocks */
698 ret = cow_file_range(inode, async_cow->locked_page,
700 async_extent->start +
701 async_extent->ram_size - 1,
702 &page_started, &nr_written, 0);
707 * if page_started, cow_file_range inserted an
708 * inline extent and took care of all the unlocking
709 * and IO for us. Otherwise, we need to submit
710 * all those pages down to the drive.
712 if (!page_started && !ret)
713 extent_write_locked_range(io_tree,
714 inode, async_extent->start,
715 async_extent->start +
716 async_extent->ram_size - 1,
720 unlock_page(async_cow->locked_page);
726 lock_extent(io_tree, async_extent->start,
727 async_extent->start + async_extent->ram_size - 1);
729 ret = btrfs_reserve_extent(root,
730 async_extent->compressed_size,
731 async_extent->compressed_size,
732 0, alloc_hint, &ins, 1, 1);
734 free_async_extent_pages(async_extent);
736 if (ret == -ENOSPC) {
737 unlock_extent(io_tree, async_extent->start,
738 async_extent->start +
739 async_extent->ram_size - 1);
742 * we need to redirty the pages if we decide to
743 * fallback to uncompressed IO, otherwise we
744 * will not submit these pages down to lower
747 extent_range_redirty_for_io(inode,
749 async_extent->start +
750 async_extent->ram_size - 1);
757 * here we're doing allocation and writeback of the
760 btrfs_drop_extent_cache(inode, async_extent->start,
761 async_extent->start +
762 async_extent->ram_size - 1, 0);
764 em = alloc_extent_map();
767 goto out_free_reserve;
769 em->start = async_extent->start;
770 em->len = async_extent->ram_size;
771 em->orig_start = em->start;
772 em->mod_start = em->start;
773 em->mod_len = em->len;
775 em->block_start = ins.objectid;
776 em->block_len = ins.offset;
777 em->orig_block_len = ins.offset;
778 em->ram_bytes = async_extent->ram_size;
779 em->bdev = root->fs_info->fs_devices->latest_bdev;
780 em->compress_type = async_extent->compress_type;
781 set_bit(EXTENT_FLAG_PINNED, &em->flags);
782 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
786 write_lock(&em_tree->lock);
787 ret = add_extent_mapping(em_tree, em, 1);
788 write_unlock(&em_tree->lock);
789 if (ret != -EEXIST) {
793 btrfs_drop_extent_cache(inode, async_extent->start,
794 async_extent->start +
795 async_extent->ram_size - 1, 0);
799 goto out_free_reserve;
801 ret = btrfs_add_ordered_extent_compress(inode,
804 async_extent->ram_size,
806 BTRFS_ORDERED_COMPRESSED,
807 async_extent->compress_type);
809 btrfs_drop_extent_cache(inode, async_extent->start,
810 async_extent->start +
811 async_extent->ram_size - 1, 0);
812 goto out_free_reserve;
816 * clear dirty, set writeback and unlock the pages.
818 extent_clear_unlock_delalloc(inode, async_extent->start,
819 async_extent->start +
820 async_extent->ram_size - 1,
821 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
822 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
824 ret = btrfs_submit_compressed_write(inode,
826 async_extent->ram_size,
828 ins.offset, async_extent->pages,
829 async_extent->nr_pages);
831 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
832 struct page *p = async_extent->pages[0];
833 const u64 start = async_extent->start;
834 const u64 end = start + async_extent->ram_size - 1;
836 p->mapping = inode->i_mapping;
837 tree->ops->writepage_end_io_hook(p, start, end,
840 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
843 free_async_extent_pages(async_extent);
845 alloc_hint = ins.objectid + ins.offset;
851 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
853 extent_clear_unlock_delalloc(inode, async_extent->start,
854 async_extent->start +
855 async_extent->ram_size - 1,
856 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
857 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
858 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
859 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
861 free_async_extent_pages(async_extent);
866 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
869 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
870 struct extent_map *em;
873 read_lock(&em_tree->lock);
874 em = search_extent_mapping(em_tree, start, num_bytes);
877 * if block start isn't an actual block number then find the
878 * first block in this inode and use that as a hint. If that
879 * block is also bogus then just don't worry about it.
881 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
883 em = search_extent_mapping(em_tree, 0, 0);
884 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
885 alloc_hint = em->block_start;
889 alloc_hint = em->block_start;
893 read_unlock(&em_tree->lock);
899 * when extent_io.c finds a delayed allocation range in the file,
900 * the call backs end up in this code. The basic idea is to
901 * allocate extents on disk for the range, and create ordered data structs
902 * in ram to track those extents.
904 * locked_page is the page that writepage had locked already. We use
905 * it to make sure we don't do extra locks or unlocks.
907 * *page_started is set to one if we unlock locked_page and do everything
908 * required to start IO on it. It may be clean and already done with
911 static noinline int cow_file_range(struct inode *inode,
912 struct page *locked_page,
913 u64 start, u64 end, int *page_started,
914 unsigned long *nr_written,
917 struct btrfs_root *root = BTRFS_I(inode)->root;
920 unsigned long ram_size;
923 u64 blocksize = root->sectorsize;
924 struct btrfs_key ins;
925 struct extent_map *em;
926 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
929 if (btrfs_is_free_space_inode(inode)) {
935 num_bytes = ALIGN(end - start + 1, blocksize);
936 num_bytes = max(blocksize, num_bytes);
937 disk_num_bytes = num_bytes;
939 /* if this is a small write inside eof, kick off defrag */
940 if (num_bytes < 64 * 1024 &&
941 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
942 btrfs_add_inode_defrag(NULL, inode);
945 /* lets try to make an inline extent */
946 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
949 extent_clear_unlock_delalloc(inode, start, end, NULL,
950 EXTENT_LOCKED | EXTENT_DELALLOC |
951 EXTENT_DEFRAG, PAGE_UNLOCK |
952 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
955 *nr_written = *nr_written +
956 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
959 } else if (ret < 0) {
964 BUG_ON(disk_num_bytes >
965 btrfs_super_total_bytes(root->fs_info->super_copy));
967 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
968 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
970 while (disk_num_bytes > 0) {
973 cur_alloc_size = disk_num_bytes;
974 ret = btrfs_reserve_extent(root, cur_alloc_size,
975 root->sectorsize, 0, alloc_hint,
980 em = alloc_extent_map();
986 em->orig_start = em->start;
987 ram_size = ins.offset;
988 em->len = ins.offset;
989 em->mod_start = em->start;
990 em->mod_len = em->len;
992 em->block_start = ins.objectid;
993 em->block_len = ins.offset;
994 em->orig_block_len = ins.offset;
995 em->ram_bytes = ram_size;
996 em->bdev = root->fs_info->fs_devices->latest_bdev;
997 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1001 write_lock(&em_tree->lock);
1002 ret = add_extent_mapping(em_tree, em, 1);
1003 write_unlock(&em_tree->lock);
1004 if (ret != -EEXIST) {
1005 free_extent_map(em);
1008 btrfs_drop_extent_cache(inode, start,
1009 start + ram_size - 1, 0);
1014 cur_alloc_size = ins.offset;
1015 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1016 ram_size, cur_alloc_size, 0);
1018 goto out_drop_extent_cache;
1020 if (root->root_key.objectid ==
1021 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1022 ret = btrfs_reloc_clone_csums(inode, start,
1025 goto out_drop_extent_cache;
1028 if (disk_num_bytes < cur_alloc_size)
1031 /* we're not doing compressed IO, don't unlock the first
1032 * page (which the caller expects to stay locked), don't
1033 * clear any dirty bits and don't set any writeback bits
1035 * Do set the Private2 bit so we know this page was properly
1036 * setup for writepage
1038 op = unlock ? PAGE_UNLOCK : 0;
1039 op |= PAGE_SET_PRIVATE2;
1041 extent_clear_unlock_delalloc(inode, start,
1042 start + ram_size - 1, locked_page,
1043 EXTENT_LOCKED | EXTENT_DELALLOC,
1045 disk_num_bytes -= cur_alloc_size;
1046 num_bytes -= cur_alloc_size;
1047 alloc_hint = ins.objectid + ins.offset;
1048 start += cur_alloc_size;
1053 out_drop_extent_cache:
1054 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1056 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1058 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1059 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1060 EXTENT_DELALLOC | EXTENT_DEFRAG,
1061 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1062 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1067 * work queue call back to started compression on a file and pages
1069 static noinline void async_cow_start(struct btrfs_work *work)
1071 struct async_cow *async_cow;
1073 async_cow = container_of(work, struct async_cow, work);
1075 compress_file_range(async_cow->inode, async_cow->locked_page,
1076 async_cow->start, async_cow->end, async_cow,
1078 if (num_added == 0) {
1079 btrfs_add_delayed_iput(async_cow->inode);
1080 async_cow->inode = NULL;
1085 * work queue call back to submit previously compressed pages
1087 static noinline void async_cow_submit(struct btrfs_work *work)
1089 struct async_cow *async_cow;
1090 struct btrfs_root *root;
1091 unsigned long nr_pages;
1093 async_cow = container_of(work, struct async_cow, work);
1095 root = async_cow->root;
1096 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1100 * atomic_sub_return implies a barrier for waitqueue_active
1102 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1104 waitqueue_active(&root->fs_info->async_submit_wait))
1105 wake_up(&root->fs_info->async_submit_wait);
1107 if (async_cow->inode)
1108 submit_compressed_extents(async_cow->inode, async_cow);
1111 static noinline void async_cow_free(struct btrfs_work *work)
1113 struct async_cow *async_cow;
1114 async_cow = container_of(work, struct async_cow, work);
1115 if (async_cow->inode)
1116 btrfs_add_delayed_iput(async_cow->inode);
1120 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1121 u64 start, u64 end, int *page_started,
1122 unsigned long *nr_written)
1124 struct async_cow *async_cow;
1125 struct btrfs_root *root = BTRFS_I(inode)->root;
1126 unsigned long nr_pages;
1128 int limit = 10 * 1024 * 1024;
1130 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1131 1, 0, NULL, GFP_NOFS);
1132 while (start < end) {
1133 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1134 BUG_ON(!async_cow); /* -ENOMEM */
1135 async_cow->inode = igrab(inode);
1136 async_cow->root = root;
1137 async_cow->locked_page = locked_page;
1138 async_cow->start = start;
1140 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1141 !btrfs_test_opt(root, FORCE_COMPRESS))
1144 cur_end = min(end, start + 512 * 1024 - 1);
1146 async_cow->end = cur_end;
1147 INIT_LIST_HEAD(&async_cow->extents);
1149 btrfs_init_work(&async_cow->work,
1150 btrfs_delalloc_helper,
1151 async_cow_start, async_cow_submit,
1154 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1156 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1158 btrfs_queue_work(root->fs_info->delalloc_workers,
1161 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1162 wait_event(root->fs_info->async_submit_wait,
1163 (atomic_read(&root->fs_info->async_delalloc_pages) <
1167 while (atomic_read(&root->fs_info->async_submit_draining) &&
1168 atomic_read(&root->fs_info->async_delalloc_pages)) {
1169 wait_event(root->fs_info->async_submit_wait,
1170 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1174 *nr_written += nr_pages;
1175 start = cur_end + 1;
1181 static noinline int csum_exist_in_range(struct btrfs_root *root,
1182 u64 bytenr, u64 num_bytes)
1185 struct btrfs_ordered_sum *sums;
1188 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1189 bytenr + num_bytes - 1, &list, 0);
1190 if (ret == 0 && list_empty(&list))
1193 while (!list_empty(&list)) {
1194 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1195 list_del(&sums->list);
1202 * when nowcow writeback call back. This checks for snapshots or COW copies
1203 * of the extents that exist in the file, and COWs the file as required.
1205 * If no cow copies or snapshots exist, we write directly to the existing
1208 static noinline int run_delalloc_nocow(struct inode *inode,
1209 struct page *locked_page,
1210 u64 start, u64 end, int *page_started, int force,
1211 unsigned long *nr_written)
1213 struct btrfs_root *root = BTRFS_I(inode)->root;
1214 struct btrfs_trans_handle *trans;
1215 struct extent_buffer *leaf;
1216 struct btrfs_path *path;
1217 struct btrfs_file_extent_item *fi;
1218 struct btrfs_key found_key;
1233 u64 ino = btrfs_ino(inode);
1235 path = btrfs_alloc_path();
1237 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1238 EXTENT_LOCKED | EXTENT_DELALLOC |
1239 EXTENT_DO_ACCOUNTING |
1240 EXTENT_DEFRAG, PAGE_UNLOCK |
1242 PAGE_SET_WRITEBACK |
1243 PAGE_END_WRITEBACK);
1247 nolock = btrfs_is_free_space_inode(inode);
1250 trans = btrfs_join_transaction_nolock(root);
1252 trans = btrfs_join_transaction(root);
1254 if (IS_ERR(trans)) {
1255 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1256 EXTENT_LOCKED | EXTENT_DELALLOC |
1257 EXTENT_DO_ACCOUNTING |
1258 EXTENT_DEFRAG, PAGE_UNLOCK |
1260 PAGE_SET_WRITEBACK |
1261 PAGE_END_WRITEBACK);
1262 btrfs_free_path(path);
1263 return PTR_ERR(trans);
1266 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1268 cow_start = (u64)-1;
1271 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1275 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1276 leaf = path->nodes[0];
1277 btrfs_item_key_to_cpu(leaf, &found_key,
1278 path->slots[0] - 1);
1279 if (found_key.objectid == ino &&
1280 found_key.type == BTRFS_EXTENT_DATA_KEY)
1285 leaf = path->nodes[0];
1286 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1287 ret = btrfs_next_leaf(root, path);
1292 leaf = path->nodes[0];
1298 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1300 if (found_key.objectid > ino ||
1301 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1302 found_key.offset > end)
1305 if (found_key.offset > cur_offset) {
1306 extent_end = found_key.offset;
1311 fi = btrfs_item_ptr(leaf, path->slots[0],
1312 struct btrfs_file_extent_item);
1313 extent_type = btrfs_file_extent_type(leaf, fi);
1315 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1316 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1317 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1318 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1319 extent_offset = btrfs_file_extent_offset(leaf, fi);
1320 extent_end = found_key.offset +
1321 btrfs_file_extent_num_bytes(leaf, fi);
1323 btrfs_file_extent_disk_num_bytes(leaf, fi);
1324 if (extent_end <= start) {
1328 if (disk_bytenr == 0)
1330 if (btrfs_file_extent_compression(leaf, fi) ||
1331 btrfs_file_extent_encryption(leaf, fi) ||
1332 btrfs_file_extent_other_encoding(leaf, fi))
1334 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1336 if (btrfs_extent_readonly(root, disk_bytenr))
1338 if (btrfs_cross_ref_exist(trans, root, ino,
1340 extent_offset, disk_bytenr))
1342 disk_bytenr += extent_offset;
1343 disk_bytenr += cur_offset - found_key.offset;
1344 num_bytes = min(end + 1, extent_end) - cur_offset;
1346 * if there are pending snapshots for this root,
1347 * we fall into common COW way.
1350 err = btrfs_start_write_no_snapshoting(root);
1355 * force cow if csum exists in the range.
1356 * this ensure that csum for a given extent are
1357 * either valid or do not exist.
1359 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1362 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1363 extent_end = found_key.offset +
1364 btrfs_file_extent_inline_len(leaf,
1365 path->slots[0], fi);
1366 extent_end = ALIGN(extent_end, root->sectorsize);
1371 if (extent_end <= start) {
1373 if (!nolock && nocow)
1374 btrfs_end_write_no_snapshoting(root);
1378 if (cow_start == (u64)-1)
1379 cow_start = cur_offset;
1380 cur_offset = extent_end;
1381 if (cur_offset > end)
1387 btrfs_release_path(path);
1388 if (cow_start != (u64)-1) {
1389 ret = cow_file_range(inode, locked_page,
1390 cow_start, found_key.offset - 1,
1391 page_started, nr_written, 1);
1393 if (!nolock && nocow)
1394 btrfs_end_write_no_snapshoting(root);
1397 cow_start = (u64)-1;
1400 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1401 struct extent_map *em;
1402 struct extent_map_tree *em_tree;
1403 em_tree = &BTRFS_I(inode)->extent_tree;
1404 em = alloc_extent_map();
1405 BUG_ON(!em); /* -ENOMEM */
1406 em->start = cur_offset;
1407 em->orig_start = found_key.offset - extent_offset;
1408 em->len = num_bytes;
1409 em->block_len = num_bytes;
1410 em->block_start = disk_bytenr;
1411 em->orig_block_len = disk_num_bytes;
1412 em->ram_bytes = ram_bytes;
1413 em->bdev = root->fs_info->fs_devices->latest_bdev;
1414 em->mod_start = em->start;
1415 em->mod_len = em->len;
1416 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1417 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1418 em->generation = -1;
1420 write_lock(&em_tree->lock);
1421 ret = add_extent_mapping(em_tree, em, 1);
1422 write_unlock(&em_tree->lock);
1423 if (ret != -EEXIST) {
1424 free_extent_map(em);
1427 btrfs_drop_extent_cache(inode, em->start,
1428 em->start + em->len - 1, 0);
1430 type = BTRFS_ORDERED_PREALLOC;
1432 type = BTRFS_ORDERED_NOCOW;
1435 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1436 num_bytes, num_bytes, type);
1437 BUG_ON(ret); /* -ENOMEM */
1439 if (root->root_key.objectid ==
1440 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1441 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1444 if (!nolock && nocow)
1445 btrfs_end_write_no_snapshoting(root);
1450 extent_clear_unlock_delalloc(inode, cur_offset,
1451 cur_offset + num_bytes - 1,
1452 locked_page, EXTENT_LOCKED |
1453 EXTENT_DELALLOC, PAGE_UNLOCK |
1455 if (!nolock && nocow)
1456 btrfs_end_write_no_snapshoting(root);
1457 cur_offset = extent_end;
1458 if (cur_offset > end)
1461 btrfs_release_path(path);
1463 if (cur_offset <= end && cow_start == (u64)-1) {
1464 cow_start = cur_offset;
1468 if (cow_start != (u64)-1) {
1469 ret = cow_file_range(inode, locked_page, cow_start, end,
1470 page_started, nr_written, 1);
1476 err = btrfs_end_transaction(trans, root);
1480 if (ret && cur_offset < end)
1481 extent_clear_unlock_delalloc(inode, cur_offset, end,
1482 locked_page, EXTENT_LOCKED |
1483 EXTENT_DELALLOC | EXTENT_DEFRAG |
1484 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1486 PAGE_SET_WRITEBACK |
1487 PAGE_END_WRITEBACK);
1488 btrfs_free_path(path);
1492 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1495 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1496 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1500 * @defrag_bytes is a hint value, no spinlock held here,
1501 * if is not zero, it means the file is defragging.
1502 * Force cow if given extent needs to be defragged.
1504 if (BTRFS_I(inode)->defrag_bytes &&
1505 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1506 EXTENT_DEFRAG, 0, NULL))
1513 * extent_io.c call back to do delayed allocation processing
1515 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1516 u64 start, u64 end, int *page_started,
1517 unsigned long *nr_written)
1520 int force_cow = need_force_cow(inode, start, end);
1522 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1523 ret = run_delalloc_nocow(inode, locked_page, start, end,
1524 page_started, 1, nr_written);
1525 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1526 ret = run_delalloc_nocow(inode, locked_page, start, end,
1527 page_started, 0, nr_written);
1528 } else if (!inode_need_compress(inode)) {
1529 ret = cow_file_range(inode, locked_page, start, end,
1530 page_started, nr_written, 1);
1532 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1533 &BTRFS_I(inode)->runtime_flags);
1534 ret = cow_file_range_async(inode, locked_page, start, end,
1535 page_started, nr_written);
1540 static void btrfs_split_extent_hook(struct inode *inode,
1541 struct extent_state *orig, u64 split)
1545 /* not delalloc, ignore it */
1546 if (!(orig->state & EXTENT_DELALLOC))
1549 size = orig->end - orig->start + 1;
1550 if (size > BTRFS_MAX_EXTENT_SIZE) {
1555 * See the explanation in btrfs_merge_extent_hook, the same
1556 * applies here, just in reverse.
1558 new_size = orig->end - split + 1;
1559 num_extents = div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1560 BTRFS_MAX_EXTENT_SIZE);
1561 new_size = split - orig->start;
1562 num_extents += div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1563 BTRFS_MAX_EXTENT_SIZE);
1564 if (div64_u64(size + BTRFS_MAX_EXTENT_SIZE - 1,
1565 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1569 spin_lock(&BTRFS_I(inode)->lock);
1570 BTRFS_I(inode)->outstanding_extents++;
1571 spin_unlock(&BTRFS_I(inode)->lock);
1575 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1576 * extents so we can keep track of new extents that are just merged onto old
1577 * extents, such as when we are doing sequential writes, so we can properly
1578 * account for the metadata space we'll need.
1580 static void btrfs_merge_extent_hook(struct inode *inode,
1581 struct extent_state *new,
1582 struct extent_state *other)
1584 u64 new_size, old_size;
1587 /* not delalloc, ignore it */
1588 if (!(other->state & EXTENT_DELALLOC))
1591 if (new->start > other->start)
1592 new_size = new->end - other->start + 1;
1594 new_size = other->end - new->start + 1;
1596 /* we're not bigger than the max, unreserve the space and go */
1597 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1598 spin_lock(&BTRFS_I(inode)->lock);
1599 BTRFS_I(inode)->outstanding_extents--;
1600 spin_unlock(&BTRFS_I(inode)->lock);
1605 * We have to add up either side to figure out how many extents were
1606 * accounted for before we merged into one big extent. If the number of
1607 * extents we accounted for is <= the amount we need for the new range
1608 * then we can return, otherwise drop. Think of it like this
1612 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1613 * need 2 outstanding extents, on one side we have 1 and the other side
1614 * we have 1 so they are == and we can return. But in this case
1616 * [MAX_SIZE+4k][MAX_SIZE+4k]
1618 * Each range on their own accounts for 2 extents, but merged together
1619 * they are only 3 extents worth of accounting, so we need to drop in
1622 old_size = other->end - other->start + 1;
1623 num_extents = div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1624 BTRFS_MAX_EXTENT_SIZE);
1625 old_size = new->end - new->start + 1;
1626 num_extents += div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1627 BTRFS_MAX_EXTENT_SIZE);
1629 if (div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1630 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1633 spin_lock(&BTRFS_I(inode)->lock);
1634 BTRFS_I(inode)->outstanding_extents--;
1635 spin_unlock(&BTRFS_I(inode)->lock);
1638 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1639 struct inode *inode)
1641 spin_lock(&root->delalloc_lock);
1642 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1643 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1644 &root->delalloc_inodes);
1645 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1646 &BTRFS_I(inode)->runtime_flags);
1647 root->nr_delalloc_inodes++;
1648 if (root->nr_delalloc_inodes == 1) {
1649 spin_lock(&root->fs_info->delalloc_root_lock);
1650 BUG_ON(!list_empty(&root->delalloc_root));
1651 list_add_tail(&root->delalloc_root,
1652 &root->fs_info->delalloc_roots);
1653 spin_unlock(&root->fs_info->delalloc_root_lock);
1656 spin_unlock(&root->delalloc_lock);
1659 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1660 struct inode *inode)
1662 spin_lock(&root->delalloc_lock);
1663 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1664 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1665 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1666 &BTRFS_I(inode)->runtime_flags);
1667 root->nr_delalloc_inodes--;
1668 if (!root->nr_delalloc_inodes) {
1669 spin_lock(&root->fs_info->delalloc_root_lock);
1670 BUG_ON(list_empty(&root->delalloc_root));
1671 list_del_init(&root->delalloc_root);
1672 spin_unlock(&root->fs_info->delalloc_root_lock);
1675 spin_unlock(&root->delalloc_lock);
1679 * extent_io.c set_bit_hook, used to track delayed allocation
1680 * bytes in this file, and to maintain the list of inodes that
1681 * have pending delalloc work to be done.
1683 static void btrfs_set_bit_hook(struct inode *inode,
1684 struct extent_state *state, unsigned *bits)
1687 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1690 * set_bit and clear bit hooks normally require _irqsave/restore
1691 * but in this case, we are only testing for the DELALLOC
1692 * bit, which is only set or cleared with irqs on
1694 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1695 struct btrfs_root *root = BTRFS_I(inode)->root;
1696 u64 len = state->end + 1 - state->start;
1697 bool do_list = !btrfs_is_free_space_inode(inode);
1699 if (*bits & EXTENT_FIRST_DELALLOC) {
1700 *bits &= ~EXTENT_FIRST_DELALLOC;
1702 spin_lock(&BTRFS_I(inode)->lock);
1703 BTRFS_I(inode)->outstanding_extents++;
1704 spin_unlock(&BTRFS_I(inode)->lock);
1707 /* For sanity tests */
1708 if (btrfs_test_is_dummy_root(root))
1711 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1712 root->fs_info->delalloc_batch);
1713 spin_lock(&BTRFS_I(inode)->lock);
1714 BTRFS_I(inode)->delalloc_bytes += len;
1715 if (*bits & EXTENT_DEFRAG)
1716 BTRFS_I(inode)->defrag_bytes += len;
1717 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1718 &BTRFS_I(inode)->runtime_flags))
1719 btrfs_add_delalloc_inodes(root, inode);
1720 spin_unlock(&BTRFS_I(inode)->lock);
1725 * extent_io.c clear_bit_hook, see set_bit_hook for why
1727 static void btrfs_clear_bit_hook(struct inode *inode,
1728 struct extent_state *state,
1731 u64 len = state->end + 1 - state->start;
1732 u64 num_extents = div64_u64(len + BTRFS_MAX_EXTENT_SIZE -1,
1733 BTRFS_MAX_EXTENT_SIZE);
1735 spin_lock(&BTRFS_I(inode)->lock);
1736 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1737 BTRFS_I(inode)->defrag_bytes -= len;
1738 spin_unlock(&BTRFS_I(inode)->lock);
1741 * set_bit and clear bit hooks normally require _irqsave/restore
1742 * but in this case, we are only testing for the DELALLOC
1743 * bit, which is only set or cleared with irqs on
1745 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1746 struct btrfs_root *root = BTRFS_I(inode)->root;
1747 bool do_list = !btrfs_is_free_space_inode(inode);
1749 if (*bits & EXTENT_FIRST_DELALLOC) {
1750 *bits &= ~EXTENT_FIRST_DELALLOC;
1751 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1752 spin_lock(&BTRFS_I(inode)->lock);
1753 BTRFS_I(inode)->outstanding_extents -= num_extents;
1754 spin_unlock(&BTRFS_I(inode)->lock);
1758 * We don't reserve metadata space for space cache inodes so we
1759 * don't need to call dellalloc_release_metadata if there is an
1762 if (*bits & EXTENT_DO_ACCOUNTING &&
1763 root != root->fs_info->tree_root)
1764 btrfs_delalloc_release_metadata(inode, len);
1766 /* For sanity tests. */
1767 if (btrfs_test_is_dummy_root(root))
1770 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1771 && do_list && !(state->state & EXTENT_NORESERVE))
1772 btrfs_free_reserved_data_space(inode, len);
1774 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1775 root->fs_info->delalloc_batch);
1776 spin_lock(&BTRFS_I(inode)->lock);
1777 BTRFS_I(inode)->delalloc_bytes -= len;
1778 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1779 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1780 &BTRFS_I(inode)->runtime_flags))
1781 btrfs_del_delalloc_inode(root, inode);
1782 spin_unlock(&BTRFS_I(inode)->lock);
1787 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1788 * we don't create bios that span stripes or chunks
1790 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1791 size_t size, struct bio *bio,
1792 unsigned long bio_flags)
1794 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1795 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1800 if (bio_flags & EXTENT_BIO_COMPRESSED)
1803 length = bio->bi_iter.bi_size;
1804 map_length = length;
1805 ret = btrfs_map_block(root->fs_info, rw, logical,
1806 &map_length, NULL, 0);
1807 /* Will always return 0 with map_multi == NULL */
1809 if (map_length < length + size)
1815 * in order to insert checksums into the metadata in large chunks,
1816 * we wait until bio submission time. All the pages in the bio are
1817 * checksummed and sums are attached onto the ordered extent record.
1819 * At IO completion time the cums attached on the ordered extent record
1820 * are inserted into the btree
1822 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1823 struct bio *bio, int mirror_num,
1824 unsigned long bio_flags,
1827 struct btrfs_root *root = BTRFS_I(inode)->root;
1830 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1831 BUG_ON(ret); /* -ENOMEM */
1836 * in order to insert checksums into the metadata in large chunks,
1837 * we wait until bio submission time. All the pages in the bio are
1838 * checksummed and sums are attached onto the ordered extent record.
1840 * At IO completion time the cums attached on the ordered extent record
1841 * are inserted into the btree
1843 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1844 int mirror_num, unsigned long bio_flags,
1847 struct btrfs_root *root = BTRFS_I(inode)->root;
1850 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1852 bio->bi_error = ret;
1859 * extent_io.c submission hook. This does the right thing for csum calculation
1860 * on write, or reading the csums from the tree before a read
1862 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1863 int mirror_num, unsigned long bio_flags,
1866 struct btrfs_root *root = BTRFS_I(inode)->root;
1870 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1872 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1874 if (btrfs_is_free_space_inode(inode))
1877 if (!(rw & REQ_WRITE)) {
1878 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1882 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1883 ret = btrfs_submit_compressed_read(inode, bio,
1887 } else if (!skip_sum) {
1888 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1893 } else if (async && !skip_sum) {
1894 /* csum items have already been cloned */
1895 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1897 /* we're doing a write, do the async checksumming */
1898 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1899 inode, rw, bio, mirror_num,
1900 bio_flags, bio_offset,
1901 __btrfs_submit_bio_start,
1902 __btrfs_submit_bio_done);
1904 } else if (!skip_sum) {
1905 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1911 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1915 bio->bi_error = ret;
1922 * given a list of ordered sums record them in the inode. This happens
1923 * at IO completion time based on sums calculated at bio submission time.
1925 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1926 struct inode *inode, u64 file_offset,
1927 struct list_head *list)
1929 struct btrfs_ordered_sum *sum;
1931 list_for_each_entry(sum, list, list) {
1932 trans->adding_csums = 1;
1933 btrfs_csum_file_blocks(trans,
1934 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1935 trans->adding_csums = 0;
1940 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1941 struct extent_state **cached_state)
1943 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1944 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1945 cached_state, GFP_NOFS);
1948 /* see btrfs_writepage_start_hook for details on why this is required */
1949 struct btrfs_writepage_fixup {
1951 struct btrfs_work work;
1954 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1956 struct btrfs_writepage_fixup *fixup;
1957 struct btrfs_ordered_extent *ordered;
1958 struct extent_state *cached_state = NULL;
1960 struct inode *inode;
1965 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1969 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1970 ClearPageChecked(page);
1974 inode = page->mapping->host;
1975 page_start = page_offset(page);
1976 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1978 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1981 /* already ordered? We're done */
1982 if (PagePrivate2(page))
1985 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1987 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1988 page_end, &cached_state, GFP_NOFS);
1990 btrfs_start_ordered_extent(inode, ordered, 1);
1991 btrfs_put_ordered_extent(ordered);
1995 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1997 mapping_set_error(page->mapping, ret);
1998 end_extent_writepage(page, ret, page_start, page_end);
1999 ClearPageChecked(page);
2003 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
2004 ClearPageChecked(page);
2005 set_page_dirty(page);
2007 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2008 &cached_state, GFP_NOFS);
2011 page_cache_release(page);
2016 * There are a few paths in the higher layers of the kernel that directly
2017 * set the page dirty bit without asking the filesystem if it is a
2018 * good idea. This causes problems because we want to make sure COW
2019 * properly happens and the data=ordered rules are followed.
2021 * In our case any range that doesn't have the ORDERED bit set
2022 * hasn't been properly setup for IO. We kick off an async process
2023 * to fix it up. The async helper will wait for ordered extents, set
2024 * the delalloc bit and make it safe to write the page.
2026 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2028 struct inode *inode = page->mapping->host;
2029 struct btrfs_writepage_fixup *fixup;
2030 struct btrfs_root *root = BTRFS_I(inode)->root;
2032 /* this page is properly in the ordered list */
2033 if (TestClearPagePrivate2(page))
2036 if (PageChecked(page))
2039 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2043 SetPageChecked(page);
2044 page_cache_get(page);
2045 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2046 btrfs_writepage_fixup_worker, NULL, NULL);
2048 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
2052 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2053 struct inode *inode, u64 file_pos,
2054 u64 disk_bytenr, u64 disk_num_bytes,
2055 u64 num_bytes, u64 ram_bytes,
2056 u8 compression, u8 encryption,
2057 u16 other_encoding, int extent_type)
2059 struct btrfs_root *root = BTRFS_I(inode)->root;
2060 struct btrfs_file_extent_item *fi;
2061 struct btrfs_path *path;
2062 struct extent_buffer *leaf;
2063 struct btrfs_key ins;
2064 int extent_inserted = 0;
2067 path = btrfs_alloc_path();
2072 * we may be replacing one extent in the tree with another.
2073 * The new extent is pinned in the extent map, and we don't want
2074 * to drop it from the cache until it is completely in the btree.
2076 * So, tell btrfs_drop_extents to leave this extent in the cache.
2077 * the caller is expected to unpin it and allow it to be merged
2080 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2081 file_pos + num_bytes, NULL, 0,
2082 1, sizeof(*fi), &extent_inserted);
2086 if (!extent_inserted) {
2087 ins.objectid = btrfs_ino(inode);
2088 ins.offset = file_pos;
2089 ins.type = BTRFS_EXTENT_DATA_KEY;
2091 path->leave_spinning = 1;
2092 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2097 leaf = path->nodes[0];
2098 fi = btrfs_item_ptr(leaf, path->slots[0],
2099 struct btrfs_file_extent_item);
2100 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2101 btrfs_set_file_extent_type(leaf, fi, extent_type);
2102 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2103 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2104 btrfs_set_file_extent_offset(leaf, fi, 0);
2105 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2106 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2107 btrfs_set_file_extent_compression(leaf, fi, compression);
2108 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2109 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2111 btrfs_mark_buffer_dirty(leaf);
2112 btrfs_release_path(path);
2114 inode_add_bytes(inode, num_bytes);
2116 ins.objectid = disk_bytenr;
2117 ins.offset = disk_num_bytes;
2118 ins.type = BTRFS_EXTENT_ITEM_KEY;
2119 ret = btrfs_alloc_reserved_file_extent(trans, root,
2120 root->root_key.objectid,
2121 btrfs_ino(inode), file_pos, &ins);
2123 btrfs_free_path(path);
2128 /* snapshot-aware defrag */
2129 struct sa_defrag_extent_backref {
2130 struct rb_node node;
2131 struct old_sa_defrag_extent *old;
2140 struct old_sa_defrag_extent {
2141 struct list_head list;
2142 struct new_sa_defrag_extent *new;
2151 struct new_sa_defrag_extent {
2152 struct rb_root root;
2153 struct list_head head;
2154 struct btrfs_path *path;
2155 struct inode *inode;
2163 static int backref_comp(struct sa_defrag_extent_backref *b1,
2164 struct sa_defrag_extent_backref *b2)
2166 if (b1->root_id < b2->root_id)
2168 else if (b1->root_id > b2->root_id)
2171 if (b1->inum < b2->inum)
2173 else if (b1->inum > b2->inum)
2176 if (b1->file_pos < b2->file_pos)
2178 else if (b1->file_pos > b2->file_pos)
2182 * [------------------------------] ===> (a range of space)
2183 * |<--->| |<---->| =============> (fs/file tree A)
2184 * |<---------------------------->| ===> (fs/file tree B)
2186 * A range of space can refer to two file extents in one tree while
2187 * refer to only one file extent in another tree.
2189 * So we may process a disk offset more than one time(two extents in A)
2190 * and locate at the same extent(one extent in B), then insert two same
2191 * backrefs(both refer to the extent in B).
2196 static void backref_insert(struct rb_root *root,
2197 struct sa_defrag_extent_backref *backref)
2199 struct rb_node **p = &root->rb_node;
2200 struct rb_node *parent = NULL;
2201 struct sa_defrag_extent_backref *entry;
2206 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2208 ret = backref_comp(backref, entry);
2212 p = &(*p)->rb_right;
2215 rb_link_node(&backref->node, parent, p);
2216 rb_insert_color(&backref->node, root);
2220 * Note the backref might has changed, and in this case we just return 0.
2222 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2225 struct btrfs_file_extent_item *extent;
2226 struct btrfs_fs_info *fs_info;
2227 struct old_sa_defrag_extent *old = ctx;
2228 struct new_sa_defrag_extent *new = old->new;
2229 struct btrfs_path *path = new->path;
2230 struct btrfs_key key;
2231 struct btrfs_root *root;
2232 struct sa_defrag_extent_backref *backref;
2233 struct extent_buffer *leaf;
2234 struct inode *inode = new->inode;
2240 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2241 inum == btrfs_ino(inode))
2244 key.objectid = root_id;
2245 key.type = BTRFS_ROOT_ITEM_KEY;
2246 key.offset = (u64)-1;
2248 fs_info = BTRFS_I(inode)->root->fs_info;
2249 root = btrfs_read_fs_root_no_name(fs_info, &key);
2251 if (PTR_ERR(root) == -ENOENT)
2254 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2255 inum, offset, root_id);
2256 return PTR_ERR(root);
2259 key.objectid = inum;
2260 key.type = BTRFS_EXTENT_DATA_KEY;
2261 if (offset > (u64)-1 << 32)
2264 key.offset = offset;
2266 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2267 if (WARN_ON(ret < 0))
2274 leaf = path->nodes[0];
2275 slot = path->slots[0];
2277 if (slot >= btrfs_header_nritems(leaf)) {
2278 ret = btrfs_next_leaf(root, path);
2281 } else if (ret > 0) {
2290 btrfs_item_key_to_cpu(leaf, &key, slot);
2292 if (key.objectid > inum)
2295 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2298 extent = btrfs_item_ptr(leaf, slot,
2299 struct btrfs_file_extent_item);
2301 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2305 * 'offset' refers to the exact key.offset,
2306 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2307 * (key.offset - extent_offset).
2309 if (key.offset != offset)
2312 extent_offset = btrfs_file_extent_offset(leaf, extent);
2313 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2315 if (extent_offset >= old->extent_offset + old->offset +
2316 old->len || extent_offset + num_bytes <=
2317 old->extent_offset + old->offset)
2322 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2328 backref->root_id = root_id;
2329 backref->inum = inum;
2330 backref->file_pos = offset;
2331 backref->num_bytes = num_bytes;
2332 backref->extent_offset = extent_offset;
2333 backref->generation = btrfs_file_extent_generation(leaf, extent);
2335 backref_insert(&new->root, backref);
2338 btrfs_release_path(path);
2343 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2344 struct new_sa_defrag_extent *new)
2346 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2347 struct old_sa_defrag_extent *old, *tmp;
2352 list_for_each_entry_safe(old, tmp, &new->head, list) {
2353 ret = iterate_inodes_from_logical(old->bytenr +
2354 old->extent_offset, fs_info,
2355 path, record_one_backref,
2357 if (ret < 0 && ret != -ENOENT)
2360 /* no backref to be processed for this extent */
2362 list_del(&old->list);
2367 if (list_empty(&new->head))
2373 static int relink_is_mergable(struct extent_buffer *leaf,
2374 struct btrfs_file_extent_item *fi,
2375 struct new_sa_defrag_extent *new)
2377 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2380 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2383 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2386 if (btrfs_file_extent_encryption(leaf, fi) ||
2387 btrfs_file_extent_other_encoding(leaf, fi))
2394 * Note the backref might has changed, and in this case we just return 0.
2396 static noinline int relink_extent_backref(struct btrfs_path *path,
2397 struct sa_defrag_extent_backref *prev,
2398 struct sa_defrag_extent_backref *backref)
2400 struct btrfs_file_extent_item *extent;
2401 struct btrfs_file_extent_item *item;
2402 struct btrfs_ordered_extent *ordered;
2403 struct btrfs_trans_handle *trans;
2404 struct btrfs_fs_info *fs_info;
2405 struct btrfs_root *root;
2406 struct btrfs_key key;
2407 struct extent_buffer *leaf;
2408 struct old_sa_defrag_extent *old = backref->old;
2409 struct new_sa_defrag_extent *new = old->new;
2410 struct inode *src_inode = new->inode;
2411 struct inode *inode;
2412 struct extent_state *cached = NULL;
2421 if (prev && prev->root_id == backref->root_id &&
2422 prev->inum == backref->inum &&
2423 prev->file_pos + prev->num_bytes == backref->file_pos)
2426 /* step 1: get root */
2427 key.objectid = backref->root_id;
2428 key.type = BTRFS_ROOT_ITEM_KEY;
2429 key.offset = (u64)-1;
2431 fs_info = BTRFS_I(src_inode)->root->fs_info;
2432 index = srcu_read_lock(&fs_info->subvol_srcu);
2434 root = btrfs_read_fs_root_no_name(fs_info, &key);
2436 srcu_read_unlock(&fs_info->subvol_srcu, index);
2437 if (PTR_ERR(root) == -ENOENT)
2439 return PTR_ERR(root);
2442 if (btrfs_root_readonly(root)) {
2443 srcu_read_unlock(&fs_info->subvol_srcu, index);
2447 /* step 2: get inode */
2448 key.objectid = backref->inum;
2449 key.type = BTRFS_INODE_ITEM_KEY;
2452 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2453 if (IS_ERR(inode)) {
2454 srcu_read_unlock(&fs_info->subvol_srcu, index);
2458 srcu_read_unlock(&fs_info->subvol_srcu, index);
2460 /* step 3: relink backref */
2461 lock_start = backref->file_pos;
2462 lock_end = backref->file_pos + backref->num_bytes - 1;
2463 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2466 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2468 btrfs_put_ordered_extent(ordered);
2472 trans = btrfs_join_transaction(root);
2473 if (IS_ERR(trans)) {
2474 ret = PTR_ERR(trans);
2478 key.objectid = backref->inum;
2479 key.type = BTRFS_EXTENT_DATA_KEY;
2480 key.offset = backref->file_pos;
2482 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2485 } else if (ret > 0) {
2490 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2491 struct btrfs_file_extent_item);
2493 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2494 backref->generation)
2497 btrfs_release_path(path);
2499 start = backref->file_pos;
2500 if (backref->extent_offset < old->extent_offset + old->offset)
2501 start += old->extent_offset + old->offset -
2502 backref->extent_offset;
2504 len = min(backref->extent_offset + backref->num_bytes,
2505 old->extent_offset + old->offset + old->len);
2506 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2508 ret = btrfs_drop_extents(trans, root, inode, start,
2513 key.objectid = btrfs_ino(inode);
2514 key.type = BTRFS_EXTENT_DATA_KEY;
2517 path->leave_spinning = 1;
2519 struct btrfs_file_extent_item *fi;
2521 struct btrfs_key found_key;
2523 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2528 leaf = path->nodes[0];
2529 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2531 fi = btrfs_item_ptr(leaf, path->slots[0],
2532 struct btrfs_file_extent_item);
2533 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2535 if (extent_len + found_key.offset == start &&
2536 relink_is_mergable(leaf, fi, new)) {
2537 btrfs_set_file_extent_num_bytes(leaf, fi,
2539 btrfs_mark_buffer_dirty(leaf);
2540 inode_add_bytes(inode, len);
2546 btrfs_release_path(path);
2551 ret = btrfs_insert_empty_item(trans, root, path, &key,
2554 btrfs_abort_transaction(trans, root, ret);
2558 leaf = path->nodes[0];
2559 item = btrfs_item_ptr(leaf, path->slots[0],
2560 struct btrfs_file_extent_item);
2561 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2562 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2563 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2564 btrfs_set_file_extent_num_bytes(leaf, item, len);
2565 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2566 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2567 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2568 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2569 btrfs_set_file_extent_encryption(leaf, item, 0);
2570 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2572 btrfs_mark_buffer_dirty(leaf);
2573 inode_add_bytes(inode, len);
2574 btrfs_release_path(path);
2576 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2578 backref->root_id, backref->inum,
2579 new->file_pos, 0); /* start - extent_offset */
2581 btrfs_abort_transaction(trans, root, ret);
2587 btrfs_release_path(path);
2588 path->leave_spinning = 0;
2589 btrfs_end_transaction(trans, root);
2591 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2597 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2599 struct old_sa_defrag_extent *old, *tmp;
2604 list_for_each_entry_safe(old, tmp, &new->head, list) {
2605 list_del(&old->list);
2611 static void relink_file_extents(struct new_sa_defrag_extent *new)
2613 struct btrfs_path *path;
2614 struct sa_defrag_extent_backref *backref;
2615 struct sa_defrag_extent_backref *prev = NULL;
2616 struct inode *inode;
2617 struct btrfs_root *root;
2618 struct rb_node *node;
2622 root = BTRFS_I(inode)->root;
2624 path = btrfs_alloc_path();
2628 if (!record_extent_backrefs(path, new)) {
2629 btrfs_free_path(path);
2632 btrfs_release_path(path);
2635 node = rb_first(&new->root);
2638 rb_erase(node, &new->root);
2640 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2642 ret = relink_extent_backref(path, prev, backref);
2655 btrfs_free_path(path);
2657 free_sa_defrag_extent(new);
2659 atomic_dec(&root->fs_info->defrag_running);
2660 wake_up(&root->fs_info->transaction_wait);
2663 static struct new_sa_defrag_extent *
2664 record_old_file_extents(struct inode *inode,
2665 struct btrfs_ordered_extent *ordered)
2667 struct btrfs_root *root = BTRFS_I(inode)->root;
2668 struct btrfs_path *path;
2669 struct btrfs_key key;
2670 struct old_sa_defrag_extent *old;
2671 struct new_sa_defrag_extent *new;
2674 new = kmalloc(sizeof(*new), GFP_NOFS);
2679 new->file_pos = ordered->file_offset;
2680 new->len = ordered->len;
2681 new->bytenr = ordered->start;
2682 new->disk_len = ordered->disk_len;
2683 new->compress_type = ordered->compress_type;
2684 new->root = RB_ROOT;
2685 INIT_LIST_HEAD(&new->head);
2687 path = btrfs_alloc_path();
2691 key.objectid = btrfs_ino(inode);
2692 key.type = BTRFS_EXTENT_DATA_KEY;
2693 key.offset = new->file_pos;
2695 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2698 if (ret > 0 && path->slots[0] > 0)
2701 /* find out all the old extents for the file range */
2703 struct btrfs_file_extent_item *extent;
2704 struct extent_buffer *l;
2713 slot = path->slots[0];
2715 if (slot >= btrfs_header_nritems(l)) {
2716 ret = btrfs_next_leaf(root, path);
2724 btrfs_item_key_to_cpu(l, &key, slot);
2726 if (key.objectid != btrfs_ino(inode))
2728 if (key.type != BTRFS_EXTENT_DATA_KEY)
2730 if (key.offset >= new->file_pos + new->len)
2733 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2735 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2736 if (key.offset + num_bytes < new->file_pos)
2739 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2743 extent_offset = btrfs_file_extent_offset(l, extent);
2745 old = kmalloc(sizeof(*old), GFP_NOFS);
2749 offset = max(new->file_pos, key.offset);
2750 end = min(new->file_pos + new->len, key.offset + num_bytes);
2752 old->bytenr = disk_bytenr;
2753 old->extent_offset = extent_offset;
2754 old->offset = offset - key.offset;
2755 old->len = end - offset;
2758 list_add_tail(&old->list, &new->head);
2764 btrfs_free_path(path);
2765 atomic_inc(&root->fs_info->defrag_running);
2770 btrfs_free_path(path);
2772 free_sa_defrag_extent(new);
2776 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2779 struct btrfs_block_group_cache *cache;
2781 cache = btrfs_lookup_block_group(root->fs_info, start);
2784 spin_lock(&cache->lock);
2785 cache->delalloc_bytes -= len;
2786 spin_unlock(&cache->lock);
2788 btrfs_put_block_group(cache);
2791 /* as ordered data IO finishes, this gets called so we can finish
2792 * an ordered extent if the range of bytes in the file it covers are
2795 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2797 struct inode *inode = ordered_extent->inode;
2798 struct btrfs_root *root = BTRFS_I(inode)->root;
2799 struct btrfs_trans_handle *trans = NULL;
2800 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2801 struct extent_state *cached_state = NULL;
2802 struct new_sa_defrag_extent *new = NULL;
2803 int compress_type = 0;
2805 u64 logical_len = ordered_extent->len;
2807 bool truncated = false;
2809 nolock = btrfs_is_free_space_inode(inode);
2811 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2816 btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2817 ordered_extent->file_offset +
2818 ordered_extent->len - 1);
2820 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2822 logical_len = ordered_extent->truncated_len;
2823 /* Truncated the entire extent, don't bother adding */
2828 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2829 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2830 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2832 trans = btrfs_join_transaction_nolock(root);
2834 trans = btrfs_join_transaction(root);
2835 if (IS_ERR(trans)) {
2836 ret = PTR_ERR(trans);
2840 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2841 ret = btrfs_update_inode_fallback(trans, root, inode);
2842 if (ret) /* -ENOMEM or corruption */
2843 btrfs_abort_transaction(trans, root, ret);
2847 lock_extent_bits(io_tree, ordered_extent->file_offset,
2848 ordered_extent->file_offset + ordered_extent->len - 1,
2851 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2852 ordered_extent->file_offset + ordered_extent->len - 1,
2853 EXTENT_DEFRAG, 1, cached_state);
2855 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2856 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2857 /* the inode is shared */
2858 new = record_old_file_extents(inode, ordered_extent);
2860 clear_extent_bit(io_tree, ordered_extent->file_offset,
2861 ordered_extent->file_offset + ordered_extent->len - 1,
2862 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2866 trans = btrfs_join_transaction_nolock(root);
2868 trans = btrfs_join_transaction(root);
2869 if (IS_ERR(trans)) {
2870 ret = PTR_ERR(trans);
2875 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2877 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2878 compress_type = ordered_extent->compress_type;
2879 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2880 BUG_ON(compress_type);
2881 ret = btrfs_mark_extent_written(trans, inode,
2882 ordered_extent->file_offset,
2883 ordered_extent->file_offset +
2886 BUG_ON(root == root->fs_info->tree_root);
2887 ret = insert_reserved_file_extent(trans, inode,
2888 ordered_extent->file_offset,
2889 ordered_extent->start,
2890 ordered_extent->disk_len,
2891 logical_len, logical_len,
2892 compress_type, 0, 0,
2893 BTRFS_FILE_EXTENT_REG);
2895 btrfs_release_delalloc_bytes(root,
2896 ordered_extent->start,
2897 ordered_extent->disk_len);
2899 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2900 ordered_extent->file_offset, ordered_extent->len,
2903 btrfs_abort_transaction(trans, root, ret);
2907 add_pending_csums(trans, inode, ordered_extent->file_offset,
2908 &ordered_extent->list);
2910 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2911 ret = btrfs_update_inode_fallback(trans, root, inode);
2912 if (ret) { /* -ENOMEM or corruption */
2913 btrfs_abort_transaction(trans, root, ret);
2918 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2919 ordered_extent->file_offset +
2920 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2922 if (root != root->fs_info->tree_root)
2923 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2925 btrfs_end_transaction(trans, root);
2927 if (ret || truncated) {
2931 start = ordered_extent->file_offset + logical_len;
2933 start = ordered_extent->file_offset;
2934 end = ordered_extent->file_offset + ordered_extent->len - 1;
2935 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2937 /* Drop the cache for the part of the extent we didn't write. */
2938 btrfs_drop_extent_cache(inode, start, end, 0);
2941 * If the ordered extent had an IOERR or something else went
2942 * wrong we need to return the space for this ordered extent
2943 * back to the allocator. We only free the extent in the
2944 * truncated case if we didn't write out the extent at all.
2946 if ((ret || !logical_len) &&
2947 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2948 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2949 btrfs_free_reserved_extent(root, ordered_extent->start,
2950 ordered_extent->disk_len, 1);
2955 * This needs to be done to make sure anybody waiting knows we are done
2956 * updating everything for this ordered extent.
2958 btrfs_remove_ordered_extent(inode, ordered_extent);
2960 /* for snapshot-aware defrag */
2963 free_sa_defrag_extent(new);
2964 atomic_dec(&root->fs_info->defrag_running);
2966 relink_file_extents(new);
2971 btrfs_put_ordered_extent(ordered_extent);
2972 /* once for the tree */
2973 btrfs_put_ordered_extent(ordered_extent);
2978 static void finish_ordered_fn(struct btrfs_work *work)
2980 struct btrfs_ordered_extent *ordered_extent;
2981 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2982 btrfs_finish_ordered_io(ordered_extent);
2985 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2986 struct extent_state *state, int uptodate)
2988 struct inode *inode = page->mapping->host;
2989 struct btrfs_root *root = BTRFS_I(inode)->root;
2990 struct btrfs_ordered_extent *ordered_extent = NULL;
2991 struct btrfs_workqueue *wq;
2992 btrfs_work_func_t func;
2994 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2996 ClearPagePrivate2(page);
2997 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2998 end - start + 1, uptodate))
3001 if (btrfs_is_free_space_inode(inode)) {
3002 wq = root->fs_info->endio_freespace_worker;
3003 func = btrfs_freespace_write_helper;
3005 wq = root->fs_info->endio_write_workers;
3006 func = btrfs_endio_write_helper;
3009 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3011 btrfs_queue_work(wq, &ordered_extent->work);
3016 static int __readpage_endio_check(struct inode *inode,
3017 struct btrfs_io_bio *io_bio,
3018 int icsum, struct page *page,
3019 int pgoff, u64 start, size_t len)
3024 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
3025 DEFAULT_RATELIMIT_BURST);
3027 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3029 kaddr = kmap_atomic(page);
3030 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3031 btrfs_csum_final(csum, (char *)&csum);
3032 if (csum != csum_expected)
3035 kunmap_atomic(kaddr);
3038 if (__ratelimit(&_rs))
3039 btrfs_warn(BTRFS_I(inode)->root->fs_info,
3040 "csum failed ino %llu off %llu csum %u expected csum %u",
3041 btrfs_ino(inode), start, csum, csum_expected);
3042 memset(kaddr + pgoff, 1, len);
3043 flush_dcache_page(page);
3044 kunmap_atomic(kaddr);
3045 if (csum_expected == 0)
3051 * when reads are done, we need to check csums to verify the data is correct
3052 * if there's a match, we allow the bio to finish. If not, the code in
3053 * extent_io.c will try to find good copies for us.
3055 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3056 u64 phy_offset, struct page *page,
3057 u64 start, u64 end, int mirror)
3059 size_t offset = start - page_offset(page);
3060 struct inode *inode = page->mapping->host;
3061 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3062 struct btrfs_root *root = BTRFS_I(inode)->root;
3064 if (PageChecked(page)) {
3065 ClearPageChecked(page);
3069 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3072 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3073 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3074 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
3079 phy_offset >>= inode->i_sb->s_blocksize_bits;
3080 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3081 start, (size_t)(end - start + 1));
3084 struct delayed_iput {
3085 struct list_head list;
3086 struct inode *inode;
3089 /* JDM: If this is fs-wide, why can't we add a pointer to
3090 * btrfs_inode instead and avoid the allocation? */
3091 void btrfs_add_delayed_iput(struct inode *inode)
3093 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3094 struct delayed_iput *delayed;
3096 if (atomic_add_unless(&inode->i_count, -1, 1))
3099 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
3100 delayed->inode = inode;
3102 spin_lock(&fs_info->delayed_iput_lock);
3103 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
3104 spin_unlock(&fs_info->delayed_iput_lock);
3107 void btrfs_run_delayed_iputs(struct btrfs_root *root)
3110 struct btrfs_fs_info *fs_info = root->fs_info;
3111 struct delayed_iput *delayed;
3114 spin_lock(&fs_info->delayed_iput_lock);
3115 empty = list_empty(&fs_info->delayed_iputs);
3116 spin_unlock(&fs_info->delayed_iput_lock);
3120 down_read(&fs_info->delayed_iput_sem);
3122 spin_lock(&fs_info->delayed_iput_lock);
3123 list_splice_init(&fs_info->delayed_iputs, &list);
3124 spin_unlock(&fs_info->delayed_iput_lock);
3126 while (!list_empty(&list)) {
3127 delayed = list_entry(list.next, struct delayed_iput, list);
3128 list_del(&delayed->list);
3129 iput(delayed->inode);
3133 up_read(&root->fs_info->delayed_iput_sem);
3137 * This is called in transaction commit time. If there are no orphan
3138 * files in the subvolume, it removes orphan item and frees block_rsv
3141 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3142 struct btrfs_root *root)
3144 struct btrfs_block_rsv *block_rsv;
3147 if (atomic_read(&root->orphan_inodes) ||
3148 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3151 spin_lock(&root->orphan_lock);
3152 if (atomic_read(&root->orphan_inodes)) {
3153 spin_unlock(&root->orphan_lock);
3157 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3158 spin_unlock(&root->orphan_lock);
3162 block_rsv = root->orphan_block_rsv;
3163 root->orphan_block_rsv = NULL;
3164 spin_unlock(&root->orphan_lock);
3166 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3167 btrfs_root_refs(&root->root_item) > 0) {
3168 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
3169 root->root_key.objectid);
3171 btrfs_abort_transaction(trans, root, ret);
3173 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3178 WARN_ON(block_rsv->size > 0);
3179 btrfs_free_block_rsv(root, block_rsv);
3184 * This creates an orphan entry for the given inode in case something goes
3185 * wrong in the middle of an unlink/truncate.
3187 * NOTE: caller of this function should reserve 5 units of metadata for
3190 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3192 struct btrfs_root *root = BTRFS_I(inode)->root;
3193 struct btrfs_block_rsv *block_rsv = NULL;
3198 if (!root->orphan_block_rsv) {
3199 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3204 spin_lock(&root->orphan_lock);
3205 if (!root->orphan_block_rsv) {
3206 root->orphan_block_rsv = block_rsv;
3207 } else if (block_rsv) {
3208 btrfs_free_block_rsv(root, block_rsv);
3212 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3213 &BTRFS_I(inode)->runtime_flags)) {
3216 * For proper ENOSPC handling, we should do orphan
3217 * cleanup when mounting. But this introduces backward
3218 * compatibility issue.
3220 if (!xchg(&root->orphan_item_inserted, 1))
3226 atomic_inc(&root->orphan_inodes);
3229 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3230 &BTRFS_I(inode)->runtime_flags))
3232 spin_unlock(&root->orphan_lock);
3234 /* grab metadata reservation from transaction handle */
3236 ret = btrfs_orphan_reserve_metadata(trans, inode);
3237 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3240 /* insert an orphan item to track this unlinked/truncated file */
3242 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3244 atomic_dec(&root->orphan_inodes);
3246 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3247 &BTRFS_I(inode)->runtime_flags);
3248 btrfs_orphan_release_metadata(inode);
3250 if (ret != -EEXIST) {
3251 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3252 &BTRFS_I(inode)->runtime_flags);
3253 btrfs_abort_transaction(trans, root, ret);
3260 /* insert an orphan item to track subvolume contains orphan files */
3262 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3263 root->root_key.objectid);
3264 if (ret && ret != -EEXIST) {
3265 btrfs_abort_transaction(trans, root, ret);
3273 * We have done the truncate/delete so we can go ahead and remove the orphan
3274 * item for this particular inode.
3276 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3277 struct inode *inode)
3279 struct btrfs_root *root = BTRFS_I(inode)->root;
3280 int delete_item = 0;
3281 int release_rsv = 0;
3284 spin_lock(&root->orphan_lock);
3285 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3286 &BTRFS_I(inode)->runtime_flags))
3289 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3290 &BTRFS_I(inode)->runtime_flags))
3292 spin_unlock(&root->orphan_lock);
3295 atomic_dec(&root->orphan_inodes);
3297 ret = btrfs_del_orphan_item(trans, root,
3302 btrfs_orphan_release_metadata(inode);
3308 * this cleans up any orphans that may be left on the list from the last use
3311 int btrfs_orphan_cleanup(struct btrfs_root *root)
3313 struct btrfs_path *path;
3314 struct extent_buffer *leaf;
3315 struct btrfs_key key, found_key;
3316 struct btrfs_trans_handle *trans;
3317 struct inode *inode;
3318 u64 last_objectid = 0;
3319 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3321 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3324 path = btrfs_alloc_path();
3331 key.objectid = BTRFS_ORPHAN_OBJECTID;
3332 key.type = BTRFS_ORPHAN_ITEM_KEY;
3333 key.offset = (u64)-1;
3336 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3341 * if ret == 0 means we found what we were searching for, which
3342 * is weird, but possible, so only screw with path if we didn't
3343 * find the key and see if we have stuff that matches
3347 if (path->slots[0] == 0)
3352 /* pull out the item */
3353 leaf = path->nodes[0];
3354 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3356 /* make sure the item matches what we want */
3357 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3359 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3362 /* release the path since we're done with it */
3363 btrfs_release_path(path);
3366 * this is where we are basically btrfs_lookup, without the
3367 * crossing root thing. we store the inode number in the
3368 * offset of the orphan item.
3371 if (found_key.offset == last_objectid) {
3372 btrfs_err(root->fs_info,
3373 "Error removing orphan entry, stopping orphan cleanup");
3378 last_objectid = found_key.offset;
3380 found_key.objectid = found_key.offset;
3381 found_key.type = BTRFS_INODE_ITEM_KEY;
3382 found_key.offset = 0;
3383 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3384 ret = PTR_ERR_OR_ZERO(inode);
3385 if (ret && ret != -ESTALE)
3388 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3389 struct btrfs_root *dead_root;
3390 struct btrfs_fs_info *fs_info = root->fs_info;
3391 int is_dead_root = 0;
3394 * this is an orphan in the tree root. Currently these
3395 * could come from 2 sources:
3396 * a) a snapshot deletion in progress
3397 * b) a free space cache inode
3398 * We need to distinguish those two, as the snapshot
3399 * orphan must not get deleted.
3400 * find_dead_roots already ran before us, so if this
3401 * is a snapshot deletion, we should find the root
3402 * in the dead_roots list
3404 spin_lock(&fs_info->trans_lock);
3405 list_for_each_entry(dead_root, &fs_info->dead_roots,
3407 if (dead_root->root_key.objectid ==
3408 found_key.objectid) {
3413 spin_unlock(&fs_info->trans_lock);
3415 /* prevent this orphan from being found again */
3416 key.offset = found_key.objectid - 1;
3421 * Inode is already gone but the orphan item is still there,
3422 * kill the orphan item.
3424 if (ret == -ESTALE) {
3425 trans = btrfs_start_transaction(root, 1);
3426 if (IS_ERR(trans)) {
3427 ret = PTR_ERR(trans);
3430 btrfs_debug(root->fs_info, "auto deleting %Lu",
3431 found_key.objectid);
3432 ret = btrfs_del_orphan_item(trans, root,
3433 found_key.objectid);
3434 btrfs_end_transaction(trans, root);
3441 * add this inode to the orphan list so btrfs_orphan_del does
3442 * the proper thing when we hit it
3444 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3445 &BTRFS_I(inode)->runtime_flags);
3446 atomic_inc(&root->orphan_inodes);
3448 /* if we have links, this was a truncate, lets do that */
3449 if (inode->i_nlink) {
3450 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3456 /* 1 for the orphan item deletion. */
3457 trans = btrfs_start_transaction(root, 1);
3458 if (IS_ERR(trans)) {
3460 ret = PTR_ERR(trans);
3463 ret = btrfs_orphan_add(trans, inode);
3464 btrfs_end_transaction(trans, root);
3470 ret = btrfs_truncate(inode);
3472 btrfs_orphan_del(NULL, inode);
3477 /* this will do delete_inode and everything for us */
3482 /* release the path since we're done with it */
3483 btrfs_release_path(path);
3485 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3487 if (root->orphan_block_rsv)
3488 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3491 if (root->orphan_block_rsv ||
3492 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3493 trans = btrfs_join_transaction(root);
3495 btrfs_end_transaction(trans, root);
3499 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3501 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3505 btrfs_err(root->fs_info,
3506 "could not do orphan cleanup %d", ret);
3507 btrfs_free_path(path);
3512 * very simple check to peek ahead in the leaf looking for xattrs. If we
3513 * don't find any xattrs, we know there can't be any acls.
3515 * slot is the slot the inode is in, objectid is the objectid of the inode
3517 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3518 int slot, u64 objectid,
3519 int *first_xattr_slot)
3521 u32 nritems = btrfs_header_nritems(leaf);
3522 struct btrfs_key found_key;
3523 static u64 xattr_access = 0;
3524 static u64 xattr_default = 0;
3527 if (!xattr_access) {
3528 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3529 strlen(POSIX_ACL_XATTR_ACCESS));
3530 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3531 strlen(POSIX_ACL_XATTR_DEFAULT));
3535 *first_xattr_slot = -1;
3536 while (slot < nritems) {
3537 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3539 /* we found a different objectid, there must not be acls */
3540 if (found_key.objectid != objectid)
3543 /* we found an xattr, assume we've got an acl */
3544 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3545 if (*first_xattr_slot == -1)
3546 *first_xattr_slot = slot;
3547 if (found_key.offset == xattr_access ||
3548 found_key.offset == xattr_default)
3553 * we found a key greater than an xattr key, there can't
3554 * be any acls later on
3556 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3563 * it goes inode, inode backrefs, xattrs, extents,
3564 * so if there are a ton of hard links to an inode there can
3565 * be a lot of backrefs. Don't waste time searching too hard,
3566 * this is just an optimization
3571 /* we hit the end of the leaf before we found an xattr or
3572 * something larger than an xattr. We have to assume the inode
3575 if (*first_xattr_slot == -1)
3576 *first_xattr_slot = slot;
3581 * read an inode from the btree into the in-memory inode
3583 static void btrfs_read_locked_inode(struct inode *inode)
3585 struct btrfs_path *path;
3586 struct extent_buffer *leaf;
3587 struct btrfs_inode_item *inode_item;
3588 struct btrfs_root *root = BTRFS_I(inode)->root;
3589 struct btrfs_key location;
3594 bool filled = false;
3595 int first_xattr_slot;
3597 ret = btrfs_fill_inode(inode, &rdev);
3601 path = btrfs_alloc_path();
3605 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3607 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3611 leaf = path->nodes[0];
3616 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3617 struct btrfs_inode_item);
3618 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3619 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3620 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3621 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3622 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3624 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3625 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3627 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3628 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3630 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3631 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3633 BTRFS_I(inode)->i_otime.tv_sec =
3634 btrfs_timespec_sec(leaf, &inode_item->otime);
3635 BTRFS_I(inode)->i_otime.tv_nsec =
3636 btrfs_timespec_nsec(leaf, &inode_item->otime);
3638 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3639 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3640 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3642 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3643 inode->i_generation = BTRFS_I(inode)->generation;
3645 rdev = btrfs_inode_rdev(leaf, inode_item);
3647 BTRFS_I(inode)->index_cnt = (u64)-1;
3648 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3652 * If we were modified in the current generation and evicted from memory
3653 * and then re-read we need to do a full sync since we don't have any
3654 * idea about which extents were modified before we were evicted from
3657 * This is required for both inode re-read from disk and delayed inode
3658 * in delayed_nodes_tree.
3660 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3661 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3662 &BTRFS_I(inode)->runtime_flags);
3665 * We don't persist the id of the transaction where an unlink operation
3666 * against the inode was last made. So here we assume the inode might
3667 * have been evicted, and therefore the exact value of last_unlink_trans
3668 * lost, and set it to last_trans to avoid metadata inconsistencies
3669 * between the inode and its parent if the inode is fsync'ed and the log
3670 * replayed. For example, in the scenario:
3673 * ln mydir/foo mydir/bar
3676 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3677 * xfs_io -c fsync mydir/foo
3679 * mount fs, triggers fsync log replay
3681 * We must make sure that when we fsync our inode foo we also log its
3682 * parent inode, otherwise after log replay the parent still has the
3683 * dentry with the "bar" name but our inode foo has a link count of 1
3684 * and doesn't have an inode ref with the name "bar" anymore.
3686 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3687 * but it guarantees correctness at the expense of ocassional full
3688 * transaction commits on fsync if our inode is a directory, or if our
3689 * inode is not a directory, logging its parent unnecessarily.
3691 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3694 if (inode->i_nlink != 1 ||
3695 path->slots[0] >= btrfs_header_nritems(leaf))
3698 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3699 if (location.objectid != btrfs_ino(inode))
3702 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3703 if (location.type == BTRFS_INODE_REF_KEY) {
3704 struct btrfs_inode_ref *ref;
3706 ref = (struct btrfs_inode_ref *)ptr;
3707 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3708 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3709 struct btrfs_inode_extref *extref;
3711 extref = (struct btrfs_inode_extref *)ptr;
3712 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3717 * try to precache a NULL acl entry for files that don't have
3718 * any xattrs or acls
3720 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3721 btrfs_ino(inode), &first_xattr_slot);
3722 if (first_xattr_slot != -1) {
3723 path->slots[0] = first_xattr_slot;
3724 ret = btrfs_load_inode_props(inode, path);
3726 btrfs_err(root->fs_info,
3727 "error loading props for ino %llu (root %llu): %d",
3729 root->root_key.objectid, ret);
3731 btrfs_free_path(path);
3734 cache_no_acl(inode);
3736 switch (inode->i_mode & S_IFMT) {
3738 inode->i_mapping->a_ops = &btrfs_aops;
3739 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3740 inode->i_fop = &btrfs_file_operations;
3741 inode->i_op = &btrfs_file_inode_operations;
3744 inode->i_fop = &btrfs_dir_file_operations;
3745 if (root == root->fs_info->tree_root)
3746 inode->i_op = &btrfs_dir_ro_inode_operations;
3748 inode->i_op = &btrfs_dir_inode_operations;
3751 inode->i_op = &btrfs_symlink_inode_operations;
3752 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3755 inode->i_op = &btrfs_special_inode_operations;
3756 init_special_inode(inode, inode->i_mode, rdev);
3760 btrfs_update_iflags(inode);
3764 btrfs_free_path(path);
3765 make_bad_inode(inode);
3769 * given a leaf and an inode, copy the inode fields into the leaf
3771 static void fill_inode_item(struct btrfs_trans_handle *trans,
3772 struct extent_buffer *leaf,
3773 struct btrfs_inode_item *item,
3774 struct inode *inode)
3776 struct btrfs_map_token token;
3778 btrfs_init_map_token(&token);
3780 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3781 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3782 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3784 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3785 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3787 btrfs_set_token_timespec_sec(leaf, &item->atime,
3788 inode->i_atime.tv_sec, &token);
3789 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3790 inode->i_atime.tv_nsec, &token);
3792 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3793 inode->i_mtime.tv_sec, &token);
3794 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3795 inode->i_mtime.tv_nsec, &token);
3797 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3798 inode->i_ctime.tv_sec, &token);
3799 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3800 inode->i_ctime.tv_nsec, &token);
3802 btrfs_set_token_timespec_sec(leaf, &item->otime,
3803 BTRFS_I(inode)->i_otime.tv_sec, &token);
3804 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3805 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3807 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3809 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3811 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3812 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3813 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3814 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3815 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3819 * copy everything in the in-memory inode into the btree.
3821 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3822 struct btrfs_root *root, struct inode *inode)
3824 struct btrfs_inode_item *inode_item;
3825 struct btrfs_path *path;
3826 struct extent_buffer *leaf;
3829 path = btrfs_alloc_path();
3833 path->leave_spinning = 1;
3834 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3842 leaf = path->nodes[0];
3843 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3844 struct btrfs_inode_item);
3846 fill_inode_item(trans, leaf, inode_item, inode);
3847 btrfs_mark_buffer_dirty(leaf);
3848 btrfs_set_inode_last_trans(trans, inode);
3851 btrfs_free_path(path);
3856 * copy everything in the in-memory inode into the btree.
3858 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3859 struct btrfs_root *root, struct inode *inode)
3864 * If the inode is a free space inode, we can deadlock during commit
3865 * if we put it into the delayed code.
3867 * The data relocation inode should also be directly updated
3870 if (!btrfs_is_free_space_inode(inode)
3871 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3872 && !root->fs_info->log_root_recovering) {
3873 btrfs_update_root_times(trans, root);
3875 ret = btrfs_delayed_update_inode(trans, root, inode);
3877 btrfs_set_inode_last_trans(trans, inode);
3881 return btrfs_update_inode_item(trans, root, inode);
3884 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3885 struct btrfs_root *root,
3886 struct inode *inode)
3890 ret = btrfs_update_inode(trans, root, inode);
3892 return btrfs_update_inode_item(trans, root, inode);
3897 * unlink helper that gets used here in inode.c and in the tree logging
3898 * recovery code. It remove a link in a directory with a given name, and
3899 * also drops the back refs in the inode to the directory
3901 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3902 struct btrfs_root *root,
3903 struct inode *dir, struct inode *inode,
3904 const char *name, int name_len)
3906 struct btrfs_path *path;
3908 struct extent_buffer *leaf;
3909 struct btrfs_dir_item *di;
3910 struct btrfs_key key;
3912 u64 ino = btrfs_ino(inode);
3913 u64 dir_ino = btrfs_ino(dir);
3915 path = btrfs_alloc_path();
3921 path->leave_spinning = 1;
3922 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3923 name, name_len, -1);
3932 leaf = path->nodes[0];
3933 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3934 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3937 btrfs_release_path(path);
3940 * If we don't have dir index, we have to get it by looking up
3941 * the inode ref, since we get the inode ref, remove it directly,
3942 * it is unnecessary to do delayed deletion.
3944 * But if we have dir index, needn't search inode ref to get it.
3945 * Since the inode ref is close to the inode item, it is better
3946 * that we delay to delete it, and just do this deletion when
3947 * we update the inode item.
3949 if (BTRFS_I(inode)->dir_index) {
3950 ret = btrfs_delayed_delete_inode_ref(inode);
3952 index = BTRFS_I(inode)->dir_index;
3957 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3960 btrfs_info(root->fs_info,
3961 "failed to delete reference to %.*s, inode %llu parent %llu",
3962 name_len, name, ino, dir_ino);
3963 btrfs_abort_transaction(trans, root, ret);
3967 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3969 btrfs_abort_transaction(trans, root, ret);
3973 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3975 if (ret != 0 && ret != -ENOENT) {
3976 btrfs_abort_transaction(trans, root, ret);
3980 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3985 btrfs_abort_transaction(trans, root, ret);
3987 btrfs_free_path(path);
3991 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3992 inode_inc_iversion(inode);
3993 inode_inc_iversion(dir);
3994 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3995 ret = btrfs_update_inode(trans, root, dir);
4000 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4001 struct btrfs_root *root,
4002 struct inode *dir, struct inode *inode,
4003 const char *name, int name_len)
4006 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4009 ret = btrfs_update_inode(trans, root, inode);
4015 * helper to start transaction for unlink and rmdir.
4017 * unlink and rmdir are special in btrfs, they do not always free space, so
4018 * if we cannot make our reservations the normal way try and see if there is
4019 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4020 * allow the unlink to occur.
4022 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4024 struct btrfs_trans_handle *trans;
4025 struct btrfs_root *root = BTRFS_I(dir)->root;
4029 * 1 for the possible orphan item
4030 * 1 for the dir item
4031 * 1 for the dir index
4032 * 1 for the inode ref
4035 trans = btrfs_start_transaction(root, 5);
4036 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
4039 if (PTR_ERR(trans) == -ENOSPC) {
4040 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
4042 trans = btrfs_start_transaction(root, 0);
4045 ret = btrfs_cond_migrate_bytes(root->fs_info,
4046 &root->fs_info->trans_block_rsv,
4049 btrfs_end_transaction(trans, root);
4050 return ERR_PTR(ret);
4052 trans->block_rsv = &root->fs_info->trans_block_rsv;
4053 trans->bytes_reserved = num_bytes;
4058 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4060 struct btrfs_root *root = BTRFS_I(dir)->root;
4061 struct btrfs_trans_handle *trans;
4062 struct inode *inode = d_inode(dentry);
4065 trans = __unlink_start_trans(dir);
4067 return PTR_ERR(trans);
4069 btrfs_record_unlink_dir(trans, dir, d_inode(dentry), 0);
4071 ret = btrfs_unlink_inode(trans, root, dir, d_inode(dentry),
4072 dentry->d_name.name, dentry->d_name.len);
4076 if (inode->i_nlink == 0) {
4077 ret = btrfs_orphan_add(trans, inode);
4083 btrfs_end_transaction(trans, root);
4084 btrfs_btree_balance_dirty(root);
4088 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4089 struct btrfs_root *root,
4090 struct inode *dir, u64 objectid,
4091 const char *name, int name_len)
4093 struct btrfs_path *path;
4094 struct extent_buffer *leaf;
4095 struct btrfs_dir_item *di;
4096 struct btrfs_key key;
4099 u64 dir_ino = btrfs_ino(dir);
4101 path = btrfs_alloc_path();
4105 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4106 name, name_len, -1);
4107 if (IS_ERR_OR_NULL(di)) {
4115 leaf = path->nodes[0];
4116 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4117 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4118 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4120 btrfs_abort_transaction(trans, root, ret);
4123 btrfs_release_path(path);
4125 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4126 objectid, root->root_key.objectid,
4127 dir_ino, &index, name, name_len);
4129 if (ret != -ENOENT) {
4130 btrfs_abort_transaction(trans, root, ret);
4133 di = btrfs_search_dir_index_item(root, path, dir_ino,
4135 if (IS_ERR_OR_NULL(di)) {
4140 btrfs_abort_transaction(trans, root, ret);
4144 leaf = path->nodes[0];
4145 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4146 btrfs_release_path(path);
4149 btrfs_release_path(path);
4151 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4153 btrfs_abort_transaction(trans, root, ret);
4157 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4158 inode_inc_iversion(dir);
4159 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
4160 ret = btrfs_update_inode_fallback(trans, root, dir);
4162 btrfs_abort_transaction(trans, root, ret);
4164 btrfs_free_path(path);
4168 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4170 struct inode *inode = d_inode(dentry);
4172 struct btrfs_root *root = BTRFS_I(dir)->root;
4173 struct btrfs_trans_handle *trans;
4175 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4177 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
4180 trans = __unlink_start_trans(dir);
4182 return PTR_ERR(trans);
4184 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4185 err = btrfs_unlink_subvol(trans, root, dir,
4186 BTRFS_I(inode)->location.objectid,
4187 dentry->d_name.name,
4188 dentry->d_name.len);
4192 err = btrfs_orphan_add(trans, inode);
4196 /* now the directory is empty */
4197 err = btrfs_unlink_inode(trans, root, dir, d_inode(dentry),
4198 dentry->d_name.name, dentry->d_name.len);
4200 btrfs_i_size_write(inode, 0);
4202 btrfs_end_transaction(trans, root);
4203 btrfs_btree_balance_dirty(root);
4208 static int truncate_space_check(struct btrfs_trans_handle *trans,
4209 struct btrfs_root *root,
4214 bytes_deleted = btrfs_csum_bytes_to_leaves(root, bytes_deleted);
4215 ret = btrfs_block_rsv_add(root, &root->fs_info->trans_block_rsv,
4216 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4218 trans->bytes_reserved += bytes_deleted;
4224 * this can truncate away extent items, csum items and directory items.
4225 * It starts at a high offset and removes keys until it can't find
4226 * any higher than new_size
4228 * csum items that cross the new i_size are truncated to the new size
4231 * min_type is the minimum key type to truncate down to. If set to 0, this
4232 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4234 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4235 struct btrfs_root *root,
4236 struct inode *inode,
4237 u64 new_size, u32 min_type)
4239 struct btrfs_path *path;
4240 struct extent_buffer *leaf;
4241 struct btrfs_file_extent_item *fi;
4242 struct btrfs_key key;
4243 struct btrfs_key found_key;
4244 u64 extent_start = 0;
4245 u64 extent_num_bytes = 0;
4246 u64 extent_offset = 0;
4248 u64 last_size = new_size;
4249 u32 found_type = (u8)-1;
4252 int pending_del_nr = 0;
4253 int pending_del_slot = 0;
4254 int extent_type = -1;
4257 u64 ino = btrfs_ino(inode);
4258 u64 bytes_deleted = 0;
4260 bool should_throttle = 0;
4261 bool should_end = 0;
4263 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4266 * for non-free space inodes and ref cows, we want to back off from
4269 if (!btrfs_is_free_space_inode(inode) &&
4270 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4273 path = btrfs_alloc_path();
4279 * We want to drop from the next block forward in case this new size is
4280 * not block aligned since we will be keeping the last block of the
4281 * extent just the way it is.
4283 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4284 root == root->fs_info->tree_root)
4285 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4286 root->sectorsize), (u64)-1, 0);
4289 * This function is also used to drop the items in the log tree before
4290 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4291 * it is used to drop the loged items. So we shouldn't kill the delayed
4294 if (min_type == 0 && root == BTRFS_I(inode)->root)
4295 btrfs_kill_delayed_inode_items(inode);
4298 key.offset = (u64)-1;
4303 * with a 16K leaf size and 128MB extents, you can actually queue
4304 * up a huge file in a single leaf. Most of the time that
4305 * bytes_deleted is > 0, it will be huge by the time we get here
4307 if (be_nice && bytes_deleted > 32 * 1024 * 1024) {
4308 if (btrfs_should_end_transaction(trans, root)) {
4315 path->leave_spinning = 1;
4316 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4323 /* there are no items in the tree for us to truncate, we're
4326 if (path->slots[0] == 0)
4333 leaf = path->nodes[0];
4334 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4335 found_type = found_key.type;
4337 if (found_key.objectid != ino)
4340 if (found_type < min_type)
4343 item_end = found_key.offset;
4344 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4345 fi = btrfs_item_ptr(leaf, path->slots[0],
4346 struct btrfs_file_extent_item);
4347 extent_type = btrfs_file_extent_type(leaf, fi);
4348 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4350 btrfs_file_extent_num_bytes(leaf, fi);
4351 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4352 item_end += btrfs_file_extent_inline_len(leaf,
4353 path->slots[0], fi);
4357 if (found_type > min_type) {
4360 if (item_end < new_size)
4362 if (found_key.offset >= new_size)
4368 /* FIXME, shrink the extent if the ref count is only 1 */
4369 if (found_type != BTRFS_EXTENT_DATA_KEY)
4373 last_size = found_key.offset;
4375 last_size = new_size;
4377 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4379 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4381 u64 orig_num_bytes =
4382 btrfs_file_extent_num_bytes(leaf, fi);
4383 extent_num_bytes = ALIGN(new_size -
4386 btrfs_set_file_extent_num_bytes(leaf, fi,
4388 num_dec = (orig_num_bytes -
4390 if (test_bit(BTRFS_ROOT_REF_COWS,
4393 inode_sub_bytes(inode, num_dec);
4394 btrfs_mark_buffer_dirty(leaf);
4397 btrfs_file_extent_disk_num_bytes(leaf,
4399 extent_offset = found_key.offset -
4400 btrfs_file_extent_offset(leaf, fi);
4402 /* FIXME blocksize != 4096 */
4403 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4404 if (extent_start != 0) {
4406 if (test_bit(BTRFS_ROOT_REF_COWS,
4408 inode_sub_bytes(inode, num_dec);
4411 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4413 * we can't truncate inline items that have had
4417 btrfs_file_extent_compression(leaf, fi) == 0 &&
4418 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4419 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4420 u32 size = new_size - found_key.offset;
4422 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4423 inode_sub_bytes(inode, item_end + 1 -
4427 * update the ram bytes to properly reflect
4428 * the new size of our item
4430 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4432 btrfs_file_extent_calc_inline_size(size);
4433 btrfs_truncate_item(root, path, size, 1);
4434 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4436 inode_sub_bytes(inode, item_end + 1 -
4442 if (!pending_del_nr) {
4443 /* no pending yet, add ourselves */
4444 pending_del_slot = path->slots[0];
4446 } else if (pending_del_nr &&
4447 path->slots[0] + 1 == pending_del_slot) {
4448 /* hop on the pending chunk */
4450 pending_del_slot = path->slots[0];
4457 should_throttle = 0;
4460 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4461 root == root->fs_info->tree_root)) {
4462 btrfs_set_path_blocking(path);
4463 bytes_deleted += extent_num_bytes;
4464 ret = btrfs_free_extent(trans, root, extent_start,
4465 extent_num_bytes, 0,
4466 btrfs_header_owner(leaf),
4467 ino, extent_offset, 0);
4469 if (btrfs_should_throttle_delayed_refs(trans, root))
4470 btrfs_async_run_delayed_refs(root,
4471 trans->delayed_ref_updates * 2, 0);
4473 if (truncate_space_check(trans, root,
4474 extent_num_bytes)) {
4477 if (btrfs_should_throttle_delayed_refs(trans,
4479 should_throttle = 1;
4484 if (found_type == BTRFS_INODE_ITEM_KEY)
4487 if (path->slots[0] == 0 ||
4488 path->slots[0] != pending_del_slot ||
4489 should_throttle || should_end) {
4490 if (pending_del_nr) {
4491 ret = btrfs_del_items(trans, root, path,
4495 btrfs_abort_transaction(trans,
4501 btrfs_release_path(path);
4502 if (should_throttle) {
4503 unsigned long updates = trans->delayed_ref_updates;
4505 trans->delayed_ref_updates = 0;
4506 ret = btrfs_run_delayed_refs(trans, root, updates * 2);
4512 * if we failed to refill our space rsv, bail out
4513 * and let the transaction restart
4525 if (pending_del_nr) {
4526 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4529 btrfs_abort_transaction(trans, root, ret);
4532 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4533 btrfs_ordered_update_i_size(inode, last_size, NULL);
4535 btrfs_free_path(path);
4537 if (be_nice && bytes_deleted > 32 * 1024 * 1024) {
4538 unsigned long updates = trans->delayed_ref_updates;
4540 trans->delayed_ref_updates = 0;
4541 ret = btrfs_run_delayed_refs(trans, root, updates * 2);
4550 * btrfs_truncate_page - read, zero a chunk and write a page
4551 * @inode - inode that we're zeroing
4552 * @from - the offset to start zeroing
4553 * @len - the length to zero, 0 to zero the entire range respective to the
4555 * @front - zero up to the offset instead of from the offset on
4557 * This will find the page for the "from" offset and cow the page and zero the
4558 * part we want to zero. This is used with truncate and hole punching.
4560 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4563 struct address_space *mapping = inode->i_mapping;
4564 struct btrfs_root *root = BTRFS_I(inode)->root;
4565 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4566 struct btrfs_ordered_extent *ordered;
4567 struct extent_state *cached_state = NULL;
4569 u32 blocksize = root->sectorsize;
4570 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4571 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4573 gfp_t mask = btrfs_alloc_write_mask(mapping);
4578 if ((offset & (blocksize - 1)) == 0 &&
4579 (!len || ((len & (blocksize - 1)) == 0)))
4581 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4586 page = find_or_create_page(mapping, index, mask);
4588 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4593 page_start = page_offset(page);
4594 page_end = page_start + PAGE_CACHE_SIZE - 1;
4596 if (!PageUptodate(page)) {
4597 ret = btrfs_readpage(NULL, page);
4599 if (page->mapping != mapping) {
4601 page_cache_release(page);
4604 if (!PageUptodate(page)) {
4609 wait_on_page_writeback(page);
4611 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4612 set_page_extent_mapped(page);
4614 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4616 unlock_extent_cached(io_tree, page_start, page_end,
4617 &cached_state, GFP_NOFS);
4619 page_cache_release(page);
4620 btrfs_start_ordered_extent(inode, ordered, 1);
4621 btrfs_put_ordered_extent(ordered);
4625 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4626 EXTENT_DIRTY | EXTENT_DELALLOC |
4627 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4628 0, 0, &cached_state, GFP_NOFS);
4630 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4633 unlock_extent_cached(io_tree, page_start, page_end,
4634 &cached_state, GFP_NOFS);
4638 if (offset != PAGE_CACHE_SIZE) {
4640 len = PAGE_CACHE_SIZE - offset;
4643 memset(kaddr, 0, offset);
4645 memset(kaddr + offset, 0, len);
4646 flush_dcache_page(page);
4649 ClearPageChecked(page);
4650 set_page_dirty(page);
4651 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4656 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4658 page_cache_release(page);
4663 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4664 u64 offset, u64 len)
4666 struct btrfs_trans_handle *trans;
4670 * Still need to make sure the inode looks like it's been updated so
4671 * that any holes get logged if we fsync.
4673 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4674 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4675 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4676 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4681 * 1 - for the one we're dropping
4682 * 1 - for the one we're adding
4683 * 1 - for updating the inode.
4685 trans = btrfs_start_transaction(root, 3);
4687 return PTR_ERR(trans);
4689 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4691 btrfs_abort_transaction(trans, root, ret);
4692 btrfs_end_transaction(trans, root);
4696 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4697 0, 0, len, 0, len, 0, 0, 0);
4699 btrfs_abort_transaction(trans, root, ret);
4701 btrfs_update_inode(trans, root, inode);
4702 btrfs_end_transaction(trans, root);
4707 * This function puts in dummy file extents for the area we're creating a hole
4708 * for. So if we are truncating this file to a larger size we need to insert
4709 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4710 * the range between oldsize and size
4712 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4714 struct btrfs_root *root = BTRFS_I(inode)->root;
4715 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4716 struct extent_map *em = NULL;
4717 struct extent_state *cached_state = NULL;
4718 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4719 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4720 u64 block_end = ALIGN(size, root->sectorsize);
4727 * If our size started in the middle of a page we need to zero out the
4728 * rest of the page before we expand the i_size, otherwise we could
4729 * expose stale data.
4731 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4735 if (size <= hole_start)
4739 struct btrfs_ordered_extent *ordered;
4741 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4743 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4744 block_end - hole_start);
4747 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4748 &cached_state, GFP_NOFS);
4749 btrfs_start_ordered_extent(inode, ordered, 1);
4750 btrfs_put_ordered_extent(ordered);
4753 cur_offset = hole_start;
4755 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4756 block_end - cur_offset, 0);
4762 last_byte = min(extent_map_end(em), block_end);
4763 last_byte = ALIGN(last_byte , root->sectorsize);
4764 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4765 struct extent_map *hole_em;
4766 hole_size = last_byte - cur_offset;
4768 err = maybe_insert_hole(root, inode, cur_offset,
4772 btrfs_drop_extent_cache(inode, cur_offset,
4773 cur_offset + hole_size - 1, 0);
4774 hole_em = alloc_extent_map();
4776 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4777 &BTRFS_I(inode)->runtime_flags);
4780 hole_em->start = cur_offset;
4781 hole_em->len = hole_size;
4782 hole_em->orig_start = cur_offset;
4784 hole_em->block_start = EXTENT_MAP_HOLE;
4785 hole_em->block_len = 0;
4786 hole_em->orig_block_len = 0;
4787 hole_em->ram_bytes = hole_size;
4788 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4789 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4790 hole_em->generation = root->fs_info->generation;
4793 write_lock(&em_tree->lock);
4794 err = add_extent_mapping(em_tree, hole_em, 1);
4795 write_unlock(&em_tree->lock);
4798 btrfs_drop_extent_cache(inode, cur_offset,
4802 free_extent_map(hole_em);
4805 free_extent_map(em);
4807 cur_offset = last_byte;
4808 if (cur_offset >= block_end)
4811 free_extent_map(em);
4812 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4817 static int wait_snapshoting_atomic_t(atomic_t *a)
4823 static void wait_for_snapshot_creation(struct btrfs_root *root)
4828 ret = btrfs_start_write_no_snapshoting(root);
4831 wait_on_atomic_t(&root->will_be_snapshoted,
4832 wait_snapshoting_atomic_t,
4833 TASK_UNINTERRUPTIBLE);
4837 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4839 struct btrfs_root *root = BTRFS_I(inode)->root;
4840 struct btrfs_trans_handle *trans;
4841 loff_t oldsize = i_size_read(inode);
4842 loff_t newsize = attr->ia_size;
4843 int mask = attr->ia_valid;
4847 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4848 * special case where we need to update the times despite not having
4849 * these flags set. For all other operations the VFS set these flags
4850 * explicitly if it wants a timestamp update.
4852 if (newsize != oldsize) {
4853 inode_inc_iversion(inode);
4854 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4855 inode->i_ctime = inode->i_mtime =
4856 current_fs_time(inode->i_sb);
4859 if (newsize > oldsize) {
4860 truncate_pagecache(inode, newsize);
4862 * Don't do an expanding truncate while snapshoting is ongoing.
4863 * This is to ensure the snapshot captures a fully consistent
4864 * state of this file - if the snapshot captures this expanding
4865 * truncation, it must capture all writes that happened before
4868 wait_for_snapshot_creation(root);
4869 ret = btrfs_cont_expand(inode, oldsize, newsize);
4871 btrfs_end_write_no_snapshoting(root);
4875 trans = btrfs_start_transaction(root, 1);
4876 if (IS_ERR(trans)) {
4877 btrfs_end_write_no_snapshoting(root);
4878 return PTR_ERR(trans);
4881 i_size_write(inode, newsize);
4882 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4883 ret = btrfs_update_inode(trans, root, inode);
4884 btrfs_end_write_no_snapshoting(root);
4885 btrfs_end_transaction(trans, root);
4889 * We're truncating a file that used to have good data down to
4890 * zero. Make sure it gets into the ordered flush list so that
4891 * any new writes get down to disk quickly.
4894 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4895 &BTRFS_I(inode)->runtime_flags);
4898 * 1 for the orphan item we're going to add
4899 * 1 for the orphan item deletion.
4901 trans = btrfs_start_transaction(root, 2);
4903 return PTR_ERR(trans);
4906 * We need to do this in case we fail at _any_ point during the
4907 * actual truncate. Once we do the truncate_setsize we could
4908 * invalidate pages which forces any outstanding ordered io to
4909 * be instantly completed which will give us extents that need
4910 * to be truncated. If we fail to get an orphan inode down we
4911 * could have left over extents that were never meant to live,
4912 * so we need to garuntee from this point on that everything
4913 * will be consistent.
4915 ret = btrfs_orphan_add(trans, inode);
4916 btrfs_end_transaction(trans, root);
4920 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4921 truncate_setsize(inode, newsize);
4923 /* Disable nonlocked read DIO to avoid the end less truncate */
4924 btrfs_inode_block_unlocked_dio(inode);
4925 inode_dio_wait(inode);
4926 btrfs_inode_resume_unlocked_dio(inode);
4928 ret = btrfs_truncate(inode);
4929 if (ret && inode->i_nlink) {
4933 * failed to truncate, disk_i_size is only adjusted down
4934 * as we remove extents, so it should represent the true
4935 * size of the inode, so reset the in memory size and
4936 * delete our orphan entry.
4938 trans = btrfs_join_transaction(root);
4939 if (IS_ERR(trans)) {
4940 btrfs_orphan_del(NULL, inode);
4943 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4944 err = btrfs_orphan_del(trans, inode);
4946 btrfs_abort_transaction(trans, root, err);
4947 btrfs_end_transaction(trans, root);
4954 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4956 struct inode *inode = d_inode(dentry);
4957 struct btrfs_root *root = BTRFS_I(inode)->root;
4960 if (btrfs_root_readonly(root))
4963 err = inode_change_ok(inode, attr);
4967 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4968 err = btrfs_setsize(inode, attr);
4973 if (attr->ia_valid) {
4974 setattr_copy(inode, attr);
4975 inode_inc_iversion(inode);
4976 err = btrfs_dirty_inode(inode);
4978 if (!err && attr->ia_valid & ATTR_MODE)
4979 err = posix_acl_chmod(inode, inode->i_mode);
4986 * While truncating the inode pages during eviction, we get the VFS calling
4987 * btrfs_invalidatepage() against each page of the inode. This is slow because
4988 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4989 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4990 * extent_state structures over and over, wasting lots of time.
4992 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4993 * those expensive operations on a per page basis and do only the ordered io
4994 * finishing, while we release here the extent_map and extent_state structures,
4995 * without the excessive merging and splitting.
4997 static void evict_inode_truncate_pages(struct inode *inode)
4999 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5000 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5001 struct rb_node *node;
5003 ASSERT(inode->i_state & I_FREEING);
5004 truncate_inode_pages_final(&inode->i_data);
5006 write_lock(&map_tree->lock);
5007 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5008 struct extent_map *em;
5010 node = rb_first(&map_tree->map);
5011 em = rb_entry(node, struct extent_map, rb_node);
5012 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5013 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5014 remove_extent_mapping(map_tree, em);
5015 free_extent_map(em);
5016 if (need_resched()) {
5017 write_unlock(&map_tree->lock);
5019 write_lock(&map_tree->lock);
5022 write_unlock(&map_tree->lock);
5025 * Keep looping until we have no more ranges in the io tree.
5026 * We can have ongoing bios started by readpages (called from readahead)
5027 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5028 * still in progress (unlocked the pages in the bio but did not yet
5029 * unlocked the ranges in the io tree). Therefore this means some
5030 * ranges can still be locked and eviction started because before
5031 * submitting those bios, which are executed by a separate task (work
5032 * queue kthread), inode references (inode->i_count) were not taken
5033 * (which would be dropped in the end io callback of each bio).
5034 * Therefore here we effectively end up waiting for those bios and
5035 * anyone else holding locked ranges without having bumped the inode's
5036 * reference count - if we don't do it, when they access the inode's
5037 * io_tree to unlock a range it may be too late, leading to an
5038 * use-after-free issue.
5040 spin_lock(&io_tree->lock);
5041 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5042 struct extent_state *state;
5043 struct extent_state *cached_state = NULL;
5047 node = rb_first(&io_tree->state);
5048 state = rb_entry(node, struct extent_state, rb_node);
5049 start = state->start;
5051 spin_unlock(&io_tree->lock);
5053 lock_extent_bits(io_tree, start, end, 0, &cached_state);
5054 clear_extent_bit(io_tree, start, end,
5055 EXTENT_LOCKED | EXTENT_DIRTY |
5056 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5057 EXTENT_DEFRAG, 1, 1,
5058 &cached_state, GFP_NOFS);
5061 spin_lock(&io_tree->lock);
5063 spin_unlock(&io_tree->lock);
5066 void btrfs_evict_inode(struct inode *inode)
5068 struct btrfs_trans_handle *trans;
5069 struct btrfs_root *root = BTRFS_I(inode)->root;
5070 struct btrfs_block_rsv *rsv, *global_rsv;
5071 int steal_from_global = 0;
5072 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
5075 trace_btrfs_inode_evict(inode);
5077 evict_inode_truncate_pages(inode);
5079 if (inode->i_nlink &&
5080 ((btrfs_root_refs(&root->root_item) != 0 &&
5081 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5082 btrfs_is_free_space_inode(inode)))
5085 if (is_bad_inode(inode)) {
5086 btrfs_orphan_del(NULL, inode);
5089 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5090 if (!special_file(inode->i_mode))
5091 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5093 btrfs_free_io_failure_record(inode, 0, (u64)-1);
5095 if (root->fs_info->log_root_recovering) {
5096 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5097 &BTRFS_I(inode)->runtime_flags));
5101 if (inode->i_nlink > 0) {
5102 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5103 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5107 ret = btrfs_commit_inode_delayed_inode(inode);
5109 btrfs_orphan_del(NULL, inode);
5113 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
5115 btrfs_orphan_del(NULL, inode);
5118 rsv->size = min_size;
5120 global_rsv = &root->fs_info->global_block_rsv;
5122 btrfs_i_size_write(inode, 0);
5125 * This is a bit simpler than btrfs_truncate since we've already
5126 * reserved our space for our orphan item in the unlink, so we just
5127 * need to reserve some slack space in case we add bytes and update
5128 * inode item when doing the truncate.
5131 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5132 BTRFS_RESERVE_FLUSH_LIMIT);
5135 * Try and steal from the global reserve since we will
5136 * likely not use this space anyway, we want to try as
5137 * hard as possible to get this to work.
5140 steal_from_global++;
5142 steal_from_global = 0;
5146 * steal_from_global == 0: we reserved stuff, hooray!
5147 * steal_from_global == 1: we didn't reserve stuff, boo!
5148 * steal_from_global == 2: we've committed, still not a lot of
5149 * room but maybe we'll have room in the global reserve this
5151 * steal_from_global == 3: abandon all hope!
5153 if (steal_from_global > 2) {
5154 btrfs_warn(root->fs_info,
5155 "Could not get space for a delete, will truncate on mount %d",
5157 btrfs_orphan_del(NULL, inode);
5158 btrfs_free_block_rsv(root, rsv);
5162 trans = btrfs_join_transaction(root);
5163 if (IS_ERR(trans)) {
5164 btrfs_orphan_del(NULL, inode);
5165 btrfs_free_block_rsv(root, rsv);
5170 * We can't just steal from the global reserve, we need tomake
5171 * sure there is room to do it, if not we need to commit and try
5174 if (steal_from_global) {
5175 if (!btrfs_check_space_for_delayed_refs(trans, root))
5176 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5183 * Couldn't steal from the global reserve, we have too much
5184 * pending stuff built up, commit the transaction and try it
5188 ret = btrfs_commit_transaction(trans, root);
5190 btrfs_orphan_del(NULL, inode);
5191 btrfs_free_block_rsv(root, rsv);
5196 steal_from_global = 0;
5199 trans->block_rsv = rsv;
5201 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5202 if (ret != -ENOSPC && ret != -EAGAIN)
5205 trans->block_rsv = &root->fs_info->trans_block_rsv;
5206 btrfs_end_transaction(trans, root);
5208 btrfs_btree_balance_dirty(root);
5211 btrfs_free_block_rsv(root, rsv);
5214 * Errors here aren't a big deal, it just means we leave orphan items
5215 * in the tree. They will be cleaned up on the next mount.
5218 trans->block_rsv = root->orphan_block_rsv;
5219 btrfs_orphan_del(trans, inode);
5221 btrfs_orphan_del(NULL, inode);
5224 trans->block_rsv = &root->fs_info->trans_block_rsv;
5225 if (!(root == root->fs_info->tree_root ||
5226 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5227 btrfs_return_ino(root, btrfs_ino(inode));
5229 btrfs_end_transaction(trans, root);
5230 btrfs_btree_balance_dirty(root);
5232 btrfs_remove_delayed_node(inode);
5238 * this returns the key found in the dir entry in the location pointer.
5239 * If no dir entries were found, location->objectid is 0.
5241 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5242 struct btrfs_key *location)
5244 const char *name = dentry->d_name.name;
5245 int namelen = dentry->d_name.len;
5246 struct btrfs_dir_item *di;
5247 struct btrfs_path *path;
5248 struct btrfs_root *root = BTRFS_I(dir)->root;
5251 path = btrfs_alloc_path();
5255 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
5260 if (IS_ERR_OR_NULL(di))
5263 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5265 btrfs_free_path(path);
5268 location->objectid = 0;
5273 * when we hit a tree root in a directory, the btrfs part of the inode
5274 * needs to be changed to reflect the root directory of the tree root. This
5275 * is kind of like crossing a mount point.
5277 static int fixup_tree_root_location(struct btrfs_root *root,
5279 struct dentry *dentry,
5280 struct btrfs_key *location,
5281 struct btrfs_root **sub_root)
5283 struct btrfs_path *path;
5284 struct btrfs_root *new_root;
5285 struct btrfs_root_ref *ref;
5286 struct extent_buffer *leaf;
5287 struct btrfs_key key;
5291 path = btrfs_alloc_path();
5298 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5299 key.type = BTRFS_ROOT_REF_KEY;
5300 key.offset = location->objectid;
5302 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, path,
5310 leaf = path->nodes[0];
5311 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5312 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5313 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5316 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5317 (unsigned long)(ref + 1),
5318 dentry->d_name.len);
5322 btrfs_release_path(path);
5324 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
5325 if (IS_ERR(new_root)) {
5326 err = PTR_ERR(new_root);
5330 *sub_root = new_root;
5331 location->objectid = btrfs_root_dirid(&new_root->root_item);
5332 location->type = BTRFS_INODE_ITEM_KEY;
5333 location->offset = 0;
5336 btrfs_free_path(path);
5340 static void inode_tree_add(struct inode *inode)
5342 struct btrfs_root *root = BTRFS_I(inode)->root;
5343 struct btrfs_inode *entry;
5345 struct rb_node *parent;
5346 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5347 u64 ino = btrfs_ino(inode);
5349 if (inode_unhashed(inode))
5352 spin_lock(&root->inode_lock);
5353 p = &root->inode_tree.rb_node;
5356 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5358 if (ino < btrfs_ino(&entry->vfs_inode))
5359 p = &parent->rb_left;
5360 else if (ino > btrfs_ino(&entry->vfs_inode))
5361 p = &parent->rb_right;
5363 WARN_ON(!(entry->vfs_inode.i_state &
5364 (I_WILL_FREE | I_FREEING)));
5365 rb_replace_node(parent, new, &root->inode_tree);
5366 RB_CLEAR_NODE(parent);
5367 spin_unlock(&root->inode_lock);
5371 rb_link_node(new, parent, p);
5372 rb_insert_color(new, &root->inode_tree);
5373 spin_unlock(&root->inode_lock);
5376 static void inode_tree_del(struct inode *inode)
5378 struct btrfs_root *root = BTRFS_I(inode)->root;
5381 spin_lock(&root->inode_lock);
5382 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5383 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5384 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5385 empty = RB_EMPTY_ROOT(&root->inode_tree);
5387 spin_unlock(&root->inode_lock);
5389 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5390 synchronize_srcu(&root->fs_info->subvol_srcu);
5391 spin_lock(&root->inode_lock);
5392 empty = RB_EMPTY_ROOT(&root->inode_tree);
5393 spin_unlock(&root->inode_lock);
5395 btrfs_add_dead_root(root);
5399 void btrfs_invalidate_inodes(struct btrfs_root *root)
5401 struct rb_node *node;
5402 struct rb_node *prev;
5403 struct btrfs_inode *entry;
5404 struct inode *inode;
5407 if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
5408 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5410 spin_lock(&root->inode_lock);
5412 node = root->inode_tree.rb_node;
5416 entry = rb_entry(node, struct btrfs_inode, rb_node);
5418 if (objectid < btrfs_ino(&entry->vfs_inode))
5419 node = node->rb_left;
5420 else if (objectid > btrfs_ino(&entry->vfs_inode))
5421 node = node->rb_right;
5427 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5428 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
5432 prev = rb_next(prev);
5436 entry = rb_entry(node, struct btrfs_inode, rb_node);
5437 objectid = btrfs_ino(&entry->vfs_inode) + 1;
5438 inode = igrab(&entry->vfs_inode);
5440 spin_unlock(&root->inode_lock);
5441 if (atomic_read(&inode->i_count) > 1)
5442 d_prune_aliases(inode);
5444 * btrfs_drop_inode will have it removed from
5445 * the inode cache when its usage count
5450 spin_lock(&root->inode_lock);
5454 if (cond_resched_lock(&root->inode_lock))
5457 node = rb_next(node);
5459 spin_unlock(&root->inode_lock);
5462 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5464 struct btrfs_iget_args *args = p;
5465 inode->i_ino = args->location->objectid;
5466 memcpy(&BTRFS_I(inode)->location, args->location,
5467 sizeof(*args->location));
5468 BTRFS_I(inode)->root = args->root;
5472 static int btrfs_find_actor(struct inode *inode, void *opaque)
5474 struct btrfs_iget_args *args = opaque;
5475 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5476 args->root == BTRFS_I(inode)->root;
5479 static struct inode *btrfs_iget_locked(struct super_block *s,
5480 struct btrfs_key *location,
5481 struct btrfs_root *root)
5483 struct inode *inode;
5484 struct btrfs_iget_args args;
5485 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5487 args.location = location;
5490 inode = iget5_locked(s, hashval, btrfs_find_actor,
5491 btrfs_init_locked_inode,
5496 /* Get an inode object given its location and corresponding root.
5497 * Returns in *is_new if the inode was read from disk
5499 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5500 struct btrfs_root *root, int *new)
5502 struct inode *inode;
5504 inode = btrfs_iget_locked(s, location, root);
5506 return ERR_PTR(-ENOMEM);
5508 if (inode->i_state & I_NEW) {
5509 btrfs_read_locked_inode(inode);
5510 if (!is_bad_inode(inode)) {
5511 inode_tree_add(inode);
5512 unlock_new_inode(inode);
5516 unlock_new_inode(inode);
5518 inode = ERR_PTR(-ESTALE);
5525 static struct inode *new_simple_dir(struct super_block *s,
5526 struct btrfs_key *key,
5527 struct btrfs_root *root)
5529 struct inode *inode = new_inode(s);
5532 return ERR_PTR(-ENOMEM);
5534 BTRFS_I(inode)->root = root;
5535 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5536 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5538 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5539 inode->i_op = &btrfs_dir_ro_inode_operations;
5540 inode->i_fop = &simple_dir_operations;
5541 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5542 inode->i_mtime = CURRENT_TIME;
5543 inode->i_atime = inode->i_mtime;
5544 inode->i_ctime = inode->i_mtime;
5545 BTRFS_I(inode)->i_otime = inode->i_mtime;
5550 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5552 struct inode *inode;
5553 struct btrfs_root *root = BTRFS_I(dir)->root;
5554 struct btrfs_root *sub_root = root;
5555 struct btrfs_key location;
5559 if (dentry->d_name.len > BTRFS_NAME_LEN)
5560 return ERR_PTR(-ENAMETOOLONG);
5562 ret = btrfs_inode_by_name(dir, dentry, &location);
5564 return ERR_PTR(ret);
5566 if (location.objectid == 0)
5567 return ERR_PTR(-ENOENT);
5569 if (location.type == BTRFS_INODE_ITEM_KEY) {
5570 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5574 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5576 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5577 ret = fixup_tree_root_location(root, dir, dentry,
5578 &location, &sub_root);
5581 inode = ERR_PTR(ret);
5583 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5585 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5587 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5589 if (!IS_ERR(inode) && root != sub_root) {
5590 down_read(&root->fs_info->cleanup_work_sem);
5591 if (!(inode->i_sb->s_flags & MS_RDONLY))
5592 ret = btrfs_orphan_cleanup(sub_root);
5593 up_read(&root->fs_info->cleanup_work_sem);
5596 inode = ERR_PTR(ret);
5603 static int btrfs_dentry_delete(const struct dentry *dentry)
5605 struct btrfs_root *root;
5606 struct inode *inode = d_inode(dentry);
5608 if (!inode && !IS_ROOT(dentry))
5609 inode = d_inode(dentry->d_parent);
5612 root = BTRFS_I(inode)->root;
5613 if (btrfs_root_refs(&root->root_item) == 0)
5616 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5622 static void btrfs_dentry_release(struct dentry *dentry)
5624 kfree(dentry->d_fsdata);
5627 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5630 struct inode *inode;
5632 inode = btrfs_lookup_dentry(dir, dentry);
5633 if (IS_ERR(inode)) {
5634 if (PTR_ERR(inode) == -ENOENT)
5637 return ERR_CAST(inode);
5640 return d_splice_alias(inode, dentry);
5643 unsigned char btrfs_filetype_table[] = {
5644 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5647 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5649 struct inode *inode = file_inode(file);
5650 struct btrfs_root *root = BTRFS_I(inode)->root;
5651 struct btrfs_item *item;
5652 struct btrfs_dir_item *di;
5653 struct btrfs_key key;
5654 struct btrfs_key found_key;
5655 struct btrfs_path *path;
5656 struct list_head ins_list;
5657 struct list_head del_list;
5659 struct extent_buffer *leaf;
5661 unsigned char d_type;
5666 int key_type = BTRFS_DIR_INDEX_KEY;
5670 int is_curr = 0; /* ctx->pos points to the current index? */
5672 /* FIXME, use a real flag for deciding about the key type */
5673 if (root->fs_info->tree_root == root)
5674 key_type = BTRFS_DIR_ITEM_KEY;
5676 if (!dir_emit_dots(file, ctx))
5679 path = btrfs_alloc_path();
5685 if (key_type == BTRFS_DIR_INDEX_KEY) {
5686 INIT_LIST_HEAD(&ins_list);
5687 INIT_LIST_HEAD(&del_list);
5688 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5691 key.type = key_type;
5692 key.offset = ctx->pos;
5693 key.objectid = btrfs_ino(inode);
5695 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5700 leaf = path->nodes[0];
5701 slot = path->slots[0];
5702 if (slot >= btrfs_header_nritems(leaf)) {
5703 ret = btrfs_next_leaf(root, path);
5711 item = btrfs_item_nr(slot);
5712 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5714 if (found_key.objectid != key.objectid)
5716 if (found_key.type != key_type)
5718 if (found_key.offset < ctx->pos)
5720 if (key_type == BTRFS_DIR_INDEX_KEY &&
5721 btrfs_should_delete_dir_index(&del_list,
5725 ctx->pos = found_key.offset;
5728 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5730 di_total = btrfs_item_size(leaf, item);
5732 while (di_cur < di_total) {
5733 struct btrfs_key location;
5735 if (verify_dir_item(root, leaf, di))
5738 name_len = btrfs_dir_name_len(leaf, di);
5739 if (name_len <= sizeof(tmp_name)) {
5740 name_ptr = tmp_name;
5742 name_ptr = kmalloc(name_len, GFP_NOFS);
5748 read_extent_buffer(leaf, name_ptr,
5749 (unsigned long)(di + 1), name_len);
5751 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5752 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5755 /* is this a reference to our own snapshot? If so
5758 * In contrast to old kernels, we insert the snapshot's
5759 * dir item and dir index after it has been created, so
5760 * we won't find a reference to our own snapshot. We
5761 * still keep the following code for backward
5764 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5765 location.objectid == root->root_key.objectid) {
5769 over = !dir_emit(ctx, name_ptr, name_len,
5770 location.objectid, d_type);
5773 if (name_ptr != tmp_name)
5778 di_len = btrfs_dir_name_len(leaf, di) +
5779 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5781 di = (struct btrfs_dir_item *)((char *)di + di_len);
5787 if (key_type == BTRFS_DIR_INDEX_KEY) {
5790 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5795 /* Reached end of directory/root. Bump pos past the last item. */
5799 * Stop new entries from being returned after we return the last
5802 * New directory entries are assigned a strictly increasing
5803 * offset. This means that new entries created during readdir
5804 * are *guaranteed* to be seen in the future by that readdir.
5805 * This has broken buggy programs which operate on names as
5806 * they're returned by readdir. Until we re-use freed offsets
5807 * we have this hack to stop new entries from being returned
5808 * under the assumption that they'll never reach this huge
5811 * This is being careful not to overflow 32bit loff_t unless the
5812 * last entry requires it because doing so has broken 32bit apps
5815 if (key_type == BTRFS_DIR_INDEX_KEY) {
5816 if (ctx->pos >= INT_MAX)
5817 ctx->pos = LLONG_MAX;
5824 if (key_type == BTRFS_DIR_INDEX_KEY)
5825 btrfs_put_delayed_items(&ins_list, &del_list);
5826 btrfs_free_path(path);
5830 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5832 struct btrfs_root *root = BTRFS_I(inode)->root;
5833 struct btrfs_trans_handle *trans;
5835 bool nolock = false;
5837 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5840 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5843 if (wbc->sync_mode == WB_SYNC_ALL) {
5845 trans = btrfs_join_transaction_nolock(root);
5847 trans = btrfs_join_transaction(root);
5849 return PTR_ERR(trans);
5850 ret = btrfs_commit_transaction(trans, root);
5856 * This is somewhat expensive, updating the tree every time the
5857 * inode changes. But, it is most likely to find the inode in cache.
5858 * FIXME, needs more benchmarking...there are no reasons other than performance
5859 * to keep or drop this code.
5861 static int btrfs_dirty_inode(struct inode *inode)
5863 struct btrfs_root *root = BTRFS_I(inode)->root;
5864 struct btrfs_trans_handle *trans;
5867 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5870 trans = btrfs_join_transaction(root);
5872 return PTR_ERR(trans);
5874 ret = btrfs_update_inode(trans, root, inode);
5875 if (ret && ret == -ENOSPC) {
5876 /* whoops, lets try again with the full transaction */
5877 btrfs_end_transaction(trans, root);
5878 trans = btrfs_start_transaction(root, 1);
5880 return PTR_ERR(trans);
5882 ret = btrfs_update_inode(trans, root, inode);
5884 btrfs_end_transaction(trans, root);
5885 if (BTRFS_I(inode)->delayed_node)
5886 btrfs_balance_delayed_items(root);
5892 * This is a copy of file_update_time. We need this so we can return error on
5893 * ENOSPC for updating the inode in the case of file write and mmap writes.
5895 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5898 struct btrfs_root *root = BTRFS_I(inode)->root;
5900 if (btrfs_root_readonly(root))
5903 if (flags & S_VERSION)
5904 inode_inc_iversion(inode);
5905 if (flags & S_CTIME)
5906 inode->i_ctime = *now;
5907 if (flags & S_MTIME)
5908 inode->i_mtime = *now;
5909 if (flags & S_ATIME)
5910 inode->i_atime = *now;
5911 return btrfs_dirty_inode(inode);
5915 * find the highest existing sequence number in a directory
5916 * and then set the in-memory index_cnt variable to reflect
5917 * free sequence numbers
5919 static int btrfs_set_inode_index_count(struct inode *inode)
5921 struct btrfs_root *root = BTRFS_I(inode)->root;
5922 struct btrfs_key key, found_key;
5923 struct btrfs_path *path;
5924 struct extent_buffer *leaf;
5927 key.objectid = btrfs_ino(inode);
5928 key.type = BTRFS_DIR_INDEX_KEY;
5929 key.offset = (u64)-1;
5931 path = btrfs_alloc_path();
5935 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5938 /* FIXME: we should be able to handle this */
5944 * MAGIC NUMBER EXPLANATION:
5945 * since we search a directory based on f_pos we have to start at 2
5946 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5947 * else has to start at 2
5949 if (path->slots[0] == 0) {
5950 BTRFS_I(inode)->index_cnt = 2;
5956 leaf = path->nodes[0];
5957 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5959 if (found_key.objectid != btrfs_ino(inode) ||
5960 found_key.type != BTRFS_DIR_INDEX_KEY) {
5961 BTRFS_I(inode)->index_cnt = 2;
5965 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5967 btrfs_free_path(path);
5972 * helper to find a free sequence number in a given directory. This current
5973 * code is very simple, later versions will do smarter things in the btree
5975 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5979 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5980 ret = btrfs_inode_delayed_dir_index_count(dir);
5982 ret = btrfs_set_inode_index_count(dir);
5988 *index = BTRFS_I(dir)->index_cnt;
5989 BTRFS_I(dir)->index_cnt++;
5994 static int btrfs_insert_inode_locked(struct inode *inode)
5996 struct btrfs_iget_args args;
5997 args.location = &BTRFS_I(inode)->location;
5998 args.root = BTRFS_I(inode)->root;
6000 return insert_inode_locked4(inode,
6001 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6002 btrfs_find_actor, &args);
6005 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6006 struct btrfs_root *root,
6008 const char *name, int name_len,
6009 u64 ref_objectid, u64 objectid,
6010 umode_t mode, u64 *index)
6012 struct inode *inode;
6013 struct btrfs_inode_item *inode_item;
6014 struct btrfs_key *location;
6015 struct btrfs_path *path;
6016 struct btrfs_inode_ref *ref;
6017 struct btrfs_key key[2];
6019 int nitems = name ? 2 : 1;
6023 path = btrfs_alloc_path();
6025 return ERR_PTR(-ENOMEM);
6027 inode = new_inode(root->fs_info->sb);
6029 btrfs_free_path(path);
6030 return ERR_PTR(-ENOMEM);
6034 * O_TMPFILE, set link count to 0, so that after this point,
6035 * we fill in an inode item with the correct link count.
6038 set_nlink(inode, 0);
6041 * we have to initialize this early, so we can reclaim the inode
6042 * number if we fail afterwards in this function.
6044 inode->i_ino = objectid;
6047 trace_btrfs_inode_request(dir);
6049 ret = btrfs_set_inode_index(dir, index);
6051 btrfs_free_path(path);
6053 return ERR_PTR(ret);
6059 * index_cnt is ignored for everything but a dir,
6060 * btrfs_get_inode_index_count has an explanation for the magic
6063 BTRFS_I(inode)->index_cnt = 2;
6064 BTRFS_I(inode)->dir_index = *index;
6065 BTRFS_I(inode)->root = root;
6066 BTRFS_I(inode)->generation = trans->transid;
6067 inode->i_generation = BTRFS_I(inode)->generation;
6070 * We could have gotten an inode number from somebody who was fsynced
6071 * and then removed in this same transaction, so let's just set full
6072 * sync since it will be a full sync anyway and this will blow away the
6073 * old info in the log.
6075 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6077 key[0].objectid = objectid;
6078 key[0].type = BTRFS_INODE_ITEM_KEY;
6081 sizes[0] = sizeof(struct btrfs_inode_item);
6085 * Start new inodes with an inode_ref. This is slightly more
6086 * efficient for small numbers of hard links since they will
6087 * be packed into one item. Extended refs will kick in if we
6088 * add more hard links than can fit in the ref item.
6090 key[1].objectid = objectid;
6091 key[1].type = BTRFS_INODE_REF_KEY;
6092 key[1].offset = ref_objectid;
6094 sizes[1] = name_len + sizeof(*ref);
6097 location = &BTRFS_I(inode)->location;
6098 location->objectid = objectid;
6099 location->offset = 0;
6100 location->type = BTRFS_INODE_ITEM_KEY;
6102 ret = btrfs_insert_inode_locked(inode);
6106 path->leave_spinning = 1;
6107 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6111 inode_init_owner(inode, dir, mode);
6112 inode_set_bytes(inode, 0);
6114 inode->i_mtime = CURRENT_TIME;
6115 inode->i_atime = inode->i_mtime;
6116 inode->i_ctime = inode->i_mtime;
6117 BTRFS_I(inode)->i_otime = inode->i_mtime;
6119 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6120 struct btrfs_inode_item);
6121 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
6122 sizeof(*inode_item));
6123 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6126 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6127 struct btrfs_inode_ref);
6128 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6129 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6130 ptr = (unsigned long)(ref + 1);
6131 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6134 btrfs_mark_buffer_dirty(path->nodes[0]);
6135 btrfs_free_path(path);
6137 btrfs_inherit_iflags(inode, dir);
6139 if (S_ISREG(mode)) {
6140 if (btrfs_test_opt(root, NODATASUM))
6141 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6142 if (btrfs_test_opt(root, NODATACOW))
6143 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6144 BTRFS_INODE_NODATASUM;
6147 inode_tree_add(inode);
6149 trace_btrfs_inode_new(inode);
6150 btrfs_set_inode_last_trans(trans, inode);
6152 btrfs_update_root_times(trans, root);
6154 ret = btrfs_inode_inherit_props(trans, inode, dir);
6156 btrfs_err(root->fs_info,
6157 "error inheriting props for ino %llu (root %llu): %d",
6158 btrfs_ino(inode), root->root_key.objectid, ret);
6163 unlock_new_inode(inode);
6166 BTRFS_I(dir)->index_cnt--;
6167 btrfs_free_path(path);
6169 return ERR_PTR(ret);
6172 static inline u8 btrfs_inode_type(struct inode *inode)
6174 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6178 * utility function to add 'inode' into 'parent_inode' with
6179 * a give name and a given sequence number.
6180 * if 'add_backref' is true, also insert a backref from the
6181 * inode to the parent directory.
6183 int btrfs_add_link(struct btrfs_trans_handle *trans,
6184 struct inode *parent_inode, struct inode *inode,
6185 const char *name, int name_len, int add_backref, u64 index)
6188 struct btrfs_key key;
6189 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
6190 u64 ino = btrfs_ino(inode);
6191 u64 parent_ino = btrfs_ino(parent_inode);
6193 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6194 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
6197 key.type = BTRFS_INODE_ITEM_KEY;
6201 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6202 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
6203 key.objectid, root->root_key.objectid,
6204 parent_ino, index, name, name_len);
6205 } else if (add_backref) {
6206 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6210 /* Nothing to clean up yet */
6214 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6216 btrfs_inode_type(inode), index);
6217 if (ret == -EEXIST || ret == -EOVERFLOW)
6220 btrfs_abort_transaction(trans, root, ret);
6224 btrfs_i_size_write(parent_inode, parent_inode->i_size +
6226 inode_inc_iversion(parent_inode);
6227 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
6228 ret = btrfs_update_inode(trans, root, parent_inode);
6230 btrfs_abort_transaction(trans, root, ret);
6234 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6237 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
6238 key.objectid, root->root_key.objectid,
6239 parent_ino, &local_index, name, name_len);
6241 } else if (add_backref) {
6245 err = btrfs_del_inode_ref(trans, root, name, name_len,
6246 ino, parent_ino, &local_index);
6251 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6252 struct inode *dir, struct dentry *dentry,
6253 struct inode *inode, int backref, u64 index)
6255 int err = btrfs_add_link(trans, dir, inode,
6256 dentry->d_name.name, dentry->d_name.len,
6263 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6264 umode_t mode, dev_t rdev)
6266 struct btrfs_trans_handle *trans;
6267 struct btrfs_root *root = BTRFS_I(dir)->root;
6268 struct inode *inode = NULL;
6274 if (!new_valid_dev(rdev))
6278 * 2 for inode item and ref
6280 * 1 for xattr if selinux is on
6282 trans = btrfs_start_transaction(root, 5);
6284 return PTR_ERR(trans);
6286 err = btrfs_find_free_ino(root, &objectid);
6290 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6291 dentry->d_name.len, btrfs_ino(dir), objectid,
6293 if (IS_ERR(inode)) {
6294 err = PTR_ERR(inode);
6299 * If the active LSM wants to access the inode during
6300 * d_instantiate it needs these. Smack checks to see
6301 * if the filesystem supports xattrs by looking at the
6304 inode->i_op = &btrfs_special_inode_operations;
6305 init_special_inode(inode, inode->i_mode, rdev);
6307 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6309 goto out_unlock_inode;
6311 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6313 goto out_unlock_inode;
6315 btrfs_update_inode(trans, root, inode);
6316 unlock_new_inode(inode);
6317 d_instantiate(dentry, inode);
6321 btrfs_end_transaction(trans, root);
6322 btrfs_balance_delayed_items(root);
6323 btrfs_btree_balance_dirty(root);
6325 inode_dec_link_count(inode);
6332 unlock_new_inode(inode);
6337 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6338 umode_t mode, bool excl)
6340 struct btrfs_trans_handle *trans;
6341 struct btrfs_root *root = BTRFS_I(dir)->root;
6342 struct inode *inode = NULL;
6343 int drop_inode_on_err = 0;
6349 * 2 for inode item and ref
6351 * 1 for xattr if selinux is on
6353 trans = btrfs_start_transaction(root, 5);
6355 return PTR_ERR(trans);
6357 err = btrfs_find_free_ino(root, &objectid);
6361 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6362 dentry->d_name.len, btrfs_ino(dir), objectid,
6364 if (IS_ERR(inode)) {
6365 err = PTR_ERR(inode);
6368 drop_inode_on_err = 1;
6370 * If the active LSM wants to access the inode during
6371 * d_instantiate it needs these. Smack checks to see
6372 * if the filesystem supports xattrs by looking at the
6375 inode->i_fop = &btrfs_file_operations;
6376 inode->i_op = &btrfs_file_inode_operations;
6377 inode->i_mapping->a_ops = &btrfs_aops;
6379 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6381 goto out_unlock_inode;
6383 err = btrfs_update_inode(trans, root, inode);
6385 goto out_unlock_inode;
6387 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6389 goto out_unlock_inode;
6391 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6392 unlock_new_inode(inode);
6393 d_instantiate(dentry, inode);
6396 btrfs_end_transaction(trans, root);
6397 if (err && drop_inode_on_err) {
6398 inode_dec_link_count(inode);
6401 btrfs_balance_delayed_items(root);
6402 btrfs_btree_balance_dirty(root);
6406 unlock_new_inode(inode);
6411 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6412 struct dentry *dentry)
6414 struct btrfs_trans_handle *trans;
6415 struct btrfs_root *root = BTRFS_I(dir)->root;
6416 struct inode *inode = d_inode(old_dentry);
6421 /* do not allow sys_link's with other subvols of the same device */
6422 if (root->objectid != BTRFS_I(inode)->root->objectid)
6425 if (inode->i_nlink >= BTRFS_LINK_MAX)
6428 err = btrfs_set_inode_index(dir, &index);
6433 * 2 items for inode and inode ref
6434 * 2 items for dir items
6435 * 1 item for parent inode
6437 trans = btrfs_start_transaction(root, 5);
6438 if (IS_ERR(trans)) {
6439 err = PTR_ERR(trans);
6443 /* There are several dir indexes for this inode, clear the cache. */
6444 BTRFS_I(inode)->dir_index = 0ULL;
6446 inode_inc_iversion(inode);
6447 inode->i_ctime = CURRENT_TIME;
6449 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6451 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
6456 struct dentry *parent = dentry->d_parent;
6457 err = btrfs_update_inode(trans, root, inode);
6460 if (inode->i_nlink == 1) {
6462 * If new hard link count is 1, it's a file created
6463 * with open(2) O_TMPFILE flag.
6465 err = btrfs_orphan_del(trans, inode);
6469 d_instantiate(dentry, inode);
6470 btrfs_log_new_name(trans, inode, NULL, parent);
6473 btrfs_end_transaction(trans, root);
6474 btrfs_balance_delayed_items(root);
6477 inode_dec_link_count(inode);
6480 btrfs_btree_balance_dirty(root);
6484 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6486 struct inode *inode = NULL;
6487 struct btrfs_trans_handle *trans;
6488 struct btrfs_root *root = BTRFS_I(dir)->root;
6490 int drop_on_err = 0;
6495 * 2 items for inode and ref
6496 * 2 items for dir items
6497 * 1 for xattr if selinux is on
6499 trans = btrfs_start_transaction(root, 5);
6501 return PTR_ERR(trans);
6503 err = btrfs_find_free_ino(root, &objectid);
6507 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6508 dentry->d_name.len, btrfs_ino(dir), objectid,
6509 S_IFDIR | mode, &index);
6510 if (IS_ERR(inode)) {
6511 err = PTR_ERR(inode);
6516 /* these must be set before we unlock the inode */
6517 inode->i_op = &btrfs_dir_inode_operations;
6518 inode->i_fop = &btrfs_dir_file_operations;
6520 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6522 goto out_fail_inode;
6524 btrfs_i_size_write(inode, 0);
6525 err = btrfs_update_inode(trans, root, inode);
6527 goto out_fail_inode;
6529 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6530 dentry->d_name.len, 0, index);
6532 goto out_fail_inode;
6534 d_instantiate(dentry, inode);
6536 * mkdir is special. We're unlocking after we call d_instantiate
6537 * to avoid a race with nfsd calling d_instantiate.
6539 unlock_new_inode(inode);
6543 btrfs_end_transaction(trans, root);
6545 inode_dec_link_count(inode);
6548 btrfs_balance_delayed_items(root);
6549 btrfs_btree_balance_dirty(root);
6553 unlock_new_inode(inode);
6557 /* Find next extent map of a given extent map, caller needs to ensure locks */
6558 static struct extent_map *next_extent_map(struct extent_map *em)
6560 struct rb_node *next;
6562 next = rb_next(&em->rb_node);
6565 return container_of(next, struct extent_map, rb_node);
6568 static struct extent_map *prev_extent_map(struct extent_map *em)
6570 struct rb_node *prev;
6572 prev = rb_prev(&em->rb_node);
6575 return container_of(prev, struct extent_map, rb_node);
6578 /* helper for btfs_get_extent. Given an existing extent in the tree,
6579 * the existing extent is the nearest extent to map_start,
6580 * and an extent that you want to insert, deal with overlap and insert
6581 * the best fitted new extent into the tree.
6583 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6584 struct extent_map *existing,
6585 struct extent_map *em,
6588 struct extent_map *prev;
6589 struct extent_map *next;
6594 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6596 if (existing->start > map_start) {
6598 prev = prev_extent_map(next);
6601 next = next_extent_map(prev);
6604 start = prev ? extent_map_end(prev) : em->start;
6605 start = max_t(u64, start, em->start);
6606 end = next ? next->start : extent_map_end(em);
6607 end = min_t(u64, end, extent_map_end(em));
6608 start_diff = start - em->start;
6610 em->len = end - start;
6611 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6612 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6613 em->block_start += start_diff;
6614 em->block_len -= start_diff;
6616 return add_extent_mapping(em_tree, em, 0);
6619 static noinline int uncompress_inline(struct btrfs_path *path,
6620 struct inode *inode, struct page *page,
6621 size_t pg_offset, u64 extent_offset,
6622 struct btrfs_file_extent_item *item)
6625 struct extent_buffer *leaf = path->nodes[0];
6628 unsigned long inline_size;
6632 WARN_ON(pg_offset != 0);
6633 compress_type = btrfs_file_extent_compression(leaf, item);
6634 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6635 inline_size = btrfs_file_extent_inline_item_len(leaf,
6636 btrfs_item_nr(path->slots[0]));
6637 tmp = kmalloc(inline_size, GFP_NOFS);
6640 ptr = btrfs_file_extent_inline_start(item);
6642 read_extent_buffer(leaf, tmp, ptr, inline_size);
6644 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6645 ret = btrfs_decompress(compress_type, tmp, page,
6646 extent_offset, inline_size, max_size);
6652 * a bit scary, this does extent mapping from logical file offset to the disk.
6653 * the ugly parts come from merging extents from the disk with the in-ram
6654 * representation. This gets more complex because of the data=ordered code,
6655 * where the in-ram extents might be locked pending data=ordered completion.
6657 * This also copies inline extents directly into the page.
6660 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6661 size_t pg_offset, u64 start, u64 len,
6666 u64 extent_start = 0;
6668 u64 objectid = btrfs_ino(inode);
6670 struct btrfs_path *path = NULL;
6671 struct btrfs_root *root = BTRFS_I(inode)->root;
6672 struct btrfs_file_extent_item *item;
6673 struct extent_buffer *leaf;
6674 struct btrfs_key found_key;
6675 struct extent_map *em = NULL;
6676 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6677 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6678 struct btrfs_trans_handle *trans = NULL;
6679 const bool new_inline = !page || create;
6682 read_lock(&em_tree->lock);
6683 em = lookup_extent_mapping(em_tree, start, len);
6685 em->bdev = root->fs_info->fs_devices->latest_bdev;
6686 read_unlock(&em_tree->lock);
6689 if (em->start > start || em->start + em->len <= start)
6690 free_extent_map(em);
6691 else if (em->block_start == EXTENT_MAP_INLINE && page)
6692 free_extent_map(em);
6696 em = alloc_extent_map();
6701 em->bdev = root->fs_info->fs_devices->latest_bdev;
6702 em->start = EXTENT_MAP_HOLE;
6703 em->orig_start = EXTENT_MAP_HOLE;
6705 em->block_len = (u64)-1;
6708 path = btrfs_alloc_path();
6714 * Chances are we'll be called again, so go ahead and do
6720 ret = btrfs_lookup_file_extent(trans, root, path,
6721 objectid, start, trans != NULL);
6728 if (path->slots[0] == 0)
6733 leaf = path->nodes[0];
6734 item = btrfs_item_ptr(leaf, path->slots[0],
6735 struct btrfs_file_extent_item);
6736 /* are we inside the extent that was found? */
6737 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6738 found_type = found_key.type;
6739 if (found_key.objectid != objectid ||
6740 found_type != BTRFS_EXTENT_DATA_KEY) {
6742 * If we backup past the first extent we want to move forward
6743 * and see if there is an extent in front of us, otherwise we'll
6744 * say there is a hole for our whole search range which can
6751 found_type = btrfs_file_extent_type(leaf, item);
6752 extent_start = found_key.offset;
6753 if (found_type == BTRFS_FILE_EXTENT_REG ||
6754 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6755 extent_end = extent_start +
6756 btrfs_file_extent_num_bytes(leaf, item);
6757 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6759 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6760 extent_end = ALIGN(extent_start + size, root->sectorsize);
6763 if (start >= extent_end) {
6765 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6766 ret = btrfs_next_leaf(root, path);
6773 leaf = path->nodes[0];
6775 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6776 if (found_key.objectid != objectid ||
6777 found_key.type != BTRFS_EXTENT_DATA_KEY)
6779 if (start + len <= found_key.offset)
6781 if (start > found_key.offset)
6784 em->orig_start = start;
6785 em->len = found_key.offset - start;
6789 btrfs_extent_item_to_extent_map(inode, path, item, new_inline, em);
6791 if (found_type == BTRFS_FILE_EXTENT_REG ||
6792 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6794 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6798 size_t extent_offset;
6804 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6805 extent_offset = page_offset(page) + pg_offset - extent_start;
6806 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6807 size - extent_offset);
6808 em->start = extent_start + extent_offset;
6809 em->len = ALIGN(copy_size, root->sectorsize);
6810 em->orig_block_len = em->len;
6811 em->orig_start = em->start;
6812 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6813 if (create == 0 && !PageUptodate(page)) {
6814 if (btrfs_file_extent_compression(leaf, item) !=
6815 BTRFS_COMPRESS_NONE) {
6816 ret = uncompress_inline(path, inode, page,
6818 extent_offset, item);
6825 read_extent_buffer(leaf, map + pg_offset, ptr,
6827 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6828 memset(map + pg_offset + copy_size, 0,
6829 PAGE_CACHE_SIZE - pg_offset -
6834 flush_dcache_page(page);
6835 } else if (create && PageUptodate(page)) {
6839 free_extent_map(em);
6842 btrfs_release_path(path);
6843 trans = btrfs_join_transaction(root);
6846 return ERR_CAST(trans);
6850 write_extent_buffer(leaf, map + pg_offset, ptr,
6853 btrfs_mark_buffer_dirty(leaf);
6855 set_extent_uptodate(io_tree, em->start,
6856 extent_map_end(em) - 1, NULL, GFP_NOFS);
6861 em->orig_start = start;
6864 em->block_start = EXTENT_MAP_HOLE;
6865 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6867 btrfs_release_path(path);
6868 if (em->start > start || extent_map_end(em) <= start) {
6869 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6870 em->start, em->len, start, len);
6876 write_lock(&em_tree->lock);
6877 ret = add_extent_mapping(em_tree, em, 0);
6878 /* it is possible that someone inserted the extent into the tree
6879 * while we had the lock dropped. It is also possible that
6880 * an overlapping map exists in the tree
6882 if (ret == -EEXIST) {
6883 struct extent_map *existing;
6887 existing = search_extent_mapping(em_tree, start, len);
6889 * existing will always be non-NULL, since there must be
6890 * extent causing the -EEXIST.
6892 if (start >= extent_map_end(existing) ||
6893 start <= existing->start) {
6895 * The existing extent map is the one nearest to
6896 * the [start, start + len) range which overlaps
6898 err = merge_extent_mapping(em_tree, existing,
6900 free_extent_map(existing);
6902 free_extent_map(em);
6906 free_extent_map(em);
6911 write_unlock(&em_tree->lock);
6914 trace_btrfs_get_extent(root, em);
6916 btrfs_free_path(path);
6918 ret = btrfs_end_transaction(trans, root);
6923 free_extent_map(em);
6924 return ERR_PTR(err);
6926 BUG_ON(!em); /* Error is always set */
6930 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6931 size_t pg_offset, u64 start, u64 len,
6934 struct extent_map *em;
6935 struct extent_map *hole_em = NULL;
6936 u64 range_start = start;
6942 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6949 * - a pre-alloc extent,
6950 * there might actually be delalloc bytes behind it.
6952 if (em->block_start != EXTENT_MAP_HOLE &&
6953 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6959 /* check to see if we've wrapped (len == -1 or similar) */
6968 /* ok, we didn't find anything, lets look for delalloc */
6969 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6970 end, len, EXTENT_DELALLOC, 1);
6971 found_end = range_start + found;
6972 if (found_end < range_start)
6973 found_end = (u64)-1;
6976 * we didn't find anything useful, return
6977 * the original results from get_extent()
6979 if (range_start > end || found_end <= start) {
6985 /* adjust the range_start to make sure it doesn't
6986 * go backwards from the start they passed in
6988 range_start = max(start, range_start);
6989 found = found_end - range_start;
6992 u64 hole_start = start;
6995 em = alloc_extent_map();
7001 * when btrfs_get_extent can't find anything it
7002 * returns one huge hole
7004 * make sure what it found really fits our range, and
7005 * adjust to make sure it is based on the start from
7009 u64 calc_end = extent_map_end(hole_em);
7011 if (calc_end <= start || (hole_em->start > end)) {
7012 free_extent_map(hole_em);
7015 hole_start = max(hole_em->start, start);
7016 hole_len = calc_end - hole_start;
7020 if (hole_em && range_start > hole_start) {
7021 /* our hole starts before our delalloc, so we
7022 * have to return just the parts of the hole
7023 * that go until the delalloc starts
7025 em->len = min(hole_len,
7026 range_start - hole_start);
7027 em->start = hole_start;
7028 em->orig_start = hole_start;
7030 * don't adjust block start at all,
7031 * it is fixed at EXTENT_MAP_HOLE
7033 em->block_start = hole_em->block_start;
7034 em->block_len = hole_len;
7035 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7036 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7038 em->start = range_start;
7040 em->orig_start = range_start;
7041 em->block_start = EXTENT_MAP_DELALLOC;
7042 em->block_len = found;
7044 } else if (hole_em) {
7049 free_extent_map(hole_em);
7051 free_extent_map(em);
7052 return ERR_PTR(err);
7057 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7060 struct btrfs_root *root = BTRFS_I(inode)->root;
7061 struct extent_map *em;
7062 struct btrfs_key ins;
7066 alloc_hint = get_extent_allocation_hint(inode, start, len);
7067 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
7068 alloc_hint, &ins, 1, 1);
7070 return ERR_PTR(ret);
7072 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
7073 ins.offset, ins.offset, ins.offset, 0);
7075 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
7079 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
7080 ins.offset, ins.offset, 0);
7082 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
7083 free_extent_map(em);
7084 return ERR_PTR(ret);
7091 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7092 * block must be cow'd
7094 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7095 u64 *orig_start, u64 *orig_block_len,
7098 struct btrfs_trans_handle *trans;
7099 struct btrfs_path *path;
7101 struct extent_buffer *leaf;
7102 struct btrfs_root *root = BTRFS_I(inode)->root;
7103 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7104 struct btrfs_file_extent_item *fi;
7105 struct btrfs_key key;
7112 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7114 path = btrfs_alloc_path();
7118 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
7123 slot = path->slots[0];
7126 /* can't find the item, must cow */
7133 leaf = path->nodes[0];
7134 btrfs_item_key_to_cpu(leaf, &key, slot);
7135 if (key.objectid != btrfs_ino(inode) ||
7136 key.type != BTRFS_EXTENT_DATA_KEY) {
7137 /* not our file or wrong item type, must cow */
7141 if (key.offset > offset) {
7142 /* Wrong offset, must cow */
7146 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7147 found_type = btrfs_file_extent_type(leaf, fi);
7148 if (found_type != BTRFS_FILE_EXTENT_REG &&
7149 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7150 /* not a regular extent, must cow */
7154 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7157 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7158 if (extent_end <= offset)
7161 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7162 if (disk_bytenr == 0)
7165 if (btrfs_file_extent_compression(leaf, fi) ||
7166 btrfs_file_extent_encryption(leaf, fi) ||
7167 btrfs_file_extent_other_encoding(leaf, fi))
7170 backref_offset = btrfs_file_extent_offset(leaf, fi);
7173 *orig_start = key.offset - backref_offset;
7174 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7175 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7178 if (btrfs_extent_readonly(root, disk_bytenr))
7181 num_bytes = min(offset + *len, extent_end) - offset;
7182 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7185 range_end = round_up(offset + num_bytes, root->sectorsize) - 1;
7186 ret = test_range_bit(io_tree, offset, range_end,
7187 EXTENT_DELALLOC, 0, NULL);
7194 btrfs_release_path(path);
7197 * look for other files referencing this extent, if we
7198 * find any we must cow
7200 trans = btrfs_join_transaction(root);
7201 if (IS_ERR(trans)) {
7206 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
7207 key.offset - backref_offset, disk_bytenr);
7208 btrfs_end_transaction(trans, root);
7215 * adjust disk_bytenr and num_bytes to cover just the bytes
7216 * in this extent we are about to write. If there
7217 * are any csums in that range we have to cow in order
7218 * to keep the csums correct
7220 disk_bytenr += backref_offset;
7221 disk_bytenr += offset - key.offset;
7222 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
7225 * all of the above have passed, it is safe to overwrite this extent
7231 btrfs_free_path(path);
7235 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7237 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7239 void **pagep = NULL;
7240 struct page *page = NULL;
7244 start_idx = start >> PAGE_CACHE_SHIFT;
7247 * end is the last byte in the last page. end == start is legal
7249 end_idx = end >> PAGE_CACHE_SHIFT;
7253 /* Most of the code in this while loop is lifted from
7254 * find_get_page. It's been modified to begin searching from a
7255 * page and return just the first page found in that range. If the
7256 * found idx is less than or equal to the end idx then we know that
7257 * a page exists. If no pages are found or if those pages are
7258 * outside of the range then we're fine (yay!) */
7259 while (page == NULL &&
7260 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7261 page = radix_tree_deref_slot(pagep);
7262 if (unlikely(!page))
7265 if (radix_tree_exception(page)) {
7266 if (radix_tree_deref_retry(page)) {
7271 * Otherwise, shmem/tmpfs must be storing a swap entry
7272 * here as an exceptional entry: so return it without
7273 * attempting to raise page count.
7276 break; /* TODO: Is this relevant for this use case? */
7279 if (!page_cache_get_speculative(page)) {
7285 * Has the page moved?
7286 * This is part of the lockless pagecache protocol. See
7287 * include/linux/pagemap.h for details.
7289 if (unlikely(page != *pagep)) {
7290 page_cache_release(page);
7296 if (page->index <= end_idx)
7298 page_cache_release(page);
7305 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7306 struct extent_state **cached_state, int writing)
7308 struct btrfs_ordered_extent *ordered;
7312 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7315 * We're concerned with the entire range that we're going to be
7316 * doing DIO to, so we need to make sure theres no ordered
7317 * extents in this range.
7319 ordered = btrfs_lookup_ordered_range(inode, lockstart,
7320 lockend - lockstart + 1);
7323 * We need to make sure there are no buffered pages in this
7324 * range either, we could have raced between the invalidate in
7325 * generic_file_direct_write and locking the extent. The
7326 * invalidate needs to happen so that reads after a write do not
7331 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7334 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7335 cached_state, GFP_NOFS);
7338 btrfs_start_ordered_extent(inode, ordered, 1);
7339 btrfs_put_ordered_extent(ordered);
7341 /* Screw you mmap */
7342 ret = btrfs_fdatawrite_range(inode, lockstart, lockend);
7345 ret = filemap_fdatawait_range(inode->i_mapping,
7352 * If we found a page that couldn't be invalidated just
7353 * fall back to buffered.
7355 ret = invalidate_inode_pages2_range(inode->i_mapping,
7356 lockstart >> PAGE_CACHE_SHIFT,
7357 lockend >> PAGE_CACHE_SHIFT);
7368 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
7369 u64 len, u64 orig_start,
7370 u64 block_start, u64 block_len,
7371 u64 orig_block_len, u64 ram_bytes,
7374 struct extent_map_tree *em_tree;
7375 struct extent_map *em;
7376 struct btrfs_root *root = BTRFS_I(inode)->root;
7379 em_tree = &BTRFS_I(inode)->extent_tree;
7380 em = alloc_extent_map();
7382 return ERR_PTR(-ENOMEM);
7385 em->orig_start = orig_start;
7386 em->mod_start = start;
7389 em->block_len = block_len;
7390 em->block_start = block_start;
7391 em->bdev = root->fs_info->fs_devices->latest_bdev;
7392 em->orig_block_len = orig_block_len;
7393 em->ram_bytes = ram_bytes;
7394 em->generation = -1;
7395 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7396 if (type == BTRFS_ORDERED_PREALLOC)
7397 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7400 btrfs_drop_extent_cache(inode, em->start,
7401 em->start + em->len - 1, 0);
7402 write_lock(&em_tree->lock);
7403 ret = add_extent_mapping(em_tree, em, 1);
7404 write_unlock(&em_tree->lock);
7405 } while (ret == -EEXIST);
7408 free_extent_map(em);
7409 return ERR_PTR(ret);
7415 struct btrfs_dio_data {
7416 u64 outstanding_extents;
7420 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7421 struct buffer_head *bh_result, int create)
7423 struct extent_map *em;
7424 struct btrfs_root *root = BTRFS_I(inode)->root;
7425 struct extent_state *cached_state = NULL;
7426 struct btrfs_dio_data *dio_data = NULL;
7427 u64 start = iblock << inode->i_blkbits;
7428 u64 lockstart, lockend;
7429 u64 len = bh_result->b_size;
7430 int unlock_bits = EXTENT_LOCKED;
7434 unlock_bits |= EXTENT_DIRTY;
7436 len = min_t(u64, len, root->sectorsize);
7439 lockend = start + len - 1;
7441 if (current->journal_info) {
7443 * Need to pull our outstanding extents and set journal_info to NULL so
7444 * that anything that needs to check if there's a transction doesn't get
7447 dio_data = current->journal_info;
7448 current->journal_info = NULL;
7452 * If this errors out it's because we couldn't invalidate pagecache for
7453 * this range and we need to fallback to buffered.
7455 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
7458 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7465 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7466 * io. INLINE is special, and we could probably kludge it in here, but
7467 * it's still buffered so for safety lets just fall back to the generic
7470 * For COMPRESSED we _have_ to read the entire extent in so we can
7471 * decompress it, so there will be buffering required no matter what we
7472 * do, so go ahead and fallback to buffered.
7474 * We return -ENOTBLK because thats what makes DIO go ahead and go back
7475 * to buffered IO. Don't blame me, this is the price we pay for using
7478 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7479 em->block_start == EXTENT_MAP_INLINE) {
7480 free_extent_map(em);
7485 /* Just a good old fashioned hole, return */
7486 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7487 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7488 free_extent_map(em);
7493 * We don't allocate a new extent in the following cases
7495 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7497 * 2) The extent is marked as PREALLOC. We're good to go here and can
7498 * just use the extent.
7502 len = min(len, em->len - (start - em->start));
7503 lockstart = start + len;
7507 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7508 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7509 em->block_start != EXTENT_MAP_HOLE)) {
7511 u64 block_start, orig_start, orig_block_len, ram_bytes;
7513 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7514 type = BTRFS_ORDERED_PREALLOC;
7516 type = BTRFS_ORDERED_NOCOW;
7517 len = min(len, em->len - (start - em->start));
7518 block_start = em->block_start + (start - em->start);
7520 if (can_nocow_extent(inode, start, &len, &orig_start,
7521 &orig_block_len, &ram_bytes) == 1) {
7522 if (type == BTRFS_ORDERED_PREALLOC) {
7523 free_extent_map(em);
7524 em = create_pinned_em(inode, start, len,
7535 ret = btrfs_add_ordered_extent_dio(inode, start,
7536 block_start, len, len, type);
7538 free_extent_map(em);
7546 * this will cow the extent, reset the len in case we changed
7549 len = bh_result->b_size;
7550 free_extent_map(em);
7551 em = btrfs_new_extent_direct(inode, start, len);
7556 len = min(len, em->len - (start - em->start));
7558 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7560 bh_result->b_size = len;
7561 bh_result->b_bdev = em->bdev;
7562 set_buffer_mapped(bh_result);
7564 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7565 set_buffer_new(bh_result);
7568 * Need to update the i_size under the extent lock so buffered
7569 * readers will get the updated i_size when we unlock.
7571 if (start + len > i_size_read(inode))
7572 i_size_write(inode, start + len);
7575 * If we have an outstanding_extents count still set then we're
7576 * within our reservation, otherwise we need to adjust our inode
7577 * counter appropriately.
7579 if (dio_data->outstanding_extents) {
7580 (dio_data->outstanding_extents)--;
7582 spin_lock(&BTRFS_I(inode)->lock);
7583 BTRFS_I(inode)->outstanding_extents++;
7584 spin_unlock(&BTRFS_I(inode)->lock);
7587 btrfs_free_reserved_data_space(inode, len);
7588 WARN_ON(dio_data->reserve < len);
7589 dio_data->reserve -= len;
7590 current->journal_info = dio_data;
7594 * In the case of write we need to clear and unlock the entire range,
7595 * in the case of read we need to unlock only the end area that we
7596 * aren't using if there is any left over space.
7598 if (lockstart < lockend) {
7599 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7600 lockend, unlock_bits, 1, 0,
7601 &cached_state, GFP_NOFS);
7603 free_extent_state(cached_state);
7606 free_extent_map(em);
7611 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7612 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7614 current->journal_info = dio_data;
7618 static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7619 int rw, int mirror_num)
7621 struct btrfs_root *root = BTRFS_I(inode)->root;
7624 BUG_ON(rw & REQ_WRITE);
7628 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7629 BTRFS_WQ_ENDIO_DIO_REPAIR);
7633 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
7639 static int btrfs_check_dio_repairable(struct inode *inode,
7640 struct bio *failed_bio,
7641 struct io_failure_record *failrec,
7646 num_copies = btrfs_num_copies(BTRFS_I(inode)->root->fs_info,
7647 failrec->logical, failrec->len);
7648 if (num_copies == 1) {
7650 * we only have a single copy of the data, so don't bother with
7651 * all the retry and error correction code that follows. no
7652 * matter what the error is, it is very likely to persist.
7654 pr_debug("Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d\n",
7655 num_copies, failrec->this_mirror, failed_mirror);
7659 failrec->failed_mirror = failed_mirror;
7660 failrec->this_mirror++;
7661 if (failrec->this_mirror == failed_mirror)
7662 failrec->this_mirror++;
7664 if (failrec->this_mirror > num_copies) {
7665 pr_debug("Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d\n",
7666 num_copies, failrec->this_mirror, failed_mirror);
7673 static int dio_read_error(struct inode *inode, struct bio *failed_bio,
7674 struct page *page, u64 start, u64 end,
7675 int failed_mirror, bio_end_io_t *repair_endio,
7678 struct io_failure_record *failrec;
7684 BUG_ON(failed_bio->bi_rw & REQ_WRITE);
7686 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7690 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7693 free_io_failure(inode, failrec);
7697 if (failed_bio->bi_vcnt > 1)
7698 read_mode = READ_SYNC | REQ_FAILFAST_DEV;
7700 read_mode = READ_SYNC;
7702 isector = start - btrfs_io_bio(failed_bio)->logical;
7703 isector >>= inode->i_sb->s_blocksize_bits;
7704 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7705 0, isector, repair_endio, repair_arg);
7707 free_io_failure(inode, failrec);
7711 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7712 "Repair DIO Read Error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d\n",
7713 read_mode, failrec->this_mirror, failrec->in_validation);
7715 ret = submit_dio_repair_bio(inode, bio, read_mode,
7716 failrec->this_mirror);
7718 free_io_failure(inode, failrec);
7725 struct btrfs_retry_complete {
7726 struct completion done;
7727 struct inode *inode;
7732 static void btrfs_retry_endio_nocsum(struct bio *bio)
7734 struct btrfs_retry_complete *done = bio->bi_private;
7735 struct bio_vec *bvec;
7742 bio_for_each_segment_all(bvec, bio, i)
7743 clean_io_failure(done->inode, done->start, bvec->bv_page, 0);
7745 complete(&done->done);
7749 static int __btrfs_correct_data_nocsum(struct inode *inode,
7750 struct btrfs_io_bio *io_bio)
7752 struct bio_vec *bvec;
7753 struct btrfs_retry_complete done;
7758 start = io_bio->logical;
7761 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7765 init_completion(&done.done);
7767 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7768 start + bvec->bv_len - 1,
7770 btrfs_retry_endio_nocsum, &done);
7774 wait_for_completion(&done.done);
7776 if (!done.uptodate) {
7777 /* We might have another mirror, so try again */
7781 start += bvec->bv_len;
7787 static void btrfs_retry_endio(struct bio *bio)
7789 struct btrfs_retry_complete *done = bio->bi_private;
7790 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7791 struct bio_vec *bvec;
7800 bio_for_each_segment_all(bvec, bio, i) {
7801 ret = __readpage_endio_check(done->inode, io_bio, i,
7803 done->start, bvec->bv_len);
7805 clean_io_failure(done->inode, done->start,
7811 done->uptodate = uptodate;
7813 complete(&done->done);
7817 static int __btrfs_subio_endio_read(struct inode *inode,
7818 struct btrfs_io_bio *io_bio, int err)
7820 struct bio_vec *bvec;
7821 struct btrfs_retry_complete done;
7828 start = io_bio->logical;
7831 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7832 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7833 0, start, bvec->bv_len);
7839 init_completion(&done.done);
7841 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7842 start + bvec->bv_len - 1,
7844 btrfs_retry_endio, &done);
7850 wait_for_completion(&done.done);
7852 if (!done.uptodate) {
7853 /* We might have another mirror, so try again */
7857 offset += bvec->bv_len;
7858 start += bvec->bv_len;
7864 static int btrfs_subio_endio_read(struct inode *inode,
7865 struct btrfs_io_bio *io_bio, int err)
7867 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7871 return __btrfs_correct_data_nocsum(inode, io_bio);
7875 return __btrfs_subio_endio_read(inode, io_bio, err);
7879 static void btrfs_endio_direct_read(struct bio *bio)
7881 struct btrfs_dio_private *dip = bio->bi_private;
7882 struct inode *inode = dip->inode;
7883 struct bio *dio_bio;
7884 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7885 int err = bio->bi_error;
7887 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
7888 err = btrfs_subio_endio_read(inode, io_bio, err);
7890 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
7891 dip->logical_offset + dip->bytes - 1);
7892 dio_bio = dip->dio_bio;
7896 dio_end_io(dio_bio, bio->bi_error);
7899 io_bio->end_io(io_bio, err);
7903 static void btrfs_endio_direct_write(struct bio *bio)
7905 struct btrfs_dio_private *dip = bio->bi_private;
7906 struct inode *inode = dip->inode;
7907 struct btrfs_root *root = BTRFS_I(inode)->root;
7908 struct btrfs_ordered_extent *ordered = NULL;
7909 u64 ordered_offset = dip->logical_offset;
7910 u64 ordered_bytes = dip->bytes;
7911 struct bio *dio_bio;
7915 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7922 btrfs_init_work(&ordered->work, btrfs_endio_write_helper,
7923 finish_ordered_fn, NULL, NULL);
7924 btrfs_queue_work(root->fs_info->endio_write_workers,
7928 * our bio might span multiple ordered extents. If we haven't
7929 * completed the accounting for the whole dio, go back and try again
7931 if (ordered_offset < dip->logical_offset + dip->bytes) {
7932 ordered_bytes = dip->logical_offset + dip->bytes -
7937 dio_bio = dip->dio_bio;
7941 dio_end_io(dio_bio, bio->bi_error);
7945 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7946 struct bio *bio, int mirror_num,
7947 unsigned long bio_flags, u64 offset)
7950 struct btrfs_root *root = BTRFS_I(inode)->root;
7951 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7952 BUG_ON(ret); /* -ENOMEM */
7956 static void btrfs_end_dio_bio(struct bio *bio)
7958 struct btrfs_dio_private *dip = bio->bi_private;
7959 int err = bio->bi_error;
7962 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7963 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
7964 btrfs_ino(dip->inode), bio->bi_rw,
7965 (unsigned long long)bio->bi_iter.bi_sector,
7966 bio->bi_iter.bi_size, err);
7968 if (dip->subio_endio)
7969 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
7975 * before atomic variable goto zero, we must make sure
7976 * dip->errors is perceived to be set.
7978 smp_mb__before_atomic();
7981 /* if there are more bios still pending for this dio, just exit */
7982 if (!atomic_dec_and_test(&dip->pending_bios))
7986 bio_io_error(dip->orig_bio);
7988 dip->dio_bio->bi_error = 0;
7989 bio_endio(dip->orig_bio);
7995 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7996 u64 first_sector, gfp_t gfp_flags)
7999 bio = btrfs_bio_alloc(bdev, first_sector, BIO_MAX_PAGES, gfp_flags);
8001 bio_associate_current(bio);
8005 static inline int btrfs_lookup_and_bind_dio_csum(struct btrfs_root *root,
8006 struct inode *inode,
8007 struct btrfs_dio_private *dip,
8011 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8012 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8016 * We load all the csum data we need when we submit
8017 * the first bio to reduce the csum tree search and
8020 if (dip->logical_offset == file_offset) {
8021 ret = btrfs_lookup_bio_sums_dio(root, inode, dip->orig_bio,
8027 if (bio == dip->orig_bio)
8030 file_offset -= dip->logical_offset;
8031 file_offset >>= inode->i_sb->s_blocksize_bits;
8032 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8037 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
8038 int rw, u64 file_offset, int skip_sum,
8041 struct btrfs_dio_private *dip = bio->bi_private;
8042 int write = rw & REQ_WRITE;
8043 struct btrfs_root *root = BTRFS_I(inode)->root;
8047 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8052 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
8053 BTRFS_WQ_ENDIO_DATA);
8061 if (write && async_submit) {
8062 ret = btrfs_wq_submit_bio(root->fs_info,
8063 inode, rw, bio, 0, 0,
8065 __btrfs_submit_bio_start_direct_io,
8066 __btrfs_submit_bio_done);
8070 * If we aren't doing async submit, calculate the csum of the
8073 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
8077 ret = btrfs_lookup_and_bind_dio_csum(root, inode, dip, bio,
8083 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
8089 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
8092 struct inode *inode = dip->inode;
8093 struct btrfs_root *root = BTRFS_I(inode)->root;
8095 struct bio *orig_bio = dip->orig_bio;
8096 struct bio_vec *bvec = orig_bio->bi_io_vec;
8097 u64 start_sector = orig_bio->bi_iter.bi_sector;
8098 u64 file_offset = dip->logical_offset;
8103 int async_submit = 0;
8105 map_length = orig_bio->bi_iter.bi_size;
8106 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
8107 &map_length, NULL, 0);
8111 if (map_length >= orig_bio->bi_iter.bi_size) {
8113 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8117 /* async crcs make it difficult to collect full stripe writes. */
8118 if (btrfs_get_alloc_profile(root, 1) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8123 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
8127 bio->bi_private = dip;
8128 bio->bi_end_io = btrfs_end_dio_bio;
8129 btrfs_io_bio(bio)->logical = file_offset;
8130 atomic_inc(&dip->pending_bios);
8132 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
8133 if (map_length < submit_len + bvec->bv_len ||
8134 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
8135 bvec->bv_offset) < bvec->bv_len) {
8137 * inc the count before we submit the bio so
8138 * we know the end IO handler won't happen before
8139 * we inc the count. Otherwise, the dip might get freed
8140 * before we're done setting it up
8142 atomic_inc(&dip->pending_bios);
8143 ret = __btrfs_submit_dio_bio(bio, inode, rw,
8144 file_offset, skip_sum,
8148 atomic_dec(&dip->pending_bios);
8152 start_sector += submit_len >> 9;
8153 file_offset += submit_len;
8158 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
8159 start_sector, GFP_NOFS);
8162 bio->bi_private = dip;
8163 bio->bi_end_io = btrfs_end_dio_bio;
8164 btrfs_io_bio(bio)->logical = file_offset;
8166 map_length = orig_bio->bi_iter.bi_size;
8167 ret = btrfs_map_block(root->fs_info, rw,
8169 &map_length, NULL, 0);
8175 submit_len += bvec->bv_len;
8182 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
8191 * before atomic variable goto zero, we must
8192 * make sure dip->errors is perceived to be set.
8194 smp_mb__before_atomic();
8195 if (atomic_dec_and_test(&dip->pending_bios))
8196 bio_io_error(dip->orig_bio);
8198 /* bio_end_io() will handle error, so we needn't return it */
8202 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
8203 struct inode *inode, loff_t file_offset)
8205 struct btrfs_dio_private *dip = NULL;
8206 struct bio *io_bio = NULL;
8207 struct btrfs_io_bio *btrfs_bio;
8209 int write = rw & REQ_WRITE;
8212 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8214 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
8220 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8226 dip->private = dio_bio->bi_private;
8228 dip->logical_offset = file_offset;
8229 dip->bytes = dio_bio->bi_iter.bi_size;
8230 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8231 io_bio->bi_private = dip;
8232 dip->orig_bio = io_bio;
8233 dip->dio_bio = dio_bio;
8234 atomic_set(&dip->pending_bios, 0);
8235 btrfs_bio = btrfs_io_bio(io_bio);
8236 btrfs_bio->logical = file_offset;
8239 io_bio->bi_end_io = btrfs_endio_direct_write;
8241 io_bio->bi_end_io = btrfs_endio_direct_read;
8242 dip->subio_endio = btrfs_subio_endio_read;
8245 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
8249 if (btrfs_bio->end_io)
8250 btrfs_bio->end_io(btrfs_bio, ret);
8254 * If we arrived here it means either we failed to submit the dip
8255 * or we either failed to clone the dio_bio or failed to allocate the
8256 * dip. If we cloned the dio_bio and allocated the dip, we can just
8257 * call bio_endio against our io_bio so that we get proper resource
8258 * cleanup if we fail to submit the dip, otherwise, we must do the
8259 * same as btrfs_endio_direct_[write|read] because we can't call these
8260 * callbacks - they require an allocated dip and a clone of dio_bio.
8262 if (io_bio && dip) {
8263 io_bio->bi_error = -EIO;
8266 * The end io callbacks free our dip, do the final put on io_bio
8267 * and all the cleanup and final put for dio_bio (through
8274 struct btrfs_ordered_extent *ordered;
8276 ordered = btrfs_lookup_ordered_extent(inode,
8278 set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
8280 * Decrements our ref on the ordered extent and removes
8281 * the ordered extent from the inode's ordered tree,
8282 * doing all the proper resource cleanup such as for the
8283 * reserved space and waking up any waiters for this
8284 * ordered extent (through btrfs_remove_ordered_extent).
8286 btrfs_finish_ordered_io(ordered);
8288 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8289 file_offset + dio_bio->bi_iter.bi_size - 1);
8291 dio_bio->bi_error = -EIO;
8293 * Releases and cleans up our dio_bio, no need to bio_put()
8294 * nor bio_endio()/bio_io_error() against dio_bio.
8296 dio_end_io(dio_bio, ret);
8303 static ssize_t check_direct_IO(struct btrfs_root *root, struct kiocb *iocb,
8304 const struct iov_iter *iter, loff_t offset)
8308 unsigned blocksize_mask = root->sectorsize - 1;
8309 ssize_t retval = -EINVAL;
8311 if (offset & blocksize_mask)
8314 if (iov_iter_alignment(iter) & blocksize_mask)
8317 /* If this is a write we don't need to check anymore */
8318 if (iov_iter_rw(iter) == WRITE)
8321 * Check to make sure we don't have duplicate iov_base's in this
8322 * iovec, if so return EINVAL, otherwise we'll get csum errors
8323 * when reading back.
8325 for (seg = 0; seg < iter->nr_segs; seg++) {
8326 for (i = seg + 1; i < iter->nr_segs; i++) {
8327 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8336 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
8339 struct file *file = iocb->ki_filp;
8340 struct inode *inode = file->f_mapping->host;
8341 struct btrfs_root *root = BTRFS_I(inode)->root;
8342 struct btrfs_dio_data dio_data = { 0 };
8346 bool relock = false;
8349 if (check_direct_IO(BTRFS_I(inode)->root, iocb, iter, offset))
8352 inode_dio_begin(inode);
8353 smp_mb__after_atomic();
8356 * The generic stuff only does filemap_write_and_wait_range, which
8357 * isn't enough if we've written compressed pages to this area, so
8358 * we need to flush the dirty pages again to make absolutely sure
8359 * that any outstanding dirty pages are on disk.
8361 count = iov_iter_count(iter);
8362 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8363 &BTRFS_I(inode)->runtime_flags))
8364 filemap_fdatawrite_range(inode->i_mapping, offset,
8365 offset + count - 1);
8367 if (iov_iter_rw(iter) == WRITE) {
8369 * If the write DIO is beyond the EOF, we need update
8370 * the isize, but it is protected by i_mutex. So we can
8371 * not unlock the i_mutex at this case.
8373 if (offset + count <= inode->i_size) {
8374 mutex_unlock(&inode->i_mutex);
8377 ret = btrfs_delalloc_reserve_space(inode, count);
8380 dio_data.outstanding_extents = div64_u64(count +
8381 BTRFS_MAX_EXTENT_SIZE - 1,
8382 BTRFS_MAX_EXTENT_SIZE);
8385 * We need to know how many extents we reserved so that we can
8386 * do the accounting properly if we go over the number we
8387 * originally calculated. Abuse current->journal_info for this.
8389 dio_data.reserve = round_up(count, root->sectorsize);
8390 current->journal_info = &dio_data;
8391 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8392 &BTRFS_I(inode)->runtime_flags)) {
8393 inode_dio_end(inode);
8394 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8398 ret = __blockdev_direct_IO(iocb, inode,
8399 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
8400 iter, offset, btrfs_get_blocks_direct, NULL,
8401 btrfs_submit_direct, flags);
8402 if (iov_iter_rw(iter) == WRITE) {
8403 current->journal_info = NULL;
8404 if (ret < 0 && ret != -EIOCBQUEUED) {
8405 if (dio_data.reserve)
8406 btrfs_delalloc_release_space(inode,
8408 } else if (ret >= 0 && (size_t)ret < count)
8409 btrfs_delalloc_release_space(inode,
8410 count - (size_t)ret);
8414 inode_dio_end(inode);
8416 mutex_lock(&inode->i_mutex);
8421 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8423 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8424 __u64 start, __u64 len)
8428 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8432 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
8435 int btrfs_readpage(struct file *file, struct page *page)
8437 struct extent_io_tree *tree;
8438 tree = &BTRFS_I(page->mapping->host)->io_tree;
8439 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8442 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8444 struct extent_io_tree *tree;
8447 if (current->flags & PF_MEMALLOC) {
8448 redirty_page_for_writepage(wbc, page);
8452 tree = &BTRFS_I(page->mapping->host)->io_tree;
8453 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
8456 static int btrfs_writepages(struct address_space *mapping,
8457 struct writeback_control *wbc)
8459 struct extent_io_tree *tree;
8461 tree = &BTRFS_I(mapping->host)->io_tree;
8462 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8466 btrfs_readpages(struct file *file, struct address_space *mapping,
8467 struct list_head *pages, unsigned nr_pages)
8469 struct extent_io_tree *tree;
8470 tree = &BTRFS_I(mapping->host)->io_tree;
8471 return extent_readpages(tree, mapping, pages, nr_pages,
8474 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8476 struct extent_io_tree *tree;
8477 struct extent_map_tree *map;
8480 tree = &BTRFS_I(page->mapping->host)->io_tree;
8481 map = &BTRFS_I(page->mapping->host)->extent_tree;
8482 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8484 ClearPagePrivate(page);
8485 set_page_private(page, 0);
8486 page_cache_release(page);
8491 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8493 if (PageWriteback(page) || PageDirty(page))
8495 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
8498 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8499 unsigned int length)
8501 struct inode *inode = page->mapping->host;
8502 struct extent_io_tree *tree;
8503 struct btrfs_ordered_extent *ordered;
8504 struct extent_state *cached_state = NULL;
8505 u64 page_start = page_offset(page);
8506 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
8507 int inode_evicting = inode->i_state & I_FREEING;
8510 * we have the page locked, so new writeback can't start,
8511 * and the dirty bit won't be cleared while we are here.
8513 * Wait for IO on this page so that we can safely clear
8514 * the PagePrivate2 bit and do ordered accounting
8516 wait_on_page_writeback(page);
8518 tree = &BTRFS_I(inode)->io_tree;
8520 btrfs_releasepage(page, GFP_NOFS);
8524 if (!inode_evicting)
8525 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
8526 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8529 * IO on this page will never be started, so we need
8530 * to account for any ordered extents now
8532 if (!inode_evicting)
8533 clear_extent_bit(tree, page_start, page_end,
8534 EXTENT_DIRTY | EXTENT_DELALLOC |
8535 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8536 EXTENT_DEFRAG, 1, 0, &cached_state,
8539 * whoever cleared the private bit is responsible
8540 * for the finish_ordered_io
8542 if (TestClearPagePrivate2(page)) {
8543 struct btrfs_ordered_inode_tree *tree;
8546 tree = &BTRFS_I(inode)->ordered_tree;
8548 spin_lock_irq(&tree->lock);
8549 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8550 new_len = page_start - ordered->file_offset;
8551 if (new_len < ordered->truncated_len)
8552 ordered->truncated_len = new_len;
8553 spin_unlock_irq(&tree->lock);
8555 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8557 PAGE_CACHE_SIZE, 1))
8558 btrfs_finish_ordered_io(ordered);
8560 btrfs_put_ordered_extent(ordered);
8561 if (!inode_evicting) {
8562 cached_state = NULL;
8563 lock_extent_bits(tree, page_start, page_end, 0,
8568 if (!inode_evicting) {
8569 clear_extent_bit(tree, page_start, page_end,
8570 EXTENT_LOCKED | EXTENT_DIRTY |
8571 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8572 EXTENT_DEFRAG, 1, 1,
8573 &cached_state, GFP_NOFS);
8575 __btrfs_releasepage(page, GFP_NOFS);
8578 ClearPageChecked(page);
8579 if (PagePrivate(page)) {
8580 ClearPagePrivate(page);
8581 set_page_private(page, 0);
8582 page_cache_release(page);
8587 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8588 * called from a page fault handler when a page is first dirtied. Hence we must
8589 * be careful to check for EOF conditions here. We set the page up correctly
8590 * for a written page which means we get ENOSPC checking when writing into
8591 * holes and correct delalloc and unwritten extent mapping on filesystems that
8592 * support these features.
8594 * We are not allowed to take the i_mutex here so we have to play games to
8595 * protect against truncate races as the page could now be beyond EOF. Because
8596 * vmtruncate() writes the inode size before removing pages, once we have the
8597 * page lock we can determine safely if the page is beyond EOF. If it is not
8598 * beyond EOF, then the page is guaranteed safe against truncation until we
8601 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
8603 struct page *page = vmf->page;
8604 struct inode *inode = file_inode(vma->vm_file);
8605 struct btrfs_root *root = BTRFS_I(inode)->root;
8606 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8607 struct btrfs_ordered_extent *ordered;
8608 struct extent_state *cached_state = NULL;
8610 unsigned long zero_start;
8617 sb_start_pagefault(inode->i_sb);
8618 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
8620 ret = file_update_time(vma->vm_file);
8626 else /* -ENOSPC, -EIO, etc */
8627 ret = VM_FAULT_SIGBUS;
8633 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8636 size = i_size_read(inode);
8637 page_start = page_offset(page);
8638 page_end = page_start + PAGE_CACHE_SIZE - 1;
8640 if ((page->mapping != inode->i_mapping) ||
8641 (page_start >= size)) {
8642 /* page got truncated out from underneath us */
8645 wait_on_page_writeback(page);
8647 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
8648 set_page_extent_mapped(page);
8651 * we can't set the delalloc bits if there are pending ordered
8652 * extents. Drop our locks and wait for them to finish
8654 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8656 unlock_extent_cached(io_tree, page_start, page_end,
8657 &cached_state, GFP_NOFS);
8659 btrfs_start_ordered_extent(inode, ordered, 1);
8660 btrfs_put_ordered_extent(ordered);
8665 * XXX - page_mkwrite gets called every time the page is dirtied, even
8666 * if it was already dirty, so for space accounting reasons we need to
8667 * clear any delalloc bits for the range we are fixing to save. There
8668 * is probably a better way to do this, but for now keep consistent with
8669 * prepare_pages in the normal write path.
8671 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
8672 EXTENT_DIRTY | EXTENT_DELALLOC |
8673 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8674 0, 0, &cached_state, GFP_NOFS);
8676 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
8679 unlock_extent_cached(io_tree, page_start, page_end,
8680 &cached_state, GFP_NOFS);
8681 ret = VM_FAULT_SIGBUS;
8686 /* page is wholly or partially inside EOF */
8687 if (page_start + PAGE_CACHE_SIZE > size)
8688 zero_start = size & ~PAGE_CACHE_MASK;
8690 zero_start = PAGE_CACHE_SIZE;
8692 if (zero_start != PAGE_CACHE_SIZE) {
8694 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
8695 flush_dcache_page(page);
8698 ClearPageChecked(page);
8699 set_page_dirty(page);
8700 SetPageUptodate(page);
8702 BTRFS_I(inode)->last_trans = root->fs_info->generation;
8703 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8704 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8706 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
8710 sb_end_pagefault(inode->i_sb);
8711 return VM_FAULT_LOCKED;
8715 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
8717 sb_end_pagefault(inode->i_sb);
8721 static int btrfs_truncate(struct inode *inode)
8723 struct btrfs_root *root = BTRFS_I(inode)->root;
8724 struct btrfs_block_rsv *rsv;
8727 struct btrfs_trans_handle *trans;
8728 u64 mask = root->sectorsize - 1;
8729 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
8731 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8737 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
8738 * 3 things going on here
8740 * 1) We need to reserve space for our orphan item and the space to
8741 * delete our orphan item. Lord knows we don't want to have a dangling
8742 * orphan item because we didn't reserve space to remove it.
8744 * 2) We need to reserve space to update our inode.
8746 * 3) We need to have something to cache all the space that is going to
8747 * be free'd up by the truncate operation, but also have some slack
8748 * space reserved in case it uses space during the truncate (thank you
8749 * very much snapshotting).
8751 * And we need these to all be seperate. The fact is we can use alot of
8752 * space doing the truncate, and we have no earthly idea how much space
8753 * we will use, so we need the truncate reservation to be seperate so it
8754 * doesn't end up using space reserved for updating the inode or
8755 * removing the orphan item. We also need to be able to stop the
8756 * transaction and start a new one, which means we need to be able to
8757 * update the inode several times, and we have no idea of knowing how
8758 * many times that will be, so we can't just reserve 1 item for the
8759 * entirety of the opration, so that has to be done seperately as well.
8760 * Then there is the orphan item, which does indeed need to be held on
8761 * to for the whole operation, and we need nobody to touch this reserved
8762 * space except the orphan code.
8764 * So that leaves us with
8766 * 1) root->orphan_block_rsv - for the orphan deletion.
8767 * 2) rsv - for the truncate reservation, which we will steal from the
8768 * transaction reservation.
8769 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
8770 * updating the inode.
8772 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
8775 rsv->size = min_size;
8779 * 1 for the truncate slack space
8780 * 1 for updating the inode.
8782 trans = btrfs_start_transaction(root, 2);
8783 if (IS_ERR(trans)) {
8784 err = PTR_ERR(trans);
8788 /* Migrate the slack space for the truncate to our reserve */
8789 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
8794 * So if we truncate and then write and fsync we normally would just
8795 * write the extents that changed, which is a problem if we need to
8796 * first truncate that entire inode. So set this flag so we write out
8797 * all of the extents in the inode to the sync log so we're completely
8800 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8801 trans->block_rsv = rsv;
8804 ret = btrfs_truncate_inode_items(trans, root, inode,
8806 BTRFS_EXTENT_DATA_KEY);
8807 if (ret != -ENOSPC && ret != -EAGAIN) {
8812 trans->block_rsv = &root->fs_info->trans_block_rsv;
8813 ret = btrfs_update_inode(trans, root, inode);
8819 btrfs_end_transaction(trans, root);
8820 btrfs_btree_balance_dirty(root);
8822 trans = btrfs_start_transaction(root, 2);
8823 if (IS_ERR(trans)) {
8824 ret = err = PTR_ERR(trans);
8829 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
8831 BUG_ON(ret); /* shouldn't happen */
8832 trans->block_rsv = rsv;
8835 if (ret == 0 && inode->i_nlink > 0) {
8836 trans->block_rsv = root->orphan_block_rsv;
8837 ret = btrfs_orphan_del(trans, inode);
8843 trans->block_rsv = &root->fs_info->trans_block_rsv;
8844 ret = btrfs_update_inode(trans, root, inode);
8848 ret = btrfs_end_transaction(trans, root);
8849 btrfs_btree_balance_dirty(root);
8853 btrfs_free_block_rsv(root, rsv);
8862 * create a new subvolume directory/inode (helper for the ioctl).
8864 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8865 struct btrfs_root *new_root,
8866 struct btrfs_root *parent_root,
8869 struct inode *inode;
8873 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8874 new_dirid, new_dirid,
8875 S_IFDIR | (~current_umask() & S_IRWXUGO),
8878 return PTR_ERR(inode);
8879 inode->i_op = &btrfs_dir_inode_operations;
8880 inode->i_fop = &btrfs_dir_file_operations;
8882 set_nlink(inode, 1);
8883 btrfs_i_size_write(inode, 0);
8884 unlock_new_inode(inode);
8886 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8888 btrfs_err(new_root->fs_info,
8889 "error inheriting subvolume %llu properties: %d",
8890 new_root->root_key.objectid, err);
8892 err = btrfs_update_inode(trans, new_root, inode);
8898 struct inode *btrfs_alloc_inode(struct super_block *sb)
8900 struct btrfs_inode *ei;
8901 struct inode *inode;
8903 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
8910 ei->last_sub_trans = 0;
8911 ei->logged_trans = 0;
8912 ei->delalloc_bytes = 0;
8913 ei->defrag_bytes = 0;
8914 ei->disk_i_size = 0;
8917 ei->index_cnt = (u64)-1;
8919 ei->last_unlink_trans = 0;
8920 ei->last_log_commit = 0;
8922 spin_lock_init(&ei->lock);
8923 ei->outstanding_extents = 0;
8924 ei->reserved_extents = 0;
8926 ei->runtime_flags = 0;
8927 ei->force_compress = BTRFS_COMPRESS_NONE;
8929 ei->delayed_node = NULL;
8931 ei->i_otime.tv_sec = 0;
8932 ei->i_otime.tv_nsec = 0;
8934 inode = &ei->vfs_inode;
8935 extent_map_tree_init(&ei->extent_tree);
8936 extent_io_tree_init(&ei->io_tree, &inode->i_data);
8937 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
8938 ei->io_tree.track_uptodate = 1;
8939 ei->io_failure_tree.track_uptodate = 1;
8940 atomic_set(&ei->sync_writers, 0);
8941 mutex_init(&ei->log_mutex);
8942 mutex_init(&ei->delalloc_mutex);
8943 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8944 INIT_LIST_HEAD(&ei->delalloc_inodes);
8945 RB_CLEAR_NODE(&ei->rb_node);
8950 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8951 void btrfs_test_destroy_inode(struct inode *inode)
8953 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8954 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8958 static void btrfs_i_callback(struct rcu_head *head)
8960 struct inode *inode = container_of(head, struct inode, i_rcu);
8961 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8964 void btrfs_destroy_inode(struct inode *inode)
8966 struct btrfs_ordered_extent *ordered;
8967 struct btrfs_root *root = BTRFS_I(inode)->root;
8969 WARN_ON(!hlist_empty(&inode->i_dentry));
8970 WARN_ON(inode->i_data.nrpages);
8971 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8972 WARN_ON(BTRFS_I(inode)->reserved_extents);
8973 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8974 WARN_ON(BTRFS_I(inode)->csum_bytes);
8975 WARN_ON(BTRFS_I(inode)->defrag_bytes);
8978 * This can happen where we create an inode, but somebody else also
8979 * created the same inode and we need to destroy the one we already
8985 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8986 &BTRFS_I(inode)->runtime_flags)) {
8987 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
8989 atomic_dec(&root->orphan_inodes);
8993 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8997 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
8998 ordered->file_offset, ordered->len);
8999 btrfs_remove_ordered_extent(inode, ordered);
9000 btrfs_put_ordered_extent(ordered);
9001 btrfs_put_ordered_extent(ordered);
9004 inode_tree_del(inode);
9005 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
9007 call_rcu(&inode->i_rcu, btrfs_i_callback);
9010 int btrfs_drop_inode(struct inode *inode)
9012 struct btrfs_root *root = BTRFS_I(inode)->root;
9017 /* the snap/subvol tree is on deleting */
9018 if (btrfs_root_refs(&root->root_item) == 0)
9021 return generic_drop_inode(inode);
9024 static void init_once(void *foo)
9026 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9028 inode_init_once(&ei->vfs_inode);
9031 void btrfs_destroy_cachep(void)
9034 * Make sure all delayed rcu free inodes are flushed before we
9038 if (btrfs_inode_cachep)
9039 kmem_cache_destroy(btrfs_inode_cachep);
9040 if (btrfs_trans_handle_cachep)
9041 kmem_cache_destroy(btrfs_trans_handle_cachep);
9042 if (btrfs_transaction_cachep)
9043 kmem_cache_destroy(btrfs_transaction_cachep);
9044 if (btrfs_path_cachep)
9045 kmem_cache_destroy(btrfs_path_cachep);
9046 if (btrfs_free_space_cachep)
9047 kmem_cache_destroy(btrfs_free_space_cachep);
9048 if (btrfs_delalloc_work_cachep)
9049 kmem_cache_destroy(btrfs_delalloc_work_cachep);
9052 int btrfs_init_cachep(void)
9054 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9055 sizeof(struct btrfs_inode), 0,
9056 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
9057 if (!btrfs_inode_cachep)
9060 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9061 sizeof(struct btrfs_trans_handle), 0,
9062 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
9063 if (!btrfs_trans_handle_cachep)
9066 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
9067 sizeof(struct btrfs_transaction), 0,
9068 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
9069 if (!btrfs_transaction_cachep)
9072 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9073 sizeof(struct btrfs_path), 0,
9074 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
9075 if (!btrfs_path_cachep)
9078 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9079 sizeof(struct btrfs_free_space), 0,
9080 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
9081 if (!btrfs_free_space_cachep)
9084 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
9085 sizeof(struct btrfs_delalloc_work), 0,
9086 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
9088 if (!btrfs_delalloc_work_cachep)
9093 btrfs_destroy_cachep();
9097 static int btrfs_getattr(struct vfsmount *mnt,
9098 struct dentry *dentry, struct kstat *stat)
9101 struct inode *inode = d_inode(dentry);
9102 u32 blocksize = inode->i_sb->s_blocksize;
9104 generic_fillattr(inode, stat);
9105 stat->dev = BTRFS_I(inode)->root->anon_dev;
9106 stat->blksize = PAGE_CACHE_SIZE;
9108 spin_lock(&BTRFS_I(inode)->lock);
9109 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
9110 spin_unlock(&BTRFS_I(inode)->lock);
9111 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9112 ALIGN(delalloc_bytes, blocksize)) >> 9;
9116 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9117 struct inode *new_dir, struct dentry *new_dentry)
9119 struct btrfs_trans_handle *trans;
9120 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9121 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9122 struct inode *new_inode = d_inode(new_dentry);
9123 struct inode *old_inode = d_inode(old_dentry);
9124 struct timespec ctime = CURRENT_TIME;
9128 u64 old_ino = btrfs_ino(old_inode);
9130 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9133 /* we only allow rename subvolume link between subvolumes */
9134 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9137 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9138 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
9141 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9142 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9146 /* check for collisions, even if the name isn't there */
9147 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9148 new_dentry->d_name.name,
9149 new_dentry->d_name.len);
9152 if (ret == -EEXIST) {
9154 * eexist without a new_inode */
9155 if (WARN_ON(!new_inode)) {
9159 /* maybe -EOVERFLOW */
9166 * we're using rename to replace one file with another. Start IO on it
9167 * now so we don't add too much work to the end of the transaction
9169 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9170 filemap_flush(old_inode->i_mapping);
9172 /* close the racy window with snapshot create/destroy ioctl */
9173 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9174 down_read(&root->fs_info->subvol_sem);
9176 * We want to reserve the absolute worst case amount of items. So if
9177 * both inodes are subvols and we need to unlink them then that would
9178 * require 4 item modifications, but if they are both normal inodes it
9179 * would require 5 item modifications, so we'll assume their normal
9180 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9181 * should cover the worst case number of items we'll modify.
9183 trans = btrfs_start_transaction(root, 11);
9184 if (IS_ERR(trans)) {
9185 ret = PTR_ERR(trans);
9190 btrfs_record_root_in_trans(trans, dest);
9192 ret = btrfs_set_inode_index(new_dir, &index);
9196 BTRFS_I(old_inode)->dir_index = 0ULL;
9197 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9198 /* force full log commit if subvolume involved. */
9199 btrfs_set_log_full_commit(root->fs_info, trans);
9201 ret = btrfs_insert_inode_ref(trans, dest,
9202 new_dentry->d_name.name,
9203 new_dentry->d_name.len,
9205 btrfs_ino(new_dir), index);
9209 * this is an ugly little race, but the rename is required
9210 * to make sure that if we crash, the inode is either at the
9211 * old name or the new one. pinning the log transaction lets
9212 * us make sure we don't allow a log commit to come in after
9213 * we unlink the name but before we add the new name back in.
9215 btrfs_pin_log_trans(root);
9218 inode_inc_iversion(old_dir);
9219 inode_inc_iversion(new_dir);
9220 inode_inc_iversion(old_inode);
9221 old_dir->i_ctime = old_dir->i_mtime = ctime;
9222 new_dir->i_ctime = new_dir->i_mtime = ctime;
9223 old_inode->i_ctime = ctime;
9225 if (old_dentry->d_parent != new_dentry->d_parent)
9226 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
9228 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9229 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9230 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9231 old_dentry->d_name.name,
9232 old_dentry->d_name.len);
9234 ret = __btrfs_unlink_inode(trans, root, old_dir,
9235 d_inode(old_dentry),
9236 old_dentry->d_name.name,
9237 old_dentry->d_name.len);
9239 ret = btrfs_update_inode(trans, root, old_inode);
9242 btrfs_abort_transaction(trans, root, ret);
9247 inode_inc_iversion(new_inode);
9248 new_inode->i_ctime = CURRENT_TIME;
9249 if (unlikely(btrfs_ino(new_inode) ==
9250 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9251 root_objectid = BTRFS_I(new_inode)->location.objectid;
9252 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9254 new_dentry->d_name.name,
9255 new_dentry->d_name.len);
9256 BUG_ON(new_inode->i_nlink == 0);
9258 ret = btrfs_unlink_inode(trans, dest, new_dir,
9259 d_inode(new_dentry),
9260 new_dentry->d_name.name,
9261 new_dentry->d_name.len);
9263 if (!ret && new_inode->i_nlink == 0)
9264 ret = btrfs_orphan_add(trans, d_inode(new_dentry));
9266 btrfs_abort_transaction(trans, root, ret);
9271 ret = btrfs_add_link(trans, new_dir, old_inode,
9272 new_dentry->d_name.name,
9273 new_dentry->d_name.len, 0, index);
9275 btrfs_abort_transaction(trans, root, ret);
9279 if (old_inode->i_nlink == 1)
9280 BTRFS_I(old_inode)->dir_index = index;
9282 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
9283 struct dentry *parent = new_dentry->d_parent;
9284 btrfs_log_new_name(trans, old_inode, old_dir, parent);
9285 btrfs_end_log_trans(root);
9288 btrfs_end_transaction(trans, root);
9290 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9291 up_read(&root->fs_info->subvol_sem);
9296 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9297 struct inode *new_dir, struct dentry *new_dentry,
9300 if (flags & ~RENAME_NOREPLACE)
9303 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry);
9306 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9308 struct btrfs_delalloc_work *delalloc_work;
9309 struct inode *inode;
9311 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9313 inode = delalloc_work->inode;
9314 if (delalloc_work->wait) {
9315 btrfs_wait_ordered_range(inode, 0, (u64)-1);
9317 filemap_flush(inode->i_mapping);
9318 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9319 &BTRFS_I(inode)->runtime_flags))
9320 filemap_flush(inode->i_mapping);
9323 if (delalloc_work->delay_iput)
9324 btrfs_add_delayed_iput(inode);
9327 complete(&delalloc_work->completion);
9330 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
9331 int wait, int delay_iput)
9333 struct btrfs_delalloc_work *work;
9335 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
9339 init_completion(&work->completion);
9340 INIT_LIST_HEAD(&work->list);
9341 work->inode = inode;
9343 work->delay_iput = delay_iput;
9344 WARN_ON_ONCE(!inode);
9345 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9346 btrfs_run_delalloc_work, NULL, NULL);
9351 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
9353 wait_for_completion(&work->completion);
9354 kmem_cache_free(btrfs_delalloc_work_cachep, work);
9358 * some fairly slow code that needs optimization. This walks the list
9359 * of all the inodes with pending delalloc and forces them to disk.
9361 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
9364 struct btrfs_inode *binode;
9365 struct inode *inode;
9366 struct btrfs_delalloc_work *work, *next;
9367 struct list_head works;
9368 struct list_head splice;
9371 INIT_LIST_HEAD(&works);
9372 INIT_LIST_HEAD(&splice);
9374 mutex_lock(&root->delalloc_mutex);
9375 spin_lock(&root->delalloc_lock);
9376 list_splice_init(&root->delalloc_inodes, &splice);
9377 while (!list_empty(&splice)) {
9378 binode = list_entry(splice.next, struct btrfs_inode,
9381 list_move_tail(&binode->delalloc_inodes,
9382 &root->delalloc_inodes);
9383 inode = igrab(&binode->vfs_inode);
9385 cond_resched_lock(&root->delalloc_lock);
9388 spin_unlock(&root->delalloc_lock);
9390 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
9393 btrfs_add_delayed_iput(inode);
9399 list_add_tail(&work->list, &works);
9400 btrfs_queue_work(root->fs_info->flush_workers,
9403 if (nr != -1 && ret >= nr)
9406 spin_lock(&root->delalloc_lock);
9408 spin_unlock(&root->delalloc_lock);
9411 list_for_each_entry_safe(work, next, &works, list) {
9412 list_del_init(&work->list);
9413 btrfs_wait_and_free_delalloc_work(work);
9416 if (!list_empty_careful(&splice)) {
9417 spin_lock(&root->delalloc_lock);
9418 list_splice_tail(&splice, &root->delalloc_inodes);
9419 spin_unlock(&root->delalloc_lock);
9421 mutex_unlock(&root->delalloc_mutex);
9425 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
9429 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
9432 ret = __start_delalloc_inodes(root, delay_iput, -1);
9436 * the filemap_flush will queue IO into the worker threads, but
9437 * we have to make sure the IO is actually started and that
9438 * ordered extents get created before we return
9440 atomic_inc(&root->fs_info->async_submit_draining);
9441 while (atomic_read(&root->fs_info->nr_async_submits) ||
9442 atomic_read(&root->fs_info->async_delalloc_pages)) {
9443 wait_event(root->fs_info->async_submit_wait,
9444 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
9445 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
9447 atomic_dec(&root->fs_info->async_submit_draining);
9451 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
9454 struct btrfs_root *root;
9455 struct list_head splice;
9458 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9461 INIT_LIST_HEAD(&splice);
9463 mutex_lock(&fs_info->delalloc_root_mutex);
9464 spin_lock(&fs_info->delalloc_root_lock);
9465 list_splice_init(&fs_info->delalloc_roots, &splice);
9466 while (!list_empty(&splice) && nr) {
9467 root = list_first_entry(&splice, struct btrfs_root,
9469 root = btrfs_grab_fs_root(root);
9471 list_move_tail(&root->delalloc_root,
9472 &fs_info->delalloc_roots);
9473 spin_unlock(&fs_info->delalloc_root_lock);
9475 ret = __start_delalloc_inodes(root, delay_iput, nr);
9476 btrfs_put_fs_root(root);
9484 spin_lock(&fs_info->delalloc_root_lock);
9486 spin_unlock(&fs_info->delalloc_root_lock);
9489 atomic_inc(&fs_info->async_submit_draining);
9490 while (atomic_read(&fs_info->nr_async_submits) ||
9491 atomic_read(&fs_info->async_delalloc_pages)) {
9492 wait_event(fs_info->async_submit_wait,
9493 (atomic_read(&fs_info->nr_async_submits) == 0 &&
9494 atomic_read(&fs_info->async_delalloc_pages) == 0));
9496 atomic_dec(&fs_info->async_submit_draining);
9498 if (!list_empty_careful(&splice)) {
9499 spin_lock(&fs_info->delalloc_root_lock);
9500 list_splice_tail(&splice, &fs_info->delalloc_roots);
9501 spin_unlock(&fs_info->delalloc_root_lock);
9503 mutex_unlock(&fs_info->delalloc_root_mutex);
9507 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9508 const char *symname)
9510 struct btrfs_trans_handle *trans;
9511 struct btrfs_root *root = BTRFS_I(dir)->root;
9512 struct btrfs_path *path;
9513 struct btrfs_key key;
9514 struct inode *inode = NULL;
9522 struct btrfs_file_extent_item *ei;
9523 struct extent_buffer *leaf;
9525 name_len = strlen(symname);
9526 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
9527 return -ENAMETOOLONG;
9530 * 2 items for inode item and ref
9531 * 2 items for dir items
9532 * 1 item for xattr if selinux is on
9534 trans = btrfs_start_transaction(root, 5);
9536 return PTR_ERR(trans);
9538 err = btrfs_find_free_ino(root, &objectid);
9542 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9543 dentry->d_name.len, btrfs_ino(dir), objectid,
9544 S_IFLNK|S_IRWXUGO, &index);
9545 if (IS_ERR(inode)) {
9546 err = PTR_ERR(inode);
9551 * If the active LSM wants to access the inode during
9552 * d_instantiate it needs these. Smack checks to see
9553 * if the filesystem supports xattrs by looking at the
9556 inode->i_fop = &btrfs_file_operations;
9557 inode->i_op = &btrfs_file_inode_operations;
9558 inode->i_mapping->a_ops = &btrfs_aops;
9559 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9561 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9563 goto out_unlock_inode;
9565 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
9567 goto out_unlock_inode;
9569 path = btrfs_alloc_path();
9572 goto out_unlock_inode;
9574 key.objectid = btrfs_ino(inode);
9576 key.type = BTRFS_EXTENT_DATA_KEY;
9577 datasize = btrfs_file_extent_calc_inline_size(name_len);
9578 err = btrfs_insert_empty_item(trans, root, path, &key,
9581 btrfs_free_path(path);
9582 goto out_unlock_inode;
9584 leaf = path->nodes[0];
9585 ei = btrfs_item_ptr(leaf, path->slots[0],
9586 struct btrfs_file_extent_item);
9587 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9588 btrfs_set_file_extent_type(leaf, ei,
9589 BTRFS_FILE_EXTENT_INLINE);
9590 btrfs_set_file_extent_encryption(leaf, ei, 0);
9591 btrfs_set_file_extent_compression(leaf, ei, 0);
9592 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9593 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9595 ptr = btrfs_file_extent_inline_start(ei);
9596 write_extent_buffer(leaf, symname, ptr, name_len);
9597 btrfs_mark_buffer_dirty(leaf);
9598 btrfs_free_path(path);
9600 inode->i_op = &btrfs_symlink_inode_operations;
9601 inode->i_mapping->a_ops = &btrfs_symlink_aops;
9602 inode_set_bytes(inode, name_len);
9603 btrfs_i_size_write(inode, name_len);
9604 err = btrfs_update_inode(trans, root, inode);
9607 goto out_unlock_inode;
9610 unlock_new_inode(inode);
9611 d_instantiate(dentry, inode);
9614 btrfs_end_transaction(trans, root);
9616 inode_dec_link_count(inode);
9619 btrfs_btree_balance_dirty(root);
9624 unlock_new_inode(inode);
9628 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9629 u64 start, u64 num_bytes, u64 min_size,
9630 loff_t actual_len, u64 *alloc_hint,
9631 struct btrfs_trans_handle *trans)
9633 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9634 struct extent_map *em;
9635 struct btrfs_root *root = BTRFS_I(inode)->root;
9636 struct btrfs_key ins;
9637 u64 cur_offset = start;
9641 bool own_trans = true;
9645 while (num_bytes > 0) {
9647 trans = btrfs_start_transaction(root, 3);
9648 if (IS_ERR(trans)) {
9649 ret = PTR_ERR(trans);
9654 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
9655 cur_bytes = max(cur_bytes, min_size);
9656 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
9657 *alloc_hint, &ins, 1, 0);
9660 btrfs_end_transaction(trans, root);
9664 ret = insert_reserved_file_extent(trans, inode,
9665 cur_offset, ins.objectid,
9666 ins.offset, ins.offset,
9667 ins.offset, 0, 0, 0,
9668 BTRFS_FILE_EXTENT_PREALLOC);
9670 btrfs_free_reserved_extent(root, ins.objectid,
9672 btrfs_abort_transaction(trans, root, ret);
9674 btrfs_end_transaction(trans, root);
9678 btrfs_drop_extent_cache(inode, cur_offset,
9679 cur_offset + ins.offset -1, 0);
9681 em = alloc_extent_map();
9683 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9684 &BTRFS_I(inode)->runtime_flags);
9688 em->start = cur_offset;
9689 em->orig_start = cur_offset;
9690 em->len = ins.offset;
9691 em->block_start = ins.objectid;
9692 em->block_len = ins.offset;
9693 em->orig_block_len = ins.offset;
9694 em->ram_bytes = ins.offset;
9695 em->bdev = root->fs_info->fs_devices->latest_bdev;
9696 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9697 em->generation = trans->transid;
9700 write_lock(&em_tree->lock);
9701 ret = add_extent_mapping(em_tree, em, 1);
9702 write_unlock(&em_tree->lock);
9705 btrfs_drop_extent_cache(inode, cur_offset,
9706 cur_offset + ins.offset - 1,
9709 free_extent_map(em);
9711 num_bytes -= ins.offset;
9712 cur_offset += ins.offset;
9713 *alloc_hint = ins.objectid + ins.offset;
9715 inode_inc_iversion(inode);
9716 inode->i_ctime = CURRENT_TIME;
9717 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9718 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9719 (actual_len > inode->i_size) &&
9720 (cur_offset > inode->i_size)) {
9721 if (cur_offset > actual_len)
9722 i_size = actual_len;
9724 i_size = cur_offset;
9725 i_size_write(inode, i_size);
9726 btrfs_ordered_update_i_size(inode, i_size, NULL);
9729 ret = btrfs_update_inode(trans, root, inode);
9732 btrfs_abort_transaction(trans, root, ret);
9734 btrfs_end_transaction(trans, root);
9739 btrfs_end_transaction(trans, root);
9744 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9745 u64 start, u64 num_bytes, u64 min_size,
9746 loff_t actual_len, u64 *alloc_hint)
9748 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9749 min_size, actual_len, alloc_hint,
9753 int btrfs_prealloc_file_range_trans(struct inode *inode,
9754 struct btrfs_trans_handle *trans, int mode,
9755 u64 start, u64 num_bytes, u64 min_size,
9756 loff_t actual_len, u64 *alloc_hint)
9758 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9759 min_size, actual_len, alloc_hint, trans);
9762 static int btrfs_set_page_dirty(struct page *page)
9764 return __set_page_dirty_nobuffers(page);
9767 static int btrfs_permission(struct inode *inode, int mask)
9769 struct btrfs_root *root = BTRFS_I(inode)->root;
9770 umode_t mode = inode->i_mode;
9772 if (mask & MAY_WRITE &&
9773 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9774 if (btrfs_root_readonly(root))
9776 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9779 return generic_permission(inode, mask);
9782 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9784 struct btrfs_trans_handle *trans;
9785 struct btrfs_root *root = BTRFS_I(dir)->root;
9786 struct inode *inode = NULL;
9792 * 5 units required for adding orphan entry
9794 trans = btrfs_start_transaction(root, 5);
9796 return PTR_ERR(trans);
9798 ret = btrfs_find_free_ino(root, &objectid);
9802 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9803 btrfs_ino(dir), objectid, mode, &index);
9804 if (IS_ERR(inode)) {
9805 ret = PTR_ERR(inode);
9810 inode->i_fop = &btrfs_file_operations;
9811 inode->i_op = &btrfs_file_inode_operations;
9813 inode->i_mapping->a_ops = &btrfs_aops;
9814 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9816 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9820 ret = btrfs_update_inode(trans, root, inode);
9823 ret = btrfs_orphan_add(trans, inode);
9828 * We set number of links to 0 in btrfs_new_inode(), and here we set
9829 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9832 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9834 set_nlink(inode, 1);
9835 unlock_new_inode(inode);
9836 d_tmpfile(dentry, inode);
9837 mark_inode_dirty(inode);
9840 btrfs_end_transaction(trans, root);
9843 btrfs_balance_delayed_items(root);
9844 btrfs_btree_balance_dirty(root);
9848 unlock_new_inode(inode);
9853 /* Inspired by filemap_check_errors() */
9854 int btrfs_inode_check_errors(struct inode *inode)
9858 if (test_bit(AS_ENOSPC, &inode->i_mapping->flags) &&
9859 test_and_clear_bit(AS_ENOSPC, &inode->i_mapping->flags))
9861 if (test_bit(AS_EIO, &inode->i_mapping->flags) &&
9862 test_and_clear_bit(AS_EIO, &inode->i_mapping->flags))
9868 static const struct inode_operations btrfs_dir_inode_operations = {
9869 .getattr = btrfs_getattr,
9870 .lookup = btrfs_lookup,
9871 .create = btrfs_create,
9872 .unlink = btrfs_unlink,
9874 .mkdir = btrfs_mkdir,
9875 .rmdir = btrfs_rmdir,
9876 .rename2 = btrfs_rename2,
9877 .symlink = btrfs_symlink,
9878 .setattr = btrfs_setattr,
9879 .mknod = btrfs_mknod,
9880 .setxattr = btrfs_setxattr,
9881 .getxattr = btrfs_getxattr,
9882 .listxattr = btrfs_listxattr,
9883 .removexattr = btrfs_removexattr,
9884 .permission = btrfs_permission,
9885 .get_acl = btrfs_get_acl,
9886 .set_acl = btrfs_set_acl,
9887 .update_time = btrfs_update_time,
9888 .tmpfile = btrfs_tmpfile,
9890 static const struct inode_operations btrfs_dir_ro_inode_operations = {
9891 .lookup = btrfs_lookup,
9892 .permission = btrfs_permission,
9893 .get_acl = btrfs_get_acl,
9894 .set_acl = btrfs_set_acl,
9895 .update_time = btrfs_update_time,
9898 static const struct file_operations btrfs_dir_file_operations = {
9899 .llseek = generic_file_llseek,
9900 .read = generic_read_dir,
9901 .iterate = btrfs_real_readdir,
9902 .unlocked_ioctl = btrfs_ioctl,
9903 #ifdef CONFIG_COMPAT
9904 .compat_ioctl = btrfs_ioctl,
9906 .release = btrfs_release_file,
9907 .fsync = btrfs_sync_file,
9910 static struct extent_io_ops btrfs_extent_io_ops = {
9911 .fill_delalloc = run_delalloc_range,
9912 .submit_bio_hook = btrfs_submit_bio_hook,
9913 .merge_bio_hook = btrfs_merge_bio_hook,
9914 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
9915 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
9916 .writepage_start_hook = btrfs_writepage_start_hook,
9917 .set_bit_hook = btrfs_set_bit_hook,
9918 .clear_bit_hook = btrfs_clear_bit_hook,
9919 .merge_extent_hook = btrfs_merge_extent_hook,
9920 .split_extent_hook = btrfs_split_extent_hook,
9924 * btrfs doesn't support the bmap operation because swapfiles
9925 * use bmap to make a mapping of extents in the file. They assume
9926 * these extents won't change over the life of the file and they
9927 * use the bmap result to do IO directly to the drive.
9929 * the btrfs bmap call would return logical addresses that aren't
9930 * suitable for IO and they also will change frequently as COW
9931 * operations happen. So, swapfile + btrfs == corruption.
9933 * For now we're avoiding this by dropping bmap.
9935 static const struct address_space_operations btrfs_aops = {
9936 .readpage = btrfs_readpage,
9937 .writepage = btrfs_writepage,
9938 .writepages = btrfs_writepages,
9939 .readpages = btrfs_readpages,
9940 .direct_IO = btrfs_direct_IO,
9941 .invalidatepage = btrfs_invalidatepage,
9942 .releasepage = btrfs_releasepage,
9943 .set_page_dirty = btrfs_set_page_dirty,
9944 .error_remove_page = generic_error_remove_page,
9947 static const struct address_space_operations btrfs_symlink_aops = {
9948 .readpage = btrfs_readpage,
9949 .writepage = btrfs_writepage,
9950 .invalidatepage = btrfs_invalidatepage,
9951 .releasepage = btrfs_releasepage,
9954 static const struct inode_operations btrfs_file_inode_operations = {
9955 .getattr = btrfs_getattr,
9956 .setattr = btrfs_setattr,
9957 .setxattr = btrfs_setxattr,
9958 .getxattr = btrfs_getxattr,
9959 .listxattr = btrfs_listxattr,
9960 .removexattr = btrfs_removexattr,
9961 .permission = btrfs_permission,
9962 .fiemap = btrfs_fiemap,
9963 .get_acl = btrfs_get_acl,
9964 .set_acl = btrfs_set_acl,
9965 .update_time = btrfs_update_time,
9967 static const struct inode_operations btrfs_special_inode_operations = {
9968 .getattr = btrfs_getattr,
9969 .setattr = btrfs_setattr,
9970 .permission = btrfs_permission,
9971 .setxattr = btrfs_setxattr,
9972 .getxattr = btrfs_getxattr,
9973 .listxattr = btrfs_listxattr,
9974 .removexattr = btrfs_removexattr,
9975 .get_acl = btrfs_get_acl,
9976 .set_acl = btrfs_set_acl,
9977 .update_time = btrfs_update_time,
9979 static const struct inode_operations btrfs_symlink_inode_operations = {
9980 .readlink = generic_readlink,
9981 .follow_link = page_follow_link_light,
9982 .put_link = page_put_link,
9983 .getattr = btrfs_getattr,
9984 .setattr = btrfs_setattr,
9985 .permission = btrfs_permission,
9986 .setxattr = btrfs_setxattr,
9987 .getxattr = btrfs_getxattr,
9988 .listxattr = btrfs_listxattr,
9989 .removexattr = btrfs_removexattr,
9990 .update_time = btrfs_update_time,
9993 const struct dentry_operations btrfs_dentry_operations = {
9994 .d_delete = btrfs_dentry_delete,
9995 .d_release = btrfs_dentry_release,