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 noinline 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 btrfs_set_key_type(&key, 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);
352 * we create compressed extents in two phases. The first
353 * phase compresses a range of pages that have already been
354 * locked (both pages and state bits are locked).
356 * This is done inside an ordered work queue, and the compression
357 * is spread across many cpus. The actual IO submission is step
358 * two, and the ordered work queue takes care of making sure that
359 * happens in the same order things were put onto the queue by
360 * writepages and friends.
362 * If this code finds it can't get good compression, it puts an
363 * entry onto the work queue to write the uncompressed bytes. This
364 * makes sure that both compressed inodes and uncompressed inodes
365 * are written in the same order that the flusher thread sent them
368 static noinline int compress_file_range(struct inode *inode,
369 struct page *locked_page,
371 struct async_cow *async_cow,
374 struct btrfs_root *root = BTRFS_I(inode)->root;
376 u64 blocksize = root->sectorsize;
378 u64 isize = i_size_read(inode);
380 struct page **pages = NULL;
381 unsigned long nr_pages;
382 unsigned long nr_pages_ret = 0;
383 unsigned long total_compressed = 0;
384 unsigned long total_in = 0;
385 unsigned long max_compressed = 128 * 1024;
386 unsigned long max_uncompressed = 128 * 1024;
389 int compress_type = root->fs_info->compress_type;
392 /* if this is a small write inside eof, kick off a defrag */
393 if ((end - start + 1) < 16 * 1024 &&
394 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
395 btrfs_add_inode_defrag(NULL, inode);
397 actual_end = min_t(u64, isize, end + 1);
400 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
401 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
404 * we don't want to send crud past the end of i_size through
405 * compression, that's just a waste of CPU time. So, if the
406 * end of the file is before the start of our current
407 * requested range of bytes, we bail out to the uncompressed
408 * cleanup code that can deal with all of this.
410 * It isn't really the fastest way to fix things, but this is a
411 * very uncommon corner.
413 if (actual_end <= start)
414 goto cleanup_and_bail_uncompressed;
416 total_compressed = actual_end - start;
418 /* we want to make sure that amount of ram required to uncompress
419 * an extent is reasonable, so we limit the total size in ram
420 * of a compressed extent to 128k. This is a crucial number
421 * because it also controls how easily we can spread reads across
422 * cpus for decompression.
424 * We also want to make sure the amount of IO required to do
425 * a random read is reasonably small, so we limit the size of
426 * a compressed extent to 128k.
428 total_compressed = min(total_compressed, max_uncompressed);
429 num_bytes = ALIGN(end - start + 1, blocksize);
430 num_bytes = max(blocksize, num_bytes);
435 * we do compression for mount -o compress and when the
436 * inode has not been flagged as nocompress. This flag can
437 * change at any time if we discover bad compression ratios.
439 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
440 (btrfs_test_opt(root, COMPRESS) ||
441 (BTRFS_I(inode)->force_compress) ||
442 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
444 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
446 /* just bail out to the uncompressed code */
450 if (BTRFS_I(inode)->force_compress)
451 compress_type = BTRFS_I(inode)->force_compress;
454 * we need to call clear_page_dirty_for_io on each
455 * page in the range. Otherwise applications with the file
456 * mmap'd can wander in and change the page contents while
457 * we are compressing them.
459 * If the compression fails for any reason, we set the pages
460 * dirty again later on.
462 extent_range_clear_dirty_for_io(inode, start, end);
464 ret = btrfs_compress_pages(compress_type,
465 inode->i_mapping, start,
466 total_compressed, pages,
467 nr_pages, &nr_pages_ret,
473 unsigned long offset = total_compressed &
474 (PAGE_CACHE_SIZE - 1);
475 struct page *page = pages[nr_pages_ret - 1];
478 /* zero the tail end of the last page, we might be
479 * sending it down to disk
482 kaddr = kmap_atomic(page);
483 memset(kaddr + offset, 0,
484 PAGE_CACHE_SIZE - offset);
485 kunmap_atomic(kaddr);
492 /* lets try to make an inline extent */
493 if (ret || total_in < (actual_end - start)) {
494 /* we didn't compress the entire range, try
495 * to make an uncompressed inline extent.
497 ret = cow_file_range_inline(root, inode, start, end,
500 /* try making a compressed inline extent */
501 ret = cow_file_range_inline(root, inode, start, end,
503 compress_type, pages);
506 unsigned long clear_flags = EXTENT_DELALLOC |
508 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
511 * inline extent creation worked or returned error,
512 * we don't need to create any more async work items.
513 * Unlock and free up our temp pages.
515 extent_clear_unlock_delalloc(inode, start, end, NULL,
516 clear_flags, PAGE_UNLOCK |
526 * we aren't doing an inline extent round the compressed size
527 * up to a block size boundary so the allocator does sane
530 total_compressed = ALIGN(total_compressed, blocksize);
533 * one last check to make sure the compression is really a
534 * win, compare the page count read with the blocks on disk
536 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
537 if (total_compressed >= total_in) {
540 num_bytes = total_in;
543 if (!will_compress && pages) {
545 * the compression code ran but failed to make things smaller,
546 * free any pages it allocated and our page pointer array
548 for (i = 0; i < nr_pages_ret; i++) {
549 WARN_ON(pages[i]->mapping);
550 page_cache_release(pages[i]);
554 total_compressed = 0;
557 /* flag the file so we don't compress in the future */
558 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
559 !(BTRFS_I(inode)->force_compress)) {
560 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
566 /* the async work queues will take care of doing actual
567 * allocation on disk for these compressed pages,
568 * and will submit them to the elevator.
570 add_async_extent(async_cow, start, num_bytes,
571 total_compressed, pages, nr_pages_ret,
574 if (start + num_bytes < end) {
581 cleanup_and_bail_uncompressed:
583 * No compression, but we still need to write the pages in
584 * the file we've been given so far. redirty the locked
585 * page if it corresponds to our extent and set things up
586 * for the async work queue to run cow_file_range to do
587 * the normal delalloc dance
589 if (page_offset(locked_page) >= start &&
590 page_offset(locked_page) <= end) {
591 __set_page_dirty_nobuffers(locked_page);
592 /* unlocked later on in the async handlers */
595 extent_range_redirty_for_io(inode, start, end);
596 add_async_extent(async_cow, start, end - start + 1,
597 0, NULL, 0, BTRFS_COMPRESS_NONE);
605 for (i = 0; i < nr_pages_ret; i++) {
606 WARN_ON(pages[i]->mapping);
607 page_cache_release(pages[i]);
615 * phase two of compressed writeback. This is the ordered portion
616 * of the code, which only gets called in the order the work was
617 * queued. We walk all the async extents created by compress_file_range
618 * and send them down to the disk.
620 static noinline int submit_compressed_extents(struct inode *inode,
621 struct async_cow *async_cow)
623 struct async_extent *async_extent;
625 struct btrfs_key ins;
626 struct extent_map *em;
627 struct btrfs_root *root = BTRFS_I(inode)->root;
628 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
629 struct extent_io_tree *io_tree;
632 if (list_empty(&async_cow->extents))
636 while (!list_empty(&async_cow->extents)) {
637 async_extent = list_entry(async_cow->extents.next,
638 struct async_extent, list);
639 list_del(&async_extent->list);
641 io_tree = &BTRFS_I(inode)->io_tree;
644 /* did the compression code fall back to uncompressed IO? */
645 if (!async_extent->pages) {
646 int page_started = 0;
647 unsigned long nr_written = 0;
649 lock_extent(io_tree, async_extent->start,
650 async_extent->start +
651 async_extent->ram_size - 1);
653 /* allocate blocks */
654 ret = cow_file_range(inode, async_cow->locked_page,
656 async_extent->start +
657 async_extent->ram_size - 1,
658 &page_started, &nr_written, 0);
663 * if page_started, cow_file_range inserted an
664 * inline extent and took care of all the unlocking
665 * and IO for us. Otherwise, we need to submit
666 * all those pages down to the drive.
668 if (!page_started && !ret)
669 extent_write_locked_range(io_tree,
670 inode, async_extent->start,
671 async_extent->start +
672 async_extent->ram_size - 1,
676 unlock_page(async_cow->locked_page);
682 lock_extent(io_tree, async_extent->start,
683 async_extent->start + async_extent->ram_size - 1);
685 ret = btrfs_reserve_extent(root,
686 async_extent->compressed_size,
687 async_extent->compressed_size,
688 0, alloc_hint, &ins, 1);
692 for (i = 0; i < async_extent->nr_pages; i++) {
693 WARN_ON(async_extent->pages[i]->mapping);
694 page_cache_release(async_extent->pages[i]);
696 kfree(async_extent->pages);
697 async_extent->nr_pages = 0;
698 async_extent->pages = NULL;
700 if (ret == -ENOSPC) {
701 unlock_extent(io_tree, async_extent->start,
702 async_extent->start +
703 async_extent->ram_size - 1);
710 * here we're doing allocation and writeback of the
713 btrfs_drop_extent_cache(inode, async_extent->start,
714 async_extent->start +
715 async_extent->ram_size - 1, 0);
717 em = alloc_extent_map();
720 goto out_free_reserve;
722 em->start = async_extent->start;
723 em->len = async_extent->ram_size;
724 em->orig_start = em->start;
725 em->mod_start = em->start;
726 em->mod_len = em->len;
728 em->block_start = ins.objectid;
729 em->block_len = ins.offset;
730 em->orig_block_len = ins.offset;
731 em->ram_bytes = async_extent->ram_size;
732 em->bdev = root->fs_info->fs_devices->latest_bdev;
733 em->compress_type = async_extent->compress_type;
734 set_bit(EXTENT_FLAG_PINNED, &em->flags);
735 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
739 write_lock(&em_tree->lock);
740 ret = add_extent_mapping(em_tree, em, 1);
741 write_unlock(&em_tree->lock);
742 if (ret != -EEXIST) {
746 btrfs_drop_extent_cache(inode, async_extent->start,
747 async_extent->start +
748 async_extent->ram_size - 1, 0);
752 goto out_free_reserve;
754 ret = btrfs_add_ordered_extent_compress(inode,
757 async_extent->ram_size,
759 BTRFS_ORDERED_COMPRESSED,
760 async_extent->compress_type);
762 goto out_free_reserve;
765 * clear dirty, set writeback and unlock the pages.
767 extent_clear_unlock_delalloc(inode, async_extent->start,
768 async_extent->start +
769 async_extent->ram_size - 1,
770 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
771 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
773 ret = btrfs_submit_compressed_write(inode,
775 async_extent->ram_size,
777 ins.offset, async_extent->pages,
778 async_extent->nr_pages);
779 alloc_hint = ins.objectid + ins.offset;
789 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
791 extent_clear_unlock_delalloc(inode, async_extent->start,
792 async_extent->start +
793 async_extent->ram_size - 1,
794 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
795 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
796 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
797 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
802 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
805 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
806 struct extent_map *em;
809 read_lock(&em_tree->lock);
810 em = search_extent_mapping(em_tree, start, num_bytes);
813 * if block start isn't an actual block number then find the
814 * first block in this inode and use that as a hint. If that
815 * block is also bogus then just don't worry about it.
817 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
819 em = search_extent_mapping(em_tree, 0, 0);
820 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
821 alloc_hint = em->block_start;
825 alloc_hint = em->block_start;
829 read_unlock(&em_tree->lock);
835 * when extent_io.c finds a delayed allocation range in the file,
836 * the call backs end up in this code. The basic idea is to
837 * allocate extents on disk for the range, and create ordered data structs
838 * in ram to track those extents.
840 * locked_page is the page that writepage had locked already. We use
841 * it to make sure we don't do extra locks or unlocks.
843 * *page_started is set to one if we unlock locked_page and do everything
844 * required to start IO on it. It may be clean and already done with
847 static noinline int cow_file_range(struct inode *inode,
848 struct page *locked_page,
849 u64 start, u64 end, int *page_started,
850 unsigned long *nr_written,
853 struct btrfs_root *root = BTRFS_I(inode)->root;
856 unsigned long ram_size;
859 u64 blocksize = root->sectorsize;
860 struct btrfs_key ins;
861 struct extent_map *em;
862 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
865 if (btrfs_is_free_space_inode(inode)) {
871 num_bytes = ALIGN(end - start + 1, blocksize);
872 num_bytes = max(blocksize, num_bytes);
873 disk_num_bytes = num_bytes;
875 /* if this is a small write inside eof, kick off defrag */
876 if (num_bytes < 64 * 1024 &&
877 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
878 btrfs_add_inode_defrag(NULL, inode);
881 /* lets try to make an inline extent */
882 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
885 extent_clear_unlock_delalloc(inode, start, end, NULL,
886 EXTENT_LOCKED | EXTENT_DELALLOC |
887 EXTENT_DEFRAG, PAGE_UNLOCK |
888 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
891 *nr_written = *nr_written +
892 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
895 } else if (ret < 0) {
900 BUG_ON(disk_num_bytes >
901 btrfs_super_total_bytes(root->fs_info->super_copy));
903 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
904 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
906 while (disk_num_bytes > 0) {
909 cur_alloc_size = disk_num_bytes;
910 ret = btrfs_reserve_extent(root, cur_alloc_size,
911 root->sectorsize, 0, alloc_hint,
916 em = alloc_extent_map();
922 em->orig_start = em->start;
923 ram_size = ins.offset;
924 em->len = ins.offset;
925 em->mod_start = em->start;
926 em->mod_len = em->len;
928 em->block_start = ins.objectid;
929 em->block_len = ins.offset;
930 em->orig_block_len = ins.offset;
931 em->ram_bytes = ram_size;
932 em->bdev = root->fs_info->fs_devices->latest_bdev;
933 set_bit(EXTENT_FLAG_PINNED, &em->flags);
937 write_lock(&em_tree->lock);
938 ret = add_extent_mapping(em_tree, em, 1);
939 write_unlock(&em_tree->lock);
940 if (ret != -EEXIST) {
944 btrfs_drop_extent_cache(inode, start,
945 start + ram_size - 1, 0);
950 cur_alloc_size = ins.offset;
951 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
952 ram_size, cur_alloc_size, 0);
956 if (root->root_key.objectid ==
957 BTRFS_DATA_RELOC_TREE_OBJECTID) {
958 ret = btrfs_reloc_clone_csums(inode, start,
964 if (disk_num_bytes < cur_alloc_size)
967 /* we're not doing compressed IO, don't unlock the first
968 * page (which the caller expects to stay locked), don't
969 * clear any dirty bits and don't set any writeback bits
971 * Do set the Private2 bit so we know this page was properly
972 * setup for writepage
974 op = unlock ? PAGE_UNLOCK : 0;
975 op |= PAGE_SET_PRIVATE2;
977 extent_clear_unlock_delalloc(inode, start,
978 start + ram_size - 1, locked_page,
979 EXTENT_LOCKED | EXTENT_DELALLOC,
981 disk_num_bytes -= cur_alloc_size;
982 num_bytes -= cur_alloc_size;
983 alloc_hint = ins.objectid + ins.offset;
984 start += cur_alloc_size;
990 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
992 extent_clear_unlock_delalloc(inode, start, end, locked_page,
993 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
994 EXTENT_DELALLOC | EXTENT_DEFRAG,
995 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
996 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1001 * work queue call back to started compression on a file and pages
1003 static noinline void async_cow_start(struct btrfs_work *work)
1005 struct async_cow *async_cow;
1007 async_cow = container_of(work, struct async_cow, work);
1009 compress_file_range(async_cow->inode, async_cow->locked_page,
1010 async_cow->start, async_cow->end, async_cow,
1012 if (num_added == 0) {
1013 btrfs_add_delayed_iput(async_cow->inode);
1014 async_cow->inode = NULL;
1019 * work queue call back to submit previously compressed pages
1021 static noinline void async_cow_submit(struct btrfs_work *work)
1023 struct async_cow *async_cow;
1024 struct btrfs_root *root;
1025 unsigned long nr_pages;
1027 async_cow = container_of(work, struct async_cow, work);
1029 root = async_cow->root;
1030 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1033 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1035 waitqueue_active(&root->fs_info->async_submit_wait))
1036 wake_up(&root->fs_info->async_submit_wait);
1038 if (async_cow->inode)
1039 submit_compressed_extents(async_cow->inode, async_cow);
1042 static noinline void async_cow_free(struct btrfs_work *work)
1044 struct async_cow *async_cow;
1045 async_cow = container_of(work, struct async_cow, work);
1046 if (async_cow->inode)
1047 btrfs_add_delayed_iput(async_cow->inode);
1051 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1052 u64 start, u64 end, int *page_started,
1053 unsigned long *nr_written)
1055 struct async_cow *async_cow;
1056 struct btrfs_root *root = BTRFS_I(inode)->root;
1057 unsigned long nr_pages;
1059 int limit = 10 * 1024 * 1024;
1061 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1062 1, 0, NULL, GFP_NOFS);
1063 while (start < end) {
1064 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1065 BUG_ON(!async_cow); /* -ENOMEM */
1066 async_cow->inode = igrab(inode);
1067 async_cow->root = root;
1068 async_cow->locked_page = locked_page;
1069 async_cow->start = start;
1071 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1074 cur_end = min(end, start + 512 * 1024 - 1);
1076 async_cow->end = cur_end;
1077 INIT_LIST_HEAD(&async_cow->extents);
1079 async_cow->work.func = async_cow_start;
1080 async_cow->work.ordered_func = async_cow_submit;
1081 async_cow->work.ordered_free = async_cow_free;
1082 async_cow->work.flags = 0;
1084 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1086 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1088 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1091 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1092 wait_event(root->fs_info->async_submit_wait,
1093 (atomic_read(&root->fs_info->async_delalloc_pages) <
1097 while (atomic_read(&root->fs_info->async_submit_draining) &&
1098 atomic_read(&root->fs_info->async_delalloc_pages)) {
1099 wait_event(root->fs_info->async_submit_wait,
1100 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1104 *nr_written += nr_pages;
1105 start = cur_end + 1;
1111 static noinline int csum_exist_in_range(struct btrfs_root *root,
1112 u64 bytenr, u64 num_bytes)
1115 struct btrfs_ordered_sum *sums;
1118 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1119 bytenr + num_bytes - 1, &list, 0);
1120 if (ret == 0 && list_empty(&list))
1123 while (!list_empty(&list)) {
1124 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1125 list_del(&sums->list);
1132 * when nowcow writeback call back. This checks for snapshots or COW copies
1133 * of the extents that exist in the file, and COWs the file as required.
1135 * If no cow copies or snapshots exist, we write directly to the existing
1138 static noinline int run_delalloc_nocow(struct inode *inode,
1139 struct page *locked_page,
1140 u64 start, u64 end, int *page_started, int force,
1141 unsigned long *nr_written)
1143 struct btrfs_root *root = BTRFS_I(inode)->root;
1144 struct btrfs_trans_handle *trans;
1145 struct extent_buffer *leaf;
1146 struct btrfs_path *path;
1147 struct btrfs_file_extent_item *fi;
1148 struct btrfs_key found_key;
1163 u64 ino = btrfs_ino(inode);
1165 path = btrfs_alloc_path();
1167 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1168 EXTENT_LOCKED | EXTENT_DELALLOC |
1169 EXTENT_DO_ACCOUNTING |
1170 EXTENT_DEFRAG, PAGE_UNLOCK |
1172 PAGE_SET_WRITEBACK |
1173 PAGE_END_WRITEBACK);
1177 nolock = btrfs_is_free_space_inode(inode);
1180 trans = btrfs_join_transaction_nolock(root);
1182 trans = btrfs_join_transaction(root);
1184 if (IS_ERR(trans)) {
1185 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1186 EXTENT_LOCKED | EXTENT_DELALLOC |
1187 EXTENT_DO_ACCOUNTING |
1188 EXTENT_DEFRAG, PAGE_UNLOCK |
1190 PAGE_SET_WRITEBACK |
1191 PAGE_END_WRITEBACK);
1192 btrfs_free_path(path);
1193 return PTR_ERR(trans);
1196 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1198 cow_start = (u64)-1;
1201 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1205 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1206 leaf = path->nodes[0];
1207 btrfs_item_key_to_cpu(leaf, &found_key,
1208 path->slots[0] - 1);
1209 if (found_key.objectid == ino &&
1210 found_key.type == BTRFS_EXTENT_DATA_KEY)
1215 leaf = path->nodes[0];
1216 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1217 ret = btrfs_next_leaf(root, path);
1222 leaf = path->nodes[0];
1228 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1230 if (found_key.objectid > ino ||
1231 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1232 found_key.offset > end)
1235 if (found_key.offset > cur_offset) {
1236 extent_end = found_key.offset;
1241 fi = btrfs_item_ptr(leaf, path->slots[0],
1242 struct btrfs_file_extent_item);
1243 extent_type = btrfs_file_extent_type(leaf, fi);
1245 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1246 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1247 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1248 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1249 extent_offset = btrfs_file_extent_offset(leaf, fi);
1250 extent_end = found_key.offset +
1251 btrfs_file_extent_num_bytes(leaf, fi);
1253 btrfs_file_extent_disk_num_bytes(leaf, fi);
1254 if (extent_end <= start) {
1258 if (disk_bytenr == 0)
1260 if (btrfs_file_extent_compression(leaf, fi) ||
1261 btrfs_file_extent_encryption(leaf, fi) ||
1262 btrfs_file_extent_other_encoding(leaf, fi))
1264 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1266 if (btrfs_extent_readonly(root, disk_bytenr))
1268 if (btrfs_cross_ref_exist(trans, root, ino,
1270 extent_offset, disk_bytenr))
1272 disk_bytenr += extent_offset;
1273 disk_bytenr += cur_offset - found_key.offset;
1274 num_bytes = min(end + 1, extent_end) - cur_offset;
1276 * force cow if csum exists in the range.
1277 * this ensure that csum for a given extent are
1278 * either valid or do not exist.
1280 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1283 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1284 extent_end = found_key.offset +
1285 btrfs_file_extent_inline_len(leaf,
1286 path->slots[0], fi);
1287 extent_end = ALIGN(extent_end, root->sectorsize);
1292 if (extent_end <= start) {
1297 if (cow_start == (u64)-1)
1298 cow_start = cur_offset;
1299 cur_offset = extent_end;
1300 if (cur_offset > end)
1306 btrfs_release_path(path);
1307 if (cow_start != (u64)-1) {
1308 ret = cow_file_range(inode, locked_page,
1309 cow_start, found_key.offset - 1,
1310 page_started, nr_written, 1);
1313 cow_start = (u64)-1;
1316 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1317 struct extent_map *em;
1318 struct extent_map_tree *em_tree;
1319 em_tree = &BTRFS_I(inode)->extent_tree;
1320 em = alloc_extent_map();
1321 BUG_ON(!em); /* -ENOMEM */
1322 em->start = cur_offset;
1323 em->orig_start = found_key.offset - extent_offset;
1324 em->len = num_bytes;
1325 em->block_len = num_bytes;
1326 em->block_start = disk_bytenr;
1327 em->orig_block_len = disk_num_bytes;
1328 em->ram_bytes = ram_bytes;
1329 em->bdev = root->fs_info->fs_devices->latest_bdev;
1330 em->mod_start = em->start;
1331 em->mod_len = em->len;
1332 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1333 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1334 em->generation = -1;
1336 write_lock(&em_tree->lock);
1337 ret = add_extent_mapping(em_tree, em, 1);
1338 write_unlock(&em_tree->lock);
1339 if (ret != -EEXIST) {
1340 free_extent_map(em);
1343 btrfs_drop_extent_cache(inode, em->start,
1344 em->start + em->len - 1, 0);
1346 type = BTRFS_ORDERED_PREALLOC;
1348 type = BTRFS_ORDERED_NOCOW;
1351 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1352 num_bytes, num_bytes, type);
1353 BUG_ON(ret); /* -ENOMEM */
1355 if (root->root_key.objectid ==
1356 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1357 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1363 extent_clear_unlock_delalloc(inode, cur_offset,
1364 cur_offset + num_bytes - 1,
1365 locked_page, EXTENT_LOCKED |
1366 EXTENT_DELALLOC, PAGE_UNLOCK |
1368 cur_offset = extent_end;
1369 if (cur_offset > end)
1372 btrfs_release_path(path);
1374 if (cur_offset <= end && cow_start == (u64)-1) {
1375 cow_start = cur_offset;
1379 if (cow_start != (u64)-1) {
1380 ret = cow_file_range(inode, locked_page, cow_start, end,
1381 page_started, nr_written, 1);
1387 err = btrfs_end_transaction(trans, root);
1391 if (ret && cur_offset < end)
1392 extent_clear_unlock_delalloc(inode, cur_offset, end,
1393 locked_page, EXTENT_LOCKED |
1394 EXTENT_DELALLOC | EXTENT_DEFRAG |
1395 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1397 PAGE_SET_WRITEBACK |
1398 PAGE_END_WRITEBACK);
1399 btrfs_free_path(path);
1404 * extent_io.c call back to do delayed allocation processing
1406 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1407 u64 start, u64 end, int *page_started,
1408 unsigned long *nr_written)
1411 struct btrfs_root *root = BTRFS_I(inode)->root;
1413 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1414 ret = run_delalloc_nocow(inode, locked_page, start, end,
1415 page_started, 1, nr_written);
1416 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1417 ret = run_delalloc_nocow(inode, locked_page, start, end,
1418 page_started, 0, nr_written);
1419 } else if (!btrfs_test_opt(root, COMPRESS) &&
1420 !(BTRFS_I(inode)->force_compress) &&
1421 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1422 ret = cow_file_range(inode, locked_page, start, end,
1423 page_started, nr_written, 1);
1425 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1426 &BTRFS_I(inode)->runtime_flags);
1427 ret = cow_file_range_async(inode, locked_page, start, end,
1428 page_started, nr_written);
1433 static void btrfs_split_extent_hook(struct inode *inode,
1434 struct extent_state *orig, u64 split)
1436 /* not delalloc, ignore it */
1437 if (!(orig->state & EXTENT_DELALLOC))
1440 spin_lock(&BTRFS_I(inode)->lock);
1441 BTRFS_I(inode)->outstanding_extents++;
1442 spin_unlock(&BTRFS_I(inode)->lock);
1446 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1447 * extents so we can keep track of new extents that are just merged onto old
1448 * extents, such as when we are doing sequential writes, so we can properly
1449 * account for the metadata space we'll need.
1451 static void btrfs_merge_extent_hook(struct inode *inode,
1452 struct extent_state *new,
1453 struct extent_state *other)
1455 /* not delalloc, ignore it */
1456 if (!(other->state & EXTENT_DELALLOC))
1459 spin_lock(&BTRFS_I(inode)->lock);
1460 BTRFS_I(inode)->outstanding_extents--;
1461 spin_unlock(&BTRFS_I(inode)->lock);
1464 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1465 struct inode *inode)
1467 spin_lock(&root->delalloc_lock);
1468 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1469 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1470 &root->delalloc_inodes);
1471 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1472 &BTRFS_I(inode)->runtime_flags);
1473 root->nr_delalloc_inodes++;
1474 if (root->nr_delalloc_inodes == 1) {
1475 spin_lock(&root->fs_info->delalloc_root_lock);
1476 BUG_ON(!list_empty(&root->delalloc_root));
1477 list_add_tail(&root->delalloc_root,
1478 &root->fs_info->delalloc_roots);
1479 spin_unlock(&root->fs_info->delalloc_root_lock);
1482 spin_unlock(&root->delalloc_lock);
1485 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1486 struct inode *inode)
1488 spin_lock(&root->delalloc_lock);
1489 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1490 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1491 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1492 &BTRFS_I(inode)->runtime_flags);
1493 root->nr_delalloc_inodes--;
1494 if (!root->nr_delalloc_inodes) {
1495 spin_lock(&root->fs_info->delalloc_root_lock);
1496 BUG_ON(list_empty(&root->delalloc_root));
1497 list_del_init(&root->delalloc_root);
1498 spin_unlock(&root->fs_info->delalloc_root_lock);
1501 spin_unlock(&root->delalloc_lock);
1505 * extent_io.c set_bit_hook, used to track delayed allocation
1506 * bytes in this file, and to maintain the list of inodes that
1507 * have pending delalloc work to be done.
1509 static void btrfs_set_bit_hook(struct inode *inode,
1510 struct extent_state *state, unsigned long *bits)
1514 * set_bit and clear bit hooks normally require _irqsave/restore
1515 * but in this case, we are only testing for the DELALLOC
1516 * bit, which is only set or cleared with irqs on
1518 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1519 struct btrfs_root *root = BTRFS_I(inode)->root;
1520 u64 len = state->end + 1 - state->start;
1521 bool do_list = !btrfs_is_free_space_inode(inode);
1523 if (*bits & EXTENT_FIRST_DELALLOC) {
1524 *bits &= ~EXTENT_FIRST_DELALLOC;
1526 spin_lock(&BTRFS_I(inode)->lock);
1527 BTRFS_I(inode)->outstanding_extents++;
1528 spin_unlock(&BTRFS_I(inode)->lock);
1531 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1532 root->fs_info->delalloc_batch);
1533 spin_lock(&BTRFS_I(inode)->lock);
1534 BTRFS_I(inode)->delalloc_bytes += len;
1535 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1536 &BTRFS_I(inode)->runtime_flags))
1537 btrfs_add_delalloc_inodes(root, inode);
1538 spin_unlock(&BTRFS_I(inode)->lock);
1543 * extent_io.c clear_bit_hook, see set_bit_hook for why
1545 static void btrfs_clear_bit_hook(struct inode *inode,
1546 struct extent_state *state,
1547 unsigned long *bits)
1550 * set_bit and clear bit hooks normally require _irqsave/restore
1551 * but in this case, we are only testing for the DELALLOC
1552 * bit, which is only set or cleared with irqs on
1554 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1555 struct btrfs_root *root = BTRFS_I(inode)->root;
1556 u64 len = state->end + 1 - state->start;
1557 bool do_list = !btrfs_is_free_space_inode(inode);
1559 if (*bits & EXTENT_FIRST_DELALLOC) {
1560 *bits &= ~EXTENT_FIRST_DELALLOC;
1561 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1562 spin_lock(&BTRFS_I(inode)->lock);
1563 BTRFS_I(inode)->outstanding_extents--;
1564 spin_unlock(&BTRFS_I(inode)->lock);
1568 * We don't reserve metadata space for space cache inodes so we
1569 * don't need to call dellalloc_release_metadata if there is an
1572 if (*bits & EXTENT_DO_ACCOUNTING &&
1573 root != root->fs_info->tree_root)
1574 btrfs_delalloc_release_metadata(inode, len);
1576 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1577 && do_list && !(state->state & EXTENT_NORESERVE))
1578 btrfs_free_reserved_data_space(inode, len);
1580 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1581 root->fs_info->delalloc_batch);
1582 spin_lock(&BTRFS_I(inode)->lock);
1583 BTRFS_I(inode)->delalloc_bytes -= len;
1584 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1585 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1586 &BTRFS_I(inode)->runtime_flags))
1587 btrfs_del_delalloc_inode(root, inode);
1588 spin_unlock(&BTRFS_I(inode)->lock);
1593 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1594 * we don't create bios that span stripes or chunks
1596 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1597 size_t size, struct bio *bio,
1598 unsigned long bio_flags)
1600 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1601 u64 logical = (u64)bio->bi_sector << 9;
1606 if (bio_flags & EXTENT_BIO_COMPRESSED)
1609 length = bio->bi_size;
1610 map_length = length;
1611 ret = btrfs_map_block(root->fs_info, rw, logical,
1612 &map_length, NULL, 0);
1613 /* Will always return 0 with map_multi == NULL */
1615 if (map_length < length + size)
1621 * in order to insert checksums into the metadata in large chunks,
1622 * we wait until bio submission time. All the pages in the bio are
1623 * checksummed and sums are attached onto the ordered extent record.
1625 * At IO completion time the cums attached on the ordered extent record
1626 * are inserted into the btree
1628 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1629 struct bio *bio, int mirror_num,
1630 unsigned long bio_flags,
1633 struct btrfs_root *root = BTRFS_I(inode)->root;
1636 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1637 BUG_ON(ret); /* -ENOMEM */
1642 * in order to insert checksums into the metadata in large chunks,
1643 * we wait until bio submission time. All the pages in the bio are
1644 * checksummed and sums are attached onto the ordered extent record.
1646 * At IO completion time the cums attached on the ordered extent record
1647 * are inserted into the btree
1649 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1650 int mirror_num, unsigned long bio_flags,
1653 struct btrfs_root *root = BTRFS_I(inode)->root;
1656 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1658 bio_endio(bio, ret);
1663 * extent_io.c submission hook. This does the right thing for csum calculation
1664 * on write, or reading the csums from the tree before a read
1666 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1667 int mirror_num, unsigned long bio_flags,
1670 struct btrfs_root *root = BTRFS_I(inode)->root;
1674 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1676 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1678 if (btrfs_is_free_space_inode(inode))
1681 if (!(rw & REQ_WRITE)) {
1682 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1686 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1687 ret = btrfs_submit_compressed_read(inode, bio,
1691 } else if (!skip_sum) {
1692 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1697 } else if (async && !skip_sum) {
1698 /* csum items have already been cloned */
1699 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1701 /* we're doing a write, do the async checksumming */
1702 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1703 inode, rw, bio, mirror_num,
1704 bio_flags, bio_offset,
1705 __btrfs_submit_bio_start,
1706 __btrfs_submit_bio_done);
1708 } else if (!skip_sum) {
1709 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1715 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1719 bio_endio(bio, ret);
1724 * given a list of ordered sums record them in the inode. This happens
1725 * at IO completion time based on sums calculated at bio submission time.
1727 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1728 struct inode *inode, u64 file_offset,
1729 struct list_head *list)
1731 struct btrfs_ordered_sum *sum;
1733 list_for_each_entry(sum, list, list) {
1734 trans->adding_csums = 1;
1735 btrfs_csum_file_blocks(trans,
1736 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1737 trans->adding_csums = 0;
1742 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1743 struct extent_state **cached_state)
1745 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1746 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1747 cached_state, GFP_NOFS);
1750 /* see btrfs_writepage_start_hook for details on why this is required */
1751 struct btrfs_writepage_fixup {
1753 struct btrfs_work work;
1756 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1758 struct btrfs_writepage_fixup *fixup;
1759 struct btrfs_ordered_extent *ordered;
1760 struct extent_state *cached_state = NULL;
1762 struct inode *inode;
1767 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1771 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1772 ClearPageChecked(page);
1776 inode = page->mapping->host;
1777 page_start = page_offset(page);
1778 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1780 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1783 /* already ordered? We're done */
1784 if (PagePrivate2(page))
1787 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1789 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1790 page_end, &cached_state, GFP_NOFS);
1792 btrfs_start_ordered_extent(inode, ordered, 1);
1793 btrfs_put_ordered_extent(ordered);
1797 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1799 mapping_set_error(page->mapping, ret);
1800 end_extent_writepage(page, ret, page_start, page_end);
1801 ClearPageChecked(page);
1805 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1806 ClearPageChecked(page);
1807 set_page_dirty(page);
1809 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1810 &cached_state, GFP_NOFS);
1813 page_cache_release(page);
1818 * There are a few paths in the higher layers of the kernel that directly
1819 * set the page dirty bit without asking the filesystem if it is a
1820 * good idea. This causes problems because we want to make sure COW
1821 * properly happens and the data=ordered rules are followed.
1823 * In our case any range that doesn't have the ORDERED bit set
1824 * hasn't been properly setup for IO. We kick off an async process
1825 * to fix it up. The async helper will wait for ordered extents, set
1826 * the delalloc bit and make it safe to write the page.
1828 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1830 struct inode *inode = page->mapping->host;
1831 struct btrfs_writepage_fixup *fixup;
1832 struct btrfs_root *root = BTRFS_I(inode)->root;
1834 /* this page is properly in the ordered list */
1835 if (TestClearPagePrivate2(page))
1838 if (PageChecked(page))
1841 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1845 SetPageChecked(page);
1846 page_cache_get(page);
1847 fixup->work.func = btrfs_writepage_fixup_worker;
1849 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1853 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1854 struct inode *inode, u64 file_pos,
1855 u64 disk_bytenr, u64 disk_num_bytes,
1856 u64 num_bytes, u64 ram_bytes,
1857 u8 compression, u8 encryption,
1858 u16 other_encoding, int extent_type)
1860 struct btrfs_root *root = BTRFS_I(inode)->root;
1861 struct btrfs_file_extent_item *fi;
1862 struct btrfs_path *path;
1863 struct extent_buffer *leaf;
1864 struct btrfs_key ins;
1865 int extent_inserted = 0;
1868 path = btrfs_alloc_path();
1873 * we may be replacing one extent in the tree with another.
1874 * The new extent is pinned in the extent map, and we don't want
1875 * to drop it from the cache until it is completely in the btree.
1877 * So, tell btrfs_drop_extents to leave this extent in the cache.
1878 * the caller is expected to unpin it and allow it to be merged
1881 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
1882 file_pos + num_bytes, NULL, 0,
1883 1, sizeof(*fi), &extent_inserted);
1887 if (!extent_inserted) {
1888 ins.objectid = btrfs_ino(inode);
1889 ins.offset = file_pos;
1890 ins.type = BTRFS_EXTENT_DATA_KEY;
1892 path->leave_spinning = 1;
1893 ret = btrfs_insert_empty_item(trans, root, path, &ins,
1898 leaf = path->nodes[0];
1899 fi = btrfs_item_ptr(leaf, path->slots[0],
1900 struct btrfs_file_extent_item);
1901 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1902 btrfs_set_file_extent_type(leaf, fi, extent_type);
1903 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1904 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1905 btrfs_set_file_extent_offset(leaf, fi, 0);
1906 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1907 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1908 btrfs_set_file_extent_compression(leaf, fi, compression);
1909 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1910 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1912 btrfs_mark_buffer_dirty(leaf);
1913 btrfs_release_path(path);
1915 inode_add_bytes(inode, num_bytes);
1917 ins.objectid = disk_bytenr;
1918 ins.offset = disk_num_bytes;
1919 ins.type = BTRFS_EXTENT_ITEM_KEY;
1920 ret = btrfs_alloc_reserved_file_extent(trans, root,
1921 root->root_key.objectid,
1922 btrfs_ino(inode), file_pos, &ins);
1924 btrfs_free_path(path);
1929 /* snapshot-aware defrag */
1930 struct sa_defrag_extent_backref {
1931 struct rb_node node;
1932 struct old_sa_defrag_extent *old;
1941 struct old_sa_defrag_extent {
1942 struct list_head list;
1943 struct new_sa_defrag_extent *new;
1952 struct new_sa_defrag_extent {
1953 struct rb_root root;
1954 struct list_head head;
1955 struct btrfs_path *path;
1956 struct inode *inode;
1964 static int backref_comp(struct sa_defrag_extent_backref *b1,
1965 struct sa_defrag_extent_backref *b2)
1967 if (b1->root_id < b2->root_id)
1969 else if (b1->root_id > b2->root_id)
1972 if (b1->inum < b2->inum)
1974 else if (b1->inum > b2->inum)
1977 if (b1->file_pos < b2->file_pos)
1979 else if (b1->file_pos > b2->file_pos)
1983 * [------------------------------] ===> (a range of space)
1984 * |<--->| |<---->| =============> (fs/file tree A)
1985 * |<---------------------------->| ===> (fs/file tree B)
1987 * A range of space can refer to two file extents in one tree while
1988 * refer to only one file extent in another tree.
1990 * So we may process a disk offset more than one time(two extents in A)
1991 * and locate at the same extent(one extent in B), then insert two same
1992 * backrefs(both refer to the extent in B).
1997 static void backref_insert(struct rb_root *root,
1998 struct sa_defrag_extent_backref *backref)
2000 struct rb_node **p = &root->rb_node;
2001 struct rb_node *parent = NULL;
2002 struct sa_defrag_extent_backref *entry;
2007 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2009 ret = backref_comp(backref, entry);
2013 p = &(*p)->rb_right;
2016 rb_link_node(&backref->node, parent, p);
2017 rb_insert_color(&backref->node, root);
2021 * Note the backref might has changed, and in this case we just return 0.
2023 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2026 struct btrfs_file_extent_item *extent;
2027 struct btrfs_fs_info *fs_info;
2028 struct old_sa_defrag_extent *old = ctx;
2029 struct new_sa_defrag_extent *new = old->new;
2030 struct btrfs_path *path = new->path;
2031 struct btrfs_key key;
2032 struct btrfs_root *root;
2033 struct sa_defrag_extent_backref *backref;
2034 struct extent_buffer *leaf;
2035 struct inode *inode = new->inode;
2041 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2042 inum == btrfs_ino(inode))
2045 key.objectid = root_id;
2046 key.type = BTRFS_ROOT_ITEM_KEY;
2047 key.offset = (u64)-1;
2049 fs_info = BTRFS_I(inode)->root->fs_info;
2050 root = btrfs_read_fs_root_no_name(fs_info, &key);
2052 if (PTR_ERR(root) == -ENOENT)
2055 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2056 inum, offset, root_id);
2057 return PTR_ERR(root);
2060 key.objectid = inum;
2061 key.type = BTRFS_EXTENT_DATA_KEY;
2062 if (offset > (u64)-1 << 32)
2065 key.offset = offset;
2067 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2068 if (WARN_ON(ret < 0))
2075 leaf = path->nodes[0];
2076 slot = path->slots[0];
2078 if (slot >= btrfs_header_nritems(leaf)) {
2079 ret = btrfs_next_leaf(root, path);
2082 } else if (ret > 0) {
2091 btrfs_item_key_to_cpu(leaf, &key, slot);
2093 if (key.objectid > inum)
2096 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2099 extent = btrfs_item_ptr(leaf, slot,
2100 struct btrfs_file_extent_item);
2102 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2106 * 'offset' refers to the exact key.offset,
2107 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2108 * (key.offset - extent_offset).
2110 if (key.offset != offset)
2113 extent_offset = btrfs_file_extent_offset(leaf, extent);
2114 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2116 if (extent_offset >= old->extent_offset + old->offset +
2117 old->len || extent_offset + num_bytes <=
2118 old->extent_offset + old->offset)
2123 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2129 backref->root_id = root_id;
2130 backref->inum = inum;
2131 backref->file_pos = offset;
2132 backref->num_bytes = num_bytes;
2133 backref->extent_offset = extent_offset;
2134 backref->generation = btrfs_file_extent_generation(leaf, extent);
2136 backref_insert(&new->root, backref);
2139 btrfs_release_path(path);
2144 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2145 struct new_sa_defrag_extent *new)
2147 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2148 struct old_sa_defrag_extent *old, *tmp;
2153 list_for_each_entry_safe(old, tmp, &new->head, list) {
2154 ret = iterate_inodes_from_logical(old->bytenr +
2155 old->extent_offset, fs_info,
2156 path, record_one_backref,
2158 if (ret < 0 && ret != -ENOENT)
2161 /* no backref to be processed for this extent */
2163 list_del(&old->list);
2168 if (list_empty(&new->head))
2174 static int relink_is_mergable(struct extent_buffer *leaf,
2175 struct btrfs_file_extent_item *fi,
2176 struct new_sa_defrag_extent *new)
2178 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2181 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2184 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2187 if (btrfs_file_extent_encryption(leaf, fi) ||
2188 btrfs_file_extent_other_encoding(leaf, fi))
2195 * Note the backref might has changed, and in this case we just return 0.
2197 static noinline int relink_extent_backref(struct btrfs_path *path,
2198 struct sa_defrag_extent_backref *prev,
2199 struct sa_defrag_extent_backref *backref)
2201 struct btrfs_file_extent_item *extent;
2202 struct btrfs_file_extent_item *item;
2203 struct btrfs_ordered_extent *ordered;
2204 struct btrfs_trans_handle *trans;
2205 struct btrfs_fs_info *fs_info;
2206 struct btrfs_root *root;
2207 struct btrfs_key key;
2208 struct extent_buffer *leaf;
2209 struct old_sa_defrag_extent *old = backref->old;
2210 struct new_sa_defrag_extent *new = old->new;
2211 struct inode *src_inode = new->inode;
2212 struct inode *inode;
2213 struct extent_state *cached = NULL;
2222 if (prev && prev->root_id == backref->root_id &&
2223 prev->inum == backref->inum &&
2224 prev->file_pos + prev->num_bytes == backref->file_pos)
2227 /* step 1: get root */
2228 key.objectid = backref->root_id;
2229 key.type = BTRFS_ROOT_ITEM_KEY;
2230 key.offset = (u64)-1;
2232 fs_info = BTRFS_I(src_inode)->root->fs_info;
2233 index = srcu_read_lock(&fs_info->subvol_srcu);
2235 root = btrfs_read_fs_root_no_name(fs_info, &key);
2237 srcu_read_unlock(&fs_info->subvol_srcu, index);
2238 if (PTR_ERR(root) == -ENOENT)
2240 return PTR_ERR(root);
2243 /* step 2: get inode */
2244 key.objectid = backref->inum;
2245 key.type = BTRFS_INODE_ITEM_KEY;
2248 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2249 if (IS_ERR(inode)) {
2250 srcu_read_unlock(&fs_info->subvol_srcu, index);
2254 srcu_read_unlock(&fs_info->subvol_srcu, index);
2256 /* step 3: relink backref */
2257 lock_start = backref->file_pos;
2258 lock_end = backref->file_pos + backref->num_bytes - 1;
2259 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2262 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2264 btrfs_put_ordered_extent(ordered);
2268 trans = btrfs_join_transaction(root);
2269 if (IS_ERR(trans)) {
2270 ret = PTR_ERR(trans);
2274 key.objectid = backref->inum;
2275 key.type = BTRFS_EXTENT_DATA_KEY;
2276 key.offset = backref->file_pos;
2278 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2281 } else if (ret > 0) {
2286 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2287 struct btrfs_file_extent_item);
2289 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2290 backref->generation)
2293 btrfs_release_path(path);
2295 start = backref->file_pos;
2296 if (backref->extent_offset < old->extent_offset + old->offset)
2297 start += old->extent_offset + old->offset -
2298 backref->extent_offset;
2300 len = min(backref->extent_offset + backref->num_bytes,
2301 old->extent_offset + old->offset + old->len);
2302 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2304 ret = btrfs_drop_extents(trans, root, inode, start,
2309 key.objectid = btrfs_ino(inode);
2310 key.type = BTRFS_EXTENT_DATA_KEY;
2313 path->leave_spinning = 1;
2315 struct btrfs_file_extent_item *fi;
2317 struct btrfs_key found_key;
2319 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2324 leaf = path->nodes[0];
2325 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2327 fi = btrfs_item_ptr(leaf, path->slots[0],
2328 struct btrfs_file_extent_item);
2329 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2331 if (extent_len + found_key.offset == start &&
2332 relink_is_mergable(leaf, fi, new)) {
2333 btrfs_set_file_extent_num_bytes(leaf, fi,
2335 btrfs_mark_buffer_dirty(leaf);
2336 inode_add_bytes(inode, len);
2342 btrfs_release_path(path);
2347 ret = btrfs_insert_empty_item(trans, root, path, &key,
2350 btrfs_abort_transaction(trans, root, ret);
2354 leaf = path->nodes[0];
2355 item = btrfs_item_ptr(leaf, path->slots[0],
2356 struct btrfs_file_extent_item);
2357 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2358 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2359 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2360 btrfs_set_file_extent_num_bytes(leaf, item, len);
2361 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2362 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2363 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2364 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2365 btrfs_set_file_extent_encryption(leaf, item, 0);
2366 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2368 btrfs_mark_buffer_dirty(leaf);
2369 inode_add_bytes(inode, len);
2370 btrfs_release_path(path);
2372 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2374 backref->root_id, backref->inum,
2375 new->file_pos, 0); /* start - extent_offset */
2377 btrfs_abort_transaction(trans, root, ret);
2383 btrfs_release_path(path);
2384 path->leave_spinning = 0;
2385 btrfs_end_transaction(trans, root);
2387 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2393 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2395 struct old_sa_defrag_extent *old, *tmp;
2400 list_for_each_entry_safe(old, tmp, &new->head, list) {
2401 list_del(&old->list);
2407 static void relink_file_extents(struct new_sa_defrag_extent *new)
2409 struct btrfs_path *path;
2410 struct sa_defrag_extent_backref *backref;
2411 struct sa_defrag_extent_backref *prev = NULL;
2412 struct inode *inode;
2413 struct btrfs_root *root;
2414 struct rb_node *node;
2418 root = BTRFS_I(inode)->root;
2420 path = btrfs_alloc_path();
2424 if (!record_extent_backrefs(path, new)) {
2425 btrfs_free_path(path);
2428 btrfs_release_path(path);
2431 node = rb_first(&new->root);
2434 rb_erase(node, &new->root);
2436 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2438 ret = relink_extent_backref(path, prev, backref);
2451 btrfs_free_path(path);
2453 free_sa_defrag_extent(new);
2455 atomic_dec(&root->fs_info->defrag_running);
2456 wake_up(&root->fs_info->transaction_wait);
2459 static struct new_sa_defrag_extent *
2460 record_old_file_extents(struct inode *inode,
2461 struct btrfs_ordered_extent *ordered)
2463 struct btrfs_root *root = BTRFS_I(inode)->root;
2464 struct btrfs_path *path;
2465 struct btrfs_key key;
2466 struct old_sa_defrag_extent *old;
2467 struct new_sa_defrag_extent *new;
2470 new = kmalloc(sizeof(*new), GFP_NOFS);
2475 new->file_pos = ordered->file_offset;
2476 new->len = ordered->len;
2477 new->bytenr = ordered->start;
2478 new->disk_len = ordered->disk_len;
2479 new->compress_type = ordered->compress_type;
2480 new->root = RB_ROOT;
2481 INIT_LIST_HEAD(&new->head);
2483 path = btrfs_alloc_path();
2487 key.objectid = btrfs_ino(inode);
2488 key.type = BTRFS_EXTENT_DATA_KEY;
2489 key.offset = new->file_pos;
2491 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2494 if (ret > 0 && path->slots[0] > 0)
2497 /* find out all the old extents for the file range */
2499 struct btrfs_file_extent_item *extent;
2500 struct extent_buffer *l;
2509 slot = path->slots[0];
2511 if (slot >= btrfs_header_nritems(l)) {
2512 ret = btrfs_next_leaf(root, path);
2520 btrfs_item_key_to_cpu(l, &key, slot);
2522 if (key.objectid != btrfs_ino(inode))
2524 if (key.type != BTRFS_EXTENT_DATA_KEY)
2526 if (key.offset >= new->file_pos + new->len)
2529 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2531 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2532 if (key.offset + num_bytes < new->file_pos)
2535 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2539 extent_offset = btrfs_file_extent_offset(l, extent);
2541 old = kmalloc(sizeof(*old), GFP_NOFS);
2545 offset = max(new->file_pos, key.offset);
2546 end = min(new->file_pos + new->len, key.offset + num_bytes);
2548 old->bytenr = disk_bytenr;
2549 old->extent_offset = extent_offset;
2550 old->offset = offset - key.offset;
2551 old->len = end - offset;
2554 list_add_tail(&old->list, &new->head);
2560 btrfs_free_path(path);
2561 atomic_inc(&root->fs_info->defrag_running);
2566 btrfs_free_path(path);
2568 free_sa_defrag_extent(new);
2572 /* as ordered data IO finishes, this gets called so we can finish
2573 * an ordered extent if the range of bytes in the file it covers are
2576 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2578 struct inode *inode = ordered_extent->inode;
2579 struct btrfs_root *root = BTRFS_I(inode)->root;
2580 struct btrfs_trans_handle *trans = NULL;
2581 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2582 struct extent_state *cached_state = NULL;
2583 struct new_sa_defrag_extent *new = NULL;
2584 int compress_type = 0;
2586 u64 logical_len = ordered_extent->len;
2588 bool truncated = false;
2590 nolock = btrfs_is_free_space_inode(inode);
2592 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2597 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2599 logical_len = ordered_extent->truncated_len;
2600 /* Truncated the entire extent, don't bother adding */
2605 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2606 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2607 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2609 trans = btrfs_join_transaction_nolock(root);
2611 trans = btrfs_join_transaction(root);
2612 if (IS_ERR(trans)) {
2613 ret = PTR_ERR(trans);
2617 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2618 ret = btrfs_update_inode_fallback(trans, root, inode);
2619 if (ret) /* -ENOMEM or corruption */
2620 btrfs_abort_transaction(trans, root, ret);
2624 lock_extent_bits(io_tree, ordered_extent->file_offset,
2625 ordered_extent->file_offset + ordered_extent->len - 1,
2628 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2629 ordered_extent->file_offset + ordered_extent->len - 1,
2630 EXTENT_DEFRAG, 1, cached_state);
2632 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2633 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2634 /* the inode is shared */
2635 new = record_old_file_extents(inode, ordered_extent);
2637 clear_extent_bit(io_tree, ordered_extent->file_offset,
2638 ordered_extent->file_offset + ordered_extent->len - 1,
2639 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2643 trans = btrfs_join_transaction_nolock(root);
2645 trans = btrfs_join_transaction(root);
2646 if (IS_ERR(trans)) {
2647 ret = PTR_ERR(trans);
2651 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2653 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2654 compress_type = ordered_extent->compress_type;
2655 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2656 BUG_ON(compress_type);
2657 ret = btrfs_mark_extent_written(trans, inode,
2658 ordered_extent->file_offset,
2659 ordered_extent->file_offset +
2662 BUG_ON(root == root->fs_info->tree_root);
2663 ret = insert_reserved_file_extent(trans, inode,
2664 ordered_extent->file_offset,
2665 ordered_extent->start,
2666 ordered_extent->disk_len,
2667 logical_len, logical_len,
2668 compress_type, 0, 0,
2669 BTRFS_FILE_EXTENT_REG);
2671 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2672 ordered_extent->file_offset, ordered_extent->len,
2675 btrfs_abort_transaction(trans, root, ret);
2679 add_pending_csums(trans, inode, ordered_extent->file_offset,
2680 &ordered_extent->list);
2682 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2683 ret = btrfs_update_inode_fallback(trans, root, inode);
2684 if (ret) { /* -ENOMEM or corruption */
2685 btrfs_abort_transaction(trans, root, ret);
2690 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2691 ordered_extent->file_offset +
2692 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2694 if (root != root->fs_info->tree_root)
2695 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2697 btrfs_end_transaction(trans, root);
2699 if (ret || truncated) {
2703 start = ordered_extent->file_offset + logical_len;
2705 start = ordered_extent->file_offset;
2706 end = ordered_extent->file_offset + ordered_extent->len - 1;
2707 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2709 /* Drop the cache for the part of the extent we didn't write. */
2710 btrfs_drop_extent_cache(inode, start, end, 0);
2713 * If the ordered extent had an IOERR or something else went
2714 * wrong we need to return the space for this ordered extent
2715 * back to the allocator. We only free the extent in the
2716 * truncated case if we didn't write out the extent at all.
2718 if ((ret || !logical_len) &&
2719 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2720 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2721 btrfs_free_reserved_extent(root, ordered_extent->start,
2722 ordered_extent->disk_len);
2727 * This needs to be done to make sure anybody waiting knows we are done
2728 * updating everything for this ordered extent.
2730 btrfs_remove_ordered_extent(inode, ordered_extent);
2732 /* for snapshot-aware defrag */
2735 free_sa_defrag_extent(new);
2736 atomic_dec(&root->fs_info->defrag_running);
2738 relink_file_extents(new);
2743 btrfs_put_ordered_extent(ordered_extent);
2744 /* once for the tree */
2745 btrfs_put_ordered_extent(ordered_extent);
2750 static void finish_ordered_fn(struct btrfs_work *work)
2752 struct btrfs_ordered_extent *ordered_extent;
2753 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2754 btrfs_finish_ordered_io(ordered_extent);
2757 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2758 struct extent_state *state, int uptodate)
2760 struct inode *inode = page->mapping->host;
2761 struct btrfs_root *root = BTRFS_I(inode)->root;
2762 struct btrfs_ordered_extent *ordered_extent = NULL;
2763 struct btrfs_workers *workers;
2765 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2767 ClearPagePrivate2(page);
2768 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2769 end - start + 1, uptodate))
2772 ordered_extent->work.func = finish_ordered_fn;
2773 ordered_extent->work.flags = 0;
2775 if (btrfs_is_free_space_inode(inode))
2776 workers = &root->fs_info->endio_freespace_worker;
2778 workers = &root->fs_info->endio_write_workers;
2779 btrfs_queue_worker(workers, &ordered_extent->work);
2785 * when reads are done, we need to check csums to verify the data is correct
2786 * if there's a match, we allow the bio to finish. If not, the code in
2787 * extent_io.c will try to find good copies for us.
2789 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2790 u64 phy_offset, struct page *page,
2791 u64 start, u64 end, int mirror)
2793 size_t offset = start - page_offset(page);
2794 struct inode *inode = page->mapping->host;
2795 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2797 struct btrfs_root *root = BTRFS_I(inode)->root;
2800 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2801 DEFAULT_RATELIMIT_BURST);
2803 if (PageChecked(page)) {
2804 ClearPageChecked(page);
2808 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2811 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2812 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2813 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2818 phy_offset >>= inode->i_sb->s_blocksize_bits;
2819 csum_expected = *(((u32 *)io_bio->csum) + phy_offset);
2821 kaddr = kmap_atomic(page);
2822 csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
2823 btrfs_csum_final(csum, (char *)&csum);
2824 if (csum != csum_expected)
2827 kunmap_atomic(kaddr);
2832 if (__ratelimit(&_rs))
2833 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
2834 btrfs_ino(page->mapping->host), start, csum, csum_expected);
2835 memset(kaddr + offset, 1, end - start + 1);
2836 flush_dcache_page(page);
2837 kunmap_atomic(kaddr);
2838 if (csum_expected == 0)
2843 struct delayed_iput {
2844 struct list_head list;
2845 struct inode *inode;
2848 /* JDM: If this is fs-wide, why can't we add a pointer to
2849 * btrfs_inode instead and avoid the allocation? */
2850 void btrfs_add_delayed_iput(struct inode *inode)
2852 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2853 struct delayed_iput *delayed;
2855 if (atomic_add_unless(&inode->i_count, -1, 1))
2858 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2859 delayed->inode = inode;
2861 spin_lock(&fs_info->delayed_iput_lock);
2862 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2863 spin_unlock(&fs_info->delayed_iput_lock);
2866 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2869 struct btrfs_fs_info *fs_info = root->fs_info;
2870 struct delayed_iput *delayed;
2873 spin_lock(&fs_info->delayed_iput_lock);
2874 empty = list_empty(&fs_info->delayed_iputs);
2875 spin_unlock(&fs_info->delayed_iput_lock);
2879 spin_lock(&fs_info->delayed_iput_lock);
2880 list_splice_init(&fs_info->delayed_iputs, &list);
2881 spin_unlock(&fs_info->delayed_iput_lock);
2883 while (!list_empty(&list)) {
2884 delayed = list_entry(list.next, struct delayed_iput, list);
2885 list_del(&delayed->list);
2886 iput(delayed->inode);
2892 * This is called in transaction commit time. If there are no orphan
2893 * files in the subvolume, it removes orphan item and frees block_rsv
2896 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2897 struct btrfs_root *root)
2899 struct btrfs_block_rsv *block_rsv;
2902 if (atomic_read(&root->orphan_inodes) ||
2903 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2906 spin_lock(&root->orphan_lock);
2907 if (atomic_read(&root->orphan_inodes)) {
2908 spin_unlock(&root->orphan_lock);
2912 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2913 spin_unlock(&root->orphan_lock);
2917 block_rsv = root->orphan_block_rsv;
2918 root->orphan_block_rsv = NULL;
2919 spin_unlock(&root->orphan_lock);
2921 if (root->orphan_item_inserted &&
2922 btrfs_root_refs(&root->root_item) > 0) {
2923 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2924 root->root_key.objectid);
2926 btrfs_abort_transaction(trans, root, ret);
2928 root->orphan_item_inserted = 0;
2932 WARN_ON(block_rsv->size > 0);
2933 btrfs_free_block_rsv(root, block_rsv);
2938 * This creates an orphan entry for the given inode in case something goes
2939 * wrong in the middle of an unlink/truncate.
2941 * NOTE: caller of this function should reserve 5 units of metadata for
2944 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2946 struct btrfs_root *root = BTRFS_I(inode)->root;
2947 struct btrfs_block_rsv *block_rsv = NULL;
2952 if (!root->orphan_block_rsv) {
2953 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2958 spin_lock(&root->orphan_lock);
2959 if (!root->orphan_block_rsv) {
2960 root->orphan_block_rsv = block_rsv;
2961 } else if (block_rsv) {
2962 btrfs_free_block_rsv(root, block_rsv);
2966 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2967 &BTRFS_I(inode)->runtime_flags)) {
2970 * For proper ENOSPC handling, we should do orphan
2971 * cleanup when mounting. But this introduces backward
2972 * compatibility issue.
2974 if (!xchg(&root->orphan_item_inserted, 1))
2980 atomic_inc(&root->orphan_inodes);
2983 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2984 &BTRFS_I(inode)->runtime_flags))
2986 spin_unlock(&root->orphan_lock);
2988 /* grab metadata reservation from transaction handle */
2990 ret = btrfs_orphan_reserve_metadata(trans, inode);
2991 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
2994 /* insert an orphan item to track this unlinked/truncated file */
2996 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2998 atomic_dec(&root->orphan_inodes);
3000 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3001 &BTRFS_I(inode)->runtime_flags);
3002 btrfs_orphan_release_metadata(inode);
3004 if (ret != -EEXIST) {
3005 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3006 &BTRFS_I(inode)->runtime_flags);
3007 btrfs_abort_transaction(trans, root, ret);
3014 /* insert an orphan item to track subvolume contains orphan files */
3016 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3017 root->root_key.objectid);
3018 if (ret && ret != -EEXIST) {
3019 btrfs_abort_transaction(trans, root, ret);
3027 * We have done the truncate/delete so we can go ahead and remove the orphan
3028 * item for this particular inode.
3030 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3031 struct inode *inode)
3033 struct btrfs_root *root = BTRFS_I(inode)->root;
3034 int delete_item = 0;
3035 int release_rsv = 0;
3038 spin_lock(&root->orphan_lock);
3039 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3040 &BTRFS_I(inode)->runtime_flags))
3043 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3044 &BTRFS_I(inode)->runtime_flags))
3046 spin_unlock(&root->orphan_lock);
3049 atomic_dec(&root->orphan_inodes);
3051 ret = btrfs_del_orphan_item(trans, root,
3056 btrfs_orphan_release_metadata(inode);
3062 * this cleans up any orphans that may be left on the list from the last use
3065 int btrfs_orphan_cleanup(struct btrfs_root *root)
3067 struct btrfs_path *path;
3068 struct extent_buffer *leaf;
3069 struct btrfs_key key, found_key;
3070 struct btrfs_trans_handle *trans;
3071 struct inode *inode;
3072 u64 last_objectid = 0;
3073 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3075 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3078 path = btrfs_alloc_path();
3085 key.objectid = BTRFS_ORPHAN_OBJECTID;
3086 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3087 key.offset = (u64)-1;
3090 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3095 * if ret == 0 means we found what we were searching for, which
3096 * is weird, but possible, so only screw with path if we didn't
3097 * find the key and see if we have stuff that matches
3101 if (path->slots[0] == 0)
3106 /* pull out the item */
3107 leaf = path->nodes[0];
3108 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3110 /* make sure the item matches what we want */
3111 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3113 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3116 /* release the path since we're done with it */
3117 btrfs_release_path(path);
3120 * this is where we are basically btrfs_lookup, without the
3121 * crossing root thing. we store the inode number in the
3122 * offset of the orphan item.
3125 if (found_key.offset == last_objectid) {
3126 btrfs_err(root->fs_info,
3127 "Error removing orphan entry, stopping orphan cleanup");
3132 last_objectid = found_key.offset;
3134 found_key.objectid = found_key.offset;
3135 found_key.type = BTRFS_INODE_ITEM_KEY;
3136 found_key.offset = 0;
3137 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3138 ret = PTR_ERR_OR_ZERO(inode);
3139 if (ret && ret != -ESTALE)
3142 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3143 struct btrfs_root *dead_root;
3144 struct btrfs_fs_info *fs_info = root->fs_info;
3145 int is_dead_root = 0;
3148 * this is an orphan in the tree root. Currently these
3149 * could come from 2 sources:
3150 * a) a snapshot deletion in progress
3151 * b) a free space cache inode
3152 * We need to distinguish those two, as the snapshot
3153 * orphan must not get deleted.
3154 * find_dead_roots already ran before us, so if this
3155 * is a snapshot deletion, we should find the root
3156 * in the dead_roots list
3158 spin_lock(&fs_info->trans_lock);
3159 list_for_each_entry(dead_root, &fs_info->dead_roots,
3161 if (dead_root->root_key.objectid ==
3162 found_key.objectid) {
3167 spin_unlock(&fs_info->trans_lock);
3169 /* prevent this orphan from being found again */
3170 key.offset = found_key.objectid - 1;
3175 * Inode is already gone but the orphan item is still there,
3176 * kill the orphan item.
3178 if (ret == -ESTALE) {
3179 trans = btrfs_start_transaction(root, 1);
3180 if (IS_ERR(trans)) {
3181 ret = PTR_ERR(trans);
3184 btrfs_debug(root->fs_info, "auto deleting %Lu",
3185 found_key.objectid);
3186 ret = btrfs_del_orphan_item(trans, root,
3187 found_key.objectid);
3188 btrfs_end_transaction(trans, root);
3195 * add this inode to the orphan list so btrfs_orphan_del does
3196 * the proper thing when we hit it
3198 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3199 &BTRFS_I(inode)->runtime_flags);
3200 atomic_inc(&root->orphan_inodes);
3202 /* if we have links, this was a truncate, lets do that */
3203 if (inode->i_nlink) {
3204 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3210 /* 1 for the orphan item deletion. */
3211 trans = btrfs_start_transaction(root, 1);
3212 if (IS_ERR(trans)) {
3214 ret = PTR_ERR(trans);
3217 ret = btrfs_orphan_add(trans, inode);
3218 btrfs_end_transaction(trans, root);
3224 ret = btrfs_truncate(inode);
3226 btrfs_orphan_del(NULL, inode);
3231 /* this will do delete_inode and everything for us */
3236 /* release the path since we're done with it */
3237 btrfs_release_path(path);
3239 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3241 if (root->orphan_block_rsv)
3242 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3245 if (root->orphan_block_rsv || root->orphan_item_inserted) {
3246 trans = btrfs_join_transaction(root);
3248 btrfs_end_transaction(trans, root);
3252 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3254 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3258 btrfs_crit(root->fs_info,
3259 "could not do orphan cleanup %d", ret);
3260 btrfs_free_path(path);
3265 * very simple check to peek ahead in the leaf looking for xattrs. If we
3266 * don't find any xattrs, we know there can't be any acls.
3268 * slot is the slot the inode is in, objectid is the objectid of the inode
3270 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3271 int slot, u64 objectid,
3272 int *first_xattr_slot)
3274 u32 nritems = btrfs_header_nritems(leaf);
3275 struct btrfs_key found_key;
3276 static u64 xattr_access = 0;
3277 static u64 xattr_default = 0;
3280 if (!xattr_access) {
3281 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3282 strlen(POSIX_ACL_XATTR_ACCESS));
3283 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3284 strlen(POSIX_ACL_XATTR_DEFAULT));
3288 *first_xattr_slot = -1;
3289 while (slot < nritems) {
3290 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3292 /* we found a different objectid, there must not be acls */
3293 if (found_key.objectid != objectid)
3296 /* we found an xattr, assume we've got an acl */
3297 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3298 if (*first_xattr_slot == -1)
3299 *first_xattr_slot = slot;
3300 if (found_key.offset == xattr_access ||
3301 found_key.offset == xattr_default)
3306 * we found a key greater than an xattr key, there can't
3307 * be any acls later on
3309 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3316 * it goes inode, inode backrefs, xattrs, extents,
3317 * so if there are a ton of hard links to an inode there can
3318 * be a lot of backrefs. Don't waste time searching too hard,
3319 * this is just an optimization
3324 /* we hit the end of the leaf before we found an xattr or
3325 * something larger than an xattr. We have to assume the inode
3328 if (*first_xattr_slot == -1)
3329 *first_xattr_slot = slot;
3334 * read an inode from the btree into the in-memory inode
3336 static void btrfs_read_locked_inode(struct inode *inode)
3338 struct btrfs_path *path;
3339 struct extent_buffer *leaf;
3340 struct btrfs_inode_item *inode_item;
3341 struct btrfs_timespec *tspec;
3342 struct btrfs_root *root = BTRFS_I(inode)->root;
3343 struct btrfs_key location;
3348 bool filled = false;
3349 int first_xattr_slot;
3351 ret = btrfs_fill_inode(inode, &rdev);
3355 path = btrfs_alloc_path();
3359 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3361 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3365 leaf = path->nodes[0];
3370 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3371 struct btrfs_inode_item);
3372 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3373 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3374 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3375 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3376 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3378 tspec = btrfs_inode_atime(inode_item);
3379 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3380 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3382 tspec = btrfs_inode_mtime(inode_item);
3383 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3384 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3386 tspec = btrfs_inode_ctime(inode_item);
3387 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3388 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3390 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3391 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3392 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3395 * If we were modified in the current generation and evicted from memory
3396 * and then re-read we need to do a full sync since we don't have any
3397 * idea about which extents were modified before we were evicted from
3400 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3401 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3402 &BTRFS_I(inode)->runtime_flags);
3404 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3405 inode->i_generation = BTRFS_I(inode)->generation;
3407 rdev = btrfs_inode_rdev(leaf, inode_item);
3409 BTRFS_I(inode)->index_cnt = (u64)-1;
3410 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3414 if (inode->i_nlink != 1 ||
3415 path->slots[0] >= btrfs_header_nritems(leaf))
3418 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3419 if (location.objectid != btrfs_ino(inode))
3422 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3423 if (location.type == BTRFS_INODE_REF_KEY) {
3424 struct btrfs_inode_ref *ref;
3426 ref = (struct btrfs_inode_ref *)ptr;
3427 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3428 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3429 struct btrfs_inode_extref *extref;
3431 extref = (struct btrfs_inode_extref *)ptr;
3432 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3437 * try to precache a NULL acl entry for files that don't have
3438 * any xattrs or acls
3440 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3441 btrfs_ino(inode), &first_xattr_slot);
3442 if (first_xattr_slot != -1) {
3443 path->slots[0] = first_xattr_slot;
3444 ret = btrfs_load_inode_props(inode, path);
3446 btrfs_err(root->fs_info,
3447 "error loading props for ino %llu (root %llu): %d\n",
3449 root->root_key.objectid, ret);
3451 btrfs_free_path(path);
3454 cache_no_acl(inode);
3456 switch (inode->i_mode & S_IFMT) {
3458 inode->i_mapping->a_ops = &btrfs_aops;
3459 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3460 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3461 inode->i_fop = &btrfs_file_operations;
3462 inode->i_op = &btrfs_file_inode_operations;
3465 inode->i_fop = &btrfs_dir_file_operations;
3466 if (root == root->fs_info->tree_root)
3467 inode->i_op = &btrfs_dir_ro_inode_operations;
3469 inode->i_op = &btrfs_dir_inode_operations;
3472 inode->i_op = &btrfs_symlink_inode_operations;
3473 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3474 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3477 inode->i_op = &btrfs_special_inode_operations;
3478 init_special_inode(inode, inode->i_mode, rdev);
3482 btrfs_update_iflags(inode);
3486 btrfs_free_path(path);
3487 make_bad_inode(inode);
3491 * given a leaf and an inode, copy the inode fields into the leaf
3493 static void fill_inode_item(struct btrfs_trans_handle *trans,
3494 struct extent_buffer *leaf,
3495 struct btrfs_inode_item *item,
3496 struct inode *inode)
3498 struct btrfs_map_token token;
3500 btrfs_init_map_token(&token);
3502 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3503 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3504 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3506 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3507 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3509 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3510 inode->i_atime.tv_sec, &token);
3511 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3512 inode->i_atime.tv_nsec, &token);
3514 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3515 inode->i_mtime.tv_sec, &token);
3516 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3517 inode->i_mtime.tv_nsec, &token);
3519 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3520 inode->i_ctime.tv_sec, &token);
3521 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3522 inode->i_ctime.tv_nsec, &token);
3524 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3526 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3528 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3529 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3530 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3531 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3532 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3536 * copy everything in the in-memory inode into the btree.
3538 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3539 struct btrfs_root *root, struct inode *inode)
3541 struct btrfs_inode_item *inode_item;
3542 struct btrfs_path *path;
3543 struct extent_buffer *leaf;
3546 path = btrfs_alloc_path();
3550 path->leave_spinning = 1;
3551 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3559 leaf = path->nodes[0];
3560 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3561 struct btrfs_inode_item);
3563 fill_inode_item(trans, leaf, inode_item, inode);
3564 btrfs_mark_buffer_dirty(leaf);
3565 btrfs_set_inode_last_trans(trans, inode);
3568 btrfs_free_path(path);
3573 * copy everything in the in-memory inode into the btree.
3575 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3576 struct btrfs_root *root, struct inode *inode)
3581 * If the inode is a free space inode, we can deadlock during commit
3582 * if we put it into the delayed code.
3584 * The data relocation inode should also be directly updated
3587 if (!btrfs_is_free_space_inode(inode)
3588 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3589 btrfs_update_root_times(trans, root);
3591 ret = btrfs_delayed_update_inode(trans, root, inode);
3593 btrfs_set_inode_last_trans(trans, inode);
3597 return btrfs_update_inode_item(trans, root, inode);
3600 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3601 struct btrfs_root *root,
3602 struct inode *inode)
3606 ret = btrfs_update_inode(trans, root, inode);
3608 return btrfs_update_inode_item(trans, root, inode);
3613 * unlink helper that gets used here in inode.c and in the tree logging
3614 * recovery code. It remove a link in a directory with a given name, and
3615 * also drops the back refs in the inode to the directory
3617 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3618 struct btrfs_root *root,
3619 struct inode *dir, struct inode *inode,
3620 const char *name, int name_len)
3622 struct btrfs_path *path;
3624 struct extent_buffer *leaf;
3625 struct btrfs_dir_item *di;
3626 struct btrfs_key key;
3628 u64 ino = btrfs_ino(inode);
3629 u64 dir_ino = btrfs_ino(dir);
3631 path = btrfs_alloc_path();
3637 path->leave_spinning = 1;
3638 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3639 name, name_len, -1);
3648 leaf = path->nodes[0];
3649 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3650 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3653 btrfs_release_path(path);
3656 * If we don't have dir index, we have to get it by looking up
3657 * the inode ref, since we get the inode ref, remove it directly,
3658 * it is unnecessary to do delayed deletion.
3660 * But if we have dir index, needn't search inode ref to get it.
3661 * Since the inode ref is close to the inode item, it is better
3662 * that we delay to delete it, and just do this deletion when
3663 * we update the inode item.
3665 if (BTRFS_I(inode)->dir_index) {
3666 ret = btrfs_delayed_delete_inode_ref(inode);
3668 index = BTRFS_I(inode)->dir_index;
3673 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3676 btrfs_info(root->fs_info,
3677 "failed to delete reference to %.*s, inode %llu parent %llu",
3678 name_len, name, ino, dir_ino);
3679 btrfs_abort_transaction(trans, root, ret);
3683 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3685 btrfs_abort_transaction(trans, root, ret);
3689 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3691 if (ret != 0 && ret != -ENOENT) {
3692 btrfs_abort_transaction(trans, root, ret);
3696 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3701 btrfs_abort_transaction(trans, root, ret);
3703 btrfs_free_path(path);
3707 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3708 inode_inc_iversion(inode);
3709 inode_inc_iversion(dir);
3710 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3711 ret = btrfs_update_inode(trans, root, dir);
3716 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3717 struct btrfs_root *root,
3718 struct inode *dir, struct inode *inode,
3719 const char *name, int name_len)
3722 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3725 ret = btrfs_update_inode(trans, root, inode);
3731 * helper to start transaction for unlink and rmdir.
3733 * unlink and rmdir are special in btrfs, they do not always free space, so
3734 * if we cannot make our reservations the normal way try and see if there is
3735 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3736 * allow the unlink to occur.
3738 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3740 struct btrfs_trans_handle *trans;
3741 struct btrfs_root *root = BTRFS_I(dir)->root;
3745 * 1 for the possible orphan item
3746 * 1 for the dir item
3747 * 1 for the dir index
3748 * 1 for the inode ref
3751 trans = btrfs_start_transaction(root, 5);
3752 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3755 if (PTR_ERR(trans) == -ENOSPC) {
3756 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3758 trans = btrfs_start_transaction(root, 0);
3761 ret = btrfs_cond_migrate_bytes(root->fs_info,
3762 &root->fs_info->trans_block_rsv,
3765 btrfs_end_transaction(trans, root);
3766 return ERR_PTR(ret);
3768 trans->block_rsv = &root->fs_info->trans_block_rsv;
3769 trans->bytes_reserved = num_bytes;
3774 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3776 struct btrfs_root *root = BTRFS_I(dir)->root;
3777 struct btrfs_trans_handle *trans;
3778 struct inode *inode = dentry->d_inode;
3781 trans = __unlink_start_trans(dir);
3783 return PTR_ERR(trans);
3785 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3787 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3788 dentry->d_name.name, dentry->d_name.len);
3792 if (inode->i_nlink == 0) {
3793 ret = btrfs_orphan_add(trans, inode);
3799 btrfs_end_transaction(trans, root);
3800 btrfs_btree_balance_dirty(root);
3804 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3805 struct btrfs_root *root,
3806 struct inode *dir, u64 objectid,
3807 const char *name, int name_len)
3809 struct btrfs_path *path;
3810 struct extent_buffer *leaf;
3811 struct btrfs_dir_item *di;
3812 struct btrfs_key key;
3815 u64 dir_ino = btrfs_ino(dir);
3817 path = btrfs_alloc_path();
3821 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3822 name, name_len, -1);
3823 if (IS_ERR_OR_NULL(di)) {
3831 leaf = path->nodes[0];
3832 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3833 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3834 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3836 btrfs_abort_transaction(trans, root, ret);
3839 btrfs_release_path(path);
3841 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3842 objectid, root->root_key.objectid,
3843 dir_ino, &index, name, name_len);
3845 if (ret != -ENOENT) {
3846 btrfs_abort_transaction(trans, root, ret);
3849 di = btrfs_search_dir_index_item(root, path, dir_ino,
3851 if (IS_ERR_OR_NULL(di)) {
3856 btrfs_abort_transaction(trans, root, ret);
3860 leaf = path->nodes[0];
3861 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3862 btrfs_release_path(path);
3865 btrfs_release_path(path);
3867 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3869 btrfs_abort_transaction(trans, root, ret);
3873 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3874 inode_inc_iversion(dir);
3875 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3876 ret = btrfs_update_inode_fallback(trans, root, dir);
3878 btrfs_abort_transaction(trans, root, ret);
3880 btrfs_free_path(path);
3884 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3886 struct inode *inode = dentry->d_inode;
3888 struct btrfs_root *root = BTRFS_I(dir)->root;
3889 struct btrfs_trans_handle *trans;
3891 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3893 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3896 trans = __unlink_start_trans(dir);
3898 return PTR_ERR(trans);
3900 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3901 err = btrfs_unlink_subvol(trans, root, dir,
3902 BTRFS_I(inode)->location.objectid,
3903 dentry->d_name.name,
3904 dentry->d_name.len);
3908 err = btrfs_orphan_add(trans, inode);
3912 /* now the directory is empty */
3913 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3914 dentry->d_name.name, dentry->d_name.len);
3916 btrfs_i_size_write(inode, 0);
3918 btrfs_end_transaction(trans, root);
3919 btrfs_btree_balance_dirty(root);
3925 * this can truncate away extent items, csum items and directory items.
3926 * It starts at a high offset and removes keys until it can't find
3927 * any higher than new_size
3929 * csum items that cross the new i_size are truncated to the new size
3932 * min_type is the minimum key type to truncate down to. If set to 0, this
3933 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3935 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3936 struct btrfs_root *root,
3937 struct inode *inode,
3938 u64 new_size, u32 min_type)
3940 struct btrfs_path *path;
3941 struct extent_buffer *leaf;
3942 struct btrfs_file_extent_item *fi;
3943 struct btrfs_key key;
3944 struct btrfs_key found_key;
3945 u64 extent_start = 0;
3946 u64 extent_num_bytes = 0;
3947 u64 extent_offset = 0;
3949 u64 last_size = (u64)-1;
3950 u32 found_type = (u8)-1;
3953 int pending_del_nr = 0;
3954 int pending_del_slot = 0;
3955 int extent_type = -1;
3958 u64 ino = btrfs_ino(inode);
3960 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3962 path = btrfs_alloc_path();
3968 * We want to drop from the next block forward in case this new size is
3969 * not block aligned since we will be keeping the last block of the
3970 * extent just the way it is.
3972 if (root->ref_cows || root == root->fs_info->tree_root)
3973 btrfs_drop_extent_cache(inode, ALIGN(new_size,
3974 root->sectorsize), (u64)-1, 0);
3977 * This function is also used to drop the items in the log tree before
3978 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3979 * it is used to drop the loged items. So we shouldn't kill the delayed
3982 if (min_type == 0 && root == BTRFS_I(inode)->root)
3983 btrfs_kill_delayed_inode_items(inode);
3986 key.offset = (u64)-1;
3990 path->leave_spinning = 1;
3991 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3998 /* there are no items in the tree for us to truncate, we're
4001 if (path->slots[0] == 0)
4008 leaf = path->nodes[0];
4009 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4010 found_type = btrfs_key_type(&found_key);
4012 if (found_key.objectid != ino)
4015 if (found_type < min_type)
4018 item_end = found_key.offset;
4019 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4020 fi = btrfs_item_ptr(leaf, path->slots[0],
4021 struct btrfs_file_extent_item);
4022 extent_type = btrfs_file_extent_type(leaf, fi);
4023 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4025 btrfs_file_extent_num_bytes(leaf, fi);
4026 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4027 item_end += btrfs_file_extent_inline_len(leaf,
4028 path->slots[0], fi);
4032 if (found_type > min_type) {
4035 if (item_end < new_size)
4037 if (found_key.offset >= new_size)
4043 /* FIXME, shrink the extent if the ref count is only 1 */
4044 if (found_type != BTRFS_EXTENT_DATA_KEY)
4048 last_size = found_key.offset;
4050 last_size = new_size;
4052 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4054 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4056 u64 orig_num_bytes =
4057 btrfs_file_extent_num_bytes(leaf, fi);
4058 extent_num_bytes = ALIGN(new_size -
4061 btrfs_set_file_extent_num_bytes(leaf, fi,
4063 num_dec = (orig_num_bytes -
4065 if (root->ref_cows && extent_start != 0)
4066 inode_sub_bytes(inode, num_dec);
4067 btrfs_mark_buffer_dirty(leaf);
4070 btrfs_file_extent_disk_num_bytes(leaf,
4072 extent_offset = found_key.offset -
4073 btrfs_file_extent_offset(leaf, fi);
4075 /* FIXME blocksize != 4096 */
4076 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4077 if (extent_start != 0) {
4080 inode_sub_bytes(inode, num_dec);
4083 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4085 * we can't truncate inline items that have had
4089 btrfs_file_extent_compression(leaf, fi) == 0 &&
4090 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4091 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4092 u32 size = new_size - found_key.offset;
4094 if (root->ref_cows) {
4095 inode_sub_bytes(inode, item_end + 1 -
4100 * update the ram bytes to properly reflect
4101 * the new size of our item
4103 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4105 btrfs_file_extent_calc_inline_size(size);
4106 btrfs_truncate_item(root, path, size, 1);
4107 } else if (root->ref_cows) {
4108 inode_sub_bytes(inode, item_end + 1 -
4114 if (!pending_del_nr) {
4115 /* no pending yet, add ourselves */
4116 pending_del_slot = path->slots[0];
4118 } else if (pending_del_nr &&
4119 path->slots[0] + 1 == pending_del_slot) {
4120 /* hop on the pending chunk */
4122 pending_del_slot = path->slots[0];
4129 if (found_extent && (root->ref_cows ||
4130 root == root->fs_info->tree_root)) {
4131 btrfs_set_path_blocking(path);
4132 ret = btrfs_free_extent(trans, root, extent_start,
4133 extent_num_bytes, 0,
4134 btrfs_header_owner(leaf),
4135 ino, extent_offset, 0);
4139 if (found_type == BTRFS_INODE_ITEM_KEY)
4142 if (path->slots[0] == 0 ||
4143 path->slots[0] != pending_del_slot) {
4144 if (pending_del_nr) {
4145 ret = btrfs_del_items(trans, root, path,
4149 btrfs_abort_transaction(trans,
4155 btrfs_release_path(path);
4162 if (pending_del_nr) {
4163 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4166 btrfs_abort_transaction(trans, root, ret);
4169 if (last_size != (u64)-1)
4170 btrfs_ordered_update_i_size(inode, last_size, NULL);
4171 btrfs_free_path(path);
4176 * btrfs_truncate_page - read, zero a chunk and write a page
4177 * @inode - inode that we're zeroing
4178 * @from - the offset to start zeroing
4179 * @len - the length to zero, 0 to zero the entire range respective to the
4181 * @front - zero up to the offset instead of from the offset on
4183 * This will find the page for the "from" offset and cow the page and zero the
4184 * part we want to zero. This is used with truncate and hole punching.
4186 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4189 struct address_space *mapping = inode->i_mapping;
4190 struct btrfs_root *root = BTRFS_I(inode)->root;
4191 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4192 struct btrfs_ordered_extent *ordered;
4193 struct extent_state *cached_state = NULL;
4195 u32 blocksize = root->sectorsize;
4196 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4197 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4199 gfp_t mask = btrfs_alloc_write_mask(mapping);
4204 if ((offset & (blocksize - 1)) == 0 &&
4205 (!len || ((len & (blocksize - 1)) == 0)))
4207 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4212 page = find_or_create_page(mapping, index, mask);
4214 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4219 page_start = page_offset(page);
4220 page_end = page_start + PAGE_CACHE_SIZE - 1;
4222 if (!PageUptodate(page)) {
4223 ret = btrfs_readpage(NULL, page);
4225 if (page->mapping != mapping) {
4227 page_cache_release(page);
4230 if (!PageUptodate(page)) {
4235 wait_on_page_writeback(page);
4237 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4238 set_page_extent_mapped(page);
4240 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4242 unlock_extent_cached(io_tree, page_start, page_end,
4243 &cached_state, GFP_NOFS);
4245 page_cache_release(page);
4246 btrfs_start_ordered_extent(inode, ordered, 1);
4247 btrfs_put_ordered_extent(ordered);
4251 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4252 EXTENT_DIRTY | EXTENT_DELALLOC |
4253 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4254 0, 0, &cached_state, GFP_NOFS);
4256 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4259 unlock_extent_cached(io_tree, page_start, page_end,
4260 &cached_state, GFP_NOFS);
4264 if (offset != PAGE_CACHE_SIZE) {
4266 len = PAGE_CACHE_SIZE - offset;
4269 memset(kaddr, 0, offset);
4271 memset(kaddr + offset, 0, len);
4272 flush_dcache_page(page);
4275 ClearPageChecked(page);
4276 set_page_dirty(page);
4277 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4282 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4284 page_cache_release(page);
4289 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4290 u64 offset, u64 len)
4292 struct btrfs_trans_handle *trans;
4296 * Still need to make sure the inode looks like it's been updated so
4297 * that any holes get logged if we fsync.
4299 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4300 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4301 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4302 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4307 * 1 - for the one we're dropping
4308 * 1 - for the one we're adding
4309 * 1 - for updating the inode.
4311 trans = btrfs_start_transaction(root, 3);
4313 return PTR_ERR(trans);
4315 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4317 btrfs_abort_transaction(trans, root, ret);
4318 btrfs_end_transaction(trans, root);
4322 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4323 0, 0, len, 0, len, 0, 0, 0);
4325 btrfs_abort_transaction(trans, root, ret);
4327 btrfs_update_inode(trans, root, inode);
4328 btrfs_end_transaction(trans, root);
4333 * This function puts in dummy file extents for the area we're creating a hole
4334 * for. So if we are truncating this file to a larger size we need to insert
4335 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4336 * the range between oldsize and size
4338 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4340 struct btrfs_root *root = BTRFS_I(inode)->root;
4341 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4342 struct extent_map *em = NULL;
4343 struct extent_state *cached_state = NULL;
4344 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4345 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4346 u64 block_end = ALIGN(size, root->sectorsize);
4353 * If our size started in the middle of a page we need to zero out the
4354 * rest of the page before we expand the i_size, otherwise we could
4355 * expose stale data.
4357 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4361 if (size <= hole_start)
4365 struct btrfs_ordered_extent *ordered;
4367 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4369 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4370 block_end - hole_start);
4373 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4374 &cached_state, GFP_NOFS);
4375 btrfs_start_ordered_extent(inode, ordered, 1);
4376 btrfs_put_ordered_extent(ordered);
4379 cur_offset = hole_start;
4381 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4382 block_end - cur_offset, 0);
4388 last_byte = min(extent_map_end(em), block_end);
4389 last_byte = ALIGN(last_byte , root->sectorsize);
4390 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4391 struct extent_map *hole_em;
4392 hole_size = last_byte - cur_offset;
4394 err = maybe_insert_hole(root, inode, cur_offset,
4398 btrfs_drop_extent_cache(inode, cur_offset,
4399 cur_offset + hole_size - 1, 0);
4400 hole_em = alloc_extent_map();
4402 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4403 &BTRFS_I(inode)->runtime_flags);
4406 hole_em->start = cur_offset;
4407 hole_em->len = hole_size;
4408 hole_em->orig_start = cur_offset;
4410 hole_em->block_start = EXTENT_MAP_HOLE;
4411 hole_em->block_len = 0;
4412 hole_em->orig_block_len = 0;
4413 hole_em->ram_bytes = hole_size;
4414 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4415 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4416 hole_em->generation = root->fs_info->generation;
4419 write_lock(&em_tree->lock);
4420 err = add_extent_mapping(em_tree, hole_em, 1);
4421 write_unlock(&em_tree->lock);
4424 btrfs_drop_extent_cache(inode, cur_offset,
4428 free_extent_map(hole_em);
4431 free_extent_map(em);
4433 cur_offset = last_byte;
4434 if (cur_offset >= block_end)
4437 free_extent_map(em);
4438 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4443 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4445 struct btrfs_root *root = BTRFS_I(inode)->root;
4446 struct btrfs_trans_handle *trans;
4447 loff_t oldsize = i_size_read(inode);
4448 loff_t newsize = attr->ia_size;
4449 int mask = attr->ia_valid;
4453 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4454 * special case where we need to update the times despite not having
4455 * these flags set. For all other operations the VFS set these flags
4456 * explicitly if it wants a timestamp update.
4458 if (newsize != oldsize && (!(mask & (ATTR_CTIME | ATTR_MTIME))))
4459 inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb);
4461 if (newsize > oldsize) {
4462 truncate_pagecache(inode, newsize);
4463 ret = btrfs_cont_expand(inode, oldsize, newsize);
4467 trans = btrfs_start_transaction(root, 1);
4469 return PTR_ERR(trans);
4471 i_size_write(inode, newsize);
4472 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4473 ret = btrfs_update_inode(trans, root, inode);
4474 btrfs_end_transaction(trans, root);
4478 * We're truncating a file that used to have good data down to
4479 * zero. Make sure it gets into the ordered flush list so that
4480 * any new writes get down to disk quickly.
4483 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4484 &BTRFS_I(inode)->runtime_flags);
4487 * 1 for the orphan item we're going to add
4488 * 1 for the orphan item deletion.
4490 trans = btrfs_start_transaction(root, 2);
4492 return PTR_ERR(trans);
4495 * We need to do this in case we fail at _any_ point during the
4496 * actual truncate. Once we do the truncate_setsize we could
4497 * invalidate pages which forces any outstanding ordered io to
4498 * be instantly completed which will give us extents that need
4499 * to be truncated. If we fail to get an orphan inode down we
4500 * could have left over extents that were never meant to live,
4501 * so we need to garuntee from this point on that everything
4502 * will be consistent.
4504 ret = btrfs_orphan_add(trans, inode);
4505 btrfs_end_transaction(trans, root);
4509 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4510 truncate_setsize(inode, newsize);
4512 /* Disable nonlocked read DIO to avoid the end less truncate */
4513 btrfs_inode_block_unlocked_dio(inode);
4514 inode_dio_wait(inode);
4515 btrfs_inode_resume_unlocked_dio(inode);
4517 ret = btrfs_truncate(inode);
4518 if (ret && inode->i_nlink) {
4522 * failed to truncate, disk_i_size is only adjusted down
4523 * as we remove extents, so it should represent the true
4524 * size of the inode, so reset the in memory size and
4525 * delete our orphan entry.
4527 trans = btrfs_join_transaction(root);
4528 if (IS_ERR(trans)) {
4529 btrfs_orphan_del(NULL, inode);
4532 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4533 err = btrfs_orphan_del(trans, inode);
4535 btrfs_abort_transaction(trans, root, err);
4536 btrfs_end_transaction(trans, root);
4543 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4545 struct inode *inode = dentry->d_inode;
4546 struct btrfs_root *root = BTRFS_I(inode)->root;
4549 if (btrfs_root_readonly(root))
4552 err = inode_change_ok(inode, attr);
4556 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4557 err = btrfs_setsize(inode, attr);
4562 if (attr->ia_valid) {
4563 setattr_copy(inode, attr);
4564 inode_inc_iversion(inode);
4565 err = btrfs_dirty_inode(inode);
4567 if (!err && attr->ia_valid & ATTR_MODE)
4568 err = btrfs_acl_chmod(inode);
4575 * While truncating the inode pages during eviction, we get the VFS calling
4576 * btrfs_invalidatepage() against each page of the inode. This is slow because
4577 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4578 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4579 * extent_state structures over and over, wasting lots of time.
4581 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4582 * those expensive operations on a per page basis and do only the ordered io
4583 * finishing, while we release here the extent_map and extent_state structures,
4584 * without the excessive merging and splitting.
4586 static void evict_inode_truncate_pages(struct inode *inode)
4588 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4589 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4590 struct rb_node *node;
4592 ASSERT(inode->i_state & I_FREEING);
4593 truncate_inode_pages(&inode->i_data, 0);
4595 write_lock(&map_tree->lock);
4596 while (!RB_EMPTY_ROOT(&map_tree->map)) {
4597 struct extent_map *em;
4599 node = rb_first(&map_tree->map);
4600 em = rb_entry(node, struct extent_map, rb_node);
4601 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4602 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4603 remove_extent_mapping(map_tree, em);
4604 free_extent_map(em);
4606 write_unlock(&map_tree->lock);
4608 spin_lock(&io_tree->lock);
4609 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4610 struct extent_state *state;
4611 struct extent_state *cached_state = NULL;
4613 node = rb_first(&io_tree->state);
4614 state = rb_entry(node, struct extent_state, rb_node);
4615 atomic_inc(&state->refs);
4616 spin_unlock(&io_tree->lock);
4618 lock_extent_bits(io_tree, state->start, state->end,
4620 clear_extent_bit(io_tree, state->start, state->end,
4621 EXTENT_LOCKED | EXTENT_DIRTY |
4622 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
4623 EXTENT_DEFRAG, 1, 1,
4624 &cached_state, GFP_NOFS);
4625 free_extent_state(state);
4627 spin_lock(&io_tree->lock);
4629 spin_unlock(&io_tree->lock);
4632 void btrfs_evict_inode(struct inode *inode)
4634 struct btrfs_trans_handle *trans;
4635 struct btrfs_root *root = BTRFS_I(inode)->root;
4636 struct btrfs_block_rsv *rsv, *global_rsv;
4637 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4640 trace_btrfs_inode_evict(inode);
4642 evict_inode_truncate_pages(inode);
4644 if (inode->i_nlink &&
4645 ((btrfs_root_refs(&root->root_item) != 0 &&
4646 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4647 btrfs_is_free_space_inode(inode)))
4650 if (is_bad_inode(inode)) {
4651 btrfs_orphan_del(NULL, inode);
4654 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4655 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4657 if (root->fs_info->log_root_recovering) {
4658 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4659 &BTRFS_I(inode)->runtime_flags));
4663 if (inode->i_nlink > 0) {
4664 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4665 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4669 ret = btrfs_commit_inode_delayed_inode(inode);
4671 btrfs_orphan_del(NULL, inode);
4675 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4677 btrfs_orphan_del(NULL, inode);
4680 rsv->size = min_size;
4682 global_rsv = &root->fs_info->global_block_rsv;
4684 btrfs_i_size_write(inode, 0);
4687 * This is a bit simpler than btrfs_truncate since we've already
4688 * reserved our space for our orphan item in the unlink, so we just
4689 * need to reserve some slack space in case we add bytes and update
4690 * inode item when doing the truncate.
4693 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4694 BTRFS_RESERVE_FLUSH_LIMIT);
4697 * Try and steal from the global reserve since we will
4698 * likely not use this space anyway, we want to try as
4699 * hard as possible to get this to work.
4702 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4705 btrfs_warn(root->fs_info,
4706 "Could not get space for a delete, will truncate on mount %d",
4708 btrfs_orphan_del(NULL, inode);
4709 btrfs_free_block_rsv(root, rsv);
4713 trans = btrfs_join_transaction(root);
4714 if (IS_ERR(trans)) {
4715 btrfs_orphan_del(NULL, inode);
4716 btrfs_free_block_rsv(root, rsv);
4720 trans->block_rsv = rsv;
4722 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4726 trans->block_rsv = &root->fs_info->trans_block_rsv;
4727 btrfs_end_transaction(trans, root);
4729 btrfs_btree_balance_dirty(root);
4732 btrfs_free_block_rsv(root, rsv);
4735 * Errors here aren't a big deal, it just means we leave orphan items
4736 * in the tree. They will be cleaned up on the next mount.
4739 trans->block_rsv = root->orphan_block_rsv;
4740 btrfs_orphan_del(trans, inode);
4742 btrfs_orphan_del(NULL, inode);
4745 trans->block_rsv = &root->fs_info->trans_block_rsv;
4746 if (!(root == root->fs_info->tree_root ||
4747 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4748 btrfs_return_ino(root, btrfs_ino(inode));
4750 btrfs_end_transaction(trans, root);
4751 btrfs_btree_balance_dirty(root);
4753 btrfs_remove_delayed_node(inode);
4759 * this returns the key found in the dir entry in the location pointer.
4760 * If no dir entries were found, location->objectid is 0.
4762 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4763 struct btrfs_key *location)
4765 const char *name = dentry->d_name.name;
4766 int namelen = dentry->d_name.len;
4767 struct btrfs_dir_item *di;
4768 struct btrfs_path *path;
4769 struct btrfs_root *root = BTRFS_I(dir)->root;
4772 path = btrfs_alloc_path();
4776 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4781 if (IS_ERR_OR_NULL(di))
4784 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4786 btrfs_free_path(path);
4789 location->objectid = 0;
4794 * when we hit a tree root in a directory, the btrfs part of the inode
4795 * needs to be changed to reflect the root directory of the tree root. This
4796 * is kind of like crossing a mount point.
4798 static int fixup_tree_root_location(struct btrfs_root *root,
4800 struct dentry *dentry,
4801 struct btrfs_key *location,
4802 struct btrfs_root **sub_root)
4804 struct btrfs_path *path;
4805 struct btrfs_root *new_root;
4806 struct btrfs_root_ref *ref;
4807 struct extent_buffer *leaf;
4811 path = btrfs_alloc_path();
4818 ret = btrfs_find_item(root->fs_info->tree_root, path,
4819 BTRFS_I(dir)->root->root_key.objectid,
4820 location->objectid, BTRFS_ROOT_REF_KEY, NULL);
4827 leaf = path->nodes[0];
4828 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4829 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4830 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4833 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4834 (unsigned long)(ref + 1),
4835 dentry->d_name.len);
4839 btrfs_release_path(path);
4841 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4842 if (IS_ERR(new_root)) {
4843 err = PTR_ERR(new_root);
4847 *sub_root = new_root;
4848 location->objectid = btrfs_root_dirid(&new_root->root_item);
4849 location->type = BTRFS_INODE_ITEM_KEY;
4850 location->offset = 0;
4853 btrfs_free_path(path);
4857 static void inode_tree_add(struct inode *inode)
4859 struct btrfs_root *root = BTRFS_I(inode)->root;
4860 struct btrfs_inode *entry;
4862 struct rb_node *parent;
4863 struct rb_node *new = &BTRFS_I(inode)->rb_node;
4864 u64 ino = btrfs_ino(inode);
4866 if (inode_unhashed(inode))
4869 spin_lock(&root->inode_lock);
4870 p = &root->inode_tree.rb_node;
4873 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4875 if (ino < btrfs_ino(&entry->vfs_inode))
4876 p = &parent->rb_left;
4877 else if (ino > btrfs_ino(&entry->vfs_inode))
4878 p = &parent->rb_right;
4880 WARN_ON(!(entry->vfs_inode.i_state &
4881 (I_WILL_FREE | I_FREEING)));
4882 rb_replace_node(parent, new, &root->inode_tree);
4883 RB_CLEAR_NODE(parent);
4884 spin_unlock(&root->inode_lock);
4888 rb_link_node(new, parent, p);
4889 rb_insert_color(new, &root->inode_tree);
4890 spin_unlock(&root->inode_lock);
4893 static void inode_tree_del(struct inode *inode)
4895 struct btrfs_root *root = BTRFS_I(inode)->root;
4898 spin_lock(&root->inode_lock);
4899 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4900 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4901 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4902 empty = RB_EMPTY_ROOT(&root->inode_tree);
4904 spin_unlock(&root->inode_lock);
4906 if (empty && btrfs_root_refs(&root->root_item) == 0) {
4907 synchronize_srcu(&root->fs_info->subvol_srcu);
4908 spin_lock(&root->inode_lock);
4909 empty = RB_EMPTY_ROOT(&root->inode_tree);
4910 spin_unlock(&root->inode_lock);
4912 btrfs_add_dead_root(root);
4916 void btrfs_invalidate_inodes(struct btrfs_root *root)
4918 struct rb_node *node;
4919 struct rb_node *prev;
4920 struct btrfs_inode *entry;
4921 struct inode *inode;
4924 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4926 spin_lock(&root->inode_lock);
4928 node = root->inode_tree.rb_node;
4932 entry = rb_entry(node, struct btrfs_inode, rb_node);
4934 if (objectid < btrfs_ino(&entry->vfs_inode))
4935 node = node->rb_left;
4936 else if (objectid > btrfs_ino(&entry->vfs_inode))
4937 node = node->rb_right;
4943 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4944 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4948 prev = rb_next(prev);
4952 entry = rb_entry(node, struct btrfs_inode, rb_node);
4953 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4954 inode = igrab(&entry->vfs_inode);
4956 spin_unlock(&root->inode_lock);
4957 if (atomic_read(&inode->i_count) > 1)
4958 d_prune_aliases(inode);
4960 * btrfs_drop_inode will have it removed from
4961 * the inode cache when its usage count
4966 spin_lock(&root->inode_lock);
4970 if (cond_resched_lock(&root->inode_lock))
4973 node = rb_next(node);
4975 spin_unlock(&root->inode_lock);
4978 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4980 struct btrfs_iget_args *args = p;
4981 inode->i_ino = args->location->objectid;
4982 memcpy(&BTRFS_I(inode)->location, args->location,
4983 sizeof(*args->location));
4984 BTRFS_I(inode)->root = args->root;
4988 static int btrfs_find_actor(struct inode *inode, void *opaque)
4990 struct btrfs_iget_args *args = opaque;
4991 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
4992 args->root == BTRFS_I(inode)->root;
4995 static struct inode *btrfs_iget_locked(struct super_block *s,
4996 struct btrfs_key *location,
4997 struct btrfs_root *root)
4999 struct inode *inode;
5000 struct btrfs_iget_args args;
5001 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5003 args.location = location;
5006 inode = iget5_locked(s, hashval, btrfs_find_actor,
5007 btrfs_init_locked_inode,
5012 /* Get an inode object given its location and corresponding root.
5013 * Returns in *is_new if the inode was read from disk
5015 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5016 struct btrfs_root *root, int *new)
5018 struct inode *inode;
5020 inode = btrfs_iget_locked(s, location, root);
5022 return ERR_PTR(-ENOMEM);
5024 if (inode->i_state & I_NEW) {
5025 btrfs_read_locked_inode(inode);
5026 if (!is_bad_inode(inode)) {
5027 inode_tree_add(inode);
5028 unlock_new_inode(inode);
5032 unlock_new_inode(inode);
5034 inode = ERR_PTR(-ESTALE);
5041 static struct inode *new_simple_dir(struct super_block *s,
5042 struct btrfs_key *key,
5043 struct btrfs_root *root)
5045 struct inode *inode = new_inode(s);
5048 return ERR_PTR(-ENOMEM);
5050 BTRFS_I(inode)->root = root;
5051 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5052 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5054 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5055 inode->i_op = &btrfs_dir_ro_inode_operations;
5056 inode->i_fop = &simple_dir_operations;
5057 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5058 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5063 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5065 struct inode *inode;
5066 struct btrfs_root *root = BTRFS_I(dir)->root;
5067 struct btrfs_root *sub_root = root;
5068 struct btrfs_key location;
5072 if (dentry->d_name.len > BTRFS_NAME_LEN)
5073 return ERR_PTR(-ENAMETOOLONG);
5075 ret = btrfs_inode_by_name(dir, dentry, &location);
5077 return ERR_PTR(ret);
5079 if (location.objectid == 0)
5080 return ERR_PTR(-ENOENT);
5082 if (location.type == BTRFS_INODE_ITEM_KEY) {
5083 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5087 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5089 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5090 ret = fixup_tree_root_location(root, dir, dentry,
5091 &location, &sub_root);
5094 inode = ERR_PTR(ret);
5096 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5098 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5100 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5102 if (!IS_ERR(inode) && root != sub_root) {
5103 down_read(&root->fs_info->cleanup_work_sem);
5104 if (!(inode->i_sb->s_flags & MS_RDONLY))
5105 ret = btrfs_orphan_cleanup(sub_root);
5106 up_read(&root->fs_info->cleanup_work_sem);
5109 inode = ERR_PTR(ret);
5116 static int btrfs_dentry_delete(const struct dentry *dentry)
5118 struct btrfs_root *root;
5119 struct inode *inode = dentry->d_inode;
5121 if (!inode && !IS_ROOT(dentry))
5122 inode = dentry->d_parent->d_inode;
5125 root = BTRFS_I(inode)->root;
5126 if (btrfs_root_refs(&root->root_item) == 0)
5129 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5135 static void btrfs_dentry_release(struct dentry *dentry)
5137 if (dentry->d_fsdata)
5138 kfree(dentry->d_fsdata);
5141 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5144 struct inode *inode;
5146 inode = btrfs_lookup_dentry(dir, dentry);
5147 if (IS_ERR(inode)) {
5148 if (PTR_ERR(inode) == -ENOENT)
5151 return ERR_CAST(inode);
5154 return d_materialise_unique(dentry, inode);
5157 unsigned char btrfs_filetype_table[] = {
5158 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5161 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5163 struct inode *inode = file_inode(file);
5164 struct btrfs_root *root = BTRFS_I(inode)->root;
5165 struct btrfs_item *item;
5166 struct btrfs_dir_item *di;
5167 struct btrfs_key key;
5168 struct btrfs_key found_key;
5169 struct btrfs_path *path;
5170 struct list_head ins_list;
5171 struct list_head del_list;
5173 struct extent_buffer *leaf;
5175 unsigned char d_type;
5180 int key_type = BTRFS_DIR_INDEX_KEY;
5184 int is_curr = 0; /* ctx->pos points to the current index? */
5186 /* FIXME, use a real flag for deciding about the key type */
5187 if (root->fs_info->tree_root == root)
5188 key_type = BTRFS_DIR_ITEM_KEY;
5190 if (!dir_emit_dots(file, ctx))
5193 path = btrfs_alloc_path();
5199 if (key_type == BTRFS_DIR_INDEX_KEY) {
5200 INIT_LIST_HEAD(&ins_list);
5201 INIT_LIST_HEAD(&del_list);
5202 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5205 btrfs_set_key_type(&key, key_type);
5206 key.offset = ctx->pos;
5207 key.objectid = btrfs_ino(inode);
5209 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5214 leaf = path->nodes[0];
5215 slot = path->slots[0];
5216 if (slot >= btrfs_header_nritems(leaf)) {
5217 ret = btrfs_next_leaf(root, path);
5225 item = btrfs_item_nr(slot);
5226 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5228 if (found_key.objectid != key.objectid)
5230 if (btrfs_key_type(&found_key) != key_type)
5232 if (found_key.offset < ctx->pos)
5234 if (key_type == BTRFS_DIR_INDEX_KEY &&
5235 btrfs_should_delete_dir_index(&del_list,
5239 ctx->pos = found_key.offset;
5242 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5244 di_total = btrfs_item_size(leaf, item);
5246 while (di_cur < di_total) {
5247 struct btrfs_key location;
5249 if (verify_dir_item(root, leaf, di))
5252 name_len = btrfs_dir_name_len(leaf, di);
5253 if (name_len <= sizeof(tmp_name)) {
5254 name_ptr = tmp_name;
5256 name_ptr = kmalloc(name_len, GFP_NOFS);
5262 read_extent_buffer(leaf, name_ptr,
5263 (unsigned long)(di + 1), name_len);
5265 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5266 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5269 /* is this a reference to our own snapshot? If so
5272 * In contrast to old kernels, we insert the snapshot's
5273 * dir item and dir index after it has been created, so
5274 * we won't find a reference to our own snapshot. We
5275 * still keep the following code for backward
5278 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5279 location.objectid == root->root_key.objectid) {
5283 over = !dir_emit(ctx, name_ptr, name_len,
5284 location.objectid, d_type);
5287 if (name_ptr != tmp_name)
5292 di_len = btrfs_dir_name_len(leaf, di) +
5293 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5295 di = (struct btrfs_dir_item *)((char *)di + di_len);
5301 if (key_type == BTRFS_DIR_INDEX_KEY) {
5304 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5309 /* Reached end of directory/root. Bump pos past the last item. */
5313 * Stop new entries from being returned after we return the last
5316 * New directory entries are assigned a strictly increasing
5317 * offset. This means that new entries created during readdir
5318 * are *guaranteed* to be seen in the future by that readdir.
5319 * This has broken buggy programs which operate on names as
5320 * they're returned by readdir. Until we re-use freed offsets
5321 * we have this hack to stop new entries from being returned
5322 * under the assumption that they'll never reach this huge
5325 * This is being careful not to overflow 32bit loff_t unless the
5326 * last entry requires it because doing so has broken 32bit apps
5329 if (key_type == BTRFS_DIR_INDEX_KEY) {
5330 if (ctx->pos >= INT_MAX)
5331 ctx->pos = LLONG_MAX;
5338 if (key_type == BTRFS_DIR_INDEX_KEY)
5339 btrfs_put_delayed_items(&ins_list, &del_list);
5340 btrfs_free_path(path);
5344 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5346 struct btrfs_root *root = BTRFS_I(inode)->root;
5347 struct btrfs_trans_handle *trans;
5349 bool nolock = false;
5351 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5354 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5357 if (wbc->sync_mode == WB_SYNC_ALL) {
5359 trans = btrfs_join_transaction_nolock(root);
5361 trans = btrfs_join_transaction(root);
5363 return PTR_ERR(trans);
5364 ret = btrfs_commit_transaction(trans, root);
5370 * This is somewhat expensive, updating the tree every time the
5371 * inode changes. But, it is most likely to find the inode in cache.
5372 * FIXME, needs more benchmarking...there are no reasons other than performance
5373 * to keep or drop this code.
5375 static int btrfs_dirty_inode(struct inode *inode)
5377 struct btrfs_root *root = BTRFS_I(inode)->root;
5378 struct btrfs_trans_handle *trans;
5381 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5384 trans = btrfs_join_transaction(root);
5386 return PTR_ERR(trans);
5388 ret = btrfs_update_inode(trans, root, inode);
5389 if (ret && ret == -ENOSPC) {
5390 /* whoops, lets try again with the full transaction */
5391 btrfs_end_transaction(trans, root);
5392 trans = btrfs_start_transaction(root, 1);
5394 return PTR_ERR(trans);
5396 ret = btrfs_update_inode(trans, root, inode);
5398 btrfs_end_transaction(trans, root);
5399 if (BTRFS_I(inode)->delayed_node)
5400 btrfs_balance_delayed_items(root);
5406 * This is a copy of file_update_time. We need this so we can return error on
5407 * ENOSPC for updating the inode in the case of file write and mmap writes.
5409 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5412 struct btrfs_root *root = BTRFS_I(inode)->root;
5414 if (btrfs_root_readonly(root))
5417 if (flags & S_VERSION)
5418 inode_inc_iversion(inode);
5419 if (flags & S_CTIME)
5420 inode->i_ctime = *now;
5421 if (flags & S_MTIME)
5422 inode->i_mtime = *now;
5423 if (flags & S_ATIME)
5424 inode->i_atime = *now;
5425 return btrfs_dirty_inode(inode);
5429 * find the highest existing sequence number in a directory
5430 * and then set the in-memory index_cnt variable to reflect
5431 * free sequence numbers
5433 static int btrfs_set_inode_index_count(struct inode *inode)
5435 struct btrfs_root *root = BTRFS_I(inode)->root;
5436 struct btrfs_key key, found_key;
5437 struct btrfs_path *path;
5438 struct extent_buffer *leaf;
5441 key.objectid = btrfs_ino(inode);
5442 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5443 key.offset = (u64)-1;
5445 path = btrfs_alloc_path();
5449 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5452 /* FIXME: we should be able to handle this */
5458 * MAGIC NUMBER EXPLANATION:
5459 * since we search a directory based on f_pos we have to start at 2
5460 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5461 * else has to start at 2
5463 if (path->slots[0] == 0) {
5464 BTRFS_I(inode)->index_cnt = 2;
5470 leaf = path->nodes[0];
5471 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5473 if (found_key.objectid != btrfs_ino(inode) ||
5474 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5475 BTRFS_I(inode)->index_cnt = 2;
5479 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5481 btrfs_free_path(path);
5486 * helper to find a free sequence number in a given directory. This current
5487 * code is very simple, later versions will do smarter things in the btree
5489 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5493 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5494 ret = btrfs_inode_delayed_dir_index_count(dir);
5496 ret = btrfs_set_inode_index_count(dir);
5502 *index = BTRFS_I(dir)->index_cnt;
5503 BTRFS_I(dir)->index_cnt++;
5508 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5509 struct btrfs_root *root,
5511 const char *name, int name_len,
5512 u64 ref_objectid, u64 objectid,
5513 umode_t mode, u64 *index)
5515 struct inode *inode;
5516 struct btrfs_inode_item *inode_item;
5517 struct btrfs_key *location;
5518 struct btrfs_path *path;
5519 struct btrfs_inode_ref *ref;
5520 struct btrfs_key key[2];
5525 path = btrfs_alloc_path();
5527 return ERR_PTR(-ENOMEM);
5529 inode = new_inode(root->fs_info->sb);
5531 btrfs_free_path(path);
5532 return ERR_PTR(-ENOMEM);
5536 * we have to initialize this early, so we can reclaim the inode
5537 * number if we fail afterwards in this function.
5539 inode->i_ino = objectid;
5542 trace_btrfs_inode_request(dir);
5544 ret = btrfs_set_inode_index(dir, index);
5546 btrfs_free_path(path);
5548 return ERR_PTR(ret);
5552 * index_cnt is ignored for everything but a dir,
5553 * btrfs_get_inode_index_count has an explanation for the magic
5556 BTRFS_I(inode)->index_cnt = 2;
5557 BTRFS_I(inode)->dir_index = *index;
5558 BTRFS_I(inode)->root = root;
5559 BTRFS_I(inode)->generation = trans->transid;
5560 inode->i_generation = BTRFS_I(inode)->generation;
5563 * We could have gotten an inode number from somebody who was fsynced
5564 * and then removed in this same transaction, so let's just set full
5565 * sync since it will be a full sync anyway and this will blow away the
5566 * old info in the log.
5568 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5570 key[0].objectid = objectid;
5571 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5575 * Start new inodes with an inode_ref. This is slightly more
5576 * efficient for small numbers of hard links since they will
5577 * be packed into one item. Extended refs will kick in if we
5578 * add more hard links than can fit in the ref item.
5580 key[1].objectid = objectid;
5581 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5582 key[1].offset = ref_objectid;
5584 sizes[0] = sizeof(struct btrfs_inode_item);
5585 sizes[1] = name_len + sizeof(*ref);
5587 path->leave_spinning = 1;
5588 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
5592 inode_init_owner(inode, dir, mode);
5593 inode_set_bytes(inode, 0);
5594 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5595 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5596 struct btrfs_inode_item);
5597 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5598 sizeof(*inode_item));
5599 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5601 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5602 struct btrfs_inode_ref);
5603 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5604 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5605 ptr = (unsigned long)(ref + 1);
5606 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5608 btrfs_mark_buffer_dirty(path->nodes[0]);
5609 btrfs_free_path(path);
5611 location = &BTRFS_I(inode)->location;
5612 location->objectid = objectid;
5613 location->offset = 0;
5614 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5616 btrfs_inherit_iflags(inode, dir);
5618 if (S_ISREG(mode)) {
5619 if (btrfs_test_opt(root, NODATASUM))
5620 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5621 if (btrfs_test_opt(root, NODATACOW))
5622 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5623 BTRFS_INODE_NODATASUM;
5626 btrfs_insert_inode_hash(inode);
5627 inode_tree_add(inode);
5629 trace_btrfs_inode_new(inode);
5630 btrfs_set_inode_last_trans(trans, inode);
5632 btrfs_update_root_times(trans, root);
5634 ret = btrfs_inode_inherit_props(trans, inode, dir);
5636 btrfs_err(root->fs_info,
5637 "error inheriting props for ino %llu (root %llu): %d",
5638 btrfs_ino(inode), root->root_key.objectid, ret);
5643 BTRFS_I(dir)->index_cnt--;
5644 btrfs_free_path(path);
5646 return ERR_PTR(ret);
5649 static inline u8 btrfs_inode_type(struct inode *inode)
5651 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5655 * utility function to add 'inode' into 'parent_inode' with
5656 * a give name and a given sequence number.
5657 * if 'add_backref' is true, also insert a backref from the
5658 * inode to the parent directory.
5660 int btrfs_add_link(struct btrfs_trans_handle *trans,
5661 struct inode *parent_inode, struct inode *inode,
5662 const char *name, int name_len, int add_backref, u64 index)
5665 struct btrfs_key key;
5666 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5667 u64 ino = btrfs_ino(inode);
5668 u64 parent_ino = btrfs_ino(parent_inode);
5670 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5671 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5674 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5678 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5679 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5680 key.objectid, root->root_key.objectid,
5681 parent_ino, index, name, name_len);
5682 } else if (add_backref) {
5683 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5687 /* Nothing to clean up yet */
5691 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5693 btrfs_inode_type(inode), index);
5694 if (ret == -EEXIST || ret == -EOVERFLOW)
5697 btrfs_abort_transaction(trans, root, ret);
5701 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5703 inode_inc_iversion(parent_inode);
5704 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5705 ret = btrfs_update_inode(trans, root, parent_inode);
5707 btrfs_abort_transaction(trans, root, ret);
5711 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5714 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5715 key.objectid, root->root_key.objectid,
5716 parent_ino, &local_index, name, name_len);
5718 } else if (add_backref) {
5722 err = btrfs_del_inode_ref(trans, root, name, name_len,
5723 ino, parent_ino, &local_index);
5728 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5729 struct inode *dir, struct dentry *dentry,
5730 struct inode *inode, int backref, u64 index)
5732 int err = btrfs_add_link(trans, dir, inode,
5733 dentry->d_name.name, dentry->d_name.len,
5740 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5741 umode_t mode, dev_t rdev)
5743 struct btrfs_trans_handle *trans;
5744 struct btrfs_root *root = BTRFS_I(dir)->root;
5745 struct inode *inode = NULL;
5751 if (!new_valid_dev(rdev))
5755 * 2 for inode item and ref
5757 * 1 for xattr if selinux is on
5759 trans = btrfs_start_transaction(root, 5);
5761 return PTR_ERR(trans);
5763 err = btrfs_find_free_ino(root, &objectid);
5767 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5768 dentry->d_name.len, btrfs_ino(dir), objectid,
5770 if (IS_ERR(inode)) {
5771 err = PTR_ERR(inode);
5775 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5782 * If the active LSM wants to access the inode during
5783 * d_instantiate it needs these. Smack checks to see
5784 * if the filesystem supports xattrs by looking at the
5788 inode->i_op = &btrfs_special_inode_operations;
5789 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5793 init_special_inode(inode, inode->i_mode, rdev);
5794 btrfs_update_inode(trans, root, inode);
5795 d_instantiate(dentry, inode);
5798 btrfs_end_transaction(trans, root);
5799 btrfs_balance_delayed_items(root);
5800 btrfs_btree_balance_dirty(root);
5802 inode_dec_link_count(inode);
5808 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5809 umode_t mode, bool excl)
5811 struct btrfs_trans_handle *trans;
5812 struct btrfs_root *root = BTRFS_I(dir)->root;
5813 struct inode *inode = NULL;
5814 int drop_inode_on_err = 0;
5820 * 2 for inode item and ref
5822 * 1 for xattr if selinux is on
5824 trans = btrfs_start_transaction(root, 5);
5826 return PTR_ERR(trans);
5828 err = btrfs_find_free_ino(root, &objectid);
5832 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5833 dentry->d_name.len, btrfs_ino(dir), objectid,
5835 if (IS_ERR(inode)) {
5836 err = PTR_ERR(inode);
5839 drop_inode_on_err = 1;
5841 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5845 err = btrfs_update_inode(trans, root, inode);
5850 * If the active LSM wants to access the inode during
5851 * d_instantiate it needs these. Smack checks to see
5852 * if the filesystem supports xattrs by looking at the
5855 inode->i_fop = &btrfs_file_operations;
5856 inode->i_op = &btrfs_file_inode_operations;
5858 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5862 inode->i_mapping->a_ops = &btrfs_aops;
5863 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5864 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5865 d_instantiate(dentry, inode);
5868 btrfs_end_transaction(trans, root);
5869 if (err && drop_inode_on_err) {
5870 inode_dec_link_count(inode);
5873 btrfs_balance_delayed_items(root);
5874 btrfs_btree_balance_dirty(root);
5878 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5879 struct dentry *dentry)
5881 struct btrfs_trans_handle *trans;
5882 struct btrfs_root *root = BTRFS_I(dir)->root;
5883 struct inode *inode = old_dentry->d_inode;
5888 /* do not allow sys_link's with other subvols of the same device */
5889 if (root->objectid != BTRFS_I(inode)->root->objectid)
5892 if (inode->i_nlink >= BTRFS_LINK_MAX)
5895 err = btrfs_set_inode_index(dir, &index);
5900 * 2 items for inode and inode ref
5901 * 2 items for dir items
5902 * 1 item for parent inode
5904 trans = btrfs_start_transaction(root, 5);
5905 if (IS_ERR(trans)) {
5906 err = PTR_ERR(trans);
5910 /* There are several dir indexes for this inode, clear the cache. */
5911 BTRFS_I(inode)->dir_index = 0ULL;
5913 inode_inc_iversion(inode);
5914 inode->i_ctime = CURRENT_TIME;
5916 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5918 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5923 struct dentry *parent = dentry->d_parent;
5924 err = btrfs_update_inode(trans, root, inode);
5927 d_instantiate(dentry, inode);
5928 btrfs_log_new_name(trans, inode, NULL, parent);
5931 btrfs_end_transaction(trans, root);
5932 btrfs_balance_delayed_items(root);
5935 inode_dec_link_count(inode);
5938 btrfs_btree_balance_dirty(root);
5942 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5944 struct inode *inode = NULL;
5945 struct btrfs_trans_handle *trans;
5946 struct btrfs_root *root = BTRFS_I(dir)->root;
5948 int drop_on_err = 0;
5953 * 2 items for inode and ref
5954 * 2 items for dir items
5955 * 1 for xattr if selinux is on
5957 trans = btrfs_start_transaction(root, 5);
5959 return PTR_ERR(trans);
5961 err = btrfs_find_free_ino(root, &objectid);
5965 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5966 dentry->d_name.len, btrfs_ino(dir), objectid,
5967 S_IFDIR | mode, &index);
5968 if (IS_ERR(inode)) {
5969 err = PTR_ERR(inode);
5975 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5979 inode->i_op = &btrfs_dir_inode_operations;
5980 inode->i_fop = &btrfs_dir_file_operations;
5982 btrfs_i_size_write(inode, 0);
5983 err = btrfs_update_inode(trans, root, inode);
5987 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5988 dentry->d_name.len, 0, index);
5992 d_instantiate(dentry, inode);
5996 btrfs_end_transaction(trans, root);
5999 btrfs_balance_delayed_items(root);
6000 btrfs_btree_balance_dirty(root);
6004 /* helper for btfs_get_extent. Given an existing extent in the tree,
6005 * and an extent that you want to insert, deal with overlap and insert
6006 * the new extent into the tree.
6008 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6009 struct extent_map *existing,
6010 struct extent_map *em,
6011 u64 map_start, u64 map_len)
6015 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6016 start_diff = map_start - em->start;
6017 em->start = map_start;
6019 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6020 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6021 em->block_start += start_diff;
6022 em->block_len -= start_diff;
6024 return add_extent_mapping(em_tree, em, 0);
6027 static noinline int uncompress_inline(struct btrfs_path *path,
6028 struct inode *inode, struct page *page,
6029 size_t pg_offset, u64 extent_offset,
6030 struct btrfs_file_extent_item *item)
6033 struct extent_buffer *leaf = path->nodes[0];
6036 unsigned long inline_size;
6040 WARN_ON(pg_offset != 0);
6041 compress_type = btrfs_file_extent_compression(leaf, item);
6042 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6043 inline_size = btrfs_file_extent_inline_item_len(leaf,
6044 btrfs_item_nr(path->slots[0]));
6045 tmp = kmalloc(inline_size, GFP_NOFS);
6048 ptr = btrfs_file_extent_inline_start(item);
6050 read_extent_buffer(leaf, tmp, ptr, inline_size);
6052 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6053 ret = btrfs_decompress(compress_type, tmp, page,
6054 extent_offset, inline_size, max_size);
6056 char *kaddr = kmap_atomic(page);
6057 unsigned long copy_size = min_t(u64,
6058 PAGE_CACHE_SIZE - pg_offset,
6059 max_size - extent_offset);
6060 memset(kaddr + pg_offset, 0, copy_size);
6061 kunmap_atomic(kaddr);
6068 * a bit scary, this does extent mapping from logical file offset to the disk.
6069 * the ugly parts come from merging extents from the disk with the in-ram
6070 * representation. This gets more complex because of the data=ordered code,
6071 * where the in-ram extents might be locked pending data=ordered completion.
6073 * This also copies inline extents directly into the page.
6076 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6077 size_t pg_offset, u64 start, u64 len,
6083 u64 extent_start = 0;
6085 u64 objectid = btrfs_ino(inode);
6087 struct btrfs_path *path = NULL;
6088 struct btrfs_root *root = BTRFS_I(inode)->root;
6089 struct btrfs_file_extent_item *item;
6090 struct extent_buffer *leaf;
6091 struct btrfs_key found_key;
6092 struct extent_map *em = NULL;
6093 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6094 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6095 struct btrfs_trans_handle *trans = NULL;
6099 read_lock(&em_tree->lock);
6100 em = lookup_extent_mapping(em_tree, start, len);
6102 em->bdev = root->fs_info->fs_devices->latest_bdev;
6103 read_unlock(&em_tree->lock);
6106 if (em->start > start || em->start + em->len <= start)
6107 free_extent_map(em);
6108 else if (em->block_start == EXTENT_MAP_INLINE && page)
6109 free_extent_map(em);
6113 em = alloc_extent_map();
6118 em->bdev = root->fs_info->fs_devices->latest_bdev;
6119 em->start = EXTENT_MAP_HOLE;
6120 em->orig_start = EXTENT_MAP_HOLE;
6122 em->block_len = (u64)-1;
6125 path = btrfs_alloc_path();
6131 * Chances are we'll be called again, so go ahead and do
6137 ret = btrfs_lookup_file_extent(trans, root, path,
6138 objectid, start, trans != NULL);
6145 if (path->slots[0] == 0)
6150 leaf = path->nodes[0];
6151 item = btrfs_item_ptr(leaf, path->slots[0],
6152 struct btrfs_file_extent_item);
6153 /* are we inside the extent that was found? */
6154 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6155 found_type = btrfs_key_type(&found_key);
6156 if (found_key.objectid != objectid ||
6157 found_type != BTRFS_EXTENT_DATA_KEY) {
6159 * If we backup past the first extent we want to move forward
6160 * and see if there is an extent in front of us, otherwise we'll
6161 * say there is a hole for our whole search range which can
6168 found_type = btrfs_file_extent_type(leaf, item);
6169 extent_start = found_key.offset;
6170 compress_type = btrfs_file_extent_compression(leaf, item);
6171 if (found_type == BTRFS_FILE_EXTENT_REG ||
6172 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6173 extent_end = extent_start +
6174 btrfs_file_extent_num_bytes(leaf, item);
6175 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6177 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6178 extent_end = ALIGN(extent_start + size, root->sectorsize);
6181 if (start >= extent_end) {
6183 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6184 ret = btrfs_next_leaf(root, path);
6191 leaf = path->nodes[0];
6193 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6194 if (found_key.objectid != objectid ||
6195 found_key.type != BTRFS_EXTENT_DATA_KEY)
6197 if (start + len <= found_key.offset)
6200 em->orig_start = start;
6201 em->len = found_key.offset - start;
6205 em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
6206 if (found_type == BTRFS_FILE_EXTENT_REG ||
6207 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6208 em->start = extent_start;
6209 em->len = extent_end - extent_start;
6210 em->orig_start = extent_start -
6211 btrfs_file_extent_offset(leaf, item);
6212 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6214 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6216 em->block_start = EXTENT_MAP_HOLE;
6219 if (compress_type != BTRFS_COMPRESS_NONE) {
6220 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6221 em->compress_type = compress_type;
6222 em->block_start = bytenr;
6223 em->block_len = em->orig_block_len;
6225 bytenr += btrfs_file_extent_offset(leaf, item);
6226 em->block_start = bytenr;
6227 em->block_len = em->len;
6228 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6229 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6232 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6236 size_t extent_offset;
6239 em->block_start = EXTENT_MAP_INLINE;
6240 if (!page || create) {
6241 em->start = extent_start;
6242 em->len = extent_end - extent_start;
6246 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6247 extent_offset = page_offset(page) + pg_offset - extent_start;
6248 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6249 size - extent_offset);
6250 em->start = extent_start + extent_offset;
6251 em->len = ALIGN(copy_size, root->sectorsize);
6252 em->orig_block_len = em->len;
6253 em->orig_start = em->start;
6254 if (compress_type) {
6255 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6256 em->compress_type = compress_type;
6258 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6259 if (create == 0 && !PageUptodate(page)) {
6260 if (btrfs_file_extent_compression(leaf, item) !=
6261 BTRFS_COMPRESS_NONE) {
6262 ret = uncompress_inline(path, inode, page,
6264 extent_offset, item);
6265 BUG_ON(ret); /* -ENOMEM */
6268 read_extent_buffer(leaf, map + pg_offset, ptr,
6270 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6271 memset(map + pg_offset + copy_size, 0,
6272 PAGE_CACHE_SIZE - pg_offset -
6277 flush_dcache_page(page);
6278 } else if (create && PageUptodate(page)) {
6282 free_extent_map(em);
6285 btrfs_release_path(path);
6286 trans = btrfs_join_transaction(root);
6289 return ERR_CAST(trans);
6293 write_extent_buffer(leaf, map + pg_offset, ptr,
6296 btrfs_mark_buffer_dirty(leaf);
6298 set_extent_uptodate(io_tree, em->start,
6299 extent_map_end(em) - 1, NULL, GFP_NOFS);
6302 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6306 em->orig_start = start;
6309 em->block_start = EXTENT_MAP_HOLE;
6310 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6312 btrfs_release_path(path);
6313 if (em->start > start || extent_map_end(em) <= start) {
6314 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6315 em->start, em->len, start, len);
6321 write_lock(&em_tree->lock);
6322 ret = add_extent_mapping(em_tree, em, 0);
6323 /* it is possible that someone inserted the extent into the tree
6324 * while we had the lock dropped. It is also possible that
6325 * an overlapping map exists in the tree
6327 if (ret == -EEXIST) {
6328 struct extent_map *existing;
6332 existing = lookup_extent_mapping(em_tree, start, len);
6333 if (existing && (existing->start > start ||
6334 existing->start + existing->len <= start)) {
6335 free_extent_map(existing);
6339 existing = lookup_extent_mapping(em_tree, em->start,
6342 err = merge_extent_mapping(em_tree, existing,
6345 free_extent_map(existing);
6347 free_extent_map(em);
6352 free_extent_map(em);
6356 free_extent_map(em);
6361 write_unlock(&em_tree->lock);
6364 trace_btrfs_get_extent(root, em);
6367 btrfs_free_path(path);
6369 ret = btrfs_end_transaction(trans, root);
6374 free_extent_map(em);
6375 return ERR_PTR(err);
6377 BUG_ON(!em); /* Error is always set */
6381 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6382 size_t pg_offset, u64 start, u64 len,
6385 struct extent_map *em;
6386 struct extent_map *hole_em = NULL;
6387 u64 range_start = start;
6393 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6400 * - a pre-alloc extent,
6401 * there might actually be delalloc bytes behind it.
6403 if (em->block_start != EXTENT_MAP_HOLE &&
6404 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6410 /* check to see if we've wrapped (len == -1 or similar) */
6419 /* ok, we didn't find anything, lets look for delalloc */
6420 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6421 end, len, EXTENT_DELALLOC, 1);
6422 found_end = range_start + found;
6423 if (found_end < range_start)
6424 found_end = (u64)-1;
6427 * we didn't find anything useful, return
6428 * the original results from get_extent()
6430 if (range_start > end || found_end <= start) {
6436 /* adjust the range_start to make sure it doesn't
6437 * go backwards from the start they passed in
6439 range_start = max(start, range_start);
6440 found = found_end - range_start;
6443 u64 hole_start = start;
6446 em = alloc_extent_map();
6452 * when btrfs_get_extent can't find anything it
6453 * returns one huge hole
6455 * make sure what it found really fits our range, and
6456 * adjust to make sure it is based on the start from
6460 u64 calc_end = extent_map_end(hole_em);
6462 if (calc_end <= start || (hole_em->start > end)) {
6463 free_extent_map(hole_em);
6466 hole_start = max(hole_em->start, start);
6467 hole_len = calc_end - hole_start;
6471 if (hole_em && range_start > hole_start) {
6472 /* our hole starts before our delalloc, so we
6473 * have to return just the parts of the hole
6474 * that go until the delalloc starts
6476 em->len = min(hole_len,
6477 range_start - hole_start);
6478 em->start = hole_start;
6479 em->orig_start = hole_start;
6481 * don't adjust block start at all,
6482 * it is fixed at EXTENT_MAP_HOLE
6484 em->block_start = hole_em->block_start;
6485 em->block_len = hole_len;
6486 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6487 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6489 em->start = range_start;
6491 em->orig_start = range_start;
6492 em->block_start = EXTENT_MAP_DELALLOC;
6493 em->block_len = found;
6495 } else if (hole_em) {
6500 free_extent_map(hole_em);
6502 free_extent_map(em);
6503 return ERR_PTR(err);
6508 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6511 struct btrfs_root *root = BTRFS_I(inode)->root;
6512 struct extent_map *em;
6513 struct btrfs_key ins;
6517 alloc_hint = get_extent_allocation_hint(inode, start, len);
6518 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
6519 alloc_hint, &ins, 1);
6521 return ERR_PTR(ret);
6523 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6524 ins.offset, ins.offset, ins.offset, 0);
6526 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6530 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6531 ins.offset, ins.offset, 0);
6533 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6534 free_extent_map(em);
6535 return ERR_PTR(ret);
6542 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6543 * block must be cow'd
6545 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6546 u64 *orig_start, u64 *orig_block_len,
6549 struct btrfs_trans_handle *trans;
6550 struct btrfs_path *path;
6552 struct extent_buffer *leaf;
6553 struct btrfs_root *root = BTRFS_I(inode)->root;
6554 struct btrfs_file_extent_item *fi;
6555 struct btrfs_key key;
6562 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6564 path = btrfs_alloc_path();
6568 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
6573 slot = path->slots[0];
6576 /* can't find the item, must cow */
6583 leaf = path->nodes[0];
6584 btrfs_item_key_to_cpu(leaf, &key, slot);
6585 if (key.objectid != btrfs_ino(inode) ||
6586 key.type != BTRFS_EXTENT_DATA_KEY) {
6587 /* not our file or wrong item type, must cow */
6591 if (key.offset > offset) {
6592 /* Wrong offset, must cow */
6596 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6597 found_type = btrfs_file_extent_type(leaf, fi);
6598 if (found_type != BTRFS_FILE_EXTENT_REG &&
6599 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6600 /* not a regular extent, must cow */
6604 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6607 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6608 if (extent_end <= offset)
6611 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6612 if (disk_bytenr == 0)
6615 if (btrfs_file_extent_compression(leaf, fi) ||
6616 btrfs_file_extent_encryption(leaf, fi) ||
6617 btrfs_file_extent_other_encoding(leaf, fi))
6620 backref_offset = btrfs_file_extent_offset(leaf, fi);
6623 *orig_start = key.offset - backref_offset;
6624 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6625 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6628 if (btrfs_extent_readonly(root, disk_bytenr))
6630 btrfs_release_path(path);
6633 * look for other files referencing this extent, if we
6634 * find any we must cow
6636 trans = btrfs_join_transaction(root);
6637 if (IS_ERR(trans)) {
6642 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6643 key.offset - backref_offset, disk_bytenr);
6644 btrfs_end_transaction(trans, root);
6651 * adjust disk_bytenr and num_bytes to cover just the bytes
6652 * in this extent we are about to write. If there
6653 * are any csums in that range we have to cow in order
6654 * to keep the csums correct
6656 disk_bytenr += backref_offset;
6657 disk_bytenr += offset - key.offset;
6658 num_bytes = min(offset + *len, extent_end) - offset;
6659 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6662 * all of the above have passed, it is safe to overwrite this extent
6668 btrfs_free_path(path);
6672 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6673 struct extent_state **cached_state, int writing)
6675 struct btrfs_ordered_extent *ordered;
6679 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6682 * We're concerned with the entire range that we're going to be
6683 * doing DIO to, so we need to make sure theres no ordered
6684 * extents in this range.
6686 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6687 lockend - lockstart + 1);
6690 * We need to make sure there are no buffered pages in this
6691 * range either, we could have raced between the invalidate in
6692 * generic_file_direct_write and locking the extent. The
6693 * invalidate needs to happen so that reads after a write do not
6696 if (!ordered && (!writing ||
6697 !test_range_bit(&BTRFS_I(inode)->io_tree,
6698 lockstart, lockend, EXTENT_UPTODATE, 0,
6702 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6703 cached_state, GFP_NOFS);
6706 btrfs_start_ordered_extent(inode, ordered, 1);
6707 btrfs_put_ordered_extent(ordered);
6709 /* Screw you mmap */
6710 ret = filemap_write_and_wait_range(inode->i_mapping,
6717 * If we found a page that couldn't be invalidated just
6718 * fall back to buffered.
6720 ret = invalidate_inode_pages2_range(inode->i_mapping,
6721 lockstart >> PAGE_CACHE_SHIFT,
6722 lockend >> PAGE_CACHE_SHIFT);
6733 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6734 u64 len, u64 orig_start,
6735 u64 block_start, u64 block_len,
6736 u64 orig_block_len, u64 ram_bytes,
6739 struct extent_map_tree *em_tree;
6740 struct extent_map *em;
6741 struct btrfs_root *root = BTRFS_I(inode)->root;
6744 em_tree = &BTRFS_I(inode)->extent_tree;
6745 em = alloc_extent_map();
6747 return ERR_PTR(-ENOMEM);
6750 em->orig_start = orig_start;
6751 em->mod_start = start;
6754 em->block_len = block_len;
6755 em->block_start = block_start;
6756 em->bdev = root->fs_info->fs_devices->latest_bdev;
6757 em->orig_block_len = orig_block_len;
6758 em->ram_bytes = ram_bytes;
6759 em->generation = -1;
6760 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6761 if (type == BTRFS_ORDERED_PREALLOC)
6762 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6765 btrfs_drop_extent_cache(inode, em->start,
6766 em->start + em->len - 1, 0);
6767 write_lock(&em_tree->lock);
6768 ret = add_extent_mapping(em_tree, em, 1);
6769 write_unlock(&em_tree->lock);
6770 } while (ret == -EEXIST);
6773 free_extent_map(em);
6774 return ERR_PTR(ret);
6781 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6782 struct buffer_head *bh_result, int create)
6784 struct extent_map *em;
6785 struct btrfs_root *root = BTRFS_I(inode)->root;
6786 struct extent_state *cached_state = NULL;
6787 u64 start = iblock << inode->i_blkbits;
6788 u64 lockstart, lockend;
6789 u64 len = bh_result->b_size;
6790 int unlock_bits = EXTENT_LOCKED;
6794 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6796 len = min_t(u64, len, root->sectorsize);
6799 lockend = start + len - 1;
6802 * If this errors out it's because we couldn't invalidate pagecache for
6803 * this range and we need to fallback to buffered.
6805 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6808 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6815 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6816 * io. INLINE is special, and we could probably kludge it in here, but
6817 * it's still buffered so for safety lets just fall back to the generic
6820 * For COMPRESSED we _have_ to read the entire extent in so we can
6821 * decompress it, so there will be buffering required no matter what we
6822 * do, so go ahead and fallback to buffered.
6824 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6825 * to buffered IO. Don't blame me, this is the price we pay for using
6828 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6829 em->block_start == EXTENT_MAP_INLINE) {
6830 free_extent_map(em);
6835 /* Just a good old fashioned hole, return */
6836 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6837 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6838 free_extent_map(em);
6843 * We don't allocate a new extent in the following cases
6845 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6847 * 2) The extent is marked as PREALLOC. We're good to go here and can
6848 * just use the extent.
6852 len = min(len, em->len - (start - em->start));
6853 lockstart = start + len;
6857 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6858 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6859 em->block_start != EXTENT_MAP_HOLE)) {
6862 u64 block_start, orig_start, orig_block_len, ram_bytes;
6864 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6865 type = BTRFS_ORDERED_PREALLOC;
6867 type = BTRFS_ORDERED_NOCOW;
6868 len = min(len, em->len - (start - em->start));
6869 block_start = em->block_start + (start - em->start);
6871 if (can_nocow_extent(inode, start, &len, &orig_start,
6872 &orig_block_len, &ram_bytes) == 1) {
6873 if (type == BTRFS_ORDERED_PREALLOC) {
6874 free_extent_map(em);
6875 em = create_pinned_em(inode, start, len,
6884 ret = btrfs_add_ordered_extent_dio(inode, start,
6885 block_start, len, len, type);
6887 free_extent_map(em);
6895 * this will cow the extent, reset the len in case we changed
6898 len = bh_result->b_size;
6899 free_extent_map(em);
6900 em = btrfs_new_extent_direct(inode, start, len);
6905 len = min(len, em->len - (start - em->start));
6907 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6909 bh_result->b_size = len;
6910 bh_result->b_bdev = em->bdev;
6911 set_buffer_mapped(bh_result);
6913 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6914 set_buffer_new(bh_result);
6917 * Need to update the i_size under the extent lock so buffered
6918 * readers will get the updated i_size when we unlock.
6920 if (start + len > i_size_read(inode))
6921 i_size_write(inode, start + len);
6923 spin_lock(&BTRFS_I(inode)->lock);
6924 BTRFS_I(inode)->outstanding_extents++;
6925 spin_unlock(&BTRFS_I(inode)->lock);
6927 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6928 lockstart + len - 1, EXTENT_DELALLOC, NULL,
6929 &cached_state, GFP_NOFS);
6934 * In the case of write we need to clear and unlock the entire range,
6935 * in the case of read we need to unlock only the end area that we
6936 * aren't using if there is any left over space.
6938 if (lockstart < lockend) {
6939 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6940 lockend, unlock_bits, 1, 0,
6941 &cached_state, GFP_NOFS);
6943 free_extent_state(cached_state);
6946 free_extent_map(em);
6951 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6952 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6956 static void btrfs_endio_direct_read(struct bio *bio, int err)
6958 struct btrfs_dio_private *dip = bio->bi_private;
6959 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6960 struct bio_vec *bvec = bio->bi_io_vec;
6961 struct inode *inode = dip->inode;
6962 struct btrfs_root *root = BTRFS_I(inode)->root;
6963 struct bio *dio_bio;
6964 u32 *csums = (u32 *)dip->csum;
6968 start = dip->logical_offset;
6970 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6971 struct page *page = bvec->bv_page;
6974 unsigned long flags;
6976 local_irq_save(flags);
6977 kaddr = kmap_atomic(page);
6978 csum = btrfs_csum_data(kaddr + bvec->bv_offset,
6979 csum, bvec->bv_len);
6980 btrfs_csum_final(csum, (char *)&csum);
6981 kunmap_atomic(kaddr);
6982 local_irq_restore(flags);
6984 flush_dcache_page(bvec->bv_page);
6985 if (csum != csums[index]) {
6986 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
6987 btrfs_ino(inode), start, csum,
6993 start += bvec->bv_len;
6996 } while (bvec <= bvec_end);
6998 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6999 dip->logical_offset + dip->bytes - 1);
7000 dio_bio = dip->dio_bio;
7004 /* If we had a csum failure make sure to clear the uptodate flag */
7006 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7007 dio_end_io(dio_bio, err);
7011 static void btrfs_endio_direct_write(struct bio *bio, int err)
7013 struct btrfs_dio_private *dip = bio->bi_private;
7014 struct inode *inode = dip->inode;
7015 struct btrfs_root *root = BTRFS_I(inode)->root;
7016 struct btrfs_ordered_extent *ordered = NULL;
7017 u64 ordered_offset = dip->logical_offset;
7018 u64 ordered_bytes = dip->bytes;
7019 struct bio *dio_bio;
7025 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7027 ordered_bytes, !err);
7031 ordered->work.func = finish_ordered_fn;
7032 ordered->work.flags = 0;
7033 btrfs_queue_worker(&root->fs_info->endio_write_workers,
7037 * our bio might span multiple ordered extents. If we haven't
7038 * completed the accounting for the whole dio, go back and try again
7040 if (ordered_offset < dip->logical_offset + dip->bytes) {
7041 ordered_bytes = dip->logical_offset + dip->bytes -
7047 dio_bio = dip->dio_bio;
7051 /* If we had an error make sure to clear the uptodate flag */
7053 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7054 dio_end_io(dio_bio, err);
7058 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7059 struct bio *bio, int mirror_num,
7060 unsigned long bio_flags, u64 offset)
7063 struct btrfs_root *root = BTRFS_I(inode)->root;
7064 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7065 BUG_ON(ret); /* -ENOMEM */
7069 static void btrfs_end_dio_bio(struct bio *bio, int err)
7071 struct btrfs_dio_private *dip = bio->bi_private;
7074 btrfs_err(BTRFS_I(dip->inode)->root->fs_info,
7075 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
7076 btrfs_ino(dip->inode), bio->bi_rw,
7077 (unsigned long long)bio->bi_sector, bio->bi_size, err);
7081 * before atomic variable goto zero, we must make sure
7082 * dip->errors is perceived to be set.
7084 smp_mb__before_atomic_dec();
7087 /* if there are more bios still pending for this dio, just exit */
7088 if (!atomic_dec_and_test(&dip->pending_bios))
7092 bio_io_error(dip->orig_bio);
7094 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
7095 bio_endio(dip->orig_bio, 0);
7101 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7102 u64 first_sector, gfp_t gfp_flags)
7104 int nr_vecs = bio_get_nr_vecs(bdev);
7105 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7108 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7109 int rw, u64 file_offset, int skip_sum,
7112 struct btrfs_dio_private *dip = bio->bi_private;
7113 int write = rw & REQ_WRITE;
7114 struct btrfs_root *root = BTRFS_I(inode)->root;
7118 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7123 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
7131 if (write && async_submit) {
7132 ret = btrfs_wq_submit_bio(root->fs_info,
7133 inode, rw, bio, 0, 0,
7135 __btrfs_submit_bio_start_direct_io,
7136 __btrfs_submit_bio_done);
7140 * If we aren't doing async submit, calculate the csum of the
7143 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7146 } else if (!skip_sum) {
7147 ret = btrfs_lookup_bio_sums_dio(root, inode, dip, bio,
7154 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7160 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7163 struct inode *inode = dip->inode;
7164 struct btrfs_root *root = BTRFS_I(inode)->root;
7166 struct bio *orig_bio = dip->orig_bio;
7167 struct bio_vec *bvec = orig_bio->bi_io_vec;
7168 u64 start_sector = orig_bio->bi_sector;
7169 u64 file_offset = dip->logical_offset;
7174 int async_submit = 0;
7176 map_length = orig_bio->bi_size;
7177 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7178 &map_length, NULL, 0);
7184 if (map_length >= orig_bio->bi_size) {
7189 /* async crcs make it difficult to collect full stripe writes. */
7190 if (btrfs_get_alloc_profile(root, 1) &
7191 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7196 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7199 bio->bi_private = dip;
7200 bio->bi_end_io = btrfs_end_dio_bio;
7201 atomic_inc(&dip->pending_bios);
7203 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7204 if (unlikely(map_length < submit_len + bvec->bv_len ||
7205 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7206 bvec->bv_offset) < bvec->bv_len)) {
7208 * inc the count before we submit the bio so
7209 * we know the end IO handler won't happen before
7210 * we inc the count. Otherwise, the dip might get freed
7211 * before we're done setting it up
7213 atomic_inc(&dip->pending_bios);
7214 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7215 file_offset, skip_sum,
7219 atomic_dec(&dip->pending_bios);
7223 start_sector += submit_len >> 9;
7224 file_offset += submit_len;
7229 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7230 start_sector, GFP_NOFS);
7233 bio->bi_private = dip;
7234 bio->bi_end_io = btrfs_end_dio_bio;
7236 map_length = orig_bio->bi_size;
7237 ret = btrfs_map_block(root->fs_info, rw,
7239 &map_length, NULL, 0);
7245 submit_len += bvec->bv_len;
7252 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7261 * before atomic variable goto zero, we must
7262 * make sure dip->errors is perceived to be set.
7264 smp_mb__before_atomic_dec();
7265 if (atomic_dec_and_test(&dip->pending_bios))
7266 bio_io_error(dip->orig_bio);
7268 /* bio_end_io() will handle error, so we needn't return it */
7272 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7273 struct inode *inode, loff_t file_offset)
7275 struct btrfs_root *root = BTRFS_I(inode)->root;
7276 struct btrfs_dio_private *dip;
7280 int write = rw & REQ_WRITE;
7284 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7286 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7292 if (!skip_sum && !write) {
7293 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
7294 sum_len = dio_bio->bi_size >> inode->i_sb->s_blocksize_bits;
7295 sum_len *= csum_size;
7300 dip = kmalloc(sizeof(*dip) + sum_len, GFP_NOFS);
7306 dip->private = dio_bio->bi_private;
7308 dip->logical_offset = file_offset;
7309 dip->bytes = dio_bio->bi_size;
7310 dip->disk_bytenr = (u64)dio_bio->bi_sector << 9;
7311 io_bio->bi_private = dip;
7313 dip->orig_bio = io_bio;
7314 dip->dio_bio = dio_bio;
7315 atomic_set(&dip->pending_bios, 0);
7318 io_bio->bi_end_io = btrfs_endio_direct_write;
7320 io_bio->bi_end_io = btrfs_endio_direct_read;
7322 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7331 * If this is a write, we need to clean up the reserved space and kill
7332 * the ordered extent.
7335 struct btrfs_ordered_extent *ordered;
7336 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7337 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7338 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7339 btrfs_free_reserved_extent(root, ordered->start,
7341 btrfs_put_ordered_extent(ordered);
7342 btrfs_put_ordered_extent(ordered);
7344 bio_endio(dio_bio, ret);
7347 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7348 const struct iovec *iov, loff_t offset,
7349 unsigned long nr_segs)
7355 unsigned blocksize_mask = root->sectorsize - 1;
7356 ssize_t retval = -EINVAL;
7357 loff_t end = offset;
7359 if (offset & blocksize_mask)
7362 /* Check the memory alignment. Blocks cannot straddle pages */
7363 for (seg = 0; seg < nr_segs; seg++) {
7364 addr = (unsigned long)iov[seg].iov_base;
7365 size = iov[seg].iov_len;
7367 if ((addr & blocksize_mask) || (size & blocksize_mask))
7370 /* If this is a write we don't need to check anymore */
7375 * Check to make sure we don't have duplicate iov_base's in this
7376 * iovec, if so return EINVAL, otherwise we'll get csum errors
7377 * when reading back.
7379 for (i = seg + 1; i < nr_segs; i++) {
7380 if (iov[seg].iov_base == iov[i].iov_base)
7389 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7390 const struct iovec *iov, loff_t offset,
7391 unsigned long nr_segs)
7393 struct file *file = iocb->ki_filp;
7394 struct inode *inode = file->f_mapping->host;
7398 bool relock = false;
7401 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7405 atomic_inc(&inode->i_dio_count);
7406 smp_mb__after_atomic_inc();
7409 * The generic stuff only does filemap_write_and_wait_range, which isn't
7410 * enough if we've written compressed pages to this area, so we need to
7411 * call btrfs_wait_ordered_range to make absolutely sure that any
7412 * outstanding dirty pages are on disk.
7414 count = iov_length(iov, nr_segs);
7415 ret = btrfs_wait_ordered_range(inode, offset, count);
7421 * If the write DIO is beyond the EOF, we need update
7422 * the isize, but it is protected by i_mutex. So we can
7423 * not unlock the i_mutex at this case.
7425 if (offset + count <= inode->i_size) {
7426 mutex_unlock(&inode->i_mutex);
7429 ret = btrfs_delalloc_reserve_space(inode, count);
7432 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7433 &BTRFS_I(inode)->runtime_flags))) {
7434 inode_dio_done(inode);
7435 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7439 ret = __blockdev_direct_IO(rw, iocb, inode,
7440 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7441 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7442 btrfs_submit_direct, flags);
7444 if (ret < 0 && ret != -EIOCBQUEUED)
7445 btrfs_delalloc_release_space(inode, count);
7446 else if (ret >= 0 && (size_t)ret < count)
7447 btrfs_delalloc_release_space(inode,
7448 count - (size_t)ret);
7450 btrfs_delalloc_release_metadata(inode, 0);
7454 inode_dio_done(inode);
7456 mutex_lock(&inode->i_mutex);
7461 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7463 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7464 __u64 start, __u64 len)
7468 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7472 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7475 int btrfs_readpage(struct file *file, struct page *page)
7477 struct extent_io_tree *tree;
7478 tree = &BTRFS_I(page->mapping->host)->io_tree;
7479 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7482 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7484 struct extent_io_tree *tree;
7487 if (current->flags & PF_MEMALLOC) {
7488 redirty_page_for_writepage(wbc, page);
7492 tree = &BTRFS_I(page->mapping->host)->io_tree;
7493 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7496 static int btrfs_writepages(struct address_space *mapping,
7497 struct writeback_control *wbc)
7499 struct extent_io_tree *tree;
7501 tree = &BTRFS_I(mapping->host)->io_tree;
7502 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7506 btrfs_readpages(struct file *file, struct address_space *mapping,
7507 struct list_head *pages, unsigned nr_pages)
7509 struct extent_io_tree *tree;
7510 tree = &BTRFS_I(mapping->host)->io_tree;
7511 return extent_readpages(tree, mapping, pages, nr_pages,
7514 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7516 struct extent_io_tree *tree;
7517 struct extent_map_tree *map;
7520 tree = &BTRFS_I(page->mapping->host)->io_tree;
7521 map = &BTRFS_I(page->mapping->host)->extent_tree;
7522 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7524 ClearPagePrivate(page);
7525 set_page_private(page, 0);
7526 page_cache_release(page);
7531 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7533 if (PageWriteback(page) || PageDirty(page))
7535 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7538 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
7539 unsigned int length)
7541 struct inode *inode = page->mapping->host;
7542 struct extent_io_tree *tree;
7543 struct btrfs_ordered_extent *ordered;
7544 struct extent_state *cached_state = NULL;
7545 u64 page_start = page_offset(page);
7546 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7547 int inode_evicting = inode->i_state & I_FREEING;
7550 * we have the page locked, so new writeback can't start,
7551 * and the dirty bit won't be cleared while we are here.
7553 * Wait for IO on this page so that we can safely clear
7554 * the PagePrivate2 bit and do ordered accounting
7556 wait_on_page_writeback(page);
7558 tree = &BTRFS_I(inode)->io_tree;
7560 btrfs_releasepage(page, GFP_NOFS);
7564 if (!inode_evicting)
7565 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7566 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7569 * IO on this page will never be started, so we need
7570 * to account for any ordered extents now
7572 if (!inode_evicting)
7573 clear_extent_bit(tree, page_start, page_end,
7574 EXTENT_DIRTY | EXTENT_DELALLOC |
7575 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7576 EXTENT_DEFRAG, 1, 0, &cached_state,
7579 * whoever cleared the private bit is responsible
7580 * for the finish_ordered_io
7582 if (TestClearPagePrivate2(page)) {
7583 struct btrfs_ordered_inode_tree *tree;
7586 tree = &BTRFS_I(inode)->ordered_tree;
7588 spin_lock_irq(&tree->lock);
7589 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
7590 new_len = page_start - ordered->file_offset;
7591 if (new_len < ordered->truncated_len)
7592 ordered->truncated_len = new_len;
7593 spin_unlock_irq(&tree->lock);
7595 if (btrfs_dec_test_ordered_pending(inode, &ordered,
7597 PAGE_CACHE_SIZE, 1))
7598 btrfs_finish_ordered_io(ordered);
7600 btrfs_put_ordered_extent(ordered);
7601 if (!inode_evicting) {
7602 cached_state = NULL;
7603 lock_extent_bits(tree, page_start, page_end, 0,
7608 if (!inode_evicting) {
7609 clear_extent_bit(tree, page_start, page_end,
7610 EXTENT_LOCKED | EXTENT_DIRTY |
7611 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
7612 EXTENT_DEFRAG, 1, 1,
7613 &cached_state, GFP_NOFS);
7615 __btrfs_releasepage(page, GFP_NOFS);
7618 ClearPageChecked(page);
7619 if (PagePrivate(page)) {
7620 ClearPagePrivate(page);
7621 set_page_private(page, 0);
7622 page_cache_release(page);
7627 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7628 * called from a page fault handler when a page is first dirtied. Hence we must
7629 * be careful to check for EOF conditions here. We set the page up correctly
7630 * for a written page which means we get ENOSPC checking when writing into
7631 * holes and correct delalloc and unwritten extent mapping on filesystems that
7632 * support these features.
7634 * We are not allowed to take the i_mutex here so we have to play games to
7635 * protect against truncate races as the page could now be beyond EOF. Because
7636 * vmtruncate() writes the inode size before removing pages, once we have the
7637 * page lock we can determine safely if the page is beyond EOF. If it is not
7638 * beyond EOF, then the page is guaranteed safe against truncation until we
7641 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7643 struct page *page = vmf->page;
7644 struct inode *inode = file_inode(vma->vm_file);
7645 struct btrfs_root *root = BTRFS_I(inode)->root;
7646 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7647 struct btrfs_ordered_extent *ordered;
7648 struct extent_state *cached_state = NULL;
7650 unsigned long zero_start;
7657 sb_start_pagefault(inode->i_sb);
7658 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7660 ret = file_update_time(vma->vm_file);
7666 else /* -ENOSPC, -EIO, etc */
7667 ret = VM_FAULT_SIGBUS;
7673 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7676 size = i_size_read(inode);
7677 page_start = page_offset(page);
7678 page_end = page_start + PAGE_CACHE_SIZE - 1;
7680 if ((page->mapping != inode->i_mapping) ||
7681 (page_start >= size)) {
7682 /* page got truncated out from underneath us */
7685 wait_on_page_writeback(page);
7687 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7688 set_page_extent_mapped(page);
7691 * we can't set the delalloc bits if there are pending ordered
7692 * extents. Drop our locks and wait for them to finish
7694 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7696 unlock_extent_cached(io_tree, page_start, page_end,
7697 &cached_state, GFP_NOFS);
7699 btrfs_start_ordered_extent(inode, ordered, 1);
7700 btrfs_put_ordered_extent(ordered);
7705 * XXX - page_mkwrite gets called every time the page is dirtied, even
7706 * if it was already dirty, so for space accounting reasons we need to
7707 * clear any delalloc bits for the range we are fixing to save. There
7708 * is probably a better way to do this, but for now keep consistent with
7709 * prepare_pages in the normal write path.
7711 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7712 EXTENT_DIRTY | EXTENT_DELALLOC |
7713 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7714 0, 0, &cached_state, GFP_NOFS);
7716 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7719 unlock_extent_cached(io_tree, page_start, page_end,
7720 &cached_state, GFP_NOFS);
7721 ret = VM_FAULT_SIGBUS;
7726 /* page is wholly or partially inside EOF */
7727 if (page_start + PAGE_CACHE_SIZE > size)
7728 zero_start = size & ~PAGE_CACHE_MASK;
7730 zero_start = PAGE_CACHE_SIZE;
7732 if (zero_start != PAGE_CACHE_SIZE) {
7734 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7735 flush_dcache_page(page);
7738 ClearPageChecked(page);
7739 set_page_dirty(page);
7740 SetPageUptodate(page);
7742 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7743 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7744 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7746 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7750 sb_end_pagefault(inode->i_sb);
7751 return VM_FAULT_LOCKED;
7755 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7757 sb_end_pagefault(inode->i_sb);
7761 static int btrfs_truncate(struct inode *inode)
7763 struct btrfs_root *root = BTRFS_I(inode)->root;
7764 struct btrfs_block_rsv *rsv;
7767 struct btrfs_trans_handle *trans;
7768 u64 mask = root->sectorsize - 1;
7769 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7771 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
7777 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7778 * 3 things going on here
7780 * 1) We need to reserve space for our orphan item and the space to
7781 * delete our orphan item. Lord knows we don't want to have a dangling
7782 * orphan item because we didn't reserve space to remove it.
7784 * 2) We need to reserve space to update our inode.
7786 * 3) We need to have something to cache all the space that is going to
7787 * be free'd up by the truncate operation, but also have some slack
7788 * space reserved in case it uses space during the truncate (thank you
7789 * very much snapshotting).
7791 * And we need these to all be seperate. The fact is we can use alot of
7792 * space doing the truncate, and we have no earthly idea how much space
7793 * we will use, so we need the truncate reservation to be seperate so it
7794 * doesn't end up using space reserved for updating the inode or
7795 * removing the orphan item. We also need to be able to stop the
7796 * transaction and start a new one, which means we need to be able to
7797 * update the inode several times, and we have no idea of knowing how
7798 * many times that will be, so we can't just reserve 1 item for the
7799 * entirety of the opration, so that has to be done seperately as well.
7800 * Then there is the orphan item, which does indeed need to be held on
7801 * to for the whole operation, and we need nobody to touch this reserved
7802 * space except the orphan code.
7804 * So that leaves us with
7806 * 1) root->orphan_block_rsv - for the orphan deletion.
7807 * 2) rsv - for the truncate reservation, which we will steal from the
7808 * transaction reservation.
7809 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7810 * updating the inode.
7812 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7815 rsv->size = min_size;
7819 * 1 for the truncate slack space
7820 * 1 for updating the inode.
7822 trans = btrfs_start_transaction(root, 2);
7823 if (IS_ERR(trans)) {
7824 err = PTR_ERR(trans);
7828 /* Migrate the slack space for the truncate to our reserve */
7829 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7834 * setattr is responsible for setting the ordered_data_close flag,
7835 * but that is only tested during the last file release. That
7836 * could happen well after the next commit, leaving a great big
7837 * window where new writes may get lost if someone chooses to write
7838 * to this file after truncating to zero
7840 * The inode doesn't have any dirty data here, and so if we commit
7841 * this is a noop. If someone immediately starts writing to the inode
7842 * it is very likely we'll catch some of their writes in this
7843 * transaction, and the commit will find this file on the ordered
7844 * data list with good things to send down.
7846 * This is a best effort solution, there is still a window where
7847 * using truncate to replace the contents of the file will
7848 * end up with a zero length file after a crash.
7850 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7851 &BTRFS_I(inode)->runtime_flags))
7852 btrfs_add_ordered_operation(trans, root, inode);
7855 * So if we truncate and then write and fsync we normally would just
7856 * write the extents that changed, which is a problem if we need to
7857 * first truncate that entire inode. So set this flag so we write out
7858 * all of the extents in the inode to the sync log so we're completely
7861 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7862 trans->block_rsv = rsv;
7865 ret = btrfs_truncate_inode_items(trans, root, inode,
7867 BTRFS_EXTENT_DATA_KEY);
7868 if (ret != -ENOSPC) {
7873 trans->block_rsv = &root->fs_info->trans_block_rsv;
7874 ret = btrfs_update_inode(trans, root, inode);
7880 btrfs_end_transaction(trans, root);
7881 btrfs_btree_balance_dirty(root);
7883 trans = btrfs_start_transaction(root, 2);
7884 if (IS_ERR(trans)) {
7885 ret = err = PTR_ERR(trans);
7890 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7892 BUG_ON(ret); /* shouldn't happen */
7893 trans->block_rsv = rsv;
7896 if (ret == 0 && inode->i_nlink > 0) {
7897 trans->block_rsv = root->orphan_block_rsv;
7898 ret = btrfs_orphan_del(trans, inode);
7904 trans->block_rsv = &root->fs_info->trans_block_rsv;
7905 ret = btrfs_update_inode(trans, root, inode);
7909 ret = btrfs_end_transaction(trans, root);
7910 btrfs_btree_balance_dirty(root);
7914 btrfs_free_block_rsv(root, rsv);
7923 * create a new subvolume directory/inode (helper for the ioctl).
7925 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7926 struct btrfs_root *new_root,
7927 struct btrfs_root *parent_root,
7930 struct inode *inode;
7934 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7935 new_dirid, new_dirid,
7936 S_IFDIR | (~current_umask() & S_IRWXUGO),
7939 return PTR_ERR(inode);
7940 inode->i_op = &btrfs_dir_inode_operations;
7941 inode->i_fop = &btrfs_dir_file_operations;
7943 set_nlink(inode, 1);
7944 btrfs_i_size_write(inode, 0);
7946 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
7948 btrfs_err(new_root->fs_info,
7949 "error inheriting subvolume %llu properties: %d\n",
7950 new_root->root_key.objectid, err);
7952 err = btrfs_update_inode(trans, new_root, inode);
7958 struct inode *btrfs_alloc_inode(struct super_block *sb)
7960 struct btrfs_inode *ei;
7961 struct inode *inode;
7963 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7970 ei->last_sub_trans = 0;
7971 ei->logged_trans = 0;
7972 ei->delalloc_bytes = 0;
7973 ei->disk_i_size = 0;
7976 ei->index_cnt = (u64)-1;
7978 ei->last_unlink_trans = 0;
7979 ei->last_log_commit = 0;
7981 spin_lock_init(&ei->lock);
7982 ei->outstanding_extents = 0;
7983 ei->reserved_extents = 0;
7985 ei->runtime_flags = 0;
7986 ei->force_compress = BTRFS_COMPRESS_NONE;
7988 ei->delayed_node = NULL;
7990 inode = &ei->vfs_inode;
7991 extent_map_tree_init(&ei->extent_tree);
7992 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7993 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7994 ei->io_tree.track_uptodate = 1;
7995 ei->io_failure_tree.track_uptodate = 1;
7996 atomic_set(&ei->sync_writers, 0);
7997 mutex_init(&ei->log_mutex);
7998 mutex_init(&ei->delalloc_mutex);
7999 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8000 INIT_LIST_HEAD(&ei->delalloc_inodes);
8001 INIT_LIST_HEAD(&ei->ordered_operations);
8002 RB_CLEAR_NODE(&ei->rb_node);
8007 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8008 void btrfs_test_destroy_inode(struct inode *inode)
8010 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8011 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8015 static void btrfs_i_callback(struct rcu_head *head)
8017 struct inode *inode = container_of(head, struct inode, i_rcu);
8018 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8021 void btrfs_destroy_inode(struct inode *inode)
8023 struct btrfs_ordered_extent *ordered;
8024 struct btrfs_root *root = BTRFS_I(inode)->root;
8026 WARN_ON(!hlist_empty(&inode->i_dentry));
8027 WARN_ON(inode->i_data.nrpages);
8028 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8029 WARN_ON(BTRFS_I(inode)->reserved_extents);
8030 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8031 WARN_ON(BTRFS_I(inode)->csum_bytes);
8034 * This can happen where we create an inode, but somebody else also
8035 * created the same inode and we need to destroy the one we already
8042 * Make sure we're properly removed from the ordered operation
8046 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
8047 spin_lock(&root->fs_info->ordered_root_lock);
8048 list_del_init(&BTRFS_I(inode)->ordered_operations);
8049 spin_unlock(&root->fs_info->ordered_root_lock);
8052 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8053 &BTRFS_I(inode)->runtime_flags)) {
8054 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
8056 atomic_dec(&root->orphan_inodes);
8060 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8064 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
8065 ordered->file_offset, ordered->len);
8066 btrfs_remove_ordered_extent(inode, ordered);
8067 btrfs_put_ordered_extent(ordered);
8068 btrfs_put_ordered_extent(ordered);
8071 inode_tree_del(inode);
8072 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8074 call_rcu(&inode->i_rcu, btrfs_i_callback);
8077 int btrfs_drop_inode(struct inode *inode)
8079 struct btrfs_root *root = BTRFS_I(inode)->root;
8084 /* the snap/subvol tree is on deleting */
8085 if (btrfs_root_refs(&root->root_item) == 0)
8088 return generic_drop_inode(inode);
8091 static void init_once(void *foo)
8093 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8095 inode_init_once(&ei->vfs_inode);
8098 void btrfs_destroy_cachep(void)
8101 * Make sure all delayed rcu free inodes are flushed before we
8105 if (btrfs_inode_cachep)
8106 kmem_cache_destroy(btrfs_inode_cachep);
8107 if (btrfs_trans_handle_cachep)
8108 kmem_cache_destroy(btrfs_trans_handle_cachep);
8109 if (btrfs_transaction_cachep)
8110 kmem_cache_destroy(btrfs_transaction_cachep);
8111 if (btrfs_path_cachep)
8112 kmem_cache_destroy(btrfs_path_cachep);
8113 if (btrfs_free_space_cachep)
8114 kmem_cache_destroy(btrfs_free_space_cachep);
8115 if (btrfs_delalloc_work_cachep)
8116 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8119 int btrfs_init_cachep(void)
8121 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8122 sizeof(struct btrfs_inode), 0,
8123 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8124 if (!btrfs_inode_cachep)
8127 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8128 sizeof(struct btrfs_trans_handle), 0,
8129 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8130 if (!btrfs_trans_handle_cachep)
8133 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8134 sizeof(struct btrfs_transaction), 0,
8135 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8136 if (!btrfs_transaction_cachep)
8139 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8140 sizeof(struct btrfs_path), 0,
8141 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8142 if (!btrfs_path_cachep)
8145 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8146 sizeof(struct btrfs_free_space), 0,
8147 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8148 if (!btrfs_free_space_cachep)
8151 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8152 sizeof(struct btrfs_delalloc_work), 0,
8153 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8155 if (!btrfs_delalloc_work_cachep)
8160 btrfs_destroy_cachep();
8164 static int btrfs_getattr(struct vfsmount *mnt,
8165 struct dentry *dentry, struct kstat *stat)
8168 struct inode *inode = dentry->d_inode;
8169 u32 blocksize = inode->i_sb->s_blocksize;
8171 generic_fillattr(inode, stat);
8172 stat->dev = BTRFS_I(inode)->root->anon_dev;
8173 stat->blksize = PAGE_CACHE_SIZE;
8175 spin_lock(&BTRFS_I(inode)->lock);
8176 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8177 spin_unlock(&BTRFS_I(inode)->lock);
8178 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8179 ALIGN(delalloc_bytes, blocksize)) >> 9;
8183 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8184 struct inode *new_dir, struct dentry *new_dentry)
8186 struct btrfs_trans_handle *trans;
8187 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8188 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8189 struct inode *new_inode = new_dentry->d_inode;
8190 struct inode *old_inode = old_dentry->d_inode;
8191 struct timespec ctime = CURRENT_TIME;
8195 u64 old_ino = btrfs_ino(old_inode);
8197 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8200 /* we only allow rename subvolume link between subvolumes */
8201 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8204 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8205 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8208 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8209 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8213 /* check for collisions, even if the name isn't there */
8214 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8215 new_dentry->d_name.name,
8216 new_dentry->d_name.len);
8219 if (ret == -EEXIST) {
8221 * eexist without a new_inode */
8222 if (WARN_ON(!new_inode)) {
8226 /* maybe -EOVERFLOW */
8233 * we're using rename to replace one file with another.
8234 * and the replacement file is large. Start IO on it now so
8235 * we don't add too much work to the end of the transaction
8237 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8238 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8239 filemap_flush(old_inode->i_mapping);
8241 /* close the racy window with snapshot create/destroy ioctl */
8242 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8243 down_read(&root->fs_info->subvol_sem);
8245 * We want to reserve the absolute worst case amount of items. So if
8246 * both inodes are subvols and we need to unlink them then that would
8247 * require 4 item modifications, but if they are both normal inodes it
8248 * would require 5 item modifications, so we'll assume their normal
8249 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8250 * should cover the worst case number of items we'll modify.
8252 trans = btrfs_start_transaction(root, 11);
8253 if (IS_ERR(trans)) {
8254 ret = PTR_ERR(trans);
8259 btrfs_record_root_in_trans(trans, dest);
8261 ret = btrfs_set_inode_index(new_dir, &index);
8265 BTRFS_I(old_inode)->dir_index = 0ULL;
8266 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8267 /* force full log commit if subvolume involved. */
8268 root->fs_info->last_trans_log_full_commit = trans->transid;
8270 ret = btrfs_insert_inode_ref(trans, dest,
8271 new_dentry->d_name.name,
8272 new_dentry->d_name.len,
8274 btrfs_ino(new_dir), index);
8278 * this is an ugly little race, but the rename is required
8279 * to make sure that if we crash, the inode is either at the
8280 * old name or the new one. pinning the log transaction lets
8281 * us make sure we don't allow a log commit to come in after
8282 * we unlink the name but before we add the new name back in.
8284 btrfs_pin_log_trans(root);
8287 * make sure the inode gets flushed if it is replacing
8290 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8291 btrfs_add_ordered_operation(trans, root, old_inode);
8293 inode_inc_iversion(old_dir);
8294 inode_inc_iversion(new_dir);
8295 inode_inc_iversion(old_inode);
8296 old_dir->i_ctime = old_dir->i_mtime = ctime;
8297 new_dir->i_ctime = new_dir->i_mtime = ctime;
8298 old_inode->i_ctime = ctime;
8300 if (old_dentry->d_parent != new_dentry->d_parent)
8301 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8303 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8304 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8305 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8306 old_dentry->d_name.name,
8307 old_dentry->d_name.len);
8309 ret = __btrfs_unlink_inode(trans, root, old_dir,
8310 old_dentry->d_inode,
8311 old_dentry->d_name.name,
8312 old_dentry->d_name.len);
8314 ret = btrfs_update_inode(trans, root, old_inode);
8317 btrfs_abort_transaction(trans, root, ret);
8322 inode_inc_iversion(new_inode);
8323 new_inode->i_ctime = CURRENT_TIME;
8324 if (unlikely(btrfs_ino(new_inode) ==
8325 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8326 root_objectid = BTRFS_I(new_inode)->location.objectid;
8327 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8329 new_dentry->d_name.name,
8330 new_dentry->d_name.len);
8331 BUG_ON(new_inode->i_nlink == 0);
8333 ret = btrfs_unlink_inode(trans, dest, new_dir,
8334 new_dentry->d_inode,
8335 new_dentry->d_name.name,
8336 new_dentry->d_name.len);
8338 if (!ret && new_inode->i_nlink == 0)
8339 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8341 btrfs_abort_transaction(trans, root, ret);
8346 ret = btrfs_add_link(trans, new_dir, old_inode,
8347 new_dentry->d_name.name,
8348 new_dentry->d_name.len, 0, index);
8350 btrfs_abort_transaction(trans, root, ret);
8354 if (old_inode->i_nlink == 1)
8355 BTRFS_I(old_inode)->dir_index = index;
8357 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8358 struct dentry *parent = new_dentry->d_parent;
8359 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8360 btrfs_end_log_trans(root);
8363 btrfs_end_transaction(trans, root);
8365 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8366 up_read(&root->fs_info->subvol_sem);
8371 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8373 struct btrfs_delalloc_work *delalloc_work;
8374 struct inode *inode;
8376 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8378 inode = delalloc_work->inode;
8379 if (delalloc_work->wait) {
8380 btrfs_wait_ordered_range(inode, 0, (u64)-1);
8382 filemap_flush(inode->i_mapping);
8383 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8384 &BTRFS_I(inode)->runtime_flags))
8385 filemap_flush(inode->i_mapping);
8388 if (delalloc_work->delay_iput)
8389 btrfs_add_delayed_iput(inode);
8392 complete(&delalloc_work->completion);
8395 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8396 int wait, int delay_iput)
8398 struct btrfs_delalloc_work *work;
8400 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8404 init_completion(&work->completion);
8405 INIT_LIST_HEAD(&work->list);
8406 work->inode = inode;
8408 work->delay_iput = delay_iput;
8409 work->work.func = btrfs_run_delalloc_work;
8414 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8416 wait_for_completion(&work->completion);
8417 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8421 * some fairly slow code that needs optimization. This walks the list
8422 * of all the inodes with pending delalloc and forces them to disk.
8424 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8426 struct btrfs_inode *binode;
8427 struct inode *inode;
8428 struct btrfs_delalloc_work *work, *next;
8429 struct list_head works;
8430 struct list_head splice;
8433 INIT_LIST_HEAD(&works);
8434 INIT_LIST_HEAD(&splice);
8436 spin_lock(&root->delalloc_lock);
8437 list_splice_init(&root->delalloc_inodes, &splice);
8438 while (!list_empty(&splice)) {
8439 binode = list_entry(splice.next, struct btrfs_inode,
8442 list_move_tail(&binode->delalloc_inodes,
8443 &root->delalloc_inodes);
8444 inode = igrab(&binode->vfs_inode);
8446 cond_resched_lock(&root->delalloc_lock);
8449 spin_unlock(&root->delalloc_lock);
8451 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8452 if (unlikely(!work)) {
8454 btrfs_add_delayed_iput(inode);
8460 list_add_tail(&work->list, &works);
8461 btrfs_queue_worker(&root->fs_info->flush_workers,
8465 spin_lock(&root->delalloc_lock);
8467 spin_unlock(&root->delalloc_lock);
8469 list_for_each_entry_safe(work, next, &works, list) {
8470 list_del_init(&work->list);
8471 btrfs_wait_and_free_delalloc_work(work);
8475 list_for_each_entry_safe(work, next, &works, list) {
8476 list_del_init(&work->list);
8477 btrfs_wait_and_free_delalloc_work(work);
8480 if (!list_empty_careful(&splice)) {
8481 spin_lock(&root->delalloc_lock);
8482 list_splice_tail(&splice, &root->delalloc_inodes);
8483 spin_unlock(&root->delalloc_lock);
8488 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8492 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
8495 ret = __start_delalloc_inodes(root, delay_iput);
8497 * the filemap_flush will queue IO into the worker threads, but
8498 * we have to make sure the IO is actually started and that
8499 * ordered extents get created before we return
8501 atomic_inc(&root->fs_info->async_submit_draining);
8502 while (atomic_read(&root->fs_info->nr_async_submits) ||
8503 atomic_read(&root->fs_info->async_delalloc_pages)) {
8504 wait_event(root->fs_info->async_submit_wait,
8505 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8506 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8508 atomic_dec(&root->fs_info->async_submit_draining);
8512 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput)
8514 struct btrfs_root *root;
8515 struct list_head splice;
8518 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
8521 INIT_LIST_HEAD(&splice);
8523 spin_lock(&fs_info->delalloc_root_lock);
8524 list_splice_init(&fs_info->delalloc_roots, &splice);
8525 while (!list_empty(&splice)) {
8526 root = list_first_entry(&splice, struct btrfs_root,
8528 root = btrfs_grab_fs_root(root);
8530 list_move_tail(&root->delalloc_root,
8531 &fs_info->delalloc_roots);
8532 spin_unlock(&fs_info->delalloc_root_lock);
8534 ret = __start_delalloc_inodes(root, delay_iput);
8535 btrfs_put_fs_root(root);
8539 spin_lock(&fs_info->delalloc_root_lock);
8541 spin_unlock(&fs_info->delalloc_root_lock);
8543 atomic_inc(&fs_info->async_submit_draining);
8544 while (atomic_read(&fs_info->nr_async_submits) ||
8545 atomic_read(&fs_info->async_delalloc_pages)) {
8546 wait_event(fs_info->async_submit_wait,
8547 (atomic_read(&fs_info->nr_async_submits) == 0 &&
8548 atomic_read(&fs_info->async_delalloc_pages) == 0));
8550 atomic_dec(&fs_info->async_submit_draining);
8553 if (!list_empty_careful(&splice)) {
8554 spin_lock(&fs_info->delalloc_root_lock);
8555 list_splice_tail(&splice, &fs_info->delalloc_roots);
8556 spin_unlock(&fs_info->delalloc_root_lock);
8561 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8562 const char *symname)
8564 struct btrfs_trans_handle *trans;
8565 struct btrfs_root *root = BTRFS_I(dir)->root;
8566 struct btrfs_path *path;
8567 struct btrfs_key key;
8568 struct inode *inode = NULL;
8576 struct btrfs_file_extent_item *ei;
8577 struct extent_buffer *leaf;
8579 name_len = strlen(symname);
8580 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8581 return -ENAMETOOLONG;
8584 * 2 items for inode item and ref
8585 * 2 items for dir items
8586 * 1 item for xattr if selinux is on
8588 trans = btrfs_start_transaction(root, 5);
8590 return PTR_ERR(trans);
8592 err = btrfs_find_free_ino(root, &objectid);
8596 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8597 dentry->d_name.len, btrfs_ino(dir), objectid,
8598 S_IFLNK|S_IRWXUGO, &index);
8599 if (IS_ERR(inode)) {
8600 err = PTR_ERR(inode);
8604 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8611 * If the active LSM wants to access the inode during
8612 * d_instantiate it needs these. Smack checks to see
8613 * if the filesystem supports xattrs by looking at the
8616 inode->i_fop = &btrfs_file_operations;
8617 inode->i_op = &btrfs_file_inode_operations;
8619 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8623 inode->i_mapping->a_ops = &btrfs_aops;
8624 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8625 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8630 path = btrfs_alloc_path();
8636 key.objectid = btrfs_ino(inode);
8638 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8639 datasize = btrfs_file_extent_calc_inline_size(name_len);
8640 err = btrfs_insert_empty_item(trans, root, path, &key,
8644 btrfs_free_path(path);
8647 leaf = path->nodes[0];
8648 ei = btrfs_item_ptr(leaf, path->slots[0],
8649 struct btrfs_file_extent_item);
8650 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8651 btrfs_set_file_extent_type(leaf, ei,
8652 BTRFS_FILE_EXTENT_INLINE);
8653 btrfs_set_file_extent_encryption(leaf, ei, 0);
8654 btrfs_set_file_extent_compression(leaf, ei, 0);
8655 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8656 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8658 ptr = btrfs_file_extent_inline_start(ei);
8659 write_extent_buffer(leaf, symname, ptr, name_len);
8660 btrfs_mark_buffer_dirty(leaf);
8661 btrfs_free_path(path);
8663 inode->i_op = &btrfs_symlink_inode_operations;
8664 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8665 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8666 inode_set_bytes(inode, name_len);
8667 btrfs_i_size_write(inode, name_len);
8668 err = btrfs_update_inode(trans, root, inode);
8674 d_instantiate(dentry, inode);
8675 btrfs_end_transaction(trans, root);
8677 inode_dec_link_count(inode);
8680 btrfs_btree_balance_dirty(root);
8684 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8685 u64 start, u64 num_bytes, u64 min_size,
8686 loff_t actual_len, u64 *alloc_hint,
8687 struct btrfs_trans_handle *trans)
8689 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8690 struct extent_map *em;
8691 struct btrfs_root *root = BTRFS_I(inode)->root;
8692 struct btrfs_key ins;
8693 u64 cur_offset = start;
8697 bool own_trans = true;
8701 while (num_bytes > 0) {
8703 trans = btrfs_start_transaction(root, 3);
8704 if (IS_ERR(trans)) {
8705 ret = PTR_ERR(trans);
8710 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8711 cur_bytes = max(cur_bytes, min_size);
8712 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
8713 *alloc_hint, &ins, 1);
8716 btrfs_end_transaction(trans, root);
8720 ret = insert_reserved_file_extent(trans, inode,
8721 cur_offset, ins.objectid,
8722 ins.offset, ins.offset,
8723 ins.offset, 0, 0, 0,
8724 BTRFS_FILE_EXTENT_PREALLOC);
8726 btrfs_free_reserved_extent(root, ins.objectid,
8728 btrfs_abort_transaction(trans, root, ret);
8730 btrfs_end_transaction(trans, root);
8733 btrfs_drop_extent_cache(inode, cur_offset,
8734 cur_offset + ins.offset -1, 0);
8736 em = alloc_extent_map();
8738 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8739 &BTRFS_I(inode)->runtime_flags);
8743 em->start = cur_offset;
8744 em->orig_start = cur_offset;
8745 em->len = ins.offset;
8746 em->block_start = ins.objectid;
8747 em->block_len = ins.offset;
8748 em->orig_block_len = ins.offset;
8749 em->ram_bytes = ins.offset;
8750 em->bdev = root->fs_info->fs_devices->latest_bdev;
8751 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8752 em->generation = trans->transid;
8755 write_lock(&em_tree->lock);
8756 ret = add_extent_mapping(em_tree, em, 1);
8757 write_unlock(&em_tree->lock);
8760 btrfs_drop_extent_cache(inode, cur_offset,
8761 cur_offset + ins.offset - 1,
8764 free_extent_map(em);
8766 num_bytes -= ins.offset;
8767 cur_offset += ins.offset;
8768 *alloc_hint = ins.objectid + ins.offset;
8770 inode_inc_iversion(inode);
8771 inode->i_ctime = CURRENT_TIME;
8772 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8773 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8774 (actual_len > inode->i_size) &&
8775 (cur_offset > inode->i_size)) {
8776 if (cur_offset > actual_len)
8777 i_size = actual_len;
8779 i_size = cur_offset;
8780 i_size_write(inode, i_size);
8781 btrfs_ordered_update_i_size(inode, i_size, NULL);
8784 ret = btrfs_update_inode(trans, root, inode);
8787 btrfs_abort_transaction(trans, root, ret);
8789 btrfs_end_transaction(trans, root);
8794 btrfs_end_transaction(trans, root);
8799 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8800 u64 start, u64 num_bytes, u64 min_size,
8801 loff_t actual_len, u64 *alloc_hint)
8803 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8804 min_size, actual_len, alloc_hint,
8808 int btrfs_prealloc_file_range_trans(struct inode *inode,
8809 struct btrfs_trans_handle *trans, int mode,
8810 u64 start, u64 num_bytes, u64 min_size,
8811 loff_t actual_len, u64 *alloc_hint)
8813 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8814 min_size, actual_len, alloc_hint, trans);
8817 static int btrfs_set_page_dirty(struct page *page)
8819 return __set_page_dirty_nobuffers(page);
8822 static int btrfs_permission(struct inode *inode, int mask)
8824 struct btrfs_root *root = BTRFS_I(inode)->root;
8825 umode_t mode = inode->i_mode;
8827 if (mask & MAY_WRITE &&
8828 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8829 if (btrfs_root_readonly(root))
8831 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8834 return generic_permission(inode, mask);
8837 static const struct inode_operations btrfs_dir_inode_operations = {
8838 .getattr = btrfs_getattr,
8839 .lookup = btrfs_lookup,
8840 .create = btrfs_create,
8841 .unlink = btrfs_unlink,
8843 .mkdir = btrfs_mkdir,
8844 .rmdir = btrfs_rmdir,
8845 .rename = btrfs_rename,
8846 .symlink = btrfs_symlink,
8847 .setattr = btrfs_setattr,
8848 .mknod = btrfs_mknod,
8849 .setxattr = btrfs_setxattr,
8850 .getxattr = btrfs_getxattr,
8851 .listxattr = btrfs_listxattr,
8852 .removexattr = btrfs_removexattr,
8853 .permission = btrfs_permission,
8854 .get_acl = btrfs_get_acl,
8855 .update_time = btrfs_update_time,
8857 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8858 .lookup = btrfs_lookup,
8859 .permission = btrfs_permission,
8860 .get_acl = btrfs_get_acl,
8861 .update_time = btrfs_update_time,
8864 static const struct file_operations btrfs_dir_file_operations = {
8865 .llseek = generic_file_llseek,
8866 .read = generic_read_dir,
8867 .iterate = btrfs_real_readdir,
8868 .unlocked_ioctl = btrfs_ioctl,
8869 #ifdef CONFIG_COMPAT
8870 .compat_ioctl = btrfs_ioctl,
8872 .release = btrfs_release_file,
8873 .fsync = btrfs_sync_file,
8876 static struct extent_io_ops btrfs_extent_io_ops = {
8877 .fill_delalloc = run_delalloc_range,
8878 .submit_bio_hook = btrfs_submit_bio_hook,
8879 .merge_bio_hook = btrfs_merge_bio_hook,
8880 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8881 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8882 .writepage_start_hook = btrfs_writepage_start_hook,
8883 .set_bit_hook = btrfs_set_bit_hook,
8884 .clear_bit_hook = btrfs_clear_bit_hook,
8885 .merge_extent_hook = btrfs_merge_extent_hook,
8886 .split_extent_hook = btrfs_split_extent_hook,
8890 * btrfs doesn't support the bmap operation because swapfiles
8891 * use bmap to make a mapping of extents in the file. They assume
8892 * these extents won't change over the life of the file and they
8893 * use the bmap result to do IO directly to the drive.
8895 * the btrfs bmap call would return logical addresses that aren't
8896 * suitable for IO and they also will change frequently as COW
8897 * operations happen. So, swapfile + btrfs == corruption.
8899 * For now we're avoiding this by dropping bmap.
8901 static const struct address_space_operations btrfs_aops = {
8902 .readpage = btrfs_readpage,
8903 .writepage = btrfs_writepage,
8904 .writepages = btrfs_writepages,
8905 .readpages = btrfs_readpages,
8906 .direct_IO = btrfs_direct_IO,
8907 .invalidatepage = btrfs_invalidatepage,
8908 .releasepage = btrfs_releasepage,
8909 .set_page_dirty = btrfs_set_page_dirty,
8910 .error_remove_page = generic_error_remove_page,
8913 static const struct address_space_operations btrfs_symlink_aops = {
8914 .readpage = btrfs_readpage,
8915 .writepage = btrfs_writepage,
8916 .invalidatepage = btrfs_invalidatepage,
8917 .releasepage = btrfs_releasepage,
8920 static const struct inode_operations btrfs_file_inode_operations = {
8921 .getattr = btrfs_getattr,
8922 .setattr = btrfs_setattr,
8923 .setxattr = btrfs_setxattr,
8924 .getxattr = btrfs_getxattr,
8925 .listxattr = btrfs_listxattr,
8926 .removexattr = btrfs_removexattr,
8927 .permission = btrfs_permission,
8928 .fiemap = btrfs_fiemap,
8929 .get_acl = btrfs_get_acl,
8930 .update_time = btrfs_update_time,
8932 static const struct inode_operations btrfs_special_inode_operations = {
8933 .getattr = btrfs_getattr,
8934 .setattr = btrfs_setattr,
8935 .permission = btrfs_permission,
8936 .setxattr = btrfs_setxattr,
8937 .getxattr = btrfs_getxattr,
8938 .listxattr = btrfs_listxattr,
8939 .removexattr = btrfs_removexattr,
8940 .get_acl = btrfs_get_acl,
8941 .update_time = btrfs_update_time,
8943 static const struct inode_operations btrfs_symlink_inode_operations = {
8944 .readlink = generic_readlink,
8945 .follow_link = page_follow_link_light,
8946 .put_link = page_put_link,
8947 .getattr = btrfs_getattr,
8948 .setattr = btrfs_setattr,
8949 .permission = btrfs_permission,
8950 .setxattr = btrfs_setxattr,
8951 .getxattr = btrfs_getxattr,
8952 .listxattr = btrfs_listxattr,
8953 .removexattr = btrfs_removexattr,
8954 .get_acl = btrfs_get_acl,
8955 .update_time = btrfs_update_time,
8958 const struct dentry_operations btrfs_dentry_operations = {
8959 .d_delete = btrfs_dentry_delete,
8960 .d_release = btrfs_dentry_release,