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/aio.h>
36 #include <linux/bit_spinlock.h>
37 #include <linux/xattr.h>
38 #include <linux/posix_acl.h>
39 #include <linux/falloc.h>
40 #include <linux/slab.h>
41 #include <linux/ratelimit.h>
42 #include <linux/mount.h>
43 #include <linux/btrfs.h>
44 #include <linux/blkdev.h>
45 #include <linux/posix_acl_xattr.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"
63 struct btrfs_iget_args {
64 struct btrfs_key *location;
65 struct btrfs_root *root;
68 static const struct inode_operations btrfs_dir_inode_operations;
69 static const struct inode_operations btrfs_symlink_inode_operations;
70 static const struct inode_operations btrfs_dir_ro_inode_operations;
71 static const struct inode_operations btrfs_special_inode_operations;
72 static const struct inode_operations btrfs_file_inode_operations;
73 static const struct address_space_operations btrfs_aops;
74 static const struct address_space_operations btrfs_symlink_aops;
75 static const struct file_operations btrfs_dir_file_operations;
76 static struct extent_io_ops btrfs_extent_io_ops;
78 static struct kmem_cache *btrfs_inode_cachep;
79 static struct kmem_cache *btrfs_delalloc_work_cachep;
80 struct kmem_cache *btrfs_trans_handle_cachep;
81 struct kmem_cache *btrfs_transaction_cachep;
82 struct kmem_cache *btrfs_path_cachep;
83 struct kmem_cache *btrfs_free_space_cachep;
86 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
87 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
88 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
89 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
90 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
91 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
92 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
93 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
96 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
97 static int btrfs_truncate(struct inode *inode);
98 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
99 static noinline int cow_file_range(struct inode *inode,
100 struct page *locked_page,
101 u64 start, u64 end, int *page_started,
102 unsigned long *nr_written, int unlock);
103 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
104 u64 len, u64 orig_start,
105 u64 block_start, u64 block_len,
106 u64 orig_block_len, u64 ram_bytes,
109 static int btrfs_dirty_inode(struct inode *inode);
111 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
112 struct inode *inode, struct inode *dir,
113 const struct qstr *qstr)
117 err = btrfs_init_acl(trans, inode, dir);
119 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
124 * this does all the hard work for inserting an inline extent into
125 * the btree. The caller should have done a btrfs_drop_extents so that
126 * no overlapping inline items exist in the btree
128 static int insert_inline_extent(struct btrfs_trans_handle *trans,
129 struct btrfs_path *path, int extent_inserted,
130 struct btrfs_root *root, struct inode *inode,
131 u64 start, size_t size, size_t compressed_size,
133 struct page **compressed_pages)
135 struct extent_buffer *leaf;
136 struct page *page = NULL;
139 struct btrfs_file_extent_item *ei;
142 size_t cur_size = size;
143 unsigned long offset;
145 if (compressed_size && compressed_pages)
146 cur_size = compressed_size;
148 inode_add_bytes(inode, size);
150 if (!extent_inserted) {
151 struct btrfs_key key;
154 key.objectid = btrfs_ino(inode);
156 key.type = BTRFS_EXTENT_DATA_KEY;
158 datasize = btrfs_file_extent_calc_inline_size(cur_size);
159 path->leave_spinning = 1;
160 ret = btrfs_insert_empty_item(trans, root, path, &key,
167 leaf = path->nodes[0];
168 ei = btrfs_item_ptr(leaf, path->slots[0],
169 struct btrfs_file_extent_item);
170 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
171 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
172 btrfs_set_file_extent_encryption(leaf, ei, 0);
173 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
174 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
175 ptr = btrfs_file_extent_inline_start(ei);
177 if (compress_type != BTRFS_COMPRESS_NONE) {
180 while (compressed_size > 0) {
181 cpage = compressed_pages[i];
182 cur_size = min_t(unsigned long, compressed_size,
185 kaddr = kmap_atomic(cpage);
186 write_extent_buffer(leaf, kaddr, ptr, cur_size);
187 kunmap_atomic(kaddr);
191 compressed_size -= cur_size;
193 btrfs_set_file_extent_compression(leaf, ei,
196 page = find_get_page(inode->i_mapping,
197 start >> PAGE_CACHE_SHIFT);
198 btrfs_set_file_extent_compression(leaf, ei, 0);
199 kaddr = kmap_atomic(page);
200 offset = start & (PAGE_CACHE_SIZE - 1);
201 write_extent_buffer(leaf, kaddr + offset, ptr, size);
202 kunmap_atomic(kaddr);
203 page_cache_release(page);
205 btrfs_mark_buffer_dirty(leaf);
206 btrfs_release_path(path);
209 * we're an inline extent, so nobody can
210 * extend the file past i_size without locking
211 * a page we already have locked.
213 * We must do any isize and inode updates
214 * before we unlock the pages. Otherwise we
215 * could end up racing with unlink.
217 BTRFS_I(inode)->disk_i_size = inode->i_size;
218 ret = btrfs_update_inode(trans, root, inode);
227 * conditionally insert an inline extent into the file. This
228 * does the checks required to make sure the data is small enough
229 * to fit as an inline extent.
231 static noinline int cow_file_range_inline(struct btrfs_root *root,
232 struct inode *inode, u64 start,
233 u64 end, size_t compressed_size,
235 struct page **compressed_pages)
237 struct btrfs_trans_handle *trans;
238 u64 isize = i_size_read(inode);
239 u64 actual_end = min(end + 1, isize);
240 u64 inline_len = actual_end - start;
241 u64 aligned_end = ALIGN(end, root->sectorsize);
242 u64 data_len = inline_len;
244 struct btrfs_path *path;
245 int extent_inserted = 0;
246 u32 extent_item_size;
249 data_len = compressed_size;
252 actual_end > PAGE_CACHE_SIZE ||
253 data_len > BTRFS_MAX_INLINE_DATA_SIZE(root) ||
255 (actual_end & (root->sectorsize - 1)) == 0) ||
257 data_len > root->fs_info->max_inline) {
261 path = btrfs_alloc_path();
265 trans = btrfs_join_transaction(root);
267 btrfs_free_path(path);
268 return PTR_ERR(trans);
270 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
272 if (compressed_size && compressed_pages)
273 extent_item_size = btrfs_file_extent_calc_inline_size(
276 extent_item_size = btrfs_file_extent_calc_inline_size(
279 ret = __btrfs_drop_extents(trans, root, inode, path,
280 start, aligned_end, NULL,
281 1, 1, extent_item_size, &extent_inserted);
283 btrfs_abort_transaction(trans, root, ret);
287 if (isize > actual_end)
288 inline_len = min_t(u64, isize, actual_end);
289 ret = insert_inline_extent(trans, path, extent_inserted,
291 inline_len, compressed_size,
292 compress_type, compressed_pages);
293 if (ret && ret != -ENOSPC) {
294 btrfs_abort_transaction(trans, root, ret);
296 } else if (ret == -ENOSPC) {
301 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
302 btrfs_delalloc_release_metadata(inode, end + 1 - start);
303 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
305 btrfs_free_path(path);
306 btrfs_end_transaction(trans, root);
310 struct async_extent {
315 unsigned long nr_pages;
317 struct list_head list;
322 struct btrfs_root *root;
323 struct page *locked_page;
326 struct list_head extents;
327 struct btrfs_work work;
330 static noinline int add_async_extent(struct async_cow *cow,
331 u64 start, u64 ram_size,
334 unsigned long nr_pages,
337 struct async_extent *async_extent;
339 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
340 BUG_ON(!async_extent); /* -ENOMEM */
341 async_extent->start = start;
342 async_extent->ram_size = ram_size;
343 async_extent->compressed_size = compressed_size;
344 async_extent->pages = pages;
345 async_extent->nr_pages = nr_pages;
346 async_extent->compress_type = compress_type;
347 list_add_tail(&async_extent->list, &cow->extents);
351 static inline int inode_need_compress(struct inode *inode)
353 struct btrfs_root *root = BTRFS_I(inode)->root;
356 if (btrfs_test_opt(root, FORCE_COMPRESS))
358 /* bad compression ratios */
359 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
361 if (btrfs_test_opt(root, COMPRESS) ||
362 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
363 BTRFS_I(inode)->force_compress)
369 * we create compressed extents in two phases. The first
370 * phase compresses a range of pages that have already been
371 * locked (both pages and state bits are locked).
373 * This is done inside an ordered work queue, and the compression
374 * is spread across many cpus. The actual IO submission is step
375 * two, and the ordered work queue takes care of making sure that
376 * happens in the same order things were put onto the queue by
377 * writepages and friends.
379 * If this code finds it can't get good compression, it puts an
380 * entry onto the work queue to write the uncompressed bytes. This
381 * makes sure that both compressed inodes and uncompressed inodes
382 * are written in the same order that the flusher thread sent them
385 static noinline void compress_file_range(struct inode *inode,
386 struct page *locked_page,
388 struct async_cow *async_cow,
391 struct btrfs_root *root = BTRFS_I(inode)->root;
393 u64 blocksize = root->sectorsize;
395 u64 isize = i_size_read(inode);
397 struct page **pages = NULL;
398 unsigned long nr_pages;
399 unsigned long nr_pages_ret = 0;
400 unsigned long total_compressed = 0;
401 unsigned long total_in = 0;
402 unsigned long max_compressed = 128 * 1024;
403 unsigned long max_uncompressed = 128 * 1024;
406 int compress_type = root->fs_info->compress_type;
409 /* if this is a small write inside eof, kick off a defrag */
410 if ((end - start + 1) < 16 * 1024 &&
411 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
412 btrfs_add_inode_defrag(NULL, inode);
414 actual_end = min_t(u64, isize, end + 1);
417 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
418 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
421 * we don't want to send crud past the end of i_size through
422 * compression, that's just a waste of CPU time. So, if the
423 * end of the file is before the start of our current
424 * requested range of bytes, we bail out to the uncompressed
425 * cleanup code that can deal with all of this.
427 * It isn't really the fastest way to fix things, but this is a
428 * very uncommon corner.
430 if (actual_end <= start)
431 goto cleanup_and_bail_uncompressed;
433 total_compressed = actual_end - start;
436 * skip compression for a small file range(<=blocksize) that
437 * isn't an inline extent, since it dosen't save disk space at all.
439 if (total_compressed <= blocksize &&
440 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
441 goto cleanup_and_bail_uncompressed;
443 /* we want to make sure that amount of ram required to uncompress
444 * an extent is reasonable, so we limit the total size in ram
445 * of a compressed extent to 128k. This is a crucial number
446 * because it also controls how easily we can spread reads across
447 * cpus for decompression.
449 * We also want to make sure the amount of IO required to do
450 * a random read is reasonably small, so we limit the size of
451 * a compressed extent to 128k.
453 total_compressed = min(total_compressed, max_uncompressed);
454 num_bytes = ALIGN(end - start + 1, blocksize);
455 num_bytes = max(blocksize, num_bytes);
460 * we do compression for mount -o compress and when the
461 * inode has not been flagged as nocompress. This flag can
462 * change at any time if we discover bad compression ratios.
464 if (inode_need_compress(inode)) {
466 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
468 /* just bail out to the uncompressed code */
472 if (BTRFS_I(inode)->force_compress)
473 compress_type = BTRFS_I(inode)->force_compress;
476 * we need to call clear_page_dirty_for_io on each
477 * page in the range. Otherwise applications with the file
478 * mmap'd can wander in and change the page contents while
479 * we are compressing them.
481 * If the compression fails for any reason, we set the pages
482 * dirty again later on.
484 extent_range_clear_dirty_for_io(inode, start, end);
486 ret = btrfs_compress_pages(compress_type,
487 inode->i_mapping, start,
488 total_compressed, pages,
489 nr_pages, &nr_pages_ret,
495 unsigned long offset = total_compressed &
496 (PAGE_CACHE_SIZE - 1);
497 struct page *page = pages[nr_pages_ret - 1];
500 /* zero the tail end of the last page, we might be
501 * sending it down to disk
504 kaddr = kmap_atomic(page);
505 memset(kaddr + offset, 0,
506 PAGE_CACHE_SIZE - offset);
507 kunmap_atomic(kaddr);
514 /* lets try to make an inline extent */
515 if (ret || total_in < (actual_end - start)) {
516 /* we didn't compress the entire range, try
517 * to make an uncompressed inline extent.
519 ret = cow_file_range_inline(root, inode, start, end,
522 /* try making a compressed inline extent */
523 ret = cow_file_range_inline(root, inode, start, end,
525 compress_type, pages);
528 unsigned long clear_flags = EXTENT_DELALLOC |
530 unsigned long page_error_op;
532 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
533 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
536 * inline extent creation worked or returned error,
537 * we don't need to create any more async work items.
538 * Unlock and free up our temp pages.
540 extent_clear_unlock_delalloc(inode, start, end, NULL,
541 clear_flags, PAGE_UNLOCK |
552 * we aren't doing an inline extent round the compressed size
553 * up to a block size boundary so the allocator does sane
556 total_compressed = ALIGN(total_compressed, blocksize);
559 * one last check to make sure the compression is really a
560 * win, compare the page count read with the blocks on disk
562 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
563 if (total_compressed >= total_in) {
566 num_bytes = total_in;
569 if (!will_compress && pages) {
571 * the compression code ran but failed to make things smaller,
572 * free any pages it allocated and our page pointer array
574 for (i = 0; i < nr_pages_ret; i++) {
575 WARN_ON(pages[i]->mapping);
576 page_cache_release(pages[i]);
580 total_compressed = 0;
583 /* flag the file so we don't compress in the future */
584 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
585 !(BTRFS_I(inode)->force_compress)) {
586 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
592 /* the async work queues will take care of doing actual
593 * allocation on disk for these compressed pages,
594 * and will submit them to the elevator.
596 add_async_extent(async_cow, start, num_bytes,
597 total_compressed, pages, nr_pages_ret,
600 if (start + num_bytes < end) {
607 cleanup_and_bail_uncompressed:
609 * No compression, but we still need to write the pages in
610 * the file we've been given so far. redirty the locked
611 * page if it corresponds to our extent and set things up
612 * for the async work queue to run cow_file_range to do
613 * the normal delalloc dance
615 if (page_offset(locked_page) >= start &&
616 page_offset(locked_page) <= end) {
617 __set_page_dirty_nobuffers(locked_page);
618 /* unlocked later on in the async handlers */
621 extent_range_redirty_for_io(inode, start, end);
622 add_async_extent(async_cow, start, end - start + 1,
623 0, NULL, 0, BTRFS_COMPRESS_NONE);
630 for (i = 0; i < nr_pages_ret; i++) {
631 WARN_ON(pages[i]->mapping);
632 page_cache_release(pages[i]);
637 static void free_async_extent_pages(struct async_extent *async_extent)
641 if (!async_extent->pages)
644 for (i = 0; i < async_extent->nr_pages; i++) {
645 WARN_ON(async_extent->pages[i]->mapping);
646 page_cache_release(async_extent->pages[i]);
648 kfree(async_extent->pages);
649 async_extent->nr_pages = 0;
650 async_extent->pages = NULL;
654 * phase two of compressed writeback. This is the ordered portion
655 * of the code, which only gets called in the order the work was
656 * queued. We walk all the async extents created by compress_file_range
657 * and send them down to the disk.
659 static noinline void submit_compressed_extents(struct inode *inode,
660 struct async_cow *async_cow)
662 struct async_extent *async_extent;
664 struct btrfs_key ins;
665 struct extent_map *em;
666 struct btrfs_root *root = BTRFS_I(inode)->root;
667 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
668 struct extent_io_tree *io_tree;
672 while (!list_empty(&async_cow->extents)) {
673 async_extent = list_entry(async_cow->extents.next,
674 struct async_extent, list);
675 list_del(&async_extent->list);
677 io_tree = &BTRFS_I(inode)->io_tree;
680 /* did the compression code fall back to uncompressed IO? */
681 if (!async_extent->pages) {
682 int page_started = 0;
683 unsigned long nr_written = 0;
685 lock_extent(io_tree, async_extent->start,
686 async_extent->start +
687 async_extent->ram_size - 1);
689 /* allocate blocks */
690 ret = cow_file_range(inode, async_cow->locked_page,
692 async_extent->start +
693 async_extent->ram_size - 1,
694 &page_started, &nr_written, 0);
699 * if page_started, cow_file_range inserted an
700 * inline extent and took care of all the unlocking
701 * and IO for us. Otherwise, we need to submit
702 * all those pages down to the drive.
704 if (!page_started && !ret)
705 extent_write_locked_range(io_tree,
706 inode, async_extent->start,
707 async_extent->start +
708 async_extent->ram_size - 1,
712 unlock_page(async_cow->locked_page);
718 lock_extent(io_tree, async_extent->start,
719 async_extent->start + async_extent->ram_size - 1);
721 ret = btrfs_reserve_extent(root,
722 async_extent->compressed_size,
723 async_extent->compressed_size,
724 0, alloc_hint, &ins, 1, 1);
726 free_async_extent_pages(async_extent);
728 if (ret == -ENOSPC) {
729 unlock_extent(io_tree, async_extent->start,
730 async_extent->start +
731 async_extent->ram_size - 1);
734 * we need to redirty the pages if we decide to
735 * fallback to uncompressed IO, otherwise we
736 * will not submit these pages down to lower
739 extent_range_redirty_for_io(inode,
741 async_extent->start +
742 async_extent->ram_size - 1);
750 * here we're doing allocation and writeback of the
753 btrfs_drop_extent_cache(inode, async_extent->start,
754 async_extent->start +
755 async_extent->ram_size - 1, 0);
757 em = alloc_extent_map();
760 goto out_free_reserve;
762 em->start = async_extent->start;
763 em->len = async_extent->ram_size;
764 em->orig_start = em->start;
765 em->mod_start = em->start;
766 em->mod_len = em->len;
768 em->block_start = ins.objectid;
769 em->block_len = ins.offset;
770 em->orig_block_len = ins.offset;
771 em->ram_bytes = async_extent->ram_size;
772 em->bdev = root->fs_info->fs_devices->latest_bdev;
773 em->compress_type = async_extent->compress_type;
774 set_bit(EXTENT_FLAG_PINNED, &em->flags);
775 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
779 write_lock(&em_tree->lock);
780 ret = add_extent_mapping(em_tree, em, 1);
781 write_unlock(&em_tree->lock);
782 if (ret != -EEXIST) {
786 btrfs_drop_extent_cache(inode, async_extent->start,
787 async_extent->start +
788 async_extent->ram_size - 1, 0);
792 goto out_free_reserve;
794 ret = btrfs_add_ordered_extent_compress(inode,
797 async_extent->ram_size,
799 BTRFS_ORDERED_COMPRESSED,
800 async_extent->compress_type);
802 btrfs_drop_extent_cache(inode, async_extent->start,
803 async_extent->start +
804 async_extent->ram_size - 1, 0);
805 goto out_free_reserve;
809 * clear dirty, set writeback and unlock the pages.
811 extent_clear_unlock_delalloc(inode, async_extent->start,
812 async_extent->start +
813 async_extent->ram_size - 1,
814 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
815 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
817 ret = btrfs_submit_compressed_write(inode,
819 async_extent->ram_size,
821 ins.offset, async_extent->pages,
822 async_extent->nr_pages);
824 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
825 struct page *p = async_extent->pages[0];
826 const u64 start = async_extent->start;
827 const u64 end = start + async_extent->ram_size - 1;
829 p->mapping = inode->i_mapping;
830 tree->ops->writepage_end_io_hook(p, start, end,
833 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
836 free_async_extent_pages(async_extent);
838 alloc_hint = ins.objectid + ins.offset;
844 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
846 extent_clear_unlock_delalloc(inode, async_extent->start,
847 async_extent->start +
848 async_extent->ram_size - 1,
849 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
850 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
851 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
852 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
854 free_async_extent_pages(async_extent);
859 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
862 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
863 struct extent_map *em;
866 read_lock(&em_tree->lock);
867 em = search_extent_mapping(em_tree, start, num_bytes);
870 * if block start isn't an actual block number then find the
871 * first block in this inode and use that as a hint. If that
872 * block is also bogus then just don't worry about it.
874 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
876 em = search_extent_mapping(em_tree, 0, 0);
877 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
878 alloc_hint = em->block_start;
882 alloc_hint = em->block_start;
886 read_unlock(&em_tree->lock);
892 * when extent_io.c finds a delayed allocation range in the file,
893 * the call backs end up in this code. The basic idea is to
894 * allocate extents on disk for the range, and create ordered data structs
895 * in ram to track those extents.
897 * locked_page is the page that writepage had locked already. We use
898 * it to make sure we don't do extra locks or unlocks.
900 * *page_started is set to one if we unlock locked_page and do everything
901 * required to start IO on it. It may be clean and already done with
904 static noinline int cow_file_range(struct inode *inode,
905 struct page *locked_page,
906 u64 start, u64 end, int *page_started,
907 unsigned long *nr_written,
910 struct btrfs_root *root = BTRFS_I(inode)->root;
913 unsigned long ram_size;
916 u64 blocksize = root->sectorsize;
917 struct btrfs_key ins;
918 struct extent_map *em;
919 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
922 if (btrfs_is_free_space_inode(inode)) {
928 num_bytes = ALIGN(end - start + 1, blocksize);
929 num_bytes = max(blocksize, num_bytes);
930 disk_num_bytes = num_bytes;
932 /* if this is a small write inside eof, kick off defrag */
933 if (num_bytes < 64 * 1024 &&
934 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
935 btrfs_add_inode_defrag(NULL, inode);
938 /* lets try to make an inline extent */
939 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
942 extent_clear_unlock_delalloc(inode, start, end, NULL,
943 EXTENT_LOCKED | EXTENT_DELALLOC |
944 EXTENT_DEFRAG, PAGE_UNLOCK |
945 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
948 *nr_written = *nr_written +
949 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
952 } else if (ret < 0) {
957 BUG_ON(disk_num_bytes >
958 btrfs_super_total_bytes(root->fs_info->super_copy));
960 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
961 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
963 while (disk_num_bytes > 0) {
966 cur_alloc_size = disk_num_bytes;
967 ret = btrfs_reserve_extent(root, cur_alloc_size,
968 root->sectorsize, 0, alloc_hint,
973 em = alloc_extent_map();
979 em->orig_start = em->start;
980 ram_size = ins.offset;
981 em->len = ins.offset;
982 em->mod_start = em->start;
983 em->mod_len = em->len;
985 em->block_start = ins.objectid;
986 em->block_len = ins.offset;
987 em->orig_block_len = ins.offset;
988 em->ram_bytes = ram_size;
989 em->bdev = root->fs_info->fs_devices->latest_bdev;
990 set_bit(EXTENT_FLAG_PINNED, &em->flags);
994 write_lock(&em_tree->lock);
995 ret = add_extent_mapping(em_tree, em, 1);
996 write_unlock(&em_tree->lock);
997 if (ret != -EEXIST) {
1001 btrfs_drop_extent_cache(inode, start,
1002 start + ram_size - 1, 0);
1007 cur_alloc_size = ins.offset;
1008 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1009 ram_size, cur_alloc_size, 0);
1011 goto out_drop_extent_cache;
1013 if (root->root_key.objectid ==
1014 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1015 ret = btrfs_reloc_clone_csums(inode, start,
1018 goto out_drop_extent_cache;
1021 if (disk_num_bytes < cur_alloc_size)
1024 /* we're not doing compressed IO, don't unlock the first
1025 * page (which the caller expects to stay locked), don't
1026 * clear any dirty bits and don't set any writeback bits
1028 * Do set the Private2 bit so we know this page was properly
1029 * setup for writepage
1031 op = unlock ? PAGE_UNLOCK : 0;
1032 op |= PAGE_SET_PRIVATE2;
1034 extent_clear_unlock_delalloc(inode, start,
1035 start + ram_size - 1, locked_page,
1036 EXTENT_LOCKED | EXTENT_DELALLOC,
1038 disk_num_bytes -= cur_alloc_size;
1039 num_bytes -= cur_alloc_size;
1040 alloc_hint = ins.objectid + ins.offset;
1041 start += cur_alloc_size;
1046 out_drop_extent_cache:
1047 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1049 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1051 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1052 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1053 EXTENT_DELALLOC | EXTENT_DEFRAG,
1054 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1055 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1060 * work queue call back to started compression on a file and pages
1062 static noinline void async_cow_start(struct btrfs_work *work)
1064 struct async_cow *async_cow;
1066 async_cow = container_of(work, struct async_cow, work);
1068 compress_file_range(async_cow->inode, async_cow->locked_page,
1069 async_cow->start, async_cow->end, async_cow,
1071 if (num_added == 0) {
1072 btrfs_add_delayed_iput(async_cow->inode);
1073 async_cow->inode = NULL;
1078 * work queue call back to submit previously compressed pages
1080 static noinline void async_cow_submit(struct btrfs_work *work)
1082 struct async_cow *async_cow;
1083 struct btrfs_root *root;
1084 unsigned long nr_pages;
1086 async_cow = container_of(work, struct async_cow, work);
1088 root = async_cow->root;
1089 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1092 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1094 waitqueue_active(&root->fs_info->async_submit_wait))
1095 wake_up(&root->fs_info->async_submit_wait);
1097 if (async_cow->inode)
1098 submit_compressed_extents(async_cow->inode, async_cow);
1101 static noinline void async_cow_free(struct btrfs_work *work)
1103 struct async_cow *async_cow;
1104 async_cow = container_of(work, struct async_cow, work);
1105 if (async_cow->inode)
1106 btrfs_add_delayed_iput(async_cow->inode);
1110 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1111 u64 start, u64 end, int *page_started,
1112 unsigned long *nr_written)
1114 struct async_cow *async_cow;
1115 struct btrfs_root *root = BTRFS_I(inode)->root;
1116 unsigned long nr_pages;
1118 int limit = 10 * 1024 * 1024;
1120 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1121 1, 0, NULL, GFP_NOFS);
1122 while (start < end) {
1123 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1124 BUG_ON(!async_cow); /* -ENOMEM */
1125 async_cow->inode = igrab(inode);
1126 async_cow->root = root;
1127 async_cow->locked_page = locked_page;
1128 async_cow->start = start;
1130 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1131 !btrfs_test_opt(root, FORCE_COMPRESS))
1134 cur_end = min(end, start + 512 * 1024 - 1);
1136 async_cow->end = cur_end;
1137 INIT_LIST_HEAD(&async_cow->extents);
1139 btrfs_init_work(&async_cow->work,
1140 btrfs_delalloc_helper,
1141 async_cow_start, async_cow_submit,
1144 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1146 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1148 btrfs_queue_work(root->fs_info->delalloc_workers,
1151 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1152 wait_event(root->fs_info->async_submit_wait,
1153 (atomic_read(&root->fs_info->async_delalloc_pages) <
1157 while (atomic_read(&root->fs_info->async_submit_draining) &&
1158 atomic_read(&root->fs_info->async_delalloc_pages)) {
1159 wait_event(root->fs_info->async_submit_wait,
1160 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1164 *nr_written += nr_pages;
1165 start = cur_end + 1;
1171 static noinline int csum_exist_in_range(struct btrfs_root *root,
1172 u64 bytenr, u64 num_bytes)
1175 struct btrfs_ordered_sum *sums;
1178 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1179 bytenr + num_bytes - 1, &list, 0);
1180 if (ret == 0 && list_empty(&list))
1183 while (!list_empty(&list)) {
1184 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1185 list_del(&sums->list);
1192 * when nowcow writeback call back. This checks for snapshots or COW copies
1193 * of the extents that exist in the file, and COWs the file as required.
1195 * If no cow copies or snapshots exist, we write directly to the existing
1198 static noinline int run_delalloc_nocow(struct inode *inode,
1199 struct page *locked_page,
1200 u64 start, u64 end, int *page_started, int force,
1201 unsigned long *nr_written)
1203 struct btrfs_root *root = BTRFS_I(inode)->root;
1204 struct btrfs_trans_handle *trans;
1205 struct extent_buffer *leaf;
1206 struct btrfs_path *path;
1207 struct btrfs_file_extent_item *fi;
1208 struct btrfs_key found_key;
1223 u64 ino = btrfs_ino(inode);
1225 path = btrfs_alloc_path();
1227 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1228 EXTENT_LOCKED | EXTENT_DELALLOC |
1229 EXTENT_DO_ACCOUNTING |
1230 EXTENT_DEFRAG, PAGE_UNLOCK |
1232 PAGE_SET_WRITEBACK |
1233 PAGE_END_WRITEBACK);
1237 nolock = btrfs_is_free_space_inode(inode);
1240 trans = btrfs_join_transaction_nolock(root);
1242 trans = btrfs_join_transaction(root);
1244 if (IS_ERR(trans)) {
1245 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1246 EXTENT_LOCKED | EXTENT_DELALLOC |
1247 EXTENT_DO_ACCOUNTING |
1248 EXTENT_DEFRAG, PAGE_UNLOCK |
1250 PAGE_SET_WRITEBACK |
1251 PAGE_END_WRITEBACK);
1252 btrfs_free_path(path);
1253 return PTR_ERR(trans);
1256 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1258 cow_start = (u64)-1;
1261 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1265 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1266 leaf = path->nodes[0];
1267 btrfs_item_key_to_cpu(leaf, &found_key,
1268 path->slots[0] - 1);
1269 if (found_key.objectid == ino &&
1270 found_key.type == BTRFS_EXTENT_DATA_KEY)
1275 leaf = path->nodes[0];
1276 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1277 ret = btrfs_next_leaf(root, path);
1282 leaf = path->nodes[0];
1288 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1290 if (found_key.objectid > ino ||
1291 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1292 found_key.offset > end)
1295 if (found_key.offset > cur_offset) {
1296 extent_end = found_key.offset;
1301 fi = btrfs_item_ptr(leaf, path->slots[0],
1302 struct btrfs_file_extent_item);
1303 extent_type = btrfs_file_extent_type(leaf, fi);
1305 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1306 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1307 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1308 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1309 extent_offset = btrfs_file_extent_offset(leaf, fi);
1310 extent_end = found_key.offset +
1311 btrfs_file_extent_num_bytes(leaf, fi);
1313 btrfs_file_extent_disk_num_bytes(leaf, fi);
1314 if (extent_end <= start) {
1318 if (disk_bytenr == 0)
1320 if (btrfs_file_extent_compression(leaf, fi) ||
1321 btrfs_file_extent_encryption(leaf, fi) ||
1322 btrfs_file_extent_other_encoding(leaf, fi))
1324 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1326 if (btrfs_extent_readonly(root, disk_bytenr))
1328 if (btrfs_cross_ref_exist(trans, root, ino,
1330 extent_offset, disk_bytenr))
1332 disk_bytenr += extent_offset;
1333 disk_bytenr += cur_offset - found_key.offset;
1334 num_bytes = min(end + 1, extent_end) - cur_offset;
1336 * if there are pending snapshots for this root,
1337 * we fall into common COW way.
1340 err = btrfs_start_nocow_write(root);
1345 * force cow if csum exists in the range.
1346 * this ensure that csum for a given extent are
1347 * either valid or do not exist.
1349 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1352 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1353 extent_end = found_key.offset +
1354 btrfs_file_extent_inline_len(leaf,
1355 path->slots[0], fi);
1356 extent_end = ALIGN(extent_end, root->sectorsize);
1361 if (extent_end <= start) {
1363 if (!nolock && nocow)
1364 btrfs_end_nocow_write(root);
1368 if (cow_start == (u64)-1)
1369 cow_start = cur_offset;
1370 cur_offset = extent_end;
1371 if (cur_offset > end)
1377 btrfs_release_path(path);
1378 if (cow_start != (u64)-1) {
1379 ret = cow_file_range(inode, locked_page,
1380 cow_start, found_key.offset - 1,
1381 page_started, nr_written, 1);
1383 if (!nolock && nocow)
1384 btrfs_end_nocow_write(root);
1387 cow_start = (u64)-1;
1390 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1391 struct extent_map *em;
1392 struct extent_map_tree *em_tree;
1393 em_tree = &BTRFS_I(inode)->extent_tree;
1394 em = alloc_extent_map();
1395 BUG_ON(!em); /* -ENOMEM */
1396 em->start = cur_offset;
1397 em->orig_start = found_key.offset - extent_offset;
1398 em->len = num_bytes;
1399 em->block_len = num_bytes;
1400 em->block_start = disk_bytenr;
1401 em->orig_block_len = disk_num_bytes;
1402 em->ram_bytes = ram_bytes;
1403 em->bdev = root->fs_info->fs_devices->latest_bdev;
1404 em->mod_start = em->start;
1405 em->mod_len = em->len;
1406 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1407 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1408 em->generation = -1;
1410 write_lock(&em_tree->lock);
1411 ret = add_extent_mapping(em_tree, em, 1);
1412 write_unlock(&em_tree->lock);
1413 if (ret != -EEXIST) {
1414 free_extent_map(em);
1417 btrfs_drop_extent_cache(inode, em->start,
1418 em->start + em->len - 1, 0);
1420 type = BTRFS_ORDERED_PREALLOC;
1422 type = BTRFS_ORDERED_NOCOW;
1425 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1426 num_bytes, num_bytes, type);
1427 BUG_ON(ret); /* -ENOMEM */
1429 if (root->root_key.objectid ==
1430 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1431 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1434 if (!nolock && nocow)
1435 btrfs_end_nocow_write(root);
1440 extent_clear_unlock_delalloc(inode, cur_offset,
1441 cur_offset + num_bytes - 1,
1442 locked_page, EXTENT_LOCKED |
1443 EXTENT_DELALLOC, PAGE_UNLOCK |
1445 if (!nolock && nocow)
1446 btrfs_end_nocow_write(root);
1447 cur_offset = extent_end;
1448 if (cur_offset > end)
1451 btrfs_release_path(path);
1453 if (cur_offset <= end && cow_start == (u64)-1) {
1454 cow_start = cur_offset;
1458 if (cow_start != (u64)-1) {
1459 ret = cow_file_range(inode, locked_page, cow_start, end,
1460 page_started, nr_written, 1);
1466 err = btrfs_end_transaction(trans, root);
1470 if (ret && cur_offset < end)
1471 extent_clear_unlock_delalloc(inode, cur_offset, end,
1472 locked_page, EXTENT_LOCKED |
1473 EXTENT_DELALLOC | EXTENT_DEFRAG |
1474 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1476 PAGE_SET_WRITEBACK |
1477 PAGE_END_WRITEBACK);
1478 btrfs_free_path(path);
1482 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1485 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1486 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1490 * @defrag_bytes is a hint value, no spinlock held here,
1491 * if is not zero, it means the file is defragging.
1492 * Force cow if given extent needs to be defragged.
1494 if (BTRFS_I(inode)->defrag_bytes &&
1495 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1496 EXTENT_DEFRAG, 0, NULL))
1503 * extent_io.c call back to do delayed allocation processing
1505 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1506 u64 start, u64 end, int *page_started,
1507 unsigned long *nr_written)
1510 int force_cow = need_force_cow(inode, start, end);
1512 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1513 ret = run_delalloc_nocow(inode, locked_page, start, end,
1514 page_started, 1, nr_written);
1515 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1516 ret = run_delalloc_nocow(inode, locked_page, start, end,
1517 page_started, 0, nr_written);
1518 } else if (!inode_need_compress(inode)) {
1519 ret = cow_file_range(inode, locked_page, start, end,
1520 page_started, nr_written, 1);
1522 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1523 &BTRFS_I(inode)->runtime_flags);
1524 ret = cow_file_range_async(inode, locked_page, start, end,
1525 page_started, nr_written);
1530 static void btrfs_split_extent_hook(struct inode *inode,
1531 struct extent_state *orig, u64 split)
1533 /* not delalloc, ignore it */
1534 if (!(orig->state & EXTENT_DELALLOC))
1537 spin_lock(&BTRFS_I(inode)->lock);
1538 BTRFS_I(inode)->outstanding_extents++;
1539 spin_unlock(&BTRFS_I(inode)->lock);
1543 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1544 * extents so we can keep track of new extents that are just merged onto old
1545 * extents, such as when we are doing sequential writes, so we can properly
1546 * account for the metadata space we'll need.
1548 static void btrfs_merge_extent_hook(struct inode *inode,
1549 struct extent_state *new,
1550 struct extent_state *other)
1552 /* not delalloc, ignore it */
1553 if (!(other->state & EXTENT_DELALLOC))
1556 spin_lock(&BTRFS_I(inode)->lock);
1557 BTRFS_I(inode)->outstanding_extents--;
1558 spin_unlock(&BTRFS_I(inode)->lock);
1561 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1562 struct inode *inode)
1564 spin_lock(&root->delalloc_lock);
1565 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1566 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1567 &root->delalloc_inodes);
1568 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1569 &BTRFS_I(inode)->runtime_flags);
1570 root->nr_delalloc_inodes++;
1571 if (root->nr_delalloc_inodes == 1) {
1572 spin_lock(&root->fs_info->delalloc_root_lock);
1573 BUG_ON(!list_empty(&root->delalloc_root));
1574 list_add_tail(&root->delalloc_root,
1575 &root->fs_info->delalloc_roots);
1576 spin_unlock(&root->fs_info->delalloc_root_lock);
1579 spin_unlock(&root->delalloc_lock);
1582 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1583 struct inode *inode)
1585 spin_lock(&root->delalloc_lock);
1586 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1587 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1588 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1589 &BTRFS_I(inode)->runtime_flags);
1590 root->nr_delalloc_inodes--;
1591 if (!root->nr_delalloc_inodes) {
1592 spin_lock(&root->fs_info->delalloc_root_lock);
1593 BUG_ON(list_empty(&root->delalloc_root));
1594 list_del_init(&root->delalloc_root);
1595 spin_unlock(&root->fs_info->delalloc_root_lock);
1598 spin_unlock(&root->delalloc_lock);
1602 * extent_io.c set_bit_hook, used to track delayed allocation
1603 * bytes in this file, and to maintain the list of inodes that
1604 * have pending delalloc work to be done.
1606 static void btrfs_set_bit_hook(struct inode *inode,
1607 struct extent_state *state, unsigned long *bits)
1610 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1613 * set_bit and clear bit hooks normally require _irqsave/restore
1614 * but in this case, we are only testing for the DELALLOC
1615 * bit, which is only set or cleared with irqs on
1617 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1618 struct btrfs_root *root = BTRFS_I(inode)->root;
1619 u64 len = state->end + 1 - state->start;
1620 bool do_list = !btrfs_is_free_space_inode(inode);
1622 if (*bits & EXTENT_FIRST_DELALLOC) {
1623 *bits &= ~EXTENT_FIRST_DELALLOC;
1625 spin_lock(&BTRFS_I(inode)->lock);
1626 BTRFS_I(inode)->outstanding_extents++;
1627 spin_unlock(&BTRFS_I(inode)->lock);
1630 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1631 root->fs_info->delalloc_batch);
1632 spin_lock(&BTRFS_I(inode)->lock);
1633 BTRFS_I(inode)->delalloc_bytes += len;
1634 if (*bits & EXTENT_DEFRAG)
1635 BTRFS_I(inode)->defrag_bytes += len;
1636 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1637 &BTRFS_I(inode)->runtime_flags))
1638 btrfs_add_delalloc_inodes(root, inode);
1639 spin_unlock(&BTRFS_I(inode)->lock);
1644 * extent_io.c clear_bit_hook, see set_bit_hook for why
1646 static void btrfs_clear_bit_hook(struct inode *inode,
1647 struct extent_state *state,
1648 unsigned long *bits)
1650 u64 len = state->end + 1 - state->start;
1652 spin_lock(&BTRFS_I(inode)->lock);
1653 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1654 BTRFS_I(inode)->defrag_bytes -= len;
1655 spin_unlock(&BTRFS_I(inode)->lock);
1658 * set_bit and clear bit hooks normally require _irqsave/restore
1659 * but in this case, we are only testing for the DELALLOC
1660 * bit, which is only set or cleared with irqs on
1662 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1663 struct btrfs_root *root = BTRFS_I(inode)->root;
1664 bool do_list = !btrfs_is_free_space_inode(inode);
1666 if (*bits & EXTENT_FIRST_DELALLOC) {
1667 *bits &= ~EXTENT_FIRST_DELALLOC;
1668 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1669 spin_lock(&BTRFS_I(inode)->lock);
1670 BTRFS_I(inode)->outstanding_extents--;
1671 spin_unlock(&BTRFS_I(inode)->lock);
1675 * We don't reserve metadata space for space cache inodes so we
1676 * don't need to call dellalloc_release_metadata if there is an
1679 if (*bits & EXTENT_DO_ACCOUNTING &&
1680 root != root->fs_info->tree_root)
1681 btrfs_delalloc_release_metadata(inode, len);
1683 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1684 && do_list && !(state->state & EXTENT_NORESERVE))
1685 btrfs_free_reserved_data_space(inode, len);
1687 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1688 root->fs_info->delalloc_batch);
1689 spin_lock(&BTRFS_I(inode)->lock);
1690 BTRFS_I(inode)->delalloc_bytes -= len;
1691 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1692 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1693 &BTRFS_I(inode)->runtime_flags))
1694 btrfs_del_delalloc_inode(root, inode);
1695 spin_unlock(&BTRFS_I(inode)->lock);
1700 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1701 * we don't create bios that span stripes or chunks
1703 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1704 size_t size, struct bio *bio,
1705 unsigned long bio_flags)
1707 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1708 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1713 if (bio_flags & EXTENT_BIO_COMPRESSED)
1716 length = bio->bi_iter.bi_size;
1717 map_length = length;
1718 ret = btrfs_map_block(root->fs_info, rw, logical,
1719 &map_length, NULL, 0);
1720 /* Will always return 0 with map_multi == NULL */
1722 if (map_length < length + size)
1728 * in order to insert checksums into the metadata in large chunks,
1729 * we wait until bio submission time. All the pages in the bio are
1730 * checksummed and sums are attached onto the ordered extent record.
1732 * At IO completion time the cums attached on the ordered extent record
1733 * are inserted into the btree
1735 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1736 struct bio *bio, int mirror_num,
1737 unsigned long bio_flags,
1740 struct btrfs_root *root = BTRFS_I(inode)->root;
1743 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1744 BUG_ON(ret); /* -ENOMEM */
1749 * in order to insert checksums into the metadata in large chunks,
1750 * we wait until bio submission time. All the pages in the bio are
1751 * checksummed and sums are attached onto the ordered extent record.
1753 * At IO completion time the cums attached on the ordered extent record
1754 * are inserted into the btree
1756 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1757 int mirror_num, unsigned long bio_flags,
1760 struct btrfs_root *root = BTRFS_I(inode)->root;
1763 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1765 bio_endio(bio, ret);
1770 * extent_io.c submission hook. This does the right thing for csum calculation
1771 * on write, or reading the csums from the tree before a read
1773 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1774 int mirror_num, unsigned long bio_flags,
1777 struct btrfs_root *root = BTRFS_I(inode)->root;
1781 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1783 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1785 if (btrfs_is_free_space_inode(inode))
1788 if (!(rw & REQ_WRITE)) {
1789 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1793 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1794 ret = btrfs_submit_compressed_read(inode, bio,
1798 } else if (!skip_sum) {
1799 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1804 } else if (async && !skip_sum) {
1805 /* csum items have already been cloned */
1806 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1808 /* we're doing a write, do the async checksumming */
1809 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1810 inode, rw, bio, mirror_num,
1811 bio_flags, bio_offset,
1812 __btrfs_submit_bio_start,
1813 __btrfs_submit_bio_done);
1815 } else if (!skip_sum) {
1816 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1822 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1826 bio_endio(bio, ret);
1831 * given a list of ordered sums record them in the inode. This happens
1832 * at IO completion time based on sums calculated at bio submission time.
1834 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1835 struct inode *inode, u64 file_offset,
1836 struct list_head *list)
1838 struct btrfs_ordered_sum *sum;
1840 list_for_each_entry(sum, list, list) {
1841 trans->adding_csums = 1;
1842 btrfs_csum_file_blocks(trans,
1843 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1844 trans->adding_csums = 0;
1849 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1850 struct extent_state **cached_state)
1852 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1853 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1854 cached_state, GFP_NOFS);
1857 /* see btrfs_writepage_start_hook for details on why this is required */
1858 struct btrfs_writepage_fixup {
1860 struct btrfs_work work;
1863 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1865 struct btrfs_writepage_fixup *fixup;
1866 struct btrfs_ordered_extent *ordered;
1867 struct extent_state *cached_state = NULL;
1869 struct inode *inode;
1874 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1878 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1879 ClearPageChecked(page);
1883 inode = page->mapping->host;
1884 page_start = page_offset(page);
1885 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1887 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1890 /* already ordered? We're done */
1891 if (PagePrivate2(page))
1894 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1896 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1897 page_end, &cached_state, GFP_NOFS);
1899 btrfs_start_ordered_extent(inode, ordered, 1);
1900 btrfs_put_ordered_extent(ordered);
1904 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1906 mapping_set_error(page->mapping, ret);
1907 end_extent_writepage(page, ret, page_start, page_end);
1908 ClearPageChecked(page);
1912 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1913 ClearPageChecked(page);
1914 set_page_dirty(page);
1916 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1917 &cached_state, GFP_NOFS);
1920 page_cache_release(page);
1925 * There are a few paths in the higher layers of the kernel that directly
1926 * set the page dirty bit without asking the filesystem if it is a
1927 * good idea. This causes problems because we want to make sure COW
1928 * properly happens and the data=ordered rules are followed.
1930 * In our case any range that doesn't have the ORDERED bit set
1931 * hasn't been properly setup for IO. We kick off an async process
1932 * to fix it up. The async helper will wait for ordered extents, set
1933 * the delalloc bit and make it safe to write the page.
1935 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1937 struct inode *inode = page->mapping->host;
1938 struct btrfs_writepage_fixup *fixup;
1939 struct btrfs_root *root = BTRFS_I(inode)->root;
1941 /* this page is properly in the ordered list */
1942 if (TestClearPagePrivate2(page))
1945 if (PageChecked(page))
1948 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1952 SetPageChecked(page);
1953 page_cache_get(page);
1954 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
1955 btrfs_writepage_fixup_worker, NULL, NULL);
1957 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
1961 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1962 struct inode *inode, u64 file_pos,
1963 u64 disk_bytenr, u64 disk_num_bytes,
1964 u64 num_bytes, u64 ram_bytes,
1965 u8 compression, u8 encryption,
1966 u16 other_encoding, int extent_type)
1968 struct btrfs_root *root = BTRFS_I(inode)->root;
1969 struct btrfs_file_extent_item *fi;
1970 struct btrfs_path *path;
1971 struct extent_buffer *leaf;
1972 struct btrfs_key ins;
1973 int extent_inserted = 0;
1976 path = btrfs_alloc_path();
1981 * we may be replacing one extent in the tree with another.
1982 * The new extent is pinned in the extent map, and we don't want
1983 * to drop it from the cache until it is completely in the btree.
1985 * So, tell btrfs_drop_extents to leave this extent in the cache.
1986 * the caller is expected to unpin it and allow it to be merged
1989 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
1990 file_pos + num_bytes, NULL, 0,
1991 1, sizeof(*fi), &extent_inserted);
1995 if (!extent_inserted) {
1996 ins.objectid = btrfs_ino(inode);
1997 ins.offset = file_pos;
1998 ins.type = BTRFS_EXTENT_DATA_KEY;
2000 path->leave_spinning = 1;
2001 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2006 leaf = path->nodes[0];
2007 fi = btrfs_item_ptr(leaf, path->slots[0],
2008 struct btrfs_file_extent_item);
2009 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2010 btrfs_set_file_extent_type(leaf, fi, extent_type);
2011 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2012 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2013 btrfs_set_file_extent_offset(leaf, fi, 0);
2014 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2015 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2016 btrfs_set_file_extent_compression(leaf, fi, compression);
2017 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2018 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2020 btrfs_mark_buffer_dirty(leaf);
2021 btrfs_release_path(path);
2023 inode_add_bytes(inode, num_bytes);
2025 ins.objectid = disk_bytenr;
2026 ins.offset = disk_num_bytes;
2027 ins.type = BTRFS_EXTENT_ITEM_KEY;
2028 ret = btrfs_alloc_reserved_file_extent(trans, root,
2029 root->root_key.objectid,
2030 btrfs_ino(inode), file_pos, &ins);
2032 btrfs_free_path(path);
2037 /* snapshot-aware defrag */
2038 struct sa_defrag_extent_backref {
2039 struct rb_node node;
2040 struct old_sa_defrag_extent *old;
2049 struct old_sa_defrag_extent {
2050 struct list_head list;
2051 struct new_sa_defrag_extent *new;
2060 struct new_sa_defrag_extent {
2061 struct rb_root root;
2062 struct list_head head;
2063 struct btrfs_path *path;
2064 struct inode *inode;
2072 static int backref_comp(struct sa_defrag_extent_backref *b1,
2073 struct sa_defrag_extent_backref *b2)
2075 if (b1->root_id < b2->root_id)
2077 else if (b1->root_id > b2->root_id)
2080 if (b1->inum < b2->inum)
2082 else if (b1->inum > b2->inum)
2085 if (b1->file_pos < b2->file_pos)
2087 else if (b1->file_pos > b2->file_pos)
2091 * [------------------------------] ===> (a range of space)
2092 * |<--->| |<---->| =============> (fs/file tree A)
2093 * |<---------------------------->| ===> (fs/file tree B)
2095 * A range of space can refer to two file extents in one tree while
2096 * refer to only one file extent in another tree.
2098 * So we may process a disk offset more than one time(two extents in A)
2099 * and locate at the same extent(one extent in B), then insert two same
2100 * backrefs(both refer to the extent in B).
2105 static void backref_insert(struct rb_root *root,
2106 struct sa_defrag_extent_backref *backref)
2108 struct rb_node **p = &root->rb_node;
2109 struct rb_node *parent = NULL;
2110 struct sa_defrag_extent_backref *entry;
2115 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2117 ret = backref_comp(backref, entry);
2121 p = &(*p)->rb_right;
2124 rb_link_node(&backref->node, parent, p);
2125 rb_insert_color(&backref->node, root);
2129 * Note the backref might has changed, and in this case we just return 0.
2131 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2134 struct btrfs_file_extent_item *extent;
2135 struct btrfs_fs_info *fs_info;
2136 struct old_sa_defrag_extent *old = ctx;
2137 struct new_sa_defrag_extent *new = old->new;
2138 struct btrfs_path *path = new->path;
2139 struct btrfs_key key;
2140 struct btrfs_root *root;
2141 struct sa_defrag_extent_backref *backref;
2142 struct extent_buffer *leaf;
2143 struct inode *inode = new->inode;
2149 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2150 inum == btrfs_ino(inode))
2153 key.objectid = root_id;
2154 key.type = BTRFS_ROOT_ITEM_KEY;
2155 key.offset = (u64)-1;
2157 fs_info = BTRFS_I(inode)->root->fs_info;
2158 root = btrfs_read_fs_root_no_name(fs_info, &key);
2160 if (PTR_ERR(root) == -ENOENT)
2163 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2164 inum, offset, root_id);
2165 return PTR_ERR(root);
2168 key.objectid = inum;
2169 key.type = BTRFS_EXTENT_DATA_KEY;
2170 if (offset > (u64)-1 << 32)
2173 key.offset = offset;
2175 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2176 if (WARN_ON(ret < 0))
2183 leaf = path->nodes[0];
2184 slot = path->slots[0];
2186 if (slot >= btrfs_header_nritems(leaf)) {
2187 ret = btrfs_next_leaf(root, path);
2190 } else if (ret > 0) {
2199 btrfs_item_key_to_cpu(leaf, &key, slot);
2201 if (key.objectid > inum)
2204 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2207 extent = btrfs_item_ptr(leaf, slot,
2208 struct btrfs_file_extent_item);
2210 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2214 * 'offset' refers to the exact key.offset,
2215 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2216 * (key.offset - extent_offset).
2218 if (key.offset != offset)
2221 extent_offset = btrfs_file_extent_offset(leaf, extent);
2222 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2224 if (extent_offset >= old->extent_offset + old->offset +
2225 old->len || extent_offset + num_bytes <=
2226 old->extent_offset + old->offset)
2231 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2237 backref->root_id = root_id;
2238 backref->inum = inum;
2239 backref->file_pos = offset;
2240 backref->num_bytes = num_bytes;
2241 backref->extent_offset = extent_offset;
2242 backref->generation = btrfs_file_extent_generation(leaf, extent);
2244 backref_insert(&new->root, backref);
2247 btrfs_release_path(path);
2252 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2253 struct new_sa_defrag_extent *new)
2255 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2256 struct old_sa_defrag_extent *old, *tmp;
2261 list_for_each_entry_safe(old, tmp, &new->head, list) {
2262 ret = iterate_inodes_from_logical(old->bytenr +
2263 old->extent_offset, fs_info,
2264 path, record_one_backref,
2266 if (ret < 0 && ret != -ENOENT)
2269 /* no backref to be processed for this extent */
2271 list_del(&old->list);
2276 if (list_empty(&new->head))
2282 static int relink_is_mergable(struct extent_buffer *leaf,
2283 struct btrfs_file_extent_item *fi,
2284 struct new_sa_defrag_extent *new)
2286 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2289 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2292 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2295 if (btrfs_file_extent_encryption(leaf, fi) ||
2296 btrfs_file_extent_other_encoding(leaf, fi))
2303 * Note the backref might has changed, and in this case we just return 0.
2305 static noinline int relink_extent_backref(struct btrfs_path *path,
2306 struct sa_defrag_extent_backref *prev,
2307 struct sa_defrag_extent_backref *backref)
2309 struct btrfs_file_extent_item *extent;
2310 struct btrfs_file_extent_item *item;
2311 struct btrfs_ordered_extent *ordered;
2312 struct btrfs_trans_handle *trans;
2313 struct btrfs_fs_info *fs_info;
2314 struct btrfs_root *root;
2315 struct btrfs_key key;
2316 struct extent_buffer *leaf;
2317 struct old_sa_defrag_extent *old = backref->old;
2318 struct new_sa_defrag_extent *new = old->new;
2319 struct inode *src_inode = new->inode;
2320 struct inode *inode;
2321 struct extent_state *cached = NULL;
2330 if (prev && prev->root_id == backref->root_id &&
2331 prev->inum == backref->inum &&
2332 prev->file_pos + prev->num_bytes == backref->file_pos)
2335 /* step 1: get root */
2336 key.objectid = backref->root_id;
2337 key.type = BTRFS_ROOT_ITEM_KEY;
2338 key.offset = (u64)-1;
2340 fs_info = BTRFS_I(src_inode)->root->fs_info;
2341 index = srcu_read_lock(&fs_info->subvol_srcu);
2343 root = btrfs_read_fs_root_no_name(fs_info, &key);
2345 srcu_read_unlock(&fs_info->subvol_srcu, index);
2346 if (PTR_ERR(root) == -ENOENT)
2348 return PTR_ERR(root);
2351 if (btrfs_root_readonly(root)) {
2352 srcu_read_unlock(&fs_info->subvol_srcu, index);
2356 /* step 2: get inode */
2357 key.objectid = backref->inum;
2358 key.type = BTRFS_INODE_ITEM_KEY;
2361 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2362 if (IS_ERR(inode)) {
2363 srcu_read_unlock(&fs_info->subvol_srcu, index);
2367 srcu_read_unlock(&fs_info->subvol_srcu, index);
2369 /* step 3: relink backref */
2370 lock_start = backref->file_pos;
2371 lock_end = backref->file_pos + backref->num_bytes - 1;
2372 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2375 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2377 btrfs_put_ordered_extent(ordered);
2381 trans = btrfs_join_transaction(root);
2382 if (IS_ERR(trans)) {
2383 ret = PTR_ERR(trans);
2387 key.objectid = backref->inum;
2388 key.type = BTRFS_EXTENT_DATA_KEY;
2389 key.offset = backref->file_pos;
2391 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2394 } else if (ret > 0) {
2399 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2400 struct btrfs_file_extent_item);
2402 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2403 backref->generation)
2406 btrfs_release_path(path);
2408 start = backref->file_pos;
2409 if (backref->extent_offset < old->extent_offset + old->offset)
2410 start += old->extent_offset + old->offset -
2411 backref->extent_offset;
2413 len = min(backref->extent_offset + backref->num_bytes,
2414 old->extent_offset + old->offset + old->len);
2415 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2417 ret = btrfs_drop_extents(trans, root, inode, start,
2422 key.objectid = btrfs_ino(inode);
2423 key.type = BTRFS_EXTENT_DATA_KEY;
2426 path->leave_spinning = 1;
2428 struct btrfs_file_extent_item *fi;
2430 struct btrfs_key found_key;
2432 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2437 leaf = path->nodes[0];
2438 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2440 fi = btrfs_item_ptr(leaf, path->slots[0],
2441 struct btrfs_file_extent_item);
2442 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2444 if (extent_len + found_key.offset == start &&
2445 relink_is_mergable(leaf, fi, new)) {
2446 btrfs_set_file_extent_num_bytes(leaf, fi,
2448 btrfs_mark_buffer_dirty(leaf);
2449 inode_add_bytes(inode, len);
2455 btrfs_release_path(path);
2460 ret = btrfs_insert_empty_item(trans, root, path, &key,
2463 btrfs_abort_transaction(trans, root, ret);
2467 leaf = path->nodes[0];
2468 item = btrfs_item_ptr(leaf, path->slots[0],
2469 struct btrfs_file_extent_item);
2470 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2471 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2472 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2473 btrfs_set_file_extent_num_bytes(leaf, item, len);
2474 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2475 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2476 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2477 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2478 btrfs_set_file_extent_encryption(leaf, item, 0);
2479 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2481 btrfs_mark_buffer_dirty(leaf);
2482 inode_add_bytes(inode, len);
2483 btrfs_release_path(path);
2485 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2487 backref->root_id, backref->inum,
2488 new->file_pos, 0); /* start - extent_offset */
2490 btrfs_abort_transaction(trans, root, ret);
2496 btrfs_release_path(path);
2497 path->leave_spinning = 0;
2498 btrfs_end_transaction(trans, root);
2500 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2506 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2508 struct old_sa_defrag_extent *old, *tmp;
2513 list_for_each_entry_safe(old, tmp, &new->head, list) {
2514 list_del(&old->list);
2520 static void relink_file_extents(struct new_sa_defrag_extent *new)
2522 struct btrfs_path *path;
2523 struct sa_defrag_extent_backref *backref;
2524 struct sa_defrag_extent_backref *prev = NULL;
2525 struct inode *inode;
2526 struct btrfs_root *root;
2527 struct rb_node *node;
2531 root = BTRFS_I(inode)->root;
2533 path = btrfs_alloc_path();
2537 if (!record_extent_backrefs(path, new)) {
2538 btrfs_free_path(path);
2541 btrfs_release_path(path);
2544 node = rb_first(&new->root);
2547 rb_erase(node, &new->root);
2549 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2551 ret = relink_extent_backref(path, prev, backref);
2564 btrfs_free_path(path);
2566 free_sa_defrag_extent(new);
2568 atomic_dec(&root->fs_info->defrag_running);
2569 wake_up(&root->fs_info->transaction_wait);
2572 static struct new_sa_defrag_extent *
2573 record_old_file_extents(struct inode *inode,
2574 struct btrfs_ordered_extent *ordered)
2576 struct btrfs_root *root = BTRFS_I(inode)->root;
2577 struct btrfs_path *path;
2578 struct btrfs_key key;
2579 struct old_sa_defrag_extent *old;
2580 struct new_sa_defrag_extent *new;
2583 new = kmalloc(sizeof(*new), GFP_NOFS);
2588 new->file_pos = ordered->file_offset;
2589 new->len = ordered->len;
2590 new->bytenr = ordered->start;
2591 new->disk_len = ordered->disk_len;
2592 new->compress_type = ordered->compress_type;
2593 new->root = RB_ROOT;
2594 INIT_LIST_HEAD(&new->head);
2596 path = btrfs_alloc_path();
2600 key.objectid = btrfs_ino(inode);
2601 key.type = BTRFS_EXTENT_DATA_KEY;
2602 key.offset = new->file_pos;
2604 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2607 if (ret > 0 && path->slots[0] > 0)
2610 /* find out all the old extents for the file range */
2612 struct btrfs_file_extent_item *extent;
2613 struct extent_buffer *l;
2622 slot = path->slots[0];
2624 if (slot >= btrfs_header_nritems(l)) {
2625 ret = btrfs_next_leaf(root, path);
2633 btrfs_item_key_to_cpu(l, &key, slot);
2635 if (key.objectid != btrfs_ino(inode))
2637 if (key.type != BTRFS_EXTENT_DATA_KEY)
2639 if (key.offset >= new->file_pos + new->len)
2642 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2644 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2645 if (key.offset + num_bytes < new->file_pos)
2648 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2652 extent_offset = btrfs_file_extent_offset(l, extent);
2654 old = kmalloc(sizeof(*old), GFP_NOFS);
2658 offset = max(new->file_pos, key.offset);
2659 end = min(new->file_pos + new->len, key.offset + num_bytes);
2661 old->bytenr = disk_bytenr;
2662 old->extent_offset = extent_offset;
2663 old->offset = offset - key.offset;
2664 old->len = end - offset;
2667 list_add_tail(&old->list, &new->head);
2673 btrfs_free_path(path);
2674 atomic_inc(&root->fs_info->defrag_running);
2679 btrfs_free_path(path);
2681 free_sa_defrag_extent(new);
2685 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2688 struct btrfs_block_group_cache *cache;
2690 cache = btrfs_lookup_block_group(root->fs_info, start);
2693 spin_lock(&cache->lock);
2694 cache->delalloc_bytes -= len;
2695 spin_unlock(&cache->lock);
2697 btrfs_put_block_group(cache);
2700 /* as ordered data IO finishes, this gets called so we can finish
2701 * an ordered extent if the range of bytes in the file it covers are
2704 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2706 struct inode *inode = ordered_extent->inode;
2707 struct btrfs_root *root = BTRFS_I(inode)->root;
2708 struct btrfs_trans_handle *trans = NULL;
2709 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2710 struct extent_state *cached_state = NULL;
2711 struct new_sa_defrag_extent *new = NULL;
2712 int compress_type = 0;
2714 u64 logical_len = ordered_extent->len;
2716 bool truncated = false;
2718 nolock = btrfs_is_free_space_inode(inode);
2720 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2725 btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2726 ordered_extent->file_offset +
2727 ordered_extent->len - 1);
2729 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2731 logical_len = ordered_extent->truncated_len;
2732 /* Truncated the entire extent, don't bother adding */
2737 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2738 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2739 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2741 trans = btrfs_join_transaction_nolock(root);
2743 trans = btrfs_join_transaction(root);
2744 if (IS_ERR(trans)) {
2745 ret = PTR_ERR(trans);
2749 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2750 ret = btrfs_update_inode_fallback(trans, root, inode);
2751 if (ret) /* -ENOMEM or corruption */
2752 btrfs_abort_transaction(trans, root, ret);
2756 lock_extent_bits(io_tree, ordered_extent->file_offset,
2757 ordered_extent->file_offset + ordered_extent->len - 1,
2760 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2761 ordered_extent->file_offset + ordered_extent->len - 1,
2762 EXTENT_DEFRAG, 1, cached_state);
2764 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2765 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2766 /* the inode is shared */
2767 new = record_old_file_extents(inode, ordered_extent);
2769 clear_extent_bit(io_tree, ordered_extent->file_offset,
2770 ordered_extent->file_offset + ordered_extent->len - 1,
2771 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2775 trans = btrfs_join_transaction_nolock(root);
2777 trans = btrfs_join_transaction(root);
2778 if (IS_ERR(trans)) {
2779 ret = PTR_ERR(trans);
2784 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2786 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2787 compress_type = ordered_extent->compress_type;
2788 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2789 BUG_ON(compress_type);
2790 ret = btrfs_mark_extent_written(trans, inode,
2791 ordered_extent->file_offset,
2792 ordered_extent->file_offset +
2795 BUG_ON(root == root->fs_info->tree_root);
2796 ret = insert_reserved_file_extent(trans, inode,
2797 ordered_extent->file_offset,
2798 ordered_extent->start,
2799 ordered_extent->disk_len,
2800 logical_len, logical_len,
2801 compress_type, 0, 0,
2802 BTRFS_FILE_EXTENT_REG);
2804 btrfs_release_delalloc_bytes(root,
2805 ordered_extent->start,
2806 ordered_extent->disk_len);
2808 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2809 ordered_extent->file_offset, ordered_extent->len,
2812 btrfs_abort_transaction(trans, root, ret);
2816 add_pending_csums(trans, inode, ordered_extent->file_offset,
2817 &ordered_extent->list);
2819 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2820 ret = btrfs_update_inode_fallback(trans, root, inode);
2821 if (ret) { /* -ENOMEM or corruption */
2822 btrfs_abort_transaction(trans, root, ret);
2827 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2828 ordered_extent->file_offset +
2829 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2831 if (root != root->fs_info->tree_root)
2832 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2834 btrfs_end_transaction(trans, root);
2836 if (ret || truncated) {
2840 start = ordered_extent->file_offset + logical_len;
2842 start = ordered_extent->file_offset;
2843 end = ordered_extent->file_offset + ordered_extent->len - 1;
2844 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2846 /* Drop the cache for the part of the extent we didn't write. */
2847 btrfs_drop_extent_cache(inode, start, end, 0);
2850 * If the ordered extent had an IOERR or something else went
2851 * wrong we need to return the space for this ordered extent
2852 * back to the allocator. We only free the extent in the
2853 * truncated case if we didn't write out the extent at all.
2855 if ((ret || !logical_len) &&
2856 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2857 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2858 btrfs_free_reserved_extent(root, ordered_extent->start,
2859 ordered_extent->disk_len, 1);
2864 * This needs to be done to make sure anybody waiting knows we are done
2865 * updating everything for this ordered extent.
2867 btrfs_remove_ordered_extent(inode, ordered_extent);
2869 /* for snapshot-aware defrag */
2872 free_sa_defrag_extent(new);
2873 atomic_dec(&root->fs_info->defrag_running);
2875 relink_file_extents(new);
2880 btrfs_put_ordered_extent(ordered_extent);
2881 /* once for the tree */
2882 btrfs_put_ordered_extent(ordered_extent);
2887 static void finish_ordered_fn(struct btrfs_work *work)
2889 struct btrfs_ordered_extent *ordered_extent;
2890 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2891 btrfs_finish_ordered_io(ordered_extent);
2894 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2895 struct extent_state *state, int uptodate)
2897 struct inode *inode = page->mapping->host;
2898 struct btrfs_root *root = BTRFS_I(inode)->root;
2899 struct btrfs_ordered_extent *ordered_extent = NULL;
2900 struct btrfs_workqueue *wq;
2901 btrfs_work_func_t func;
2903 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2905 ClearPagePrivate2(page);
2906 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2907 end - start + 1, uptodate))
2910 if (btrfs_is_free_space_inode(inode)) {
2911 wq = root->fs_info->endio_freespace_worker;
2912 func = btrfs_freespace_write_helper;
2914 wq = root->fs_info->endio_write_workers;
2915 func = btrfs_endio_write_helper;
2918 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
2920 btrfs_queue_work(wq, &ordered_extent->work);
2925 static int __readpage_endio_check(struct inode *inode,
2926 struct btrfs_io_bio *io_bio,
2927 int icsum, struct page *page,
2928 int pgoff, u64 start, size_t len)
2933 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2934 DEFAULT_RATELIMIT_BURST);
2936 csum_expected = *(((u32 *)io_bio->csum) + icsum);
2938 kaddr = kmap_atomic(page);
2939 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
2940 btrfs_csum_final(csum, (char *)&csum);
2941 if (csum != csum_expected)
2944 kunmap_atomic(kaddr);
2947 if (__ratelimit(&_rs))
2948 btrfs_info(BTRFS_I(inode)->root->fs_info,
2949 "csum failed ino %llu off %llu csum %u expected csum %u",
2950 btrfs_ino(inode), start, csum, csum_expected);
2951 memset(kaddr + pgoff, 1, len);
2952 flush_dcache_page(page);
2953 kunmap_atomic(kaddr);
2954 if (csum_expected == 0)
2960 * when reads are done, we need to check csums to verify the data is correct
2961 * if there's a match, we allow the bio to finish. If not, the code in
2962 * extent_io.c will try to find good copies for us.
2964 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2965 u64 phy_offset, struct page *page,
2966 u64 start, u64 end, int mirror)
2968 size_t offset = start - page_offset(page);
2969 struct inode *inode = page->mapping->host;
2970 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2971 struct btrfs_root *root = BTRFS_I(inode)->root;
2973 if (PageChecked(page)) {
2974 ClearPageChecked(page);
2978 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2981 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2982 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2983 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2988 phy_offset >>= inode->i_sb->s_blocksize_bits;
2989 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
2990 start, (size_t)(end - start + 1));
2993 struct delayed_iput {
2994 struct list_head list;
2995 struct inode *inode;
2998 /* JDM: If this is fs-wide, why can't we add a pointer to
2999 * btrfs_inode instead and avoid the allocation? */
3000 void btrfs_add_delayed_iput(struct inode *inode)
3002 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3003 struct delayed_iput *delayed;
3005 if (atomic_add_unless(&inode->i_count, -1, 1))
3008 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
3009 delayed->inode = inode;
3011 spin_lock(&fs_info->delayed_iput_lock);
3012 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
3013 spin_unlock(&fs_info->delayed_iput_lock);
3016 void btrfs_run_delayed_iputs(struct btrfs_root *root)
3019 struct btrfs_fs_info *fs_info = root->fs_info;
3020 struct delayed_iput *delayed;
3023 spin_lock(&fs_info->delayed_iput_lock);
3024 empty = list_empty(&fs_info->delayed_iputs);
3025 spin_unlock(&fs_info->delayed_iput_lock);
3029 spin_lock(&fs_info->delayed_iput_lock);
3030 list_splice_init(&fs_info->delayed_iputs, &list);
3031 spin_unlock(&fs_info->delayed_iput_lock);
3033 while (!list_empty(&list)) {
3034 delayed = list_entry(list.next, struct delayed_iput, list);
3035 list_del(&delayed->list);
3036 iput(delayed->inode);
3042 * This is called in transaction commit time. If there are no orphan
3043 * files in the subvolume, it removes orphan item and frees block_rsv
3046 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3047 struct btrfs_root *root)
3049 struct btrfs_block_rsv *block_rsv;
3052 if (atomic_read(&root->orphan_inodes) ||
3053 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3056 spin_lock(&root->orphan_lock);
3057 if (atomic_read(&root->orphan_inodes)) {
3058 spin_unlock(&root->orphan_lock);
3062 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3063 spin_unlock(&root->orphan_lock);
3067 block_rsv = root->orphan_block_rsv;
3068 root->orphan_block_rsv = NULL;
3069 spin_unlock(&root->orphan_lock);
3071 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3072 btrfs_root_refs(&root->root_item) > 0) {
3073 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
3074 root->root_key.objectid);
3076 btrfs_abort_transaction(trans, root, ret);
3078 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3083 WARN_ON(block_rsv->size > 0);
3084 btrfs_free_block_rsv(root, block_rsv);
3089 * This creates an orphan entry for the given inode in case something goes
3090 * wrong in the middle of an unlink/truncate.
3092 * NOTE: caller of this function should reserve 5 units of metadata for
3095 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3097 struct btrfs_root *root = BTRFS_I(inode)->root;
3098 struct btrfs_block_rsv *block_rsv = NULL;
3103 if (!root->orphan_block_rsv) {
3104 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3109 spin_lock(&root->orphan_lock);
3110 if (!root->orphan_block_rsv) {
3111 root->orphan_block_rsv = block_rsv;
3112 } else if (block_rsv) {
3113 btrfs_free_block_rsv(root, block_rsv);
3117 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3118 &BTRFS_I(inode)->runtime_flags)) {
3121 * For proper ENOSPC handling, we should do orphan
3122 * cleanup when mounting. But this introduces backward
3123 * compatibility issue.
3125 if (!xchg(&root->orphan_item_inserted, 1))
3131 atomic_inc(&root->orphan_inodes);
3134 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3135 &BTRFS_I(inode)->runtime_flags))
3137 spin_unlock(&root->orphan_lock);
3139 /* grab metadata reservation from transaction handle */
3141 ret = btrfs_orphan_reserve_metadata(trans, inode);
3142 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3145 /* insert an orphan item to track this unlinked/truncated file */
3147 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3149 atomic_dec(&root->orphan_inodes);
3151 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3152 &BTRFS_I(inode)->runtime_flags);
3153 btrfs_orphan_release_metadata(inode);
3155 if (ret != -EEXIST) {
3156 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3157 &BTRFS_I(inode)->runtime_flags);
3158 btrfs_abort_transaction(trans, root, ret);
3165 /* insert an orphan item to track subvolume contains orphan files */
3167 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3168 root->root_key.objectid);
3169 if (ret && ret != -EEXIST) {
3170 btrfs_abort_transaction(trans, root, ret);
3178 * We have done the truncate/delete so we can go ahead and remove the orphan
3179 * item for this particular inode.
3181 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3182 struct inode *inode)
3184 struct btrfs_root *root = BTRFS_I(inode)->root;
3185 int delete_item = 0;
3186 int release_rsv = 0;
3189 spin_lock(&root->orphan_lock);
3190 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3191 &BTRFS_I(inode)->runtime_flags))
3194 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3195 &BTRFS_I(inode)->runtime_flags))
3197 spin_unlock(&root->orphan_lock);
3200 atomic_dec(&root->orphan_inodes);
3202 ret = btrfs_del_orphan_item(trans, root,
3207 btrfs_orphan_release_metadata(inode);
3213 * this cleans up any orphans that may be left on the list from the last use
3216 int btrfs_orphan_cleanup(struct btrfs_root *root)
3218 struct btrfs_path *path;
3219 struct extent_buffer *leaf;
3220 struct btrfs_key key, found_key;
3221 struct btrfs_trans_handle *trans;
3222 struct inode *inode;
3223 u64 last_objectid = 0;
3224 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3226 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3229 path = btrfs_alloc_path();
3236 key.objectid = BTRFS_ORPHAN_OBJECTID;
3237 key.type = BTRFS_ORPHAN_ITEM_KEY;
3238 key.offset = (u64)-1;
3241 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3246 * if ret == 0 means we found what we were searching for, which
3247 * is weird, but possible, so only screw with path if we didn't
3248 * find the key and see if we have stuff that matches
3252 if (path->slots[0] == 0)
3257 /* pull out the item */
3258 leaf = path->nodes[0];
3259 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3261 /* make sure the item matches what we want */
3262 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3264 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3267 /* release the path since we're done with it */
3268 btrfs_release_path(path);
3271 * this is where we are basically btrfs_lookup, without the
3272 * crossing root thing. we store the inode number in the
3273 * offset of the orphan item.
3276 if (found_key.offset == last_objectid) {
3277 btrfs_err(root->fs_info,
3278 "Error removing orphan entry, stopping orphan cleanup");
3283 last_objectid = found_key.offset;
3285 found_key.objectid = found_key.offset;
3286 found_key.type = BTRFS_INODE_ITEM_KEY;
3287 found_key.offset = 0;
3288 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3289 ret = PTR_ERR_OR_ZERO(inode);
3290 if (ret && ret != -ESTALE)
3293 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3294 struct btrfs_root *dead_root;
3295 struct btrfs_fs_info *fs_info = root->fs_info;
3296 int is_dead_root = 0;
3299 * this is an orphan in the tree root. Currently these
3300 * could come from 2 sources:
3301 * a) a snapshot deletion in progress
3302 * b) a free space cache inode
3303 * We need to distinguish those two, as the snapshot
3304 * orphan must not get deleted.
3305 * find_dead_roots already ran before us, so if this
3306 * is a snapshot deletion, we should find the root
3307 * in the dead_roots list
3309 spin_lock(&fs_info->trans_lock);
3310 list_for_each_entry(dead_root, &fs_info->dead_roots,
3312 if (dead_root->root_key.objectid ==
3313 found_key.objectid) {
3318 spin_unlock(&fs_info->trans_lock);
3320 /* prevent this orphan from being found again */
3321 key.offset = found_key.objectid - 1;
3326 * Inode is already gone but the orphan item is still there,
3327 * kill the orphan item.
3329 if (ret == -ESTALE) {
3330 trans = btrfs_start_transaction(root, 1);
3331 if (IS_ERR(trans)) {
3332 ret = PTR_ERR(trans);
3335 btrfs_debug(root->fs_info, "auto deleting %Lu",
3336 found_key.objectid);
3337 ret = btrfs_del_orphan_item(trans, root,
3338 found_key.objectid);
3339 btrfs_end_transaction(trans, root);
3346 * add this inode to the orphan list so btrfs_orphan_del does
3347 * the proper thing when we hit it
3349 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3350 &BTRFS_I(inode)->runtime_flags);
3351 atomic_inc(&root->orphan_inodes);
3353 /* if we have links, this was a truncate, lets do that */
3354 if (inode->i_nlink) {
3355 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3361 /* 1 for the orphan item deletion. */
3362 trans = btrfs_start_transaction(root, 1);
3363 if (IS_ERR(trans)) {
3365 ret = PTR_ERR(trans);
3368 ret = btrfs_orphan_add(trans, inode);
3369 btrfs_end_transaction(trans, root);
3375 ret = btrfs_truncate(inode);
3377 btrfs_orphan_del(NULL, inode);
3382 /* this will do delete_inode and everything for us */
3387 /* release the path since we're done with it */
3388 btrfs_release_path(path);
3390 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3392 if (root->orphan_block_rsv)
3393 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3396 if (root->orphan_block_rsv ||
3397 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3398 trans = btrfs_join_transaction(root);
3400 btrfs_end_transaction(trans, root);
3404 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3406 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3410 btrfs_crit(root->fs_info,
3411 "could not do orphan cleanup %d", ret);
3412 btrfs_free_path(path);
3417 * very simple check to peek ahead in the leaf looking for xattrs. If we
3418 * don't find any xattrs, we know there can't be any acls.
3420 * slot is the slot the inode is in, objectid is the objectid of the inode
3422 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3423 int slot, u64 objectid,
3424 int *first_xattr_slot)
3426 u32 nritems = btrfs_header_nritems(leaf);
3427 struct btrfs_key found_key;
3428 static u64 xattr_access = 0;
3429 static u64 xattr_default = 0;
3432 if (!xattr_access) {
3433 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3434 strlen(POSIX_ACL_XATTR_ACCESS));
3435 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3436 strlen(POSIX_ACL_XATTR_DEFAULT));
3440 *first_xattr_slot = -1;
3441 while (slot < nritems) {
3442 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3444 /* we found a different objectid, there must not be acls */
3445 if (found_key.objectid != objectid)
3448 /* we found an xattr, assume we've got an acl */
3449 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3450 if (*first_xattr_slot == -1)
3451 *first_xattr_slot = slot;
3452 if (found_key.offset == xattr_access ||
3453 found_key.offset == xattr_default)
3458 * we found a key greater than an xattr key, there can't
3459 * be any acls later on
3461 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3468 * it goes inode, inode backrefs, xattrs, extents,
3469 * so if there are a ton of hard links to an inode there can
3470 * be a lot of backrefs. Don't waste time searching too hard,
3471 * this is just an optimization
3476 /* we hit the end of the leaf before we found an xattr or
3477 * something larger than an xattr. We have to assume the inode
3480 if (*first_xattr_slot == -1)
3481 *first_xattr_slot = slot;
3486 * read an inode from the btree into the in-memory inode
3488 static void btrfs_read_locked_inode(struct inode *inode)
3490 struct btrfs_path *path;
3491 struct extent_buffer *leaf;
3492 struct btrfs_inode_item *inode_item;
3493 struct btrfs_timespec *tspec;
3494 struct btrfs_root *root = BTRFS_I(inode)->root;
3495 struct btrfs_key location;
3500 bool filled = false;
3501 int first_xattr_slot;
3503 ret = btrfs_fill_inode(inode, &rdev);
3507 path = btrfs_alloc_path();
3511 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3513 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3517 leaf = path->nodes[0];
3522 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3523 struct btrfs_inode_item);
3524 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3525 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3526 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3527 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3528 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3530 tspec = btrfs_inode_atime(inode_item);
3531 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3532 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3534 tspec = btrfs_inode_mtime(inode_item);
3535 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3536 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3538 tspec = btrfs_inode_ctime(inode_item);
3539 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3540 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3542 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3543 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3544 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3547 * If we were modified in the current generation and evicted from memory
3548 * and then re-read we need to do a full sync since we don't have any
3549 * idea about which extents were modified before we were evicted from
3552 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3553 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3554 &BTRFS_I(inode)->runtime_flags);
3556 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3557 inode->i_generation = BTRFS_I(inode)->generation;
3559 rdev = btrfs_inode_rdev(leaf, inode_item);
3561 BTRFS_I(inode)->index_cnt = (u64)-1;
3562 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3566 if (inode->i_nlink != 1 ||
3567 path->slots[0] >= btrfs_header_nritems(leaf))
3570 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3571 if (location.objectid != btrfs_ino(inode))
3574 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3575 if (location.type == BTRFS_INODE_REF_KEY) {
3576 struct btrfs_inode_ref *ref;
3578 ref = (struct btrfs_inode_ref *)ptr;
3579 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3580 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3581 struct btrfs_inode_extref *extref;
3583 extref = (struct btrfs_inode_extref *)ptr;
3584 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3589 * try to precache a NULL acl entry for files that don't have
3590 * any xattrs or acls
3592 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3593 btrfs_ino(inode), &first_xattr_slot);
3594 if (first_xattr_slot != -1) {
3595 path->slots[0] = first_xattr_slot;
3596 ret = btrfs_load_inode_props(inode, path);
3598 btrfs_err(root->fs_info,
3599 "error loading props for ino %llu (root %llu): %d",
3601 root->root_key.objectid, ret);
3603 btrfs_free_path(path);
3606 cache_no_acl(inode);
3608 switch (inode->i_mode & S_IFMT) {
3610 inode->i_mapping->a_ops = &btrfs_aops;
3611 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3612 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3613 inode->i_fop = &btrfs_file_operations;
3614 inode->i_op = &btrfs_file_inode_operations;
3617 inode->i_fop = &btrfs_dir_file_operations;
3618 if (root == root->fs_info->tree_root)
3619 inode->i_op = &btrfs_dir_ro_inode_operations;
3621 inode->i_op = &btrfs_dir_inode_operations;
3624 inode->i_op = &btrfs_symlink_inode_operations;
3625 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3626 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3629 inode->i_op = &btrfs_special_inode_operations;
3630 init_special_inode(inode, inode->i_mode, rdev);
3634 btrfs_update_iflags(inode);
3638 btrfs_free_path(path);
3639 make_bad_inode(inode);
3643 * given a leaf and an inode, copy the inode fields into the leaf
3645 static void fill_inode_item(struct btrfs_trans_handle *trans,
3646 struct extent_buffer *leaf,
3647 struct btrfs_inode_item *item,
3648 struct inode *inode)
3650 struct btrfs_map_token token;
3652 btrfs_init_map_token(&token);
3654 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3655 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3656 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3658 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3659 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3661 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3662 inode->i_atime.tv_sec, &token);
3663 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3664 inode->i_atime.tv_nsec, &token);
3666 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3667 inode->i_mtime.tv_sec, &token);
3668 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3669 inode->i_mtime.tv_nsec, &token);
3671 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3672 inode->i_ctime.tv_sec, &token);
3673 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3674 inode->i_ctime.tv_nsec, &token);
3676 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3678 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3680 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3681 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3682 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3683 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3684 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3688 * copy everything in the in-memory inode into the btree.
3690 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3691 struct btrfs_root *root, struct inode *inode)
3693 struct btrfs_inode_item *inode_item;
3694 struct btrfs_path *path;
3695 struct extent_buffer *leaf;
3698 path = btrfs_alloc_path();
3702 path->leave_spinning = 1;
3703 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3711 leaf = path->nodes[0];
3712 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3713 struct btrfs_inode_item);
3715 fill_inode_item(trans, leaf, inode_item, inode);
3716 btrfs_mark_buffer_dirty(leaf);
3717 btrfs_set_inode_last_trans(trans, inode);
3720 btrfs_free_path(path);
3725 * copy everything in the in-memory inode into the btree.
3727 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3728 struct btrfs_root *root, struct inode *inode)
3733 * If the inode is a free space inode, we can deadlock during commit
3734 * if we put it into the delayed code.
3736 * The data relocation inode should also be directly updated
3739 if (!btrfs_is_free_space_inode(inode)
3740 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3741 && !root->fs_info->log_root_recovering) {
3742 btrfs_update_root_times(trans, root);
3744 ret = btrfs_delayed_update_inode(trans, root, inode);
3746 btrfs_set_inode_last_trans(trans, inode);
3750 return btrfs_update_inode_item(trans, root, inode);
3753 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3754 struct btrfs_root *root,
3755 struct inode *inode)
3759 ret = btrfs_update_inode(trans, root, inode);
3761 return btrfs_update_inode_item(trans, root, inode);
3766 * unlink helper that gets used here in inode.c and in the tree logging
3767 * recovery code. It remove a link in a directory with a given name, and
3768 * also drops the back refs in the inode to the directory
3770 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3771 struct btrfs_root *root,
3772 struct inode *dir, struct inode *inode,
3773 const char *name, int name_len)
3775 struct btrfs_path *path;
3777 struct extent_buffer *leaf;
3778 struct btrfs_dir_item *di;
3779 struct btrfs_key key;
3781 u64 ino = btrfs_ino(inode);
3782 u64 dir_ino = btrfs_ino(dir);
3784 path = btrfs_alloc_path();
3790 path->leave_spinning = 1;
3791 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3792 name, name_len, -1);
3801 leaf = path->nodes[0];
3802 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3803 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3806 btrfs_release_path(path);
3809 * If we don't have dir index, we have to get it by looking up
3810 * the inode ref, since we get the inode ref, remove it directly,
3811 * it is unnecessary to do delayed deletion.
3813 * But if we have dir index, needn't search inode ref to get it.
3814 * Since the inode ref is close to the inode item, it is better
3815 * that we delay to delete it, and just do this deletion when
3816 * we update the inode item.
3818 if (BTRFS_I(inode)->dir_index) {
3819 ret = btrfs_delayed_delete_inode_ref(inode);
3821 index = BTRFS_I(inode)->dir_index;
3826 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3829 btrfs_info(root->fs_info,
3830 "failed to delete reference to %.*s, inode %llu parent %llu",
3831 name_len, name, ino, dir_ino);
3832 btrfs_abort_transaction(trans, root, ret);
3836 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3838 btrfs_abort_transaction(trans, root, ret);
3842 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3844 if (ret != 0 && ret != -ENOENT) {
3845 btrfs_abort_transaction(trans, root, ret);
3849 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3854 btrfs_abort_transaction(trans, root, ret);
3856 btrfs_free_path(path);
3860 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3861 inode_inc_iversion(inode);
3862 inode_inc_iversion(dir);
3863 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3864 ret = btrfs_update_inode(trans, root, dir);
3869 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3870 struct btrfs_root *root,
3871 struct inode *dir, struct inode *inode,
3872 const char *name, int name_len)
3875 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3878 ret = btrfs_update_inode(trans, root, inode);
3884 * helper to start transaction for unlink and rmdir.
3886 * unlink and rmdir are special in btrfs, they do not always free space, so
3887 * if we cannot make our reservations the normal way try and see if there is
3888 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3889 * allow the unlink to occur.
3891 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3893 struct btrfs_trans_handle *trans;
3894 struct btrfs_root *root = BTRFS_I(dir)->root;
3898 * 1 for the possible orphan item
3899 * 1 for the dir item
3900 * 1 for the dir index
3901 * 1 for the inode ref
3904 trans = btrfs_start_transaction(root, 5);
3905 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3908 if (PTR_ERR(trans) == -ENOSPC) {
3909 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3911 trans = btrfs_start_transaction(root, 0);
3914 ret = btrfs_cond_migrate_bytes(root->fs_info,
3915 &root->fs_info->trans_block_rsv,
3918 btrfs_end_transaction(trans, root);
3919 return ERR_PTR(ret);
3921 trans->block_rsv = &root->fs_info->trans_block_rsv;
3922 trans->bytes_reserved = num_bytes;
3927 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3929 struct btrfs_root *root = BTRFS_I(dir)->root;
3930 struct btrfs_trans_handle *trans;
3931 struct inode *inode = dentry->d_inode;
3934 trans = __unlink_start_trans(dir);
3936 return PTR_ERR(trans);
3938 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3940 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3941 dentry->d_name.name, dentry->d_name.len);
3945 if (inode->i_nlink == 0) {
3946 ret = btrfs_orphan_add(trans, inode);
3952 btrfs_end_transaction(trans, root);
3953 btrfs_btree_balance_dirty(root);
3957 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3958 struct btrfs_root *root,
3959 struct inode *dir, u64 objectid,
3960 const char *name, int name_len)
3962 struct btrfs_path *path;
3963 struct extent_buffer *leaf;
3964 struct btrfs_dir_item *di;
3965 struct btrfs_key key;
3968 u64 dir_ino = btrfs_ino(dir);
3970 path = btrfs_alloc_path();
3974 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3975 name, name_len, -1);
3976 if (IS_ERR_OR_NULL(di)) {
3984 leaf = path->nodes[0];
3985 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3986 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3987 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3989 btrfs_abort_transaction(trans, root, ret);
3992 btrfs_release_path(path);
3994 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3995 objectid, root->root_key.objectid,
3996 dir_ino, &index, name, name_len);
3998 if (ret != -ENOENT) {
3999 btrfs_abort_transaction(trans, root, ret);
4002 di = btrfs_search_dir_index_item(root, path, dir_ino,
4004 if (IS_ERR_OR_NULL(di)) {
4009 btrfs_abort_transaction(trans, root, ret);
4013 leaf = path->nodes[0];
4014 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4015 btrfs_release_path(path);
4018 btrfs_release_path(path);
4020 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4022 btrfs_abort_transaction(trans, root, ret);
4026 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4027 inode_inc_iversion(dir);
4028 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
4029 ret = btrfs_update_inode_fallback(trans, root, dir);
4031 btrfs_abort_transaction(trans, root, ret);
4033 btrfs_free_path(path);
4037 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4039 struct inode *inode = dentry->d_inode;
4041 struct btrfs_root *root = BTRFS_I(dir)->root;
4042 struct btrfs_trans_handle *trans;
4044 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4046 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
4049 trans = __unlink_start_trans(dir);
4051 return PTR_ERR(trans);
4053 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4054 err = btrfs_unlink_subvol(trans, root, dir,
4055 BTRFS_I(inode)->location.objectid,
4056 dentry->d_name.name,
4057 dentry->d_name.len);
4061 err = btrfs_orphan_add(trans, inode);
4065 /* now the directory is empty */
4066 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
4067 dentry->d_name.name, dentry->d_name.len);
4069 btrfs_i_size_write(inode, 0);
4071 btrfs_end_transaction(trans, root);
4072 btrfs_btree_balance_dirty(root);
4078 * this can truncate away extent items, csum items and directory items.
4079 * It starts at a high offset and removes keys until it can't find
4080 * any higher than new_size
4082 * csum items that cross the new i_size are truncated to the new size
4085 * min_type is the minimum key type to truncate down to. If set to 0, this
4086 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4088 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4089 struct btrfs_root *root,
4090 struct inode *inode,
4091 u64 new_size, u32 min_type)
4093 struct btrfs_path *path;
4094 struct extent_buffer *leaf;
4095 struct btrfs_file_extent_item *fi;
4096 struct btrfs_key key;
4097 struct btrfs_key found_key;
4098 u64 extent_start = 0;
4099 u64 extent_num_bytes = 0;
4100 u64 extent_offset = 0;
4102 u64 last_size = (u64)-1;
4103 u32 found_type = (u8)-1;
4106 int pending_del_nr = 0;
4107 int pending_del_slot = 0;
4108 int extent_type = -1;
4111 u64 ino = btrfs_ino(inode);
4113 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4115 path = btrfs_alloc_path();
4121 * We want to drop from the next block forward in case this new size is
4122 * not block aligned since we will be keeping the last block of the
4123 * extent just the way it is.
4125 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4126 root == root->fs_info->tree_root)
4127 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4128 root->sectorsize), (u64)-1, 0);
4131 * This function is also used to drop the items in the log tree before
4132 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4133 * it is used to drop the loged items. So we shouldn't kill the delayed
4136 if (min_type == 0 && root == BTRFS_I(inode)->root)
4137 btrfs_kill_delayed_inode_items(inode);
4140 key.offset = (u64)-1;
4144 path->leave_spinning = 1;
4145 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4152 /* there are no items in the tree for us to truncate, we're
4155 if (path->slots[0] == 0)
4162 leaf = path->nodes[0];
4163 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4164 found_type = found_key.type;
4166 if (found_key.objectid != ino)
4169 if (found_type < min_type)
4172 item_end = found_key.offset;
4173 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4174 fi = btrfs_item_ptr(leaf, path->slots[0],
4175 struct btrfs_file_extent_item);
4176 extent_type = btrfs_file_extent_type(leaf, fi);
4177 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4179 btrfs_file_extent_num_bytes(leaf, fi);
4180 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4181 item_end += btrfs_file_extent_inline_len(leaf,
4182 path->slots[0], fi);
4186 if (found_type > min_type) {
4189 if (item_end < new_size)
4191 if (found_key.offset >= new_size)
4197 /* FIXME, shrink the extent if the ref count is only 1 */
4198 if (found_type != BTRFS_EXTENT_DATA_KEY)
4202 last_size = found_key.offset;
4204 last_size = new_size;
4206 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4208 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4210 u64 orig_num_bytes =
4211 btrfs_file_extent_num_bytes(leaf, fi);
4212 extent_num_bytes = ALIGN(new_size -
4215 btrfs_set_file_extent_num_bytes(leaf, fi,
4217 num_dec = (orig_num_bytes -
4219 if (test_bit(BTRFS_ROOT_REF_COWS,
4222 inode_sub_bytes(inode, num_dec);
4223 btrfs_mark_buffer_dirty(leaf);
4226 btrfs_file_extent_disk_num_bytes(leaf,
4228 extent_offset = found_key.offset -
4229 btrfs_file_extent_offset(leaf, fi);
4231 /* FIXME blocksize != 4096 */
4232 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4233 if (extent_start != 0) {
4235 if (test_bit(BTRFS_ROOT_REF_COWS,
4237 inode_sub_bytes(inode, num_dec);
4240 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4242 * we can't truncate inline items that have had
4246 btrfs_file_extent_compression(leaf, fi) == 0 &&
4247 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4248 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4249 u32 size = new_size - found_key.offset;
4251 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4252 inode_sub_bytes(inode, item_end + 1 -
4256 * update the ram bytes to properly reflect
4257 * the new size of our item
4259 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4261 btrfs_file_extent_calc_inline_size(size);
4262 btrfs_truncate_item(root, path, size, 1);
4263 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4265 inode_sub_bytes(inode, item_end + 1 -
4271 if (!pending_del_nr) {
4272 /* no pending yet, add ourselves */
4273 pending_del_slot = path->slots[0];
4275 } else if (pending_del_nr &&
4276 path->slots[0] + 1 == pending_del_slot) {
4277 /* hop on the pending chunk */
4279 pending_del_slot = path->slots[0];
4287 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4288 root == root->fs_info->tree_root)) {
4289 btrfs_set_path_blocking(path);
4290 ret = btrfs_free_extent(trans, root, extent_start,
4291 extent_num_bytes, 0,
4292 btrfs_header_owner(leaf),
4293 ino, extent_offset, 0);
4297 if (found_type == BTRFS_INODE_ITEM_KEY)
4300 if (path->slots[0] == 0 ||
4301 path->slots[0] != pending_del_slot) {
4302 if (pending_del_nr) {
4303 ret = btrfs_del_items(trans, root, path,
4307 btrfs_abort_transaction(trans,
4313 btrfs_release_path(path);
4320 if (pending_del_nr) {
4321 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4324 btrfs_abort_transaction(trans, root, ret);
4327 if (last_size != (u64)-1 &&
4328 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4329 btrfs_ordered_update_i_size(inode, last_size, NULL);
4330 btrfs_free_path(path);
4335 * btrfs_truncate_page - read, zero a chunk and write a page
4336 * @inode - inode that we're zeroing
4337 * @from - the offset to start zeroing
4338 * @len - the length to zero, 0 to zero the entire range respective to the
4340 * @front - zero up to the offset instead of from the offset on
4342 * This will find the page for the "from" offset and cow the page and zero the
4343 * part we want to zero. This is used with truncate and hole punching.
4345 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4348 struct address_space *mapping = inode->i_mapping;
4349 struct btrfs_root *root = BTRFS_I(inode)->root;
4350 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4351 struct btrfs_ordered_extent *ordered;
4352 struct extent_state *cached_state = NULL;
4354 u32 blocksize = root->sectorsize;
4355 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4356 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4358 gfp_t mask = btrfs_alloc_write_mask(mapping);
4363 if ((offset & (blocksize - 1)) == 0 &&
4364 (!len || ((len & (blocksize - 1)) == 0)))
4366 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4371 page = find_or_create_page(mapping, index, mask);
4373 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4378 page_start = page_offset(page);
4379 page_end = page_start + PAGE_CACHE_SIZE - 1;
4381 if (!PageUptodate(page)) {
4382 ret = btrfs_readpage(NULL, page);
4384 if (page->mapping != mapping) {
4386 page_cache_release(page);
4389 if (!PageUptodate(page)) {
4394 wait_on_page_writeback(page);
4396 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4397 set_page_extent_mapped(page);
4399 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4401 unlock_extent_cached(io_tree, page_start, page_end,
4402 &cached_state, GFP_NOFS);
4404 page_cache_release(page);
4405 btrfs_start_ordered_extent(inode, ordered, 1);
4406 btrfs_put_ordered_extent(ordered);
4410 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4411 EXTENT_DIRTY | EXTENT_DELALLOC |
4412 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4413 0, 0, &cached_state, GFP_NOFS);
4415 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4418 unlock_extent_cached(io_tree, page_start, page_end,
4419 &cached_state, GFP_NOFS);
4423 if (offset != PAGE_CACHE_SIZE) {
4425 len = PAGE_CACHE_SIZE - offset;
4428 memset(kaddr, 0, offset);
4430 memset(kaddr + offset, 0, len);
4431 flush_dcache_page(page);
4434 ClearPageChecked(page);
4435 set_page_dirty(page);
4436 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4441 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4443 page_cache_release(page);
4448 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4449 u64 offset, u64 len)
4451 struct btrfs_trans_handle *trans;
4455 * Still need to make sure the inode looks like it's been updated so
4456 * that any holes get logged if we fsync.
4458 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4459 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4460 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4461 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4466 * 1 - for the one we're dropping
4467 * 1 - for the one we're adding
4468 * 1 - for updating the inode.
4470 trans = btrfs_start_transaction(root, 3);
4472 return PTR_ERR(trans);
4474 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4476 btrfs_abort_transaction(trans, root, ret);
4477 btrfs_end_transaction(trans, root);
4481 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4482 0, 0, len, 0, len, 0, 0, 0);
4484 btrfs_abort_transaction(trans, root, ret);
4486 btrfs_update_inode(trans, root, inode);
4487 btrfs_end_transaction(trans, root);
4492 * This function puts in dummy file extents for the area we're creating a hole
4493 * for. So if we are truncating this file to a larger size we need to insert
4494 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4495 * the range between oldsize and size
4497 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4499 struct btrfs_root *root = BTRFS_I(inode)->root;
4500 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4501 struct extent_map *em = NULL;
4502 struct extent_state *cached_state = NULL;
4503 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4504 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4505 u64 block_end = ALIGN(size, root->sectorsize);
4512 * If our size started in the middle of a page we need to zero out the
4513 * rest of the page before we expand the i_size, otherwise we could
4514 * expose stale data.
4516 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4520 if (size <= hole_start)
4524 struct btrfs_ordered_extent *ordered;
4526 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4528 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4529 block_end - hole_start);
4532 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4533 &cached_state, GFP_NOFS);
4534 btrfs_start_ordered_extent(inode, ordered, 1);
4535 btrfs_put_ordered_extent(ordered);
4538 cur_offset = hole_start;
4540 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4541 block_end - cur_offset, 0);
4547 last_byte = min(extent_map_end(em), block_end);
4548 last_byte = ALIGN(last_byte , root->sectorsize);
4549 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4550 struct extent_map *hole_em;
4551 hole_size = last_byte - cur_offset;
4553 err = maybe_insert_hole(root, inode, cur_offset,
4557 btrfs_drop_extent_cache(inode, cur_offset,
4558 cur_offset + hole_size - 1, 0);
4559 hole_em = alloc_extent_map();
4561 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4562 &BTRFS_I(inode)->runtime_flags);
4565 hole_em->start = cur_offset;
4566 hole_em->len = hole_size;
4567 hole_em->orig_start = cur_offset;
4569 hole_em->block_start = EXTENT_MAP_HOLE;
4570 hole_em->block_len = 0;
4571 hole_em->orig_block_len = 0;
4572 hole_em->ram_bytes = hole_size;
4573 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4574 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4575 hole_em->generation = root->fs_info->generation;
4578 write_lock(&em_tree->lock);
4579 err = add_extent_mapping(em_tree, hole_em, 1);
4580 write_unlock(&em_tree->lock);
4583 btrfs_drop_extent_cache(inode, cur_offset,
4587 free_extent_map(hole_em);
4590 free_extent_map(em);
4592 cur_offset = last_byte;
4593 if (cur_offset >= block_end)
4596 free_extent_map(em);
4597 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4602 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4604 struct btrfs_root *root = BTRFS_I(inode)->root;
4605 struct btrfs_trans_handle *trans;
4606 loff_t oldsize = i_size_read(inode);
4607 loff_t newsize = attr->ia_size;
4608 int mask = attr->ia_valid;
4612 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4613 * special case where we need to update the times despite not having
4614 * these flags set. For all other operations the VFS set these flags
4615 * explicitly if it wants a timestamp update.
4617 if (newsize != oldsize) {
4618 inode_inc_iversion(inode);
4619 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4620 inode->i_ctime = inode->i_mtime =
4621 current_fs_time(inode->i_sb);
4624 if (newsize > oldsize) {
4625 truncate_pagecache(inode, newsize);
4626 ret = btrfs_cont_expand(inode, oldsize, newsize);
4630 trans = btrfs_start_transaction(root, 1);
4632 return PTR_ERR(trans);
4634 i_size_write(inode, newsize);
4635 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4636 ret = btrfs_update_inode(trans, root, inode);
4637 btrfs_end_transaction(trans, root);
4641 * We're truncating a file that used to have good data down to
4642 * zero. Make sure it gets into the ordered flush list so that
4643 * any new writes get down to disk quickly.
4646 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4647 &BTRFS_I(inode)->runtime_flags);
4650 * 1 for the orphan item we're going to add
4651 * 1 for the orphan item deletion.
4653 trans = btrfs_start_transaction(root, 2);
4655 return PTR_ERR(trans);
4658 * We need to do this in case we fail at _any_ point during the
4659 * actual truncate. Once we do the truncate_setsize we could
4660 * invalidate pages which forces any outstanding ordered io to
4661 * be instantly completed which will give us extents that need
4662 * to be truncated. If we fail to get an orphan inode down we
4663 * could have left over extents that were never meant to live,
4664 * so we need to garuntee from this point on that everything
4665 * will be consistent.
4667 ret = btrfs_orphan_add(trans, inode);
4668 btrfs_end_transaction(trans, root);
4672 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4673 truncate_setsize(inode, newsize);
4675 /* Disable nonlocked read DIO to avoid the end less truncate */
4676 btrfs_inode_block_unlocked_dio(inode);
4677 inode_dio_wait(inode);
4678 btrfs_inode_resume_unlocked_dio(inode);
4680 ret = btrfs_truncate(inode);
4681 if (ret && inode->i_nlink) {
4685 * failed to truncate, disk_i_size is only adjusted down
4686 * as we remove extents, so it should represent the true
4687 * size of the inode, so reset the in memory size and
4688 * delete our orphan entry.
4690 trans = btrfs_join_transaction(root);
4691 if (IS_ERR(trans)) {
4692 btrfs_orphan_del(NULL, inode);
4695 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4696 err = btrfs_orphan_del(trans, inode);
4698 btrfs_abort_transaction(trans, root, err);
4699 btrfs_end_transaction(trans, root);
4706 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4708 struct inode *inode = dentry->d_inode;
4709 struct btrfs_root *root = BTRFS_I(inode)->root;
4712 if (btrfs_root_readonly(root))
4715 err = inode_change_ok(inode, attr);
4719 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4720 err = btrfs_setsize(inode, attr);
4725 if (attr->ia_valid) {
4726 setattr_copy(inode, attr);
4727 inode_inc_iversion(inode);
4728 err = btrfs_dirty_inode(inode);
4730 if (!err && attr->ia_valid & ATTR_MODE)
4731 err = posix_acl_chmod(inode, inode->i_mode);
4738 * While truncating the inode pages during eviction, we get the VFS calling
4739 * btrfs_invalidatepage() against each page of the inode. This is slow because
4740 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4741 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4742 * extent_state structures over and over, wasting lots of time.
4744 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4745 * those expensive operations on a per page basis and do only the ordered io
4746 * finishing, while we release here the extent_map and extent_state structures,
4747 * without the excessive merging and splitting.
4749 static void evict_inode_truncate_pages(struct inode *inode)
4751 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4752 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4753 struct rb_node *node;
4755 ASSERT(inode->i_state & I_FREEING);
4756 truncate_inode_pages_final(&inode->i_data);
4758 write_lock(&map_tree->lock);
4759 while (!RB_EMPTY_ROOT(&map_tree->map)) {
4760 struct extent_map *em;
4762 node = rb_first(&map_tree->map);
4763 em = rb_entry(node, struct extent_map, rb_node);
4764 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4765 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4766 remove_extent_mapping(map_tree, em);
4767 free_extent_map(em);
4768 if (need_resched()) {
4769 write_unlock(&map_tree->lock);
4771 write_lock(&map_tree->lock);
4774 write_unlock(&map_tree->lock);
4776 spin_lock(&io_tree->lock);
4777 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4778 struct extent_state *state;
4779 struct extent_state *cached_state = NULL;
4781 node = rb_first(&io_tree->state);
4782 state = rb_entry(node, struct extent_state, rb_node);
4783 atomic_inc(&state->refs);
4784 spin_unlock(&io_tree->lock);
4786 lock_extent_bits(io_tree, state->start, state->end,
4788 clear_extent_bit(io_tree, state->start, state->end,
4789 EXTENT_LOCKED | EXTENT_DIRTY |
4790 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
4791 EXTENT_DEFRAG, 1, 1,
4792 &cached_state, GFP_NOFS);
4793 free_extent_state(state);
4796 spin_lock(&io_tree->lock);
4798 spin_unlock(&io_tree->lock);
4801 void btrfs_evict_inode(struct inode *inode)
4803 struct btrfs_trans_handle *trans;
4804 struct btrfs_root *root = BTRFS_I(inode)->root;
4805 struct btrfs_block_rsv *rsv, *global_rsv;
4806 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4809 trace_btrfs_inode_evict(inode);
4811 evict_inode_truncate_pages(inode);
4813 if (inode->i_nlink &&
4814 ((btrfs_root_refs(&root->root_item) != 0 &&
4815 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4816 btrfs_is_free_space_inode(inode)))
4819 if (is_bad_inode(inode)) {
4820 btrfs_orphan_del(NULL, inode);
4823 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4824 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4826 btrfs_free_io_failure_record(inode, 0, (u64)-1);
4828 if (root->fs_info->log_root_recovering) {
4829 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4830 &BTRFS_I(inode)->runtime_flags));
4834 if (inode->i_nlink > 0) {
4835 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4836 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4840 ret = btrfs_commit_inode_delayed_inode(inode);
4842 btrfs_orphan_del(NULL, inode);
4846 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4848 btrfs_orphan_del(NULL, inode);
4851 rsv->size = min_size;
4853 global_rsv = &root->fs_info->global_block_rsv;
4855 btrfs_i_size_write(inode, 0);
4858 * This is a bit simpler than btrfs_truncate since we've already
4859 * reserved our space for our orphan item in the unlink, so we just
4860 * need to reserve some slack space in case we add bytes and update
4861 * inode item when doing the truncate.
4864 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4865 BTRFS_RESERVE_FLUSH_LIMIT);
4868 * Try and steal from the global reserve since we will
4869 * likely not use this space anyway, we want to try as
4870 * hard as possible to get this to work.
4873 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4876 btrfs_warn(root->fs_info,
4877 "Could not get space for a delete, will truncate on mount %d",
4879 btrfs_orphan_del(NULL, inode);
4880 btrfs_free_block_rsv(root, rsv);
4884 trans = btrfs_join_transaction(root);
4885 if (IS_ERR(trans)) {
4886 btrfs_orphan_del(NULL, inode);
4887 btrfs_free_block_rsv(root, rsv);
4891 trans->block_rsv = rsv;
4893 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4897 trans->block_rsv = &root->fs_info->trans_block_rsv;
4898 btrfs_end_transaction(trans, root);
4900 btrfs_btree_balance_dirty(root);
4903 btrfs_free_block_rsv(root, rsv);
4906 * Errors here aren't a big deal, it just means we leave orphan items
4907 * in the tree. They will be cleaned up on the next mount.
4910 trans->block_rsv = root->orphan_block_rsv;
4911 btrfs_orphan_del(trans, inode);
4913 btrfs_orphan_del(NULL, inode);
4916 trans->block_rsv = &root->fs_info->trans_block_rsv;
4917 if (!(root == root->fs_info->tree_root ||
4918 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4919 btrfs_return_ino(root, btrfs_ino(inode));
4921 btrfs_end_transaction(trans, root);
4922 btrfs_btree_balance_dirty(root);
4924 btrfs_remove_delayed_node(inode);
4930 * this returns the key found in the dir entry in the location pointer.
4931 * If no dir entries were found, location->objectid is 0.
4933 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4934 struct btrfs_key *location)
4936 const char *name = dentry->d_name.name;
4937 int namelen = dentry->d_name.len;
4938 struct btrfs_dir_item *di;
4939 struct btrfs_path *path;
4940 struct btrfs_root *root = BTRFS_I(dir)->root;
4943 path = btrfs_alloc_path();
4947 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4952 if (IS_ERR_OR_NULL(di))
4955 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4957 btrfs_free_path(path);
4960 location->objectid = 0;
4965 * when we hit a tree root in a directory, the btrfs part of the inode
4966 * needs to be changed to reflect the root directory of the tree root. This
4967 * is kind of like crossing a mount point.
4969 static int fixup_tree_root_location(struct btrfs_root *root,
4971 struct dentry *dentry,
4972 struct btrfs_key *location,
4973 struct btrfs_root **sub_root)
4975 struct btrfs_path *path;
4976 struct btrfs_root *new_root;
4977 struct btrfs_root_ref *ref;
4978 struct extent_buffer *leaf;
4982 path = btrfs_alloc_path();
4989 ret = btrfs_find_item(root->fs_info->tree_root, path,
4990 BTRFS_I(dir)->root->root_key.objectid,
4991 location->objectid, BTRFS_ROOT_REF_KEY, NULL);
4998 leaf = path->nodes[0];
4999 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5000 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5001 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5004 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5005 (unsigned long)(ref + 1),
5006 dentry->d_name.len);
5010 btrfs_release_path(path);
5012 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
5013 if (IS_ERR(new_root)) {
5014 err = PTR_ERR(new_root);
5018 *sub_root = new_root;
5019 location->objectid = btrfs_root_dirid(&new_root->root_item);
5020 location->type = BTRFS_INODE_ITEM_KEY;
5021 location->offset = 0;
5024 btrfs_free_path(path);
5028 static void inode_tree_add(struct inode *inode)
5030 struct btrfs_root *root = BTRFS_I(inode)->root;
5031 struct btrfs_inode *entry;
5033 struct rb_node *parent;
5034 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5035 u64 ino = btrfs_ino(inode);
5037 if (inode_unhashed(inode))
5040 spin_lock(&root->inode_lock);
5041 p = &root->inode_tree.rb_node;
5044 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5046 if (ino < btrfs_ino(&entry->vfs_inode))
5047 p = &parent->rb_left;
5048 else if (ino > btrfs_ino(&entry->vfs_inode))
5049 p = &parent->rb_right;
5051 WARN_ON(!(entry->vfs_inode.i_state &
5052 (I_WILL_FREE | I_FREEING)));
5053 rb_replace_node(parent, new, &root->inode_tree);
5054 RB_CLEAR_NODE(parent);
5055 spin_unlock(&root->inode_lock);
5059 rb_link_node(new, parent, p);
5060 rb_insert_color(new, &root->inode_tree);
5061 spin_unlock(&root->inode_lock);
5064 static void inode_tree_del(struct inode *inode)
5066 struct btrfs_root *root = BTRFS_I(inode)->root;
5069 spin_lock(&root->inode_lock);
5070 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5071 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5072 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5073 empty = RB_EMPTY_ROOT(&root->inode_tree);
5075 spin_unlock(&root->inode_lock);
5077 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5078 synchronize_srcu(&root->fs_info->subvol_srcu);
5079 spin_lock(&root->inode_lock);
5080 empty = RB_EMPTY_ROOT(&root->inode_tree);
5081 spin_unlock(&root->inode_lock);
5083 btrfs_add_dead_root(root);
5087 void btrfs_invalidate_inodes(struct btrfs_root *root)
5089 struct rb_node *node;
5090 struct rb_node *prev;
5091 struct btrfs_inode *entry;
5092 struct inode *inode;
5095 if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
5096 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5098 spin_lock(&root->inode_lock);
5100 node = root->inode_tree.rb_node;
5104 entry = rb_entry(node, struct btrfs_inode, rb_node);
5106 if (objectid < btrfs_ino(&entry->vfs_inode))
5107 node = node->rb_left;
5108 else if (objectid > btrfs_ino(&entry->vfs_inode))
5109 node = node->rb_right;
5115 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5116 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
5120 prev = rb_next(prev);
5124 entry = rb_entry(node, struct btrfs_inode, rb_node);
5125 objectid = btrfs_ino(&entry->vfs_inode) + 1;
5126 inode = igrab(&entry->vfs_inode);
5128 spin_unlock(&root->inode_lock);
5129 if (atomic_read(&inode->i_count) > 1)
5130 d_prune_aliases(inode);
5132 * btrfs_drop_inode will have it removed from
5133 * the inode cache when its usage count
5138 spin_lock(&root->inode_lock);
5142 if (cond_resched_lock(&root->inode_lock))
5145 node = rb_next(node);
5147 spin_unlock(&root->inode_lock);
5150 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5152 struct btrfs_iget_args *args = p;
5153 inode->i_ino = args->location->objectid;
5154 memcpy(&BTRFS_I(inode)->location, args->location,
5155 sizeof(*args->location));
5156 BTRFS_I(inode)->root = args->root;
5160 static int btrfs_find_actor(struct inode *inode, void *opaque)
5162 struct btrfs_iget_args *args = opaque;
5163 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5164 args->root == BTRFS_I(inode)->root;
5167 static struct inode *btrfs_iget_locked(struct super_block *s,
5168 struct btrfs_key *location,
5169 struct btrfs_root *root)
5171 struct inode *inode;
5172 struct btrfs_iget_args args;
5173 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5175 args.location = location;
5178 inode = iget5_locked(s, hashval, btrfs_find_actor,
5179 btrfs_init_locked_inode,
5184 /* Get an inode object given its location and corresponding root.
5185 * Returns in *is_new if the inode was read from disk
5187 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5188 struct btrfs_root *root, int *new)
5190 struct inode *inode;
5192 inode = btrfs_iget_locked(s, location, root);
5194 return ERR_PTR(-ENOMEM);
5196 if (inode->i_state & I_NEW) {
5197 btrfs_read_locked_inode(inode);
5198 if (!is_bad_inode(inode)) {
5199 inode_tree_add(inode);
5200 unlock_new_inode(inode);
5204 unlock_new_inode(inode);
5206 inode = ERR_PTR(-ESTALE);
5213 static struct inode *new_simple_dir(struct super_block *s,
5214 struct btrfs_key *key,
5215 struct btrfs_root *root)
5217 struct inode *inode = new_inode(s);
5220 return ERR_PTR(-ENOMEM);
5222 BTRFS_I(inode)->root = root;
5223 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5224 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5226 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5227 inode->i_op = &btrfs_dir_ro_inode_operations;
5228 inode->i_fop = &simple_dir_operations;
5229 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5230 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5235 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5237 struct inode *inode;
5238 struct btrfs_root *root = BTRFS_I(dir)->root;
5239 struct btrfs_root *sub_root = root;
5240 struct btrfs_key location;
5244 if (dentry->d_name.len > BTRFS_NAME_LEN)
5245 return ERR_PTR(-ENAMETOOLONG);
5247 ret = btrfs_inode_by_name(dir, dentry, &location);
5249 return ERR_PTR(ret);
5251 if (location.objectid == 0)
5252 return ERR_PTR(-ENOENT);
5254 if (location.type == BTRFS_INODE_ITEM_KEY) {
5255 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5259 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5261 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5262 ret = fixup_tree_root_location(root, dir, dentry,
5263 &location, &sub_root);
5266 inode = ERR_PTR(ret);
5268 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5270 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5272 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5274 if (!IS_ERR(inode) && root != sub_root) {
5275 down_read(&root->fs_info->cleanup_work_sem);
5276 if (!(inode->i_sb->s_flags & MS_RDONLY))
5277 ret = btrfs_orphan_cleanup(sub_root);
5278 up_read(&root->fs_info->cleanup_work_sem);
5281 inode = ERR_PTR(ret);
5288 static int btrfs_dentry_delete(const struct dentry *dentry)
5290 struct btrfs_root *root;
5291 struct inode *inode = dentry->d_inode;
5293 if (!inode && !IS_ROOT(dentry))
5294 inode = dentry->d_parent->d_inode;
5297 root = BTRFS_I(inode)->root;
5298 if (btrfs_root_refs(&root->root_item) == 0)
5301 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5307 static void btrfs_dentry_release(struct dentry *dentry)
5309 kfree(dentry->d_fsdata);
5312 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5315 struct inode *inode;
5317 inode = btrfs_lookup_dentry(dir, dentry);
5318 if (IS_ERR(inode)) {
5319 if (PTR_ERR(inode) == -ENOENT)
5322 return ERR_CAST(inode);
5325 return d_materialise_unique(dentry, inode);
5328 unsigned char btrfs_filetype_table[] = {
5329 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5332 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5334 struct inode *inode = file_inode(file);
5335 struct btrfs_root *root = BTRFS_I(inode)->root;
5336 struct btrfs_item *item;
5337 struct btrfs_dir_item *di;
5338 struct btrfs_key key;
5339 struct btrfs_key found_key;
5340 struct btrfs_path *path;
5341 struct list_head ins_list;
5342 struct list_head del_list;
5344 struct extent_buffer *leaf;
5346 unsigned char d_type;
5351 int key_type = BTRFS_DIR_INDEX_KEY;
5355 int is_curr = 0; /* ctx->pos points to the current index? */
5357 /* FIXME, use a real flag for deciding about the key type */
5358 if (root->fs_info->tree_root == root)
5359 key_type = BTRFS_DIR_ITEM_KEY;
5361 if (!dir_emit_dots(file, ctx))
5364 path = btrfs_alloc_path();
5370 if (key_type == BTRFS_DIR_INDEX_KEY) {
5371 INIT_LIST_HEAD(&ins_list);
5372 INIT_LIST_HEAD(&del_list);
5373 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5376 key.type = key_type;
5377 key.offset = ctx->pos;
5378 key.objectid = btrfs_ino(inode);
5380 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5385 leaf = path->nodes[0];
5386 slot = path->slots[0];
5387 if (slot >= btrfs_header_nritems(leaf)) {
5388 ret = btrfs_next_leaf(root, path);
5396 item = btrfs_item_nr(slot);
5397 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5399 if (found_key.objectid != key.objectid)
5401 if (found_key.type != key_type)
5403 if (found_key.offset < ctx->pos)
5405 if (key_type == BTRFS_DIR_INDEX_KEY &&
5406 btrfs_should_delete_dir_index(&del_list,
5410 ctx->pos = found_key.offset;
5413 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5415 di_total = btrfs_item_size(leaf, item);
5417 while (di_cur < di_total) {
5418 struct btrfs_key location;
5420 if (verify_dir_item(root, leaf, di))
5423 name_len = btrfs_dir_name_len(leaf, di);
5424 if (name_len <= sizeof(tmp_name)) {
5425 name_ptr = tmp_name;
5427 name_ptr = kmalloc(name_len, GFP_NOFS);
5433 read_extent_buffer(leaf, name_ptr,
5434 (unsigned long)(di + 1), name_len);
5436 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5437 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5440 /* is this a reference to our own snapshot? If so
5443 * In contrast to old kernels, we insert the snapshot's
5444 * dir item and dir index after it has been created, so
5445 * we won't find a reference to our own snapshot. We
5446 * still keep the following code for backward
5449 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5450 location.objectid == root->root_key.objectid) {
5454 over = !dir_emit(ctx, name_ptr, name_len,
5455 location.objectid, d_type);
5458 if (name_ptr != tmp_name)
5463 di_len = btrfs_dir_name_len(leaf, di) +
5464 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5466 di = (struct btrfs_dir_item *)((char *)di + di_len);
5472 if (key_type == BTRFS_DIR_INDEX_KEY) {
5475 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5480 /* Reached end of directory/root. Bump pos past the last item. */
5484 * Stop new entries from being returned after we return the last
5487 * New directory entries are assigned a strictly increasing
5488 * offset. This means that new entries created during readdir
5489 * are *guaranteed* to be seen in the future by that readdir.
5490 * This has broken buggy programs which operate on names as
5491 * they're returned by readdir. Until we re-use freed offsets
5492 * we have this hack to stop new entries from being returned
5493 * under the assumption that they'll never reach this huge
5496 * This is being careful not to overflow 32bit loff_t unless the
5497 * last entry requires it because doing so has broken 32bit apps
5500 if (key_type == BTRFS_DIR_INDEX_KEY) {
5501 if (ctx->pos >= INT_MAX)
5502 ctx->pos = LLONG_MAX;
5509 if (key_type == BTRFS_DIR_INDEX_KEY)
5510 btrfs_put_delayed_items(&ins_list, &del_list);
5511 btrfs_free_path(path);
5515 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5517 struct btrfs_root *root = BTRFS_I(inode)->root;
5518 struct btrfs_trans_handle *trans;
5520 bool nolock = false;
5522 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5525 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5528 if (wbc->sync_mode == WB_SYNC_ALL) {
5530 trans = btrfs_join_transaction_nolock(root);
5532 trans = btrfs_join_transaction(root);
5534 return PTR_ERR(trans);
5535 ret = btrfs_commit_transaction(trans, root);
5541 * This is somewhat expensive, updating the tree every time the
5542 * inode changes. But, it is most likely to find the inode in cache.
5543 * FIXME, needs more benchmarking...there are no reasons other than performance
5544 * to keep or drop this code.
5546 static int btrfs_dirty_inode(struct inode *inode)
5548 struct btrfs_root *root = BTRFS_I(inode)->root;
5549 struct btrfs_trans_handle *trans;
5552 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5555 trans = btrfs_join_transaction(root);
5557 return PTR_ERR(trans);
5559 ret = btrfs_update_inode(trans, root, inode);
5560 if (ret && ret == -ENOSPC) {
5561 /* whoops, lets try again with the full transaction */
5562 btrfs_end_transaction(trans, root);
5563 trans = btrfs_start_transaction(root, 1);
5565 return PTR_ERR(trans);
5567 ret = btrfs_update_inode(trans, root, inode);
5569 btrfs_end_transaction(trans, root);
5570 if (BTRFS_I(inode)->delayed_node)
5571 btrfs_balance_delayed_items(root);
5577 * This is a copy of file_update_time. We need this so we can return error on
5578 * ENOSPC for updating the inode in the case of file write and mmap writes.
5580 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5583 struct btrfs_root *root = BTRFS_I(inode)->root;
5585 if (btrfs_root_readonly(root))
5588 if (flags & S_VERSION)
5589 inode_inc_iversion(inode);
5590 if (flags & S_CTIME)
5591 inode->i_ctime = *now;
5592 if (flags & S_MTIME)
5593 inode->i_mtime = *now;
5594 if (flags & S_ATIME)
5595 inode->i_atime = *now;
5596 return btrfs_dirty_inode(inode);
5600 * find the highest existing sequence number in a directory
5601 * and then set the in-memory index_cnt variable to reflect
5602 * free sequence numbers
5604 static int btrfs_set_inode_index_count(struct inode *inode)
5606 struct btrfs_root *root = BTRFS_I(inode)->root;
5607 struct btrfs_key key, found_key;
5608 struct btrfs_path *path;
5609 struct extent_buffer *leaf;
5612 key.objectid = btrfs_ino(inode);
5613 key.type = BTRFS_DIR_INDEX_KEY;
5614 key.offset = (u64)-1;
5616 path = btrfs_alloc_path();
5620 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5623 /* FIXME: we should be able to handle this */
5629 * MAGIC NUMBER EXPLANATION:
5630 * since we search a directory based on f_pos we have to start at 2
5631 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5632 * else has to start at 2
5634 if (path->slots[0] == 0) {
5635 BTRFS_I(inode)->index_cnt = 2;
5641 leaf = path->nodes[0];
5642 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5644 if (found_key.objectid != btrfs_ino(inode) ||
5645 found_key.type != BTRFS_DIR_INDEX_KEY) {
5646 BTRFS_I(inode)->index_cnt = 2;
5650 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5652 btrfs_free_path(path);
5657 * helper to find a free sequence number in a given directory. This current
5658 * code is very simple, later versions will do smarter things in the btree
5660 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5664 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5665 ret = btrfs_inode_delayed_dir_index_count(dir);
5667 ret = btrfs_set_inode_index_count(dir);
5673 *index = BTRFS_I(dir)->index_cnt;
5674 BTRFS_I(dir)->index_cnt++;
5679 static int btrfs_insert_inode_locked(struct inode *inode)
5681 struct btrfs_iget_args args;
5682 args.location = &BTRFS_I(inode)->location;
5683 args.root = BTRFS_I(inode)->root;
5685 return insert_inode_locked4(inode,
5686 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5687 btrfs_find_actor, &args);
5690 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5691 struct btrfs_root *root,
5693 const char *name, int name_len,
5694 u64 ref_objectid, u64 objectid,
5695 umode_t mode, u64 *index)
5697 struct inode *inode;
5698 struct btrfs_inode_item *inode_item;
5699 struct btrfs_key *location;
5700 struct btrfs_path *path;
5701 struct btrfs_inode_ref *ref;
5702 struct btrfs_key key[2];
5704 int nitems = name ? 2 : 1;
5708 path = btrfs_alloc_path();
5710 return ERR_PTR(-ENOMEM);
5712 inode = new_inode(root->fs_info->sb);
5714 btrfs_free_path(path);
5715 return ERR_PTR(-ENOMEM);
5719 * O_TMPFILE, set link count to 0, so that after this point,
5720 * we fill in an inode item with the correct link count.
5723 set_nlink(inode, 0);
5726 * we have to initialize this early, so we can reclaim the inode
5727 * number if we fail afterwards in this function.
5729 inode->i_ino = objectid;
5732 trace_btrfs_inode_request(dir);
5734 ret = btrfs_set_inode_index(dir, index);
5736 btrfs_free_path(path);
5738 return ERR_PTR(ret);
5744 * index_cnt is ignored for everything but a dir,
5745 * btrfs_get_inode_index_count has an explanation for the magic
5748 BTRFS_I(inode)->index_cnt = 2;
5749 BTRFS_I(inode)->dir_index = *index;
5750 BTRFS_I(inode)->root = root;
5751 BTRFS_I(inode)->generation = trans->transid;
5752 inode->i_generation = BTRFS_I(inode)->generation;
5755 * We could have gotten an inode number from somebody who was fsynced
5756 * and then removed in this same transaction, so let's just set full
5757 * sync since it will be a full sync anyway and this will blow away the
5758 * old info in the log.
5760 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5762 key[0].objectid = objectid;
5763 key[0].type = BTRFS_INODE_ITEM_KEY;
5766 sizes[0] = sizeof(struct btrfs_inode_item);
5770 * Start new inodes with an inode_ref. This is slightly more
5771 * efficient for small numbers of hard links since they will
5772 * be packed into one item. Extended refs will kick in if we
5773 * add more hard links than can fit in the ref item.
5775 key[1].objectid = objectid;
5776 key[1].type = BTRFS_INODE_REF_KEY;
5777 key[1].offset = ref_objectid;
5779 sizes[1] = name_len + sizeof(*ref);
5782 location = &BTRFS_I(inode)->location;
5783 location->objectid = objectid;
5784 location->offset = 0;
5785 location->type = BTRFS_INODE_ITEM_KEY;
5787 ret = btrfs_insert_inode_locked(inode);
5791 path->leave_spinning = 1;
5792 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
5796 inode_init_owner(inode, dir, mode);
5797 inode_set_bytes(inode, 0);
5798 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5799 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5800 struct btrfs_inode_item);
5801 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5802 sizeof(*inode_item));
5803 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5806 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5807 struct btrfs_inode_ref);
5808 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5809 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5810 ptr = (unsigned long)(ref + 1);
5811 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5814 btrfs_mark_buffer_dirty(path->nodes[0]);
5815 btrfs_free_path(path);
5817 btrfs_inherit_iflags(inode, dir);
5819 if (S_ISREG(mode)) {
5820 if (btrfs_test_opt(root, NODATASUM))
5821 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5822 if (btrfs_test_opt(root, NODATACOW))
5823 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5824 BTRFS_INODE_NODATASUM;
5827 inode_tree_add(inode);
5829 trace_btrfs_inode_new(inode);
5830 btrfs_set_inode_last_trans(trans, inode);
5832 btrfs_update_root_times(trans, root);
5834 ret = btrfs_inode_inherit_props(trans, inode, dir);
5836 btrfs_err(root->fs_info,
5837 "error inheriting props for ino %llu (root %llu): %d",
5838 btrfs_ino(inode), root->root_key.objectid, ret);
5843 unlock_new_inode(inode);
5846 BTRFS_I(dir)->index_cnt--;
5847 btrfs_free_path(path);
5849 return ERR_PTR(ret);
5852 static inline u8 btrfs_inode_type(struct inode *inode)
5854 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5858 * utility function to add 'inode' into 'parent_inode' with
5859 * a give name and a given sequence number.
5860 * if 'add_backref' is true, also insert a backref from the
5861 * inode to the parent directory.
5863 int btrfs_add_link(struct btrfs_trans_handle *trans,
5864 struct inode *parent_inode, struct inode *inode,
5865 const char *name, int name_len, int add_backref, u64 index)
5868 struct btrfs_key key;
5869 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5870 u64 ino = btrfs_ino(inode);
5871 u64 parent_ino = btrfs_ino(parent_inode);
5873 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5874 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5877 key.type = BTRFS_INODE_ITEM_KEY;
5881 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5882 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5883 key.objectid, root->root_key.objectid,
5884 parent_ino, index, name, name_len);
5885 } else if (add_backref) {
5886 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5890 /* Nothing to clean up yet */
5894 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5896 btrfs_inode_type(inode), index);
5897 if (ret == -EEXIST || ret == -EOVERFLOW)
5900 btrfs_abort_transaction(trans, root, ret);
5904 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5906 inode_inc_iversion(parent_inode);
5907 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5908 ret = btrfs_update_inode(trans, root, parent_inode);
5910 btrfs_abort_transaction(trans, root, ret);
5914 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5917 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5918 key.objectid, root->root_key.objectid,
5919 parent_ino, &local_index, name, name_len);
5921 } else if (add_backref) {
5925 err = btrfs_del_inode_ref(trans, root, name, name_len,
5926 ino, parent_ino, &local_index);
5931 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5932 struct inode *dir, struct dentry *dentry,
5933 struct inode *inode, int backref, u64 index)
5935 int err = btrfs_add_link(trans, dir, inode,
5936 dentry->d_name.name, dentry->d_name.len,
5943 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5944 umode_t mode, dev_t rdev)
5946 struct btrfs_trans_handle *trans;
5947 struct btrfs_root *root = BTRFS_I(dir)->root;
5948 struct inode *inode = NULL;
5954 if (!new_valid_dev(rdev))
5958 * 2 for inode item and ref
5960 * 1 for xattr if selinux is on
5962 trans = btrfs_start_transaction(root, 5);
5964 return PTR_ERR(trans);
5966 err = btrfs_find_free_ino(root, &objectid);
5970 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5971 dentry->d_name.len, btrfs_ino(dir), objectid,
5973 if (IS_ERR(inode)) {
5974 err = PTR_ERR(inode);
5979 * If the active LSM wants to access the inode during
5980 * d_instantiate it needs these. Smack checks to see
5981 * if the filesystem supports xattrs by looking at the
5984 inode->i_op = &btrfs_special_inode_operations;
5985 init_special_inode(inode, inode->i_mode, rdev);
5987 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5989 goto out_unlock_inode;
5991 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5993 goto out_unlock_inode;
5995 btrfs_update_inode(trans, root, inode);
5996 unlock_new_inode(inode);
5997 d_instantiate(dentry, inode);
6001 btrfs_end_transaction(trans, root);
6002 btrfs_balance_delayed_items(root);
6003 btrfs_btree_balance_dirty(root);
6005 inode_dec_link_count(inode);
6012 unlock_new_inode(inode);
6017 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6018 umode_t mode, bool excl)
6020 struct btrfs_trans_handle *trans;
6021 struct btrfs_root *root = BTRFS_I(dir)->root;
6022 struct inode *inode = NULL;
6023 int drop_inode_on_err = 0;
6029 * 2 for inode item and ref
6031 * 1 for xattr if selinux is on
6033 trans = btrfs_start_transaction(root, 5);
6035 return PTR_ERR(trans);
6037 err = btrfs_find_free_ino(root, &objectid);
6041 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6042 dentry->d_name.len, btrfs_ino(dir), objectid,
6044 if (IS_ERR(inode)) {
6045 err = PTR_ERR(inode);
6048 drop_inode_on_err = 1;
6050 * If the active LSM wants to access the inode during
6051 * d_instantiate it needs these. Smack checks to see
6052 * if the filesystem supports xattrs by looking at the
6055 inode->i_fop = &btrfs_file_operations;
6056 inode->i_op = &btrfs_file_inode_operations;
6057 inode->i_mapping->a_ops = &btrfs_aops;
6058 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
6060 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6062 goto out_unlock_inode;
6064 err = btrfs_update_inode(trans, root, inode);
6066 goto out_unlock_inode;
6068 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6070 goto out_unlock_inode;
6072 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6073 unlock_new_inode(inode);
6074 d_instantiate(dentry, inode);
6077 btrfs_end_transaction(trans, root);
6078 if (err && drop_inode_on_err) {
6079 inode_dec_link_count(inode);
6082 btrfs_balance_delayed_items(root);
6083 btrfs_btree_balance_dirty(root);
6087 unlock_new_inode(inode);
6092 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6093 struct dentry *dentry)
6095 struct btrfs_trans_handle *trans;
6096 struct btrfs_root *root = BTRFS_I(dir)->root;
6097 struct inode *inode = old_dentry->d_inode;
6102 /* do not allow sys_link's with other subvols of the same device */
6103 if (root->objectid != BTRFS_I(inode)->root->objectid)
6106 if (inode->i_nlink >= BTRFS_LINK_MAX)
6109 err = btrfs_set_inode_index(dir, &index);
6114 * 2 items for inode and inode ref
6115 * 2 items for dir items
6116 * 1 item for parent inode
6118 trans = btrfs_start_transaction(root, 5);
6119 if (IS_ERR(trans)) {
6120 err = PTR_ERR(trans);
6124 /* There are several dir indexes for this inode, clear the cache. */
6125 BTRFS_I(inode)->dir_index = 0ULL;
6127 inode_inc_iversion(inode);
6128 inode->i_ctime = CURRENT_TIME;
6130 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6132 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
6137 struct dentry *parent = dentry->d_parent;
6138 err = btrfs_update_inode(trans, root, inode);
6141 if (inode->i_nlink == 1) {
6143 * If new hard link count is 1, it's a file created
6144 * with open(2) O_TMPFILE flag.
6146 err = btrfs_orphan_del(trans, inode);
6150 d_instantiate(dentry, inode);
6151 btrfs_log_new_name(trans, inode, NULL, parent);
6154 btrfs_end_transaction(trans, root);
6155 btrfs_balance_delayed_items(root);
6158 inode_dec_link_count(inode);
6161 btrfs_btree_balance_dirty(root);
6165 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6167 struct inode *inode = NULL;
6168 struct btrfs_trans_handle *trans;
6169 struct btrfs_root *root = BTRFS_I(dir)->root;
6171 int drop_on_err = 0;
6176 * 2 items for inode and ref
6177 * 2 items for dir items
6178 * 1 for xattr if selinux is on
6180 trans = btrfs_start_transaction(root, 5);
6182 return PTR_ERR(trans);
6184 err = btrfs_find_free_ino(root, &objectid);
6188 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6189 dentry->d_name.len, btrfs_ino(dir), objectid,
6190 S_IFDIR | mode, &index);
6191 if (IS_ERR(inode)) {
6192 err = PTR_ERR(inode);
6197 /* these must be set before we unlock the inode */
6198 inode->i_op = &btrfs_dir_inode_operations;
6199 inode->i_fop = &btrfs_dir_file_operations;
6201 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6203 goto out_fail_inode;
6205 btrfs_i_size_write(inode, 0);
6206 err = btrfs_update_inode(trans, root, inode);
6208 goto out_fail_inode;
6210 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6211 dentry->d_name.len, 0, index);
6213 goto out_fail_inode;
6215 d_instantiate(dentry, inode);
6217 * mkdir is special. We're unlocking after we call d_instantiate
6218 * to avoid a race with nfsd calling d_instantiate.
6220 unlock_new_inode(inode);
6224 btrfs_end_transaction(trans, root);
6227 btrfs_balance_delayed_items(root);
6228 btrfs_btree_balance_dirty(root);
6232 unlock_new_inode(inode);
6236 /* Find next extent map of a given extent map, caller needs to ensure locks */
6237 static struct extent_map *next_extent_map(struct extent_map *em)
6239 struct rb_node *next;
6241 next = rb_next(&em->rb_node);
6244 return container_of(next, struct extent_map, rb_node);
6247 static struct extent_map *prev_extent_map(struct extent_map *em)
6249 struct rb_node *prev;
6251 prev = rb_prev(&em->rb_node);
6254 return container_of(prev, struct extent_map, rb_node);
6257 /* helper for btfs_get_extent. Given an existing extent in the tree,
6258 * the existing extent is the nearest extent to map_start,
6259 * and an extent that you want to insert, deal with overlap and insert
6260 * the best fitted new extent into the tree.
6262 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6263 struct extent_map *existing,
6264 struct extent_map *em,
6267 struct extent_map *prev;
6268 struct extent_map *next;
6273 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6275 if (existing->start > map_start) {
6277 prev = prev_extent_map(next);
6280 next = next_extent_map(prev);
6283 start = prev ? extent_map_end(prev) : em->start;
6284 start = max_t(u64, start, em->start);
6285 end = next ? next->start : extent_map_end(em);
6286 end = min_t(u64, end, extent_map_end(em));
6287 start_diff = start - em->start;
6289 em->len = end - start;
6290 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6291 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6292 em->block_start += start_diff;
6293 em->block_len -= start_diff;
6295 return add_extent_mapping(em_tree, em, 0);
6298 static noinline int uncompress_inline(struct btrfs_path *path,
6299 struct inode *inode, struct page *page,
6300 size_t pg_offset, u64 extent_offset,
6301 struct btrfs_file_extent_item *item)
6304 struct extent_buffer *leaf = path->nodes[0];
6307 unsigned long inline_size;
6311 WARN_ON(pg_offset != 0);
6312 compress_type = btrfs_file_extent_compression(leaf, item);
6313 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6314 inline_size = btrfs_file_extent_inline_item_len(leaf,
6315 btrfs_item_nr(path->slots[0]));
6316 tmp = kmalloc(inline_size, GFP_NOFS);
6319 ptr = btrfs_file_extent_inline_start(item);
6321 read_extent_buffer(leaf, tmp, ptr, inline_size);
6323 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6324 ret = btrfs_decompress(compress_type, tmp, page,
6325 extent_offset, inline_size, max_size);
6331 * a bit scary, this does extent mapping from logical file offset to the disk.
6332 * the ugly parts come from merging extents from the disk with the in-ram
6333 * representation. This gets more complex because of the data=ordered code,
6334 * where the in-ram extents might be locked pending data=ordered completion.
6336 * This also copies inline extents directly into the page.
6339 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6340 size_t pg_offset, u64 start, u64 len,
6345 u64 extent_start = 0;
6347 u64 objectid = btrfs_ino(inode);
6349 struct btrfs_path *path = NULL;
6350 struct btrfs_root *root = BTRFS_I(inode)->root;
6351 struct btrfs_file_extent_item *item;
6352 struct extent_buffer *leaf;
6353 struct btrfs_key found_key;
6354 struct extent_map *em = NULL;
6355 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6356 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6357 struct btrfs_trans_handle *trans = NULL;
6358 const bool new_inline = !page || create;
6361 read_lock(&em_tree->lock);
6362 em = lookup_extent_mapping(em_tree, start, len);
6364 em->bdev = root->fs_info->fs_devices->latest_bdev;
6365 read_unlock(&em_tree->lock);
6368 if (em->start > start || em->start + em->len <= start)
6369 free_extent_map(em);
6370 else if (em->block_start == EXTENT_MAP_INLINE && page)
6371 free_extent_map(em);
6375 em = alloc_extent_map();
6380 em->bdev = root->fs_info->fs_devices->latest_bdev;
6381 em->start = EXTENT_MAP_HOLE;
6382 em->orig_start = EXTENT_MAP_HOLE;
6384 em->block_len = (u64)-1;
6387 path = btrfs_alloc_path();
6393 * Chances are we'll be called again, so go ahead and do
6399 ret = btrfs_lookup_file_extent(trans, root, path,
6400 objectid, start, trans != NULL);
6407 if (path->slots[0] == 0)
6412 leaf = path->nodes[0];
6413 item = btrfs_item_ptr(leaf, path->slots[0],
6414 struct btrfs_file_extent_item);
6415 /* are we inside the extent that was found? */
6416 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6417 found_type = found_key.type;
6418 if (found_key.objectid != objectid ||
6419 found_type != BTRFS_EXTENT_DATA_KEY) {
6421 * If we backup past the first extent we want to move forward
6422 * and see if there is an extent in front of us, otherwise we'll
6423 * say there is a hole for our whole search range which can
6430 found_type = btrfs_file_extent_type(leaf, item);
6431 extent_start = found_key.offset;
6432 if (found_type == BTRFS_FILE_EXTENT_REG ||
6433 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6434 extent_end = extent_start +
6435 btrfs_file_extent_num_bytes(leaf, item);
6436 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6438 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6439 extent_end = ALIGN(extent_start + size, root->sectorsize);
6442 if (start >= extent_end) {
6444 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6445 ret = btrfs_next_leaf(root, path);
6452 leaf = path->nodes[0];
6454 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6455 if (found_key.objectid != objectid ||
6456 found_key.type != BTRFS_EXTENT_DATA_KEY)
6458 if (start + len <= found_key.offset)
6460 if (start > found_key.offset)
6463 em->orig_start = start;
6464 em->len = found_key.offset - start;
6468 btrfs_extent_item_to_extent_map(inode, path, item, new_inline, em);
6470 if (found_type == BTRFS_FILE_EXTENT_REG ||
6471 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6473 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6477 size_t extent_offset;
6483 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6484 extent_offset = page_offset(page) + pg_offset - extent_start;
6485 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6486 size - extent_offset);
6487 em->start = extent_start + extent_offset;
6488 em->len = ALIGN(copy_size, root->sectorsize);
6489 em->orig_block_len = em->len;
6490 em->orig_start = em->start;
6491 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6492 if (create == 0 && !PageUptodate(page)) {
6493 if (btrfs_file_extent_compression(leaf, item) !=
6494 BTRFS_COMPRESS_NONE) {
6495 ret = uncompress_inline(path, inode, page,
6497 extent_offset, item);
6504 read_extent_buffer(leaf, map + pg_offset, ptr,
6506 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6507 memset(map + pg_offset + copy_size, 0,
6508 PAGE_CACHE_SIZE - pg_offset -
6513 flush_dcache_page(page);
6514 } else if (create && PageUptodate(page)) {
6518 free_extent_map(em);
6521 btrfs_release_path(path);
6522 trans = btrfs_join_transaction(root);
6525 return ERR_CAST(trans);
6529 write_extent_buffer(leaf, map + pg_offset, ptr,
6532 btrfs_mark_buffer_dirty(leaf);
6534 set_extent_uptodate(io_tree, em->start,
6535 extent_map_end(em) - 1, NULL, GFP_NOFS);
6540 em->orig_start = start;
6543 em->block_start = EXTENT_MAP_HOLE;
6544 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6546 btrfs_release_path(path);
6547 if (em->start > start || extent_map_end(em) <= start) {
6548 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6549 em->start, em->len, start, len);
6555 write_lock(&em_tree->lock);
6556 ret = add_extent_mapping(em_tree, em, 0);
6557 /* it is possible that someone inserted the extent into the tree
6558 * while we had the lock dropped. It is also possible that
6559 * an overlapping map exists in the tree
6561 if (ret == -EEXIST) {
6562 struct extent_map *existing;
6566 existing = search_extent_mapping(em_tree, start, len);
6568 * existing will always be non-NULL, since there must be
6569 * extent causing the -EEXIST.
6571 if (start >= extent_map_end(existing) ||
6572 start <= existing->start) {
6574 * The existing extent map is the one nearest to
6575 * the [start, start + len) range which overlaps
6577 err = merge_extent_mapping(em_tree, existing,
6579 free_extent_map(existing);
6581 free_extent_map(em);
6585 free_extent_map(em);
6590 write_unlock(&em_tree->lock);
6593 trace_btrfs_get_extent(root, em);
6596 btrfs_free_path(path);
6598 ret = btrfs_end_transaction(trans, root);
6603 free_extent_map(em);
6604 return ERR_PTR(err);
6606 BUG_ON(!em); /* Error is always set */
6610 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6611 size_t pg_offset, u64 start, u64 len,
6614 struct extent_map *em;
6615 struct extent_map *hole_em = NULL;
6616 u64 range_start = start;
6622 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6629 * - a pre-alloc extent,
6630 * there might actually be delalloc bytes behind it.
6632 if (em->block_start != EXTENT_MAP_HOLE &&
6633 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6639 /* check to see if we've wrapped (len == -1 or similar) */
6648 /* ok, we didn't find anything, lets look for delalloc */
6649 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6650 end, len, EXTENT_DELALLOC, 1);
6651 found_end = range_start + found;
6652 if (found_end < range_start)
6653 found_end = (u64)-1;
6656 * we didn't find anything useful, return
6657 * the original results from get_extent()
6659 if (range_start > end || found_end <= start) {
6665 /* adjust the range_start to make sure it doesn't
6666 * go backwards from the start they passed in
6668 range_start = max(start, range_start);
6669 found = found_end - range_start;
6672 u64 hole_start = start;
6675 em = alloc_extent_map();
6681 * when btrfs_get_extent can't find anything it
6682 * returns one huge hole
6684 * make sure what it found really fits our range, and
6685 * adjust to make sure it is based on the start from
6689 u64 calc_end = extent_map_end(hole_em);
6691 if (calc_end <= start || (hole_em->start > end)) {
6692 free_extent_map(hole_em);
6695 hole_start = max(hole_em->start, start);
6696 hole_len = calc_end - hole_start;
6700 if (hole_em && range_start > hole_start) {
6701 /* our hole starts before our delalloc, so we
6702 * have to return just the parts of the hole
6703 * that go until the delalloc starts
6705 em->len = min(hole_len,
6706 range_start - hole_start);
6707 em->start = hole_start;
6708 em->orig_start = hole_start;
6710 * don't adjust block start at all,
6711 * it is fixed at EXTENT_MAP_HOLE
6713 em->block_start = hole_em->block_start;
6714 em->block_len = hole_len;
6715 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6716 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6718 em->start = range_start;
6720 em->orig_start = range_start;
6721 em->block_start = EXTENT_MAP_DELALLOC;
6722 em->block_len = found;
6724 } else if (hole_em) {
6729 free_extent_map(hole_em);
6731 free_extent_map(em);
6732 return ERR_PTR(err);
6737 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6740 struct btrfs_root *root = BTRFS_I(inode)->root;
6741 struct extent_map *em;
6742 struct btrfs_key ins;
6746 alloc_hint = get_extent_allocation_hint(inode, start, len);
6747 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
6748 alloc_hint, &ins, 1, 1);
6750 return ERR_PTR(ret);
6752 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6753 ins.offset, ins.offset, ins.offset, 0);
6755 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
6759 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6760 ins.offset, ins.offset, 0);
6762 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
6763 free_extent_map(em);
6764 return ERR_PTR(ret);
6771 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6772 * block must be cow'd
6774 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6775 u64 *orig_start, u64 *orig_block_len,
6778 struct btrfs_trans_handle *trans;
6779 struct btrfs_path *path;
6781 struct extent_buffer *leaf;
6782 struct btrfs_root *root = BTRFS_I(inode)->root;
6783 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6784 struct btrfs_file_extent_item *fi;
6785 struct btrfs_key key;
6792 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6794 path = btrfs_alloc_path();
6798 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
6803 slot = path->slots[0];
6806 /* can't find the item, must cow */
6813 leaf = path->nodes[0];
6814 btrfs_item_key_to_cpu(leaf, &key, slot);
6815 if (key.objectid != btrfs_ino(inode) ||
6816 key.type != BTRFS_EXTENT_DATA_KEY) {
6817 /* not our file or wrong item type, must cow */
6821 if (key.offset > offset) {
6822 /* Wrong offset, must cow */
6826 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6827 found_type = btrfs_file_extent_type(leaf, fi);
6828 if (found_type != BTRFS_FILE_EXTENT_REG &&
6829 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6830 /* not a regular extent, must cow */
6834 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6837 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6838 if (extent_end <= offset)
6841 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6842 if (disk_bytenr == 0)
6845 if (btrfs_file_extent_compression(leaf, fi) ||
6846 btrfs_file_extent_encryption(leaf, fi) ||
6847 btrfs_file_extent_other_encoding(leaf, fi))
6850 backref_offset = btrfs_file_extent_offset(leaf, fi);
6853 *orig_start = key.offset - backref_offset;
6854 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6855 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6858 if (btrfs_extent_readonly(root, disk_bytenr))
6861 num_bytes = min(offset + *len, extent_end) - offset;
6862 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6865 range_end = round_up(offset + num_bytes, root->sectorsize) - 1;
6866 ret = test_range_bit(io_tree, offset, range_end,
6867 EXTENT_DELALLOC, 0, NULL);
6874 btrfs_release_path(path);
6877 * look for other files referencing this extent, if we
6878 * find any we must cow
6880 trans = btrfs_join_transaction(root);
6881 if (IS_ERR(trans)) {
6886 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6887 key.offset - backref_offset, disk_bytenr);
6888 btrfs_end_transaction(trans, root);
6895 * adjust disk_bytenr and num_bytes to cover just the bytes
6896 * in this extent we are about to write. If there
6897 * are any csums in that range we have to cow in order
6898 * to keep the csums correct
6900 disk_bytenr += backref_offset;
6901 disk_bytenr += offset - key.offset;
6902 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6905 * all of the above have passed, it is safe to overwrite this extent
6911 btrfs_free_path(path);
6915 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
6917 struct radix_tree_root *root = &inode->i_mapping->page_tree;
6919 void **pagep = NULL;
6920 struct page *page = NULL;
6924 start_idx = start >> PAGE_CACHE_SHIFT;
6927 * end is the last byte in the last page. end == start is legal
6929 end_idx = end >> PAGE_CACHE_SHIFT;
6933 /* Most of the code in this while loop is lifted from
6934 * find_get_page. It's been modified to begin searching from a
6935 * page and return just the first page found in that range. If the
6936 * found idx is less than or equal to the end idx then we know that
6937 * a page exists. If no pages are found or if those pages are
6938 * outside of the range then we're fine (yay!) */
6939 while (page == NULL &&
6940 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
6941 page = radix_tree_deref_slot(pagep);
6942 if (unlikely(!page))
6945 if (radix_tree_exception(page)) {
6946 if (radix_tree_deref_retry(page)) {
6951 * Otherwise, shmem/tmpfs must be storing a swap entry
6952 * here as an exceptional entry: so return it without
6953 * attempting to raise page count.
6956 break; /* TODO: Is this relevant for this use case? */
6959 if (!page_cache_get_speculative(page)) {
6965 * Has the page moved?
6966 * This is part of the lockless pagecache protocol. See
6967 * include/linux/pagemap.h for details.
6969 if (unlikely(page != *pagep)) {
6970 page_cache_release(page);
6976 if (page->index <= end_idx)
6978 page_cache_release(page);
6985 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6986 struct extent_state **cached_state, int writing)
6988 struct btrfs_ordered_extent *ordered;
6992 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6995 * We're concerned with the entire range that we're going to be
6996 * doing DIO to, so we need to make sure theres no ordered
6997 * extents in this range.
6999 ordered = btrfs_lookup_ordered_range(inode, lockstart,
7000 lockend - lockstart + 1);
7003 * We need to make sure there are no buffered pages in this
7004 * range either, we could have raced between the invalidate in
7005 * generic_file_direct_write and locking the extent. The
7006 * invalidate needs to happen so that reads after a write do not
7011 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7014 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7015 cached_state, GFP_NOFS);
7018 btrfs_start_ordered_extent(inode, ordered, 1);
7019 btrfs_put_ordered_extent(ordered);
7021 /* Screw you mmap */
7022 ret = btrfs_fdatawrite_range(inode, lockstart, lockend);
7025 ret = filemap_fdatawait_range(inode->i_mapping,
7032 * If we found a page that couldn't be invalidated just
7033 * fall back to buffered.
7035 ret = invalidate_inode_pages2_range(inode->i_mapping,
7036 lockstart >> PAGE_CACHE_SHIFT,
7037 lockend >> PAGE_CACHE_SHIFT);
7048 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
7049 u64 len, u64 orig_start,
7050 u64 block_start, u64 block_len,
7051 u64 orig_block_len, u64 ram_bytes,
7054 struct extent_map_tree *em_tree;
7055 struct extent_map *em;
7056 struct btrfs_root *root = BTRFS_I(inode)->root;
7059 em_tree = &BTRFS_I(inode)->extent_tree;
7060 em = alloc_extent_map();
7062 return ERR_PTR(-ENOMEM);
7065 em->orig_start = orig_start;
7066 em->mod_start = start;
7069 em->block_len = block_len;
7070 em->block_start = block_start;
7071 em->bdev = root->fs_info->fs_devices->latest_bdev;
7072 em->orig_block_len = orig_block_len;
7073 em->ram_bytes = ram_bytes;
7074 em->generation = -1;
7075 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7076 if (type == BTRFS_ORDERED_PREALLOC)
7077 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7080 btrfs_drop_extent_cache(inode, em->start,
7081 em->start + em->len - 1, 0);
7082 write_lock(&em_tree->lock);
7083 ret = add_extent_mapping(em_tree, em, 1);
7084 write_unlock(&em_tree->lock);
7085 } while (ret == -EEXIST);
7088 free_extent_map(em);
7089 return ERR_PTR(ret);
7096 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7097 struct buffer_head *bh_result, int create)
7099 struct extent_map *em;
7100 struct btrfs_root *root = BTRFS_I(inode)->root;
7101 struct extent_state *cached_state = NULL;
7102 u64 start = iblock << inode->i_blkbits;
7103 u64 lockstart, lockend;
7104 u64 len = bh_result->b_size;
7105 int unlock_bits = EXTENT_LOCKED;
7109 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
7111 len = min_t(u64, len, root->sectorsize);
7114 lockend = start + len - 1;
7117 * If this errors out it's because we couldn't invalidate pagecache for
7118 * this range and we need to fallback to buffered.
7120 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
7123 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7130 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7131 * io. INLINE is special, and we could probably kludge it in here, but
7132 * it's still buffered so for safety lets just fall back to the generic
7135 * For COMPRESSED we _have_ to read the entire extent in so we can
7136 * decompress it, so there will be buffering required no matter what we
7137 * do, so go ahead and fallback to buffered.
7139 * We return -ENOTBLK because thats what makes DIO go ahead and go back
7140 * to buffered IO. Don't blame me, this is the price we pay for using
7143 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7144 em->block_start == EXTENT_MAP_INLINE) {
7145 free_extent_map(em);
7150 /* Just a good old fashioned hole, return */
7151 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7152 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7153 free_extent_map(em);
7158 * We don't allocate a new extent in the following cases
7160 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7162 * 2) The extent is marked as PREALLOC. We're good to go here and can
7163 * just use the extent.
7167 len = min(len, em->len - (start - em->start));
7168 lockstart = start + len;
7172 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7173 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7174 em->block_start != EXTENT_MAP_HOLE)) {
7177 u64 block_start, orig_start, orig_block_len, ram_bytes;
7179 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7180 type = BTRFS_ORDERED_PREALLOC;
7182 type = BTRFS_ORDERED_NOCOW;
7183 len = min(len, em->len - (start - em->start));
7184 block_start = em->block_start + (start - em->start);
7186 if (can_nocow_extent(inode, start, &len, &orig_start,
7187 &orig_block_len, &ram_bytes) == 1) {
7188 if (type == BTRFS_ORDERED_PREALLOC) {
7189 free_extent_map(em);
7190 em = create_pinned_em(inode, start, len,
7201 ret = btrfs_add_ordered_extent_dio(inode, start,
7202 block_start, len, len, type);
7204 free_extent_map(em);
7212 * this will cow the extent, reset the len in case we changed
7215 len = bh_result->b_size;
7216 free_extent_map(em);
7217 em = btrfs_new_extent_direct(inode, start, len);
7222 len = min(len, em->len - (start - em->start));
7224 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7226 bh_result->b_size = len;
7227 bh_result->b_bdev = em->bdev;
7228 set_buffer_mapped(bh_result);
7230 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7231 set_buffer_new(bh_result);
7234 * Need to update the i_size under the extent lock so buffered
7235 * readers will get the updated i_size when we unlock.
7237 if (start + len > i_size_read(inode))
7238 i_size_write(inode, start + len);
7240 spin_lock(&BTRFS_I(inode)->lock);
7241 BTRFS_I(inode)->outstanding_extents++;
7242 spin_unlock(&BTRFS_I(inode)->lock);
7244 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7245 lockstart + len - 1, EXTENT_DELALLOC, NULL,
7246 &cached_state, GFP_NOFS);
7251 * In the case of write we need to clear and unlock the entire range,
7252 * in the case of read we need to unlock only the end area that we
7253 * aren't using if there is any left over space.
7255 if (lockstart < lockend) {
7256 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7257 lockend, unlock_bits, 1, 0,
7258 &cached_state, GFP_NOFS);
7260 free_extent_state(cached_state);
7263 free_extent_map(em);
7268 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7269 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7273 static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7274 int rw, int mirror_num)
7276 struct btrfs_root *root = BTRFS_I(inode)->root;
7279 BUG_ON(rw & REQ_WRITE);
7283 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7284 BTRFS_WQ_ENDIO_DIO_REPAIR);
7288 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
7294 static int btrfs_check_dio_repairable(struct inode *inode,
7295 struct bio *failed_bio,
7296 struct io_failure_record *failrec,
7301 num_copies = btrfs_num_copies(BTRFS_I(inode)->root->fs_info,
7302 failrec->logical, failrec->len);
7303 if (num_copies == 1) {
7305 * we only have a single copy of the data, so don't bother with
7306 * all the retry and error correction code that follows. no
7307 * matter what the error is, it is very likely to persist.
7309 pr_debug("Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d\n",
7310 num_copies, failrec->this_mirror, failed_mirror);
7314 failrec->failed_mirror = failed_mirror;
7315 failrec->this_mirror++;
7316 if (failrec->this_mirror == failed_mirror)
7317 failrec->this_mirror++;
7319 if (failrec->this_mirror > num_copies) {
7320 pr_debug("Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d\n",
7321 num_copies, failrec->this_mirror, failed_mirror);
7328 static int dio_read_error(struct inode *inode, struct bio *failed_bio,
7329 struct page *page, u64 start, u64 end,
7330 int failed_mirror, bio_end_io_t *repair_endio,
7333 struct io_failure_record *failrec;
7339 BUG_ON(failed_bio->bi_rw & REQ_WRITE);
7341 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7345 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7348 free_io_failure(inode, failrec);
7352 if (failed_bio->bi_vcnt > 1)
7353 read_mode = READ_SYNC | REQ_FAILFAST_DEV;
7355 read_mode = READ_SYNC;
7357 isector = start - btrfs_io_bio(failed_bio)->logical;
7358 isector >>= inode->i_sb->s_blocksize_bits;
7359 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7360 0, isector, repair_endio, repair_arg);
7362 free_io_failure(inode, failrec);
7366 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7367 "Repair DIO Read Error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d\n",
7368 read_mode, failrec->this_mirror, failrec->in_validation);
7370 ret = submit_dio_repair_bio(inode, bio, read_mode,
7371 failrec->this_mirror);
7373 free_io_failure(inode, failrec);
7380 struct btrfs_retry_complete {
7381 struct completion done;
7382 struct inode *inode;
7387 static void btrfs_retry_endio_nocsum(struct bio *bio, int err)
7389 struct btrfs_retry_complete *done = bio->bi_private;
7390 struct bio_vec *bvec;
7397 bio_for_each_segment_all(bvec, bio, i)
7398 clean_io_failure(done->inode, done->start, bvec->bv_page, 0);
7400 complete(&done->done);
7404 static int __btrfs_correct_data_nocsum(struct inode *inode,
7405 struct btrfs_io_bio *io_bio)
7407 struct bio_vec *bvec;
7408 struct btrfs_retry_complete done;
7413 start = io_bio->logical;
7416 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7420 init_completion(&done.done);
7422 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7423 start + bvec->bv_len - 1,
7425 btrfs_retry_endio_nocsum, &done);
7429 wait_for_completion(&done.done);
7431 if (!done.uptodate) {
7432 /* We might have another mirror, so try again */
7436 start += bvec->bv_len;
7442 static void btrfs_retry_endio(struct bio *bio, int err)
7444 struct btrfs_retry_complete *done = bio->bi_private;
7445 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7446 struct bio_vec *bvec;
7455 bio_for_each_segment_all(bvec, bio, i) {
7456 ret = __readpage_endio_check(done->inode, io_bio, i,
7458 done->start, bvec->bv_len);
7460 clean_io_failure(done->inode, done->start,
7466 done->uptodate = uptodate;
7468 complete(&done->done);
7472 static int __btrfs_subio_endio_read(struct inode *inode,
7473 struct btrfs_io_bio *io_bio, int err)
7475 struct bio_vec *bvec;
7476 struct btrfs_retry_complete done;
7483 start = io_bio->logical;
7486 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7487 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7488 0, start, bvec->bv_len);
7494 init_completion(&done.done);
7496 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7497 start + bvec->bv_len - 1,
7499 btrfs_retry_endio, &done);
7505 wait_for_completion(&done.done);
7507 if (!done.uptodate) {
7508 /* We might have another mirror, so try again */
7512 offset += bvec->bv_len;
7513 start += bvec->bv_len;
7519 static int btrfs_subio_endio_read(struct inode *inode,
7520 struct btrfs_io_bio *io_bio, int err)
7522 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7526 return __btrfs_correct_data_nocsum(inode, io_bio);
7530 return __btrfs_subio_endio_read(inode, io_bio, err);
7534 static void btrfs_endio_direct_read(struct bio *bio, int err)
7536 struct btrfs_dio_private *dip = bio->bi_private;
7537 struct inode *inode = dip->inode;
7538 struct bio *dio_bio;
7539 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7541 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
7542 err = btrfs_subio_endio_read(inode, io_bio, err);
7544 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
7545 dip->logical_offset + dip->bytes - 1);
7546 dio_bio = dip->dio_bio;
7550 /* If we had a csum failure make sure to clear the uptodate flag */
7552 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7553 dio_end_io(dio_bio, err);
7556 io_bio->end_io(io_bio, err);
7560 static void btrfs_endio_direct_write(struct bio *bio, int err)
7562 struct btrfs_dio_private *dip = bio->bi_private;
7563 struct inode *inode = dip->inode;
7564 struct btrfs_root *root = BTRFS_I(inode)->root;
7565 struct btrfs_ordered_extent *ordered = NULL;
7566 u64 ordered_offset = dip->logical_offset;
7567 u64 ordered_bytes = dip->bytes;
7568 struct bio *dio_bio;
7574 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7576 ordered_bytes, !err);
7580 btrfs_init_work(&ordered->work, btrfs_endio_write_helper,
7581 finish_ordered_fn, NULL, NULL);
7582 btrfs_queue_work(root->fs_info->endio_write_workers,
7586 * our bio might span multiple ordered extents. If we haven't
7587 * completed the accounting for the whole dio, go back and try again
7589 if (ordered_offset < dip->logical_offset + dip->bytes) {
7590 ordered_bytes = dip->logical_offset + dip->bytes -
7596 dio_bio = dip->dio_bio;
7600 /* If we had an error make sure to clear the uptodate flag */
7602 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7603 dio_end_io(dio_bio, err);
7607 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7608 struct bio *bio, int mirror_num,
7609 unsigned long bio_flags, u64 offset)
7612 struct btrfs_root *root = BTRFS_I(inode)->root;
7613 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7614 BUG_ON(ret); /* -ENOMEM */
7618 static void btrfs_end_dio_bio(struct bio *bio, int err)
7620 struct btrfs_dio_private *dip = bio->bi_private;
7623 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7624 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
7625 btrfs_ino(dip->inode), bio->bi_rw,
7626 (unsigned long long)bio->bi_iter.bi_sector,
7627 bio->bi_iter.bi_size, err);
7629 if (dip->subio_endio)
7630 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
7636 * before atomic variable goto zero, we must make sure
7637 * dip->errors is perceived to be set.
7639 smp_mb__before_atomic();
7642 /* if there are more bios still pending for this dio, just exit */
7643 if (!atomic_dec_and_test(&dip->pending_bios))
7647 bio_io_error(dip->orig_bio);
7649 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
7650 bio_endio(dip->orig_bio, 0);
7656 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7657 u64 first_sector, gfp_t gfp_flags)
7659 int nr_vecs = bio_get_nr_vecs(bdev);
7660 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7663 static inline int btrfs_lookup_and_bind_dio_csum(struct btrfs_root *root,
7664 struct inode *inode,
7665 struct btrfs_dio_private *dip,
7669 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7670 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
7674 * We load all the csum data we need when we submit
7675 * the first bio to reduce the csum tree search and
7678 if (dip->logical_offset == file_offset) {
7679 ret = btrfs_lookup_bio_sums_dio(root, inode, dip->orig_bio,
7685 if (bio == dip->orig_bio)
7688 file_offset -= dip->logical_offset;
7689 file_offset >>= inode->i_sb->s_blocksize_bits;
7690 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
7695 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7696 int rw, u64 file_offset, int skip_sum,
7699 struct btrfs_dio_private *dip = bio->bi_private;
7700 int write = rw & REQ_WRITE;
7701 struct btrfs_root *root = BTRFS_I(inode)->root;
7705 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7710 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7711 BTRFS_WQ_ENDIO_DATA);
7719 if (write && async_submit) {
7720 ret = btrfs_wq_submit_bio(root->fs_info,
7721 inode, rw, bio, 0, 0,
7723 __btrfs_submit_bio_start_direct_io,
7724 __btrfs_submit_bio_done);
7728 * If we aren't doing async submit, calculate the csum of the
7731 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7735 ret = btrfs_lookup_and_bind_dio_csum(root, inode, dip, bio,
7741 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7747 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7750 struct inode *inode = dip->inode;
7751 struct btrfs_root *root = BTRFS_I(inode)->root;
7753 struct bio *orig_bio = dip->orig_bio;
7754 struct bio_vec *bvec = orig_bio->bi_io_vec;
7755 u64 start_sector = orig_bio->bi_iter.bi_sector;
7756 u64 file_offset = dip->logical_offset;
7761 int async_submit = 0;
7763 map_length = orig_bio->bi_iter.bi_size;
7764 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7765 &map_length, NULL, 0);
7769 if (map_length >= orig_bio->bi_iter.bi_size) {
7771 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
7775 /* async crcs make it difficult to collect full stripe writes. */
7776 if (btrfs_get_alloc_profile(root, 1) &
7777 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7782 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7786 bio->bi_private = dip;
7787 bio->bi_end_io = btrfs_end_dio_bio;
7788 btrfs_io_bio(bio)->logical = file_offset;
7789 atomic_inc(&dip->pending_bios);
7791 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7792 if (map_length < submit_len + bvec->bv_len ||
7793 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7794 bvec->bv_offset) < bvec->bv_len) {
7796 * inc the count before we submit the bio so
7797 * we know the end IO handler won't happen before
7798 * we inc the count. Otherwise, the dip might get freed
7799 * before we're done setting it up
7801 atomic_inc(&dip->pending_bios);
7802 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7803 file_offset, skip_sum,
7807 atomic_dec(&dip->pending_bios);
7811 start_sector += submit_len >> 9;
7812 file_offset += submit_len;
7817 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7818 start_sector, GFP_NOFS);
7821 bio->bi_private = dip;
7822 bio->bi_end_io = btrfs_end_dio_bio;
7823 btrfs_io_bio(bio)->logical = file_offset;
7825 map_length = orig_bio->bi_iter.bi_size;
7826 ret = btrfs_map_block(root->fs_info, rw,
7828 &map_length, NULL, 0);
7834 submit_len += bvec->bv_len;
7841 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7850 * before atomic variable goto zero, we must
7851 * make sure dip->errors is perceived to be set.
7853 smp_mb__before_atomic();
7854 if (atomic_dec_and_test(&dip->pending_bios))
7855 bio_io_error(dip->orig_bio);
7857 /* bio_end_io() will handle error, so we needn't return it */
7861 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7862 struct inode *inode, loff_t file_offset)
7864 struct btrfs_root *root = BTRFS_I(inode)->root;
7865 struct btrfs_dio_private *dip;
7867 struct btrfs_io_bio *btrfs_bio;
7869 int write = rw & REQ_WRITE;
7872 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7874 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7880 dip = kzalloc(sizeof(*dip), GFP_NOFS);
7886 dip->private = dio_bio->bi_private;
7888 dip->logical_offset = file_offset;
7889 dip->bytes = dio_bio->bi_iter.bi_size;
7890 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7891 io_bio->bi_private = dip;
7892 dip->orig_bio = io_bio;
7893 dip->dio_bio = dio_bio;
7894 atomic_set(&dip->pending_bios, 0);
7895 btrfs_bio = btrfs_io_bio(io_bio);
7896 btrfs_bio->logical = file_offset;
7899 io_bio->bi_end_io = btrfs_endio_direct_write;
7901 io_bio->bi_end_io = btrfs_endio_direct_read;
7902 dip->subio_endio = btrfs_subio_endio_read;
7905 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7909 if (btrfs_bio->end_io)
7910 btrfs_bio->end_io(btrfs_bio, ret);
7916 * If this is a write, we need to clean up the reserved space and kill
7917 * the ordered extent.
7920 struct btrfs_ordered_extent *ordered;
7921 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7922 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7923 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7924 btrfs_free_reserved_extent(root, ordered->start,
7925 ordered->disk_len, 1);
7926 btrfs_put_ordered_extent(ordered);
7927 btrfs_put_ordered_extent(ordered);
7929 bio_endio(dio_bio, ret);
7932 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7933 const struct iov_iter *iter, loff_t offset)
7937 unsigned blocksize_mask = root->sectorsize - 1;
7938 ssize_t retval = -EINVAL;
7940 if (offset & blocksize_mask)
7943 if (iov_iter_alignment(iter) & blocksize_mask)
7946 /* If this is a write we don't need to check anymore */
7950 * Check to make sure we don't have duplicate iov_base's in this
7951 * iovec, if so return EINVAL, otherwise we'll get csum errors
7952 * when reading back.
7954 for (seg = 0; seg < iter->nr_segs; seg++) {
7955 for (i = seg + 1; i < iter->nr_segs; i++) {
7956 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
7965 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7966 struct iov_iter *iter, loff_t offset)
7968 struct file *file = iocb->ki_filp;
7969 struct inode *inode = file->f_mapping->host;
7973 bool relock = false;
7976 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iter, offset))
7979 atomic_inc(&inode->i_dio_count);
7980 smp_mb__after_atomic();
7983 * The generic stuff only does filemap_write_and_wait_range, which
7984 * isn't enough if we've written compressed pages to this area, so
7985 * we need to flush the dirty pages again to make absolutely sure
7986 * that any outstanding dirty pages are on disk.
7988 count = iov_iter_count(iter);
7989 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7990 &BTRFS_I(inode)->runtime_flags))
7991 filemap_fdatawrite_range(inode->i_mapping, offset,
7992 offset + count - 1);
7996 * If the write DIO is beyond the EOF, we need update
7997 * the isize, but it is protected by i_mutex. So we can
7998 * not unlock the i_mutex at this case.
8000 if (offset + count <= inode->i_size) {
8001 mutex_unlock(&inode->i_mutex);
8004 ret = btrfs_delalloc_reserve_space(inode, count);
8007 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8008 &BTRFS_I(inode)->runtime_flags)) {
8009 inode_dio_done(inode);
8010 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8014 ret = __blockdev_direct_IO(rw, iocb, inode,
8015 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
8016 iter, offset, btrfs_get_blocks_direct, NULL,
8017 btrfs_submit_direct, flags);
8019 if (ret < 0 && ret != -EIOCBQUEUED)
8020 btrfs_delalloc_release_space(inode, count);
8021 else if (ret >= 0 && (size_t)ret < count)
8022 btrfs_delalloc_release_space(inode,
8023 count - (size_t)ret);
8025 btrfs_delalloc_release_metadata(inode, 0);
8029 inode_dio_done(inode);
8031 mutex_lock(&inode->i_mutex);
8036 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8038 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8039 __u64 start, __u64 len)
8043 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8047 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
8050 int btrfs_readpage(struct file *file, struct page *page)
8052 struct extent_io_tree *tree;
8053 tree = &BTRFS_I(page->mapping->host)->io_tree;
8054 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8057 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8059 struct extent_io_tree *tree;
8062 if (current->flags & PF_MEMALLOC) {
8063 redirty_page_for_writepage(wbc, page);
8067 tree = &BTRFS_I(page->mapping->host)->io_tree;
8068 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
8071 static int btrfs_writepages(struct address_space *mapping,
8072 struct writeback_control *wbc)
8074 struct extent_io_tree *tree;
8076 tree = &BTRFS_I(mapping->host)->io_tree;
8077 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8081 btrfs_readpages(struct file *file, struct address_space *mapping,
8082 struct list_head *pages, unsigned nr_pages)
8084 struct extent_io_tree *tree;
8085 tree = &BTRFS_I(mapping->host)->io_tree;
8086 return extent_readpages(tree, mapping, pages, nr_pages,
8089 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8091 struct extent_io_tree *tree;
8092 struct extent_map_tree *map;
8095 tree = &BTRFS_I(page->mapping->host)->io_tree;
8096 map = &BTRFS_I(page->mapping->host)->extent_tree;
8097 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8099 ClearPagePrivate(page);
8100 set_page_private(page, 0);
8101 page_cache_release(page);
8106 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8108 if (PageWriteback(page) || PageDirty(page))
8110 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
8113 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8114 unsigned int length)
8116 struct inode *inode = page->mapping->host;
8117 struct extent_io_tree *tree;
8118 struct btrfs_ordered_extent *ordered;
8119 struct extent_state *cached_state = NULL;
8120 u64 page_start = page_offset(page);
8121 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
8122 int inode_evicting = inode->i_state & I_FREEING;
8125 * we have the page locked, so new writeback can't start,
8126 * and the dirty bit won't be cleared while we are here.
8128 * Wait for IO on this page so that we can safely clear
8129 * the PagePrivate2 bit and do ordered accounting
8131 wait_on_page_writeback(page);
8133 tree = &BTRFS_I(inode)->io_tree;
8135 btrfs_releasepage(page, GFP_NOFS);
8139 if (!inode_evicting)
8140 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
8141 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8144 * IO on this page will never be started, so we need
8145 * to account for any ordered extents now
8147 if (!inode_evicting)
8148 clear_extent_bit(tree, page_start, page_end,
8149 EXTENT_DIRTY | EXTENT_DELALLOC |
8150 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8151 EXTENT_DEFRAG, 1, 0, &cached_state,
8154 * whoever cleared the private bit is responsible
8155 * for the finish_ordered_io
8157 if (TestClearPagePrivate2(page)) {
8158 struct btrfs_ordered_inode_tree *tree;
8161 tree = &BTRFS_I(inode)->ordered_tree;
8163 spin_lock_irq(&tree->lock);
8164 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8165 new_len = page_start - ordered->file_offset;
8166 if (new_len < ordered->truncated_len)
8167 ordered->truncated_len = new_len;
8168 spin_unlock_irq(&tree->lock);
8170 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8172 PAGE_CACHE_SIZE, 1))
8173 btrfs_finish_ordered_io(ordered);
8175 btrfs_put_ordered_extent(ordered);
8176 if (!inode_evicting) {
8177 cached_state = NULL;
8178 lock_extent_bits(tree, page_start, page_end, 0,
8183 if (!inode_evicting) {
8184 clear_extent_bit(tree, page_start, page_end,
8185 EXTENT_LOCKED | EXTENT_DIRTY |
8186 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8187 EXTENT_DEFRAG, 1, 1,
8188 &cached_state, GFP_NOFS);
8190 __btrfs_releasepage(page, GFP_NOFS);
8193 ClearPageChecked(page);
8194 if (PagePrivate(page)) {
8195 ClearPagePrivate(page);
8196 set_page_private(page, 0);
8197 page_cache_release(page);
8202 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8203 * called from a page fault handler when a page is first dirtied. Hence we must
8204 * be careful to check for EOF conditions here. We set the page up correctly
8205 * for a written page which means we get ENOSPC checking when writing into
8206 * holes and correct delalloc and unwritten extent mapping on filesystems that
8207 * support these features.
8209 * We are not allowed to take the i_mutex here so we have to play games to
8210 * protect against truncate races as the page could now be beyond EOF. Because
8211 * vmtruncate() writes the inode size before removing pages, once we have the
8212 * page lock we can determine safely if the page is beyond EOF. If it is not
8213 * beyond EOF, then the page is guaranteed safe against truncation until we
8216 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
8218 struct page *page = vmf->page;
8219 struct inode *inode = file_inode(vma->vm_file);
8220 struct btrfs_root *root = BTRFS_I(inode)->root;
8221 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8222 struct btrfs_ordered_extent *ordered;
8223 struct extent_state *cached_state = NULL;
8225 unsigned long zero_start;
8232 sb_start_pagefault(inode->i_sb);
8233 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
8235 ret = file_update_time(vma->vm_file);
8241 else /* -ENOSPC, -EIO, etc */
8242 ret = VM_FAULT_SIGBUS;
8248 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8251 size = i_size_read(inode);
8252 page_start = page_offset(page);
8253 page_end = page_start + PAGE_CACHE_SIZE - 1;
8255 if ((page->mapping != inode->i_mapping) ||
8256 (page_start >= size)) {
8257 /* page got truncated out from underneath us */
8260 wait_on_page_writeback(page);
8262 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
8263 set_page_extent_mapped(page);
8266 * we can't set the delalloc bits if there are pending ordered
8267 * extents. Drop our locks and wait for them to finish
8269 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8271 unlock_extent_cached(io_tree, page_start, page_end,
8272 &cached_state, GFP_NOFS);
8274 btrfs_start_ordered_extent(inode, ordered, 1);
8275 btrfs_put_ordered_extent(ordered);
8280 * XXX - page_mkwrite gets called every time the page is dirtied, even
8281 * if it was already dirty, so for space accounting reasons we need to
8282 * clear any delalloc bits for the range we are fixing to save. There
8283 * is probably a better way to do this, but for now keep consistent with
8284 * prepare_pages in the normal write path.
8286 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
8287 EXTENT_DIRTY | EXTENT_DELALLOC |
8288 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8289 0, 0, &cached_state, GFP_NOFS);
8291 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
8294 unlock_extent_cached(io_tree, page_start, page_end,
8295 &cached_state, GFP_NOFS);
8296 ret = VM_FAULT_SIGBUS;
8301 /* page is wholly or partially inside EOF */
8302 if (page_start + PAGE_CACHE_SIZE > size)
8303 zero_start = size & ~PAGE_CACHE_MASK;
8305 zero_start = PAGE_CACHE_SIZE;
8307 if (zero_start != PAGE_CACHE_SIZE) {
8309 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
8310 flush_dcache_page(page);
8313 ClearPageChecked(page);
8314 set_page_dirty(page);
8315 SetPageUptodate(page);
8317 BTRFS_I(inode)->last_trans = root->fs_info->generation;
8318 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8319 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8321 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
8325 sb_end_pagefault(inode->i_sb);
8326 return VM_FAULT_LOCKED;
8330 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
8332 sb_end_pagefault(inode->i_sb);
8336 static int btrfs_truncate(struct inode *inode)
8338 struct btrfs_root *root = BTRFS_I(inode)->root;
8339 struct btrfs_block_rsv *rsv;
8342 struct btrfs_trans_handle *trans;
8343 u64 mask = root->sectorsize - 1;
8344 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
8346 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8352 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
8353 * 3 things going on here
8355 * 1) We need to reserve space for our orphan item and the space to
8356 * delete our orphan item. Lord knows we don't want to have a dangling
8357 * orphan item because we didn't reserve space to remove it.
8359 * 2) We need to reserve space to update our inode.
8361 * 3) We need to have something to cache all the space that is going to
8362 * be free'd up by the truncate operation, but also have some slack
8363 * space reserved in case it uses space during the truncate (thank you
8364 * very much snapshotting).
8366 * And we need these to all be seperate. The fact is we can use alot of
8367 * space doing the truncate, and we have no earthly idea how much space
8368 * we will use, so we need the truncate reservation to be seperate so it
8369 * doesn't end up using space reserved for updating the inode or
8370 * removing the orphan item. We also need to be able to stop the
8371 * transaction and start a new one, which means we need to be able to
8372 * update the inode several times, and we have no idea of knowing how
8373 * many times that will be, so we can't just reserve 1 item for the
8374 * entirety of the opration, so that has to be done seperately as well.
8375 * Then there is the orphan item, which does indeed need to be held on
8376 * to for the whole operation, and we need nobody to touch this reserved
8377 * space except the orphan code.
8379 * So that leaves us with
8381 * 1) root->orphan_block_rsv - for the orphan deletion.
8382 * 2) rsv - for the truncate reservation, which we will steal from the
8383 * transaction reservation.
8384 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
8385 * updating the inode.
8387 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
8390 rsv->size = min_size;
8394 * 1 for the truncate slack space
8395 * 1 for updating the inode.
8397 trans = btrfs_start_transaction(root, 2);
8398 if (IS_ERR(trans)) {
8399 err = PTR_ERR(trans);
8403 /* Migrate the slack space for the truncate to our reserve */
8404 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
8409 * So if we truncate and then write and fsync we normally would just
8410 * write the extents that changed, which is a problem if we need to
8411 * first truncate that entire inode. So set this flag so we write out
8412 * all of the extents in the inode to the sync log so we're completely
8415 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8416 trans->block_rsv = rsv;
8419 ret = btrfs_truncate_inode_items(trans, root, inode,
8421 BTRFS_EXTENT_DATA_KEY);
8422 if (ret != -ENOSPC) {
8427 trans->block_rsv = &root->fs_info->trans_block_rsv;
8428 ret = btrfs_update_inode(trans, root, inode);
8434 btrfs_end_transaction(trans, root);
8435 btrfs_btree_balance_dirty(root);
8437 trans = btrfs_start_transaction(root, 2);
8438 if (IS_ERR(trans)) {
8439 ret = err = PTR_ERR(trans);
8444 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
8446 BUG_ON(ret); /* shouldn't happen */
8447 trans->block_rsv = rsv;
8450 if (ret == 0 && inode->i_nlink > 0) {
8451 trans->block_rsv = root->orphan_block_rsv;
8452 ret = btrfs_orphan_del(trans, inode);
8458 trans->block_rsv = &root->fs_info->trans_block_rsv;
8459 ret = btrfs_update_inode(trans, root, inode);
8463 ret = btrfs_end_transaction(trans, root);
8464 btrfs_btree_balance_dirty(root);
8468 btrfs_free_block_rsv(root, rsv);
8477 * create a new subvolume directory/inode (helper for the ioctl).
8479 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8480 struct btrfs_root *new_root,
8481 struct btrfs_root *parent_root,
8484 struct inode *inode;
8488 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8489 new_dirid, new_dirid,
8490 S_IFDIR | (~current_umask() & S_IRWXUGO),
8493 return PTR_ERR(inode);
8494 inode->i_op = &btrfs_dir_inode_operations;
8495 inode->i_fop = &btrfs_dir_file_operations;
8497 set_nlink(inode, 1);
8498 btrfs_i_size_write(inode, 0);
8499 unlock_new_inode(inode);
8501 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8503 btrfs_err(new_root->fs_info,
8504 "error inheriting subvolume %llu properties: %d",
8505 new_root->root_key.objectid, err);
8507 err = btrfs_update_inode(trans, new_root, inode);
8513 struct inode *btrfs_alloc_inode(struct super_block *sb)
8515 struct btrfs_inode *ei;
8516 struct inode *inode;
8518 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
8525 ei->last_sub_trans = 0;
8526 ei->logged_trans = 0;
8527 ei->delalloc_bytes = 0;
8528 ei->defrag_bytes = 0;
8529 ei->disk_i_size = 0;
8532 ei->index_cnt = (u64)-1;
8534 ei->last_unlink_trans = 0;
8535 ei->last_log_commit = 0;
8537 spin_lock_init(&ei->lock);
8538 ei->outstanding_extents = 0;
8539 ei->reserved_extents = 0;
8541 ei->runtime_flags = 0;
8542 ei->force_compress = BTRFS_COMPRESS_NONE;
8544 ei->delayed_node = NULL;
8546 inode = &ei->vfs_inode;
8547 extent_map_tree_init(&ei->extent_tree);
8548 extent_io_tree_init(&ei->io_tree, &inode->i_data);
8549 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
8550 ei->io_tree.track_uptodate = 1;
8551 ei->io_failure_tree.track_uptodate = 1;
8552 atomic_set(&ei->sync_writers, 0);
8553 mutex_init(&ei->log_mutex);
8554 mutex_init(&ei->delalloc_mutex);
8555 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8556 INIT_LIST_HEAD(&ei->delalloc_inodes);
8557 RB_CLEAR_NODE(&ei->rb_node);
8562 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8563 void btrfs_test_destroy_inode(struct inode *inode)
8565 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8566 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8570 static void btrfs_i_callback(struct rcu_head *head)
8572 struct inode *inode = container_of(head, struct inode, i_rcu);
8573 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8576 void btrfs_destroy_inode(struct inode *inode)
8578 struct btrfs_ordered_extent *ordered;
8579 struct btrfs_root *root = BTRFS_I(inode)->root;
8581 WARN_ON(!hlist_empty(&inode->i_dentry));
8582 WARN_ON(inode->i_data.nrpages);
8583 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8584 WARN_ON(BTRFS_I(inode)->reserved_extents);
8585 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8586 WARN_ON(BTRFS_I(inode)->csum_bytes);
8587 WARN_ON(BTRFS_I(inode)->defrag_bytes);
8590 * This can happen where we create an inode, but somebody else also
8591 * created the same inode and we need to destroy the one we already
8597 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8598 &BTRFS_I(inode)->runtime_flags)) {
8599 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
8601 atomic_dec(&root->orphan_inodes);
8605 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8609 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
8610 ordered->file_offset, ordered->len);
8611 btrfs_remove_ordered_extent(inode, ordered);
8612 btrfs_put_ordered_extent(ordered);
8613 btrfs_put_ordered_extent(ordered);
8616 inode_tree_del(inode);
8617 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8619 call_rcu(&inode->i_rcu, btrfs_i_callback);
8622 int btrfs_drop_inode(struct inode *inode)
8624 struct btrfs_root *root = BTRFS_I(inode)->root;
8629 /* the snap/subvol tree is on deleting */
8630 if (btrfs_root_refs(&root->root_item) == 0)
8633 return generic_drop_inode(inode);
8636 static void init_once(void *foo)
8638 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8640 inode_init_once(&ei->vfs_inode);
8643 void btrfs_destroy_cachep(void)
8646 * Make sure all delayed rcu free inodes are flushed before we
8650 if (btrfs_inode_cachep)
8651 kmem_cache_destroy(btrfs_inode_cachep);
8652 if (btrfs_trans_handle_cachep)
8653 kmem_cache_destroy(btrfs_trans_handle_cachep);
8654 if (btrfs_transaction_cachep)
8655 kmem_cache_destroy(btrfs_transaction_cachep);
8656 if (btrfs_path_cachep)
8657 kmem_cache_destroy(btrfs_path_cachep);
8658 if (btrfs_free_space_cachep)
8659 kmem_cache_destroy(btrfs_free_space_cachep);
8660 if (btrfs_delalloc_work_cachep)
8661 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8664 int btrfs_init_cachep(void)
8666 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8667 sizeof(struct btrfs_inode), 0,
8668 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8669 if (!btrfs_inode_cachep)
8672 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8673 sizeof(struct btrfs_trans_handle), 0,
8674 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8675 if (!btrfs_trans_handle_cachep)
8678 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8679 sizeof(struct btrfs_transaction), 0,
8680 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8681 if (!btrfs_transaction_cachep)
8684 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8685 sizeof(struct btrfs_path), 0,
8686 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8687 if (!btrfs_path_cachep)
8690 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8691 sizeof(struct btrfs_free_space), 0,
8692 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8693 if (!btrfs_free_space_cachep)
8696 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8697 sizeof(struct btrfs_delalloc_work), 0,
8698 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8700 if (!btrfs_delalloc_work_cachep)
8705 btrfs_destroy_cachep();
8709 static int btrfs_getattr(struct vfsmount *mnt,
8710 struct dentry *dentry, struct kstat *stat)
8713 struct inode *inode = dentry->d_inode;
8714 u32 blocksize = inode->i_sb->s_blocksize;
8716 generic_fillattr(inode, stat);
8717 stat->dev = BTRFS_I(inode)->root->anon_dev;
8718 stat->blksize = PAGE_CACHE_SIZE;
8720 spin_lock(&BTRFS_I(inode)->lock);
8721 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8722 spin_unlock(&BTRFS_I(inode)->lock);
8723 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8724 ALIGN(delalloc_bytes, blocksize)) >> 9;
8728 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8729 struct inode *new_dir, struct dentry *new_dentry)
8731 struct btrfs_trans_handle *trans;
8732 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8733 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8734 struct inode *new_inode = new_dentry->d_inode;
8735 struct inode *old_inode = old_dentry->d_inode;
8736 struct timespec ctime = CURRENT_TIME;
8740 u64 old_ino = btrfs_ino(old_inode);
8742 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8745 /* we only allow rename subvolume link between subvolumes */
8746 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8749 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8750 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8753 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8754 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8758 /* check for collisions, even if the name isn't there */
8759 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8760 new_dentry->d_name.name,
8761 new_dentry->d_name.len);
8764 if (ret == -EEXIST) {
8766 * eexist without a new_inode */
8767 if (WARN_ON(!new_inode)) {
8771 /* maybe -EOVERFLOW */
8778 * we're using rename to replace one file with another. Start IO on it
8779 * now so we don't add too much work to the end of the transaction
8781 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
8782 filemap_flush(old_inode->i_mapping);
8784 /* close the racy window with snapshot create/destroy ioctl */
8785 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8786 down_read(&root->fs_info->subvol_sem);
8788 * We want to reserve the absolute worst case amount of items. So if
8789 * both inodes are subvols and we need to unlink them then that would
8790 * require 4 item modifications, but if they are both normal inodes it
8791 * would require 5 item modifications, so we'll assume their normal
8792 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8793 * should cover the worst case number of items we'll modify.
8795 trans = btrfs_start_transaction(root, 11);
8796 if (IS_ERR(trans)) {
8797 ret = PTR_ERR(trans);
8802 btrfs_record_root_in_trans(trans, dest);
8804 ret = btrfs_set_inode_index(new_dir, &index);
8808 BTRFS_I(old_inode)->dir_index = 0ULL;
8809 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8810 /* force full log commit if subvolume involved. */
8811 btrfs_set_log_full_commit(root->fs_info, trans);
8813 ret = btrfs_insert_inode_ref(trans, dest,
8814 new_dentry->d_name.name,
8815 new_dentry->d_name.len,
8817 btrfs_ino(new_dir), index);
8821 * this is an ugly little race, but the rename is required
8822 * to make sure that if we crash, the inode is either at the
8823 * old name or the new one. pinning the log transaction lets
8824 * us make sure we don't allow a log commit to come in after
8825 * we unlink the name but before we add the new name back in.
8827 btrfs_pin_log_trans(root);
8830 inode_inc_iversion(old_dir);
8831 inode_inc_iversion(new_dir);
8832 inode_inc_iversion(old_inode);
8833 old_dir->i_ctime = old_dir->i_mtime = ctime;
8834 new_dir->i_ctime = new_dir->i_mtime = ctime;
8835 old_inode->i_ctime = ctime;
8837 if (old_dentry->d_parent != new_dentry->d_parent)
8838 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8840 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8841 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8842 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8843 old_dentry->d_name.name,
8844 old_dentry->d_name.len);
8846 ret = __btrfs_unlink_inode(trans, root, old_dir,
8847 old_dentry->d_inode,
8848 old_dentry->d_name.name,
8849 old_dentry->d_name.len);
8851 ret = btrfs_update_inode(trans, root, old_inode);
8854 btrfs_abort_transaction(trans, root, ret);
8859 inode_inc_iversion(new_inode);
8860 new_inode->i_ctime = CURRENT_TIME;
8861 if (unlikely(btrfs_ino(new_inode) ==
8862 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8863 root_objectid = BTRFS_I(new_inode)->location.objectid;
8864 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8866 new_dentry->d_name.name,
8867 new_dentry->d_name.len);
8868 BUG_ON(new_inode->i_nlink == 0);
8870 ret = btrfs_unlink_inode(trans, dest, new_dir,
8871 new_dentry->d_inode,
8872 new_dentry->d_name.name,
8873 new_dentry->d_name.len);
8875 if (!ret && new_inode->i_nlink == 0)
8876 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8878 btrfs_abort_transaction(trans, root, ret);
8883 ret = btrfs_add_link(trans, new_dir, old_inode,
8884 new_dentry->d_name.name,
8885 new_dentry->d_name.len, 0, index);
8887 btrfs_abort_transaction(trans, root, ret);
8891 if (old_inode->i_nlink == 1)
8892 BTRFS_I(old_inode)->dir_index = index;
8894 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8895 struct dentry *parent = new_dentry->d_parent;
8896 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8897 btrfs_end_log_trans(root);
8900 btrfs_end_transaction(trans, root);
8902 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8903 up_read(&root->fs_info->subvol_sem);
8908 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
8909 struct inode *new_dir, struct dentry *new_dentry,
8912 if (flags & ~RENAME_NOREPLACE)
8915 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry);
8918 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8920 struct btrfs_delalloc_work *delalloc_work;
8921 struct inode *inode;
8923 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8925 inode = delalloc_work->inode;
8926 if (delalloc_work->wait) {
8927 btrfs_wait_ordered_range(inode, 0, (u64)-1);
8929 filemap_flush(inode->i_mapping);
8930 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8931 &BTRFS_I(inode)->runtime_flags))
8932 filemap_flush(inode->i_mapping);
8935 if (delalloc_work->delay_iput)
8936 btrfs_add_delayed_iput(inode);
8939 complete(&delalloc_work->completion);
8942 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8943 int wait, int delay_iput)
8945 struct btrfs_delalloc_work *work;
8947 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8951 init_completion(&work->completion);
8952 INIT_LIST_HEAD(&work->list);
8953 work->inode = inode;
8955 work->delay_iput = delay_iput;
8956 WARN_ON_ONCE(!inode);
8957 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
8958 btrfs_run_delalloc_work, NULL, NULL);
8963 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8965 wait_for_completion(&work->completion);
8966 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8970 * some fairly slow code that needs optimization. This walks the list
8971 * of all the inodes with pending delalloc and forces them to disk.
8973 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
8976 struct btrfs_inode *binode;
8977 struct inode *inode;
8978 struct btrfs_delalloc_work *work, *next;
8979 struct list_head works;
8980 struct list_head splice;
8983 INIT_LIST_HEAD(&works);
8984 INIT_LIST_HEAD(&splice);
8986 mutex_lock(&root->delalloc_mutex);
8987 spin_lock(&root->delalloc_lock);
8988 list_splice_init(&root->delalloc_inodes, &splice);
8989 while (!list_empty(&splice)) {
8990 binode = list_entry(splice.next, struct btrfs_inode,
8993 list_move_tail(&binode->delalloc_inodes,
8994 &root->delalloc_inodes);
8995 inode = igrab(&binode->vfs_inode);
8997 cond_resched_lock(&root->delalloc_lock);
9000 spin_unlock(&root->delalloc_lock);
9002 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
9005 btrfs_add_delayed_iput(inode);
9011 list_add_tail(&work->list, &works);
9012 btrfs_queue_work(root->fs_info->flush_workers,
9015 if (nr != -1 && ret >= nr)
9018 spin_lock(&root->delalloc_lock);
9020 spin_unlock(&root->delalloc_lock);
9023 list_for_each_entry_safe(work, next, &works, list) {
9024 list_del_init(&work->list);
9025 btrfs_wait_and_free_delalloc_work(work);
9028 if (!list_empty_careful(&splice)) {
9029 spin_lock(&root->delalloc_lock);
9030 list_splice_tail(&splice, &root->delalloc_inodes);
9031 spin_unlock(&root->delalloc_lock);
9033 mutex_unlock(&root->delalloc_mutex);
9037 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
9041 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
9044 ret = __start_delalloc_inodes(root, delay_iput, -1);
9048 * the filemap_flush will queue IO into the worker threads, but
9049 * we have to make sure the IO is actually started and that
9050 * ordered extents get created before we return
9052 atomic_inc(&root->fs_info->async_submit_draining);
9053 while (atomic_read(&root->fs_info->nr_async_submits) ||
9054 atomic_read(&root->fs_info->async_delalloc_pages)) {
9055 wait_event(root->fs_info->async_submit_wait,
9056 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
9057 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
9059 atomic_dec(&root->fs_info->async_submit_draining);
9063 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
9066 struct btrfs_root *root;
9067 struct list_head splice;
9070 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9073 INIT_LIST_HEAD(&splice);
9075 mutex_lock(&fs_info->delalloc_root_mutex);
9076 spin_lock(&fs_info->delalloc_root_lock);
9077 list_splice_init(&fs_info->delalloc_roots, &splice);
9078 while (!list_empty(&splice) && nr) {
9079 root = list_first_entry(&splice, struct btrfs_root,
9081 root = btrfs_grab_fs_root(root);
9083 list_move_tail(&root->delalloc_root,
9084 &fs_info->delalloc_roots);
9085 spin_unlock(&fs_info->delalloc_root_lock);
9087 ret = __start_delalloc_inodes(root, delay_iput, nr);
9088 btrfs_put_fs_root(root);
9096 spin_lock(&fs_info->delalloc_root_lock);
9098 spin_unlock(&fs_info->delalloc_root_lock);
9101 atomic_inc(&fs_info->async_submit_draining);
9102 while (atomic_read(&fs_info->nr_async_submits) ||
9103 atomic_read(&fs_info->async_delalloc_pages)) {
9104 wait_event(fs_info->async_submit_wait,
9105 (atomic_read(&fs_info->nr_async_submits) == 0 &&
9106 atomic_read(&fs_info->async_delalloc_pages) == 0));
9108 atomic_dec(&fs_info->async_submit_draining);
9110 if (!list_empty_careful(&splice)) {
9111 spin_lock(&fs_info->delalloc_root_lock);
9112 list_splice_tail(&splice, &fs_info->delalloc_roots);
9113 spin_unlock(&fs_info->delalloc_root_lock);
9115 mutex_unlock(&fs_info->delalloc_root_mutex);
9119 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9120 const char *symname)
9122 struct btrfs_trans_handle *trans;
9123 struct btrfs_root *root = BTRFS_I(dir)->root;
9124 struct btrfs_path *path;
9125 struct btrfs_key key;
9126 struct inode *inode = NULL;
9134 struct btrfs_file_extent_item *ei;
9135 struct extent_buffer *leaf;
9137 name_len = strlen(symname);
9138 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
9139 return -ENAMETOOLONG;
9142 * 2 items for inode item and ref
9143 * 2 items for dir items
9144 * 1 item for xattr if selinux is on
9146 trans = btrfs_start_transaction(root, 5);
9148 return PTR_ERR(trans);
9150 err = btrfs_find_free_ino(root, &objectid);
9154 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9155 dentry->d_name.len, btrfs_ino(dir), objectid,
9156 S_IFLNK|S_IRWXUGO, &index);
9157 if (IS_ERR(inode)) {
9158 err = PTR_ERR(inode);
9163 * If the active LSM wants to access the inode during
9164 * d_instantiate it needs these. Smack checks to see
9165 * if the filesystem supports xattrs by looking at the
9168 inode->i_fop = &btrfs_file_operations;
9169 inode->i_op = &btrfs_file_inode_operations;
9170 inode->i_mapping->a_ops = &btrfs_aops;
9171 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9172 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9174 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9176 goto out_unlock_inode;
9178 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
9180 goto out_unlock_inode;
9182 path = btrfs_alloc_path();
9185 goto out_unlock_inode;
9187 key.objectid = btrfs_ino(inode);
9189 key.type = BTRFS_EXTENT_DATA_KEY;
9190 datasize = btrfs_file_extent_calc_inline_size(name_len);
9191 err = btrfs_insert_empty_item(trans, root, path, &key,
9194 btrfs_free_path(path);
9195 goto out_unlock_inode;
9197 leaf = path->nodes[0];
9198 ei = btrfs_item_ptr(leaf, path->slots[0],
9199 struct btrfs_file_extent_item);
9200 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9201 btrfs_set_file_extent_type(leaf, ei,
9202 BTRFS_FILE_EXTENT_INLINE);
9203 btrfs_set_file_extent_encryption(leaf, ei, 0);
9204 btrfs_set_file_extent_compression(leaf, ei, 0);
9205 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9206 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9208 ptr = btrfs_file_extent_inline_start(ei);
9209 write_extent_buffer(leaf, symname, ptr, name_len);
9210 btrfs_mark_buffer_dirty(leaf);
9211 btrfs_free_path(path);
9213 inode->i_op = &btrfs_symlink_inode_operations;
9214 inode->i_mapping->a_ops = &btrfs_symlink_aops;
9215 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9216 inode_set_bytes(inode, name_len);
9217 btrfs_i_size_write(inode, name_len);
9218 err = btrfs_update_inode(trans, root, inode);
9221 goto out_unlock_inode;
9224 unlock_new_inode(inode);
9225 d_instantiate(dentry, inode);
9228 btrfs_end_transaction(trans, root);
9230 inode_dec_link_count(inode);
9233 btrfs_btree_balance_dirty(root);
9238 unlock_new_inode(inode);
9242 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9243 u64 start, u64 num_bytes, u64 min_size,
9244 loff_t actual_len, u64 *alloc_hint,
9245 struct btrfs_trans_handle *trans)
9247 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9248 struct extent_map *em;
9249 struct btrfs_root *root = BTRFS_I(inode)->root;
9250 struct btrfs_key ins;
9251 u64 cur_offset = start;
9255 bool own_trans = true;
9259 while (num_bytes > 0) {
9261 trans = btrfs_start_transaction(root, 3);
9262 if (IS_ERR(trans)) {
9263 ret = PTR_ERR(trans);
9268 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
9269 cur_bytes = max(cur_bytes, min_size);
9270 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
9271 *alloc_hint, &ins, 1, 0);
9274 btrfs_end_transaction(trans, root);
9278 ret = insert_reserved_file_extent(trans, inode,
9279 cur_offset, ins.objectid,
9280 ins.offset, ins.offset,
9281 ins.offset, 0, 0, 0,
9282 BTRFS_FILE_EXTENT_PREALLOC);
9284 btrfs_free_reserved_extent(root, ins.objectid,
9286 btrfs_abort_transaction(trans, root, ret);
9288 btrfs_end_transaction(trans, root);
9291 btrfs_drop_extent_cache(inode, cur_offset,
9292 cur_offset + ins.offset -1, 0);
9294 em = alloc_extent_map();
9296 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9297 &BTRFS_I(inode)->runtime_flags);
9301 em->start = cur_offset;
9302 em->orig_start = cur_offset;
9303 em->len = ins.offset;
9304 em->block_start = ins.objectid;
9305 em->block_len = ins.offset;
9306 em->orig_block_len = ins.offset;
9307 em->ram_bytes = ins.offset;
9308 em->bdev = root->fs_info->fs_devices->latest_bdev;
9309 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9310 em->generation = trans->transid;
9313 write_lock(&em_tree->lock);
9314 ret = add_extent_mapping(em_tree, em, 1);
9315 write_unlock(&em_tree->lock);
9318 btrfs_drop_extent_cache(inode, cur_offset,
9319 cur_offset + ins.offset - 1,
9322 free_extent_map(em);
9324 num_bytes -= ins.offset;
9325 cur_offset += ins.offset;
9326 *alloc_hint = ins.objectid + ins.offset;
9328 inode_inc_iversion(inode);
9329 inode->i_ctime = CURRENT_TIME;
9330 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9331 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9332 (actual_len > inode->i_size) &&
9333 (cur_offset > inode->i_size)) {
9334 if (cur_offset > actual_len)
9335 i_size = actual_len;
9337 i_size = cur_offset;
9338 i_size_write(inode, i_size);
9339 btrfs_ordered_update_i_size(inode, i_size, NULL);
9342 ret = btrfs_update_inode(trans, root, inode);
9345 btrfs_abort_transaction(trans, root, ret);
9347 btrfs_end_transaction(trans, root);
9352 btrfs_end_transaction(trans, root);
9357 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9358 u64 start, u64 num_bytes, u64 min_size,
9359 loff_t actual_len, u64 *alloc_hint)
9361 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9362 min_size, actual_len, alloc_hint,
9366 int btrfs_prealloc_file_range_trans(struct inode *inode,
9367 struct btrfs_trans_handle *trans, int mode,
9368 u64 start, u64 num_bytes, u64 min_size,
9369 loff_t actual_len, u64 *alloc_hint)
9371 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9372 min_size, actual_len, alloc_hint, trans);
9375 static int btrfs_set_page_dirty(struct page *page)
9377 return __set_page_dirty_nobuffers(page);
9380 static int btrfs_permission(struct inode *inode, int mask)
9382 struct btrfs_root *root = BTRFS_I(inode)->root;
9383 umode_t mode = inode->i_mode;
9385 if (mask & MAY_WRITE &&
9386 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9387 if (btrfs_root_readonly(root))
9389 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9392 return generic_permission(inode, mask);
9395 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9397 struct btrfs_trans_handle *trans;
9398 struct btrfs_root *root = BTRFS_I(dir)->root;
9399 struct inode *inode = NULL;
9405 * 5 units required for adding orphan entry
9407 trans = btrfs_start_transaction(root, 5);
9409 return PTR_ERR(trans);
9411 ret = btrfs_find_free_ino(root, &objectid);
9415 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9416 btrfs_ino(dir), objectid, mode, &index);
9417 if (IS_ERR(inode)) {
9418 ret = PTR_ERR(inode);
9423 inode->i_fop = &btrfs_file_operations;
9424 inode->i_op = &btrfs_file_inode_operations;
9426 inode->i_mapping->a_ops = &btrfs_aops;
9427 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9428 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9430 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9434 ret = btrfs_update_inode(trans, root, inode);
9437 ret = btrfs_orphan_add(trans, inode);
9442 * We set number of links to 0 in btrfs_new_inode(), and here we set
9443 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9446 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9448 set_nlink(inode, 1);
9449 unlock_new_inode(inode);
9450 d_tmpfile(dentry, inode);
9451 mark_inode_dirty(inode);
9454 btrfs_end_transaction(trans, root);
9457 btrfs_balance_delayed_items(root);
9458 btrfs_btree_balance_dirty(root);
9462 unlock_new_inode(inode);
9467 static const struct inode_operations btrfs_dir_inode_operations = {
9468 .getattr = btrfs_getattr,
9469 .lookup = btrfs_lookup,
9470 .create = btrfs_create,
9471 .unlink = btrfs_unlink,
9473 .mkdir = btrfs_mkdir,
9474 .rmdir = btrfs_rmdir,
9475 .rename2 = btrfs_rename2,
9476 .symlink = btrfs_symlink,
9477 .setattr = btrfs_setattr,
9478 .mknod = btrfs_mknod,
9479 .setxattr = btrfs_setxattr,
9480 .getxattr = btrfs_getxattr,
9481 .listxattr = btrfs_listxattr,
9482 .removexattr = btrfs_removexattr,
9483 .permission = btrfs_permission,
9484 .get_acl = btrfs_get_acl,
9485 .set_acl = btrfs_set_acl,
9486 .update_time = btrfs_update_time,
9487 .tmpfile = btrfs_tmpfile,
9489 static const struct inode_operations btrfs_dir_ro_inode_operations = {
9490 .lookup = btrfs_lookup,
9491 .permission = btrfs_permission,
9492 .get_acl = btrfs_get_acl,
9493 .set_acl = btrfs_set_acl,
9494 .update_time = btrfs_update_time,
9497 static const struct file_operations btrfs_dir_file_operations = {
9498 .llseek = generic_file_llseek,
9499 .read = generic_read_dir,
9500 .iterate = btrfs_real_readdir,
9501 .unlocked_ioctl = btrfs_ioctl,
9502 #ifdef CONFIG_COMPAT
9503 .compat_ioctl = btrfs_ioctl,
9505 .release = btrfs_release_file,
9506 .fsync = btrfs_sync_file,
9509 static struct extent_io_ops btrfs_extent_io_ops = {
9510 .fill_delalloc = run_delalloc_range,
9511 .submit_bio_hook = btrfs_submit_bio_hook,
9512 .merge_bio_hook = btrfs_merge_bio_hook,
9513 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
9514 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
9515 .writepage_start_hook = btrfs_writepage_start_hook,
9516 .set_bit_hook = btrfs_set_bit_hook,
9517 .clear_bit_hook = btrfs_clear_bit_hook,
9518 .merge_extent_hook = btrfs_merge_extent_hook,
9519 .split_extent_hook = btrfs_split_extent_hook,
9523 * btrfs doesn't support the bmap operation because swapfiles
9524 * use bmap to make a mapping of extents in the file. They assume
9525 * these extents won't change over the life of the file and they
9526 * use the bmap result to do IO directly to the drive.
9528 * the btrfs bmap call would return logical addresses that aren't
9529 * suitable for IO and they also will change frequently as COW
9530 * operations happen. So, swapfile + btrfs == corruption.
9532 * For now we're avoiding this by dropping bmap.
9534 static const struct address_space_operations btrfs_aops = {
9535 .readpage = btrfs_readpage,
9536 .writepage = btrfs_writepage,
9537 .writepages = btrfs_writepages,
9538 .readpages = btrfs_readpages,
9539 .direct_IO = btrfs_direct_IO,
9540 .invalidatepage = btrfs_invalidatepage,
9541 .releasepage = btrfs_releasepage,
9542 .set_page_dirty = btrfs_set_page_dirty,
9543 .error_remove_page = generic_error_remove_page,
9546 static const struct address_space_operations btrfs_symlink_aops = {
9547 .readpage = btrfs_readpage,
9548 .writepage = btrfs_writepage,
9549 .invalidatepage = btrfs_invalidatepage,
9550 .releasepage = btrfs_releasepage,
9553 static const struct inode_operations btrfs_file_inode_operations = {
9554 .getattr = btrfs_getattr,
9555 .setattr = btrfs_setattr,
9556 .setxattr = btrfs_setxattr,
9557 .getxattr = btrfs_getxattr,
9558 .listxattr = btrfs_listxattr,
9559 .removexattr = btrfs_removexattr,
9560 .permission = btrfs_permission,
9561 .fiemap = btrfs_fiemap,
9562 .get_acl = btrfs_get_acl,
9563 .set_acl = btrfs_set_acl,
9564 .update_time = btrfs_update_time,
9566 static const struct inode_operations btrfs_special_inode_operations = {
9567 .getattr = btrfs_getattr,
9568 .setattr = btrfs_setattr,
9569 .permission = btrfs_permission,
9570 .setxattr = btrfs_setxattr,
9571 .getxattr = btrfs_getxattr,
9572 .listxattr = btrfs_listxattr,
9573 .removexattr = btrfs_removexattr,
9574 .get_acl = btrfs_get_acl,
9575 .set_acl = btrfs_set_acl,
9576 .update_time = btrfs_update_time,
9578 static const struct inode_operations btrfs_symlink_inode_operations = {
9579 .readlink = generic_readlink,
9580 .follow_link = page_follow_link_light,
9581 .put_link = page_put_link,
9582 .getattr = btrfs_getattr,
9583 .setattr = btrfs_setattr,
9584 .permission = btrfs_permission,
9585 .setxattr = btrfs_setxattr,
9586 .getxattr = btrfs_getxattr,
9587 .listxattr = btrfs_listxattr,
9588 .removexattr = btrfs_removexattr,
9589 .update_time = btrfs_update_time,
9592 const struct dentry_operations btrfs_dentry_operations = {
9593 .d_delete = btrfs_dentry_delete,
9594 .d_release = btrfs_dentry_release,