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);
706 * we need to redirty the pages if we decide to
707 * fallback to uncompressed IO, otherwise we
708 * will not submit these pages down to lower
711 extent_range_redirty_for_io(inode,
713 async_extent->start +
714 async_extent->ram_size - 1);
722 * here we're doing allocation and writeback of the
725 btrfs_drop_extent_cache(inode, async_extent->start,
726 async_extent->start +
727 async_extent->ram_size - 1, 0);
729 em = alloc_extent_map();
732 goto out_free_reserve;
734 em->start = async_extent->start;
735 em->len = async_extent->ram_size;
736 em->orig_start = em->start;
737 em->mod_start = em->start;
738 em->mod_len = em->len;
740 em->block_start = ins.objectid;
741 em->block_len = ins.offset;
742 em->orig_block_len = ins.offset;
743 em->ram_bytes = async_extent->ram_size;
744 em->bdev = root->fs_info->fs_devices->latest_bdev;
745 em->compress_type = async_extent->compress_type;
746 set_bit(EXTENT_FLAG_PINNED, &em->flags);
747 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
751 write_lock(&em_tree->lock);
752 ret = add_extent_mapping(em_tree, em, 1);
753 write_unlock(&em_tree->lock);
754 if (ret != -EEXIST) {
758 btrfs_drop_extent_cache(inode, async_extent->start,
759 async_extent->start +
760 async_extent->ram_size - 1, 0);
764 goto out_free_reserve;
766 ret = btrfs_add_ordered_extent_compress(inode,
769 async_extent->ram_size,
771 BTRFS_ORDERED_COMPRESSED,
772 async_extent->compress_type);
774 goto out_free_reserve;
777 * clear dirty, set writeback and unlock the pages.
779 extent_clear_unlock_delalloc(inode, async_extent->start,
780 async_extent->start +
781 async_extent->ram_size - 1,
782 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
783 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
785 ret = btrfs_submit_compressed_write(inode,
787 async_extent->ram_size,
789 ins.offset, async_extent->pages,
790 async_extent->nr_pages);
791 alloc_hint = ins.objectid + ins.offset;
801 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
803 extent_clear_unlock_delalloc(inode, async_extent->start,
804 async_extent->start +
805 async_extent->ram_size - 1,
806 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
807 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
808 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
809 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
814 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
817 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
818 struct extent_map *em;
821 read_lock(&em_tree->lock);
822 em = search_extent_mapping(em_tree, start, num_bytes);
825 * if block start isn't an actual block number then find the
826 * first block in this inode and use that as a hint. If that
827 * block is also bogus then just don't worry about it.
829 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
831 em = search_extent_mapping(em_tree, 0, 0);
832 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
833 alloc_hint = em->block_start;
837 alloc_hint = em->block_start;
841 read_unlock(&em_tree->lock);
847 * when extent_io.c finds a delayed allocation range in the file,
848 * the call backs end up in this code. The basic idea is to
849 * allocate extents on disk for the range, and create ordered data structs
850 * in ram to track those extents.
852 * locked_page is the page that writepage had locked already. We use
853 * it to make sure we don't do extra locks or unlocks.
855 * *page_started is set to one if we unlock locked_page and do everything
856 * required to start IO on it. It may be clean and already done with
859 static noinline int cow_file_range(struct inode *inode,
860 struct page *locked_page,
861 u64 start, u64 end, int *page_started,
862 unsigned long *nr_written,
865 struct btrfs_root *root = BTRFS_I(inode)->root;
868 unsigned long ram_size;
871 u64 blocksize = root->sectorsize;
872 struct btrfs_key ins;
873 struct extent_map *em;
874 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
877 if (btrfs_is_free_space_inode(inode)) {
882 num_bytes = ALIGN(end - start + 1, blocksize);
883 num_bytes = max(blocksize, num_bytes);
884 disk_num_bytes = num_bytes;
886 /* if this is a small write inside eof, kick off defrag */
887 if (num_bytes < 64 * 1024 &&
888 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
889 btrfs_add_inode_defrag(NULL, inode);
892 /* lets try to make an inline extent */
893 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
896 extent_clear_unlock_delalloc(inode, start, end, NULL,
897 EXTENT_LOCKED | EXTENT_DELALLOC |
898 EXTENT_DEFRAG, PAGE_UNLOCK |
899 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
902 *nr_written = *nr_written +
903 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
906 } else if (ret < 0) {
911 BUG_ON(disk_num_bytes >
912 btrfs_super_total_bytes(root->fs_info->super_copy));
914 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
915 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
917 while (disk_num_bytes > 0) {
920 cur_alloc_size = disk_num_bytes;
921 ret = btrfs_reserve_extent(root, cur_alloc_size,
922 root->sectorsize, 0, alloc_hint,
927 em = alloc_extent_map();
933 em->orig_start = em->start;
934 ram_size = ins.offset;
935 em->len = ins.offset;
936 em->mod_start = em->start;
937 em->mod_len = em->len;
939 em->block_start = ins.objectid;
940 em->block_len = ins.offset;
941 em->orig_block_len = ins.offset;
942 em->ram_bytes = ram_size;
943 em->bdev = root->fs_info->fs_devices->latest_bdev;
944 set_bit(EXTENT_FLAG_PINNED, &em->flags);
948 write_lock(&em_tree->lock);
949 ret = add_extent_mapping(em_tree, em, 1);
950 write_unlock(&em_tree->lock);
951 if (ret != -EEXIST) {
955 btrfs_drop_extent_cache(inode, start,
956 start + ram_size - 1, 0);
961 cur_alloc_size = ins.offset;
962 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
963 ram_size, cur_alloc_size, 0);
967 if (root->root_key.objectid ==
968 BTRFS_DATA_RELOC_TREE_OBJECTID) {
969 ret = btrfs_reloc_clone_csums(inode, start,
975 if (disk_num_bytes < cur_alloc_size)
978 /* we're not doing compressed IO, don't unlock the first
979 * page (which the caller expects to stay locked), don't
980 * clear any dirty bits and don't set any writeback bits
982 * Do set the Private2 bit so we know this page was properly
983 * setup for writepage
985 op = unlock ? PAGE_UNLOCK : 0;
986 op |= PAGE_SET_PRIVATE2;
988 extent_clear_unlock_delalloc(inode, start,
989 start + ram_size - 1, locked_page,
990 EXTENT_LOCKED | EXTENT_DELALLOC,
992 disk_num_bytes -= cur_alloc_size;
993 num_bytes -= cur_alloc_size;
994 alloc_hint = ins.objectid + ins.offset;
995 start += cur_alloc_size;
1001 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
1003 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1004 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1005 EXTENT_DELALLOC | EXTENT_DEFRAG,
1006 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1007 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1012 * work queue call back to started compression on a file and pages
1014 static noinline void async_cow_start(struct btrfs_work *work)
1016 struct async_cow *async_cow;
1018 async_cow = container_of(work, struct async_cow, work);
1020 compress_file_range(async_cow->inode, async_cow->locked_page,
1021 async_cow->start, async_cow->end, async_cow,
1023 if (num_added == 0) {
1024 btrfs_add_delayed_iput(async_cow->inode);
1025 async_cow->inode = NULL;
1030 * work queue call back to submit previously compressed pages
1032 static noinline void async_cow_submit(struct btrfs_work *work)
1034 struct async_cow *async_cow;
1035 struct btrfs_root *root;
1036 unsigned long nr_pages;
1038 async_cow = container_of(work, struct async_cow, work);
1040 root = async_cow->root;
1041 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1044 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1046 waitqueue_active(&root->fs_info->async_submit_wait))
1047 wake_up(&root->fs_info->async_submit_wait);
1049 if (async_cow->inode)
1050 submit_compressed_extents(async_cow->inode, async_cow);
1053 static noinline void async_cow_free(struct btrfs_work *work)
1055 struct async_cow *async_cow;
1056 async_cow = container_of(work, struct async_cow, work);
1057 if (async_cow->inode)
1058 btrfs_add_delayed_iput(async_cow->inode);
1062 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1063 u64 start, u64 end, int *page_started,
1064 unsigned long *nr_written)
1066 struct async_cow *async_cow;
1067 struct btrfs_root *root = BTRFS_I(inode)->root;
1068 unsigned long nr_pages;
1070 int limit = 10 * 1024 * 1024;
1072 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1073 1, 0, NULL, GFP_NOFS);
1074 while (start < end) {
1075 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1076 BUG_ON(!async_cow); /* -ENOMEM */
1077 async_cow->inode = igrab(inode);
1078 async_cow->root = root;
1079 async_cow->locked_page = locked_page;
1080 async_cow->start = start;
1082 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1085 cur_end = min(end, start + 512 * 1024 - 1);
1087 async_cow->end = cur_end;
1088 INIT_LIST_HEAD(&async_cow->extents);
1090 async_cow->work.func = async_cow_start;
1091 async_cow->work.ordered_func = async_cow_submit;
1092 async_cow->work.ordered_free = async_cow_free;
1093 async_cow->work.flags = 0;
1095 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1097 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1099 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1102 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1103 wait_event(root->fs_info->async_submit_wait,
1104 (atomic_read(&root->fs_info->async_delalloc_pages) <
1108 while (atomic_read(&root->fs_info->async_submit_draining) &&
1109 atomic_read(&root->fs_info->async_delalloc_pages)) {
1110 wait_event(root->fs_info->async_submit_wait,
1111 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1115 *nr_written += nr_pages;
1116 start = cur_end + 1;
1122 static noinline int csum_exist_in_range(struct btrfs_root *root,
1123 u64 bytenr, u64 num_bytes)
1126 struct btrfs_ordered_sum *sums;
1129 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1130 bytenr + num_bytes - 1, &list, 0);
1131 if (ret == 0 && list_empty(&list))
1134 while (!list_empty(&list)) {
1135 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1136 list_del(&sums->list);
1143 * when nowcow writeback call back. This checks for snapshots or COW copies
1144 * of the extents that exist in the file, and COWs the file as required.
1146 * If no cow copies or snapshots exist, we write directly to the existing
1149 static noinline int run_delalloc_nocow(struct inode *inode,
1150 struct page *locked_page,
1151 u64 start, u64 end, int *page_started, int force,
1152 unsigned long *nr_written)
1154 struct btrfs_root *root = BTRFS_I(inode)->root;
1155 struct btrfs_trans_handle *trans;
1156 struct extent_buffer *leaf;
1157 struct btrfs_path *path;
1158 struct btrfs_file_extent_item *fi;
1159 struct btrfs_key found_key;
1174 u64 ino = btrfs_ino(inode);
1176 path = btrfs_alloc_path();
1178 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1179 EXTENT_LOCKED | EXTENT_DELALLOC |
1180 EXTENT_DO_ACCOUNTING |
1181 EXTENT_DEFRAG, PAGE_UNLOCK |
1183 PAGE_SET_WRITEBACK |
1184 PAGE_END_WRITEBACK);
1188 nolock = btrfs_is_free_space_inode(inode);
1191 trans = btrfs_join_transaction_nolock(root);
1193 trans = btrfs_join_transaction(root);
1195 if (IS_ERR(trans)) {
1196 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1197 EXTENT_LOCKED | EXTENT_DELALLOC |
1198 EXTENT_DO_ACCOUNTING |
1199 EXTENT_DEFRAG, PAGE_UNLOCK |
1201 PAGE_SET_WRITEBACK |
1202 PAGE_END_WRITEBACK);
1203 btrfs_free_path(path);
1204 return PTR_ERR(trans);
1207 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1209 cow_start = (u64)-1;
1212 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1216 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1217 leaf = path->nodes[0];
1218 btrfs_item_key_to_cpu(leaf, &found_key,
1219 path->slots[0] - 1);
1220 if (found_key.objectid == ino &&
1221 found_key.type == BTRFS_EXTENT_DATA_KEY)
1226 leaf = path->nodes[0];
1227 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1228 ret = btrfs_next_leaf(root, path);
1233 leaf = path->nodes[0];
1239 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1241 if (found_key.objectid > ino ||
1242 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1243 found_key.offset > end)
1246 if (found_key.offset > cur_offset) {
1247 extent_end = found_key.offset;
1252 fi = btrfs_item_ptr(leaf, path->slots[0],
1253 struct btrfs_file_extent_item);
1254 extent_type = btrfs_file_extent_type(leaf, fi);
1256 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1257 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1258 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1259 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1260 extent_offset = btrfs_file_extent_offset(leaf, fi);
1261 extent_end = found_key.offset +
1262 btrfs_file_extent_num_bytes(leaf, fi);
1264 btrfs_file_extent_disk_num_bytes(leaf, fi);
1265 if (extent_end <= start) {
1269 if (disk_bytenr == 0)
1271 if (btrfs_file_extent_compression(leaf, fi) ||
1272 btrfs_file_extent_encryption(leaf, fi) ||
1273 btrfs_file_extent_other_encoding(leaf, fi))
1275 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1277 if (btrfs_extent_readonly(root, disk_bytenr))
1279 if (btrfs_cross_ref_exist(trans, root, ino,
1281 extent_offset, disk_bytenr))
1283 disk_bytenr += extent_offset;
1284 disk_bytenr += cur_offset - found_key.offset;
1285 num_bytes = min(end + 1, extent_end) - cur_offset;
1287 * force cow if csum exists in the range.
1288 * this ensure that csum for a given extent are
1289 * either valid or do not exist.
1291 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1294 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1295 extent_end = found_key.offset +
1296 btrfs_file_extent_inline_len(leaf,
1297 path->slots[0], fi);
1298 extent_end = ALIGN(extent_end, root->sectorsize);
1303 if (extent_end <= start) {
1308 if (cow_start == (u64)-1)
1309 cow_start = cur_offset;
1310 cur_offset = extent_end;
1311 if (cur_offset > end)
1317 btrfs_release_path(path);
1318 if (cow_start != (u64)-1) {
1319 ret = cow_file_range(inode, locked_page,
1320 cow_start, found_key.offset - 1,
1321 page_started, nr_written, 1);
1324 cow_start = (u64)-1;
1327 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1328 struct extent_map *em;
1329 struct extent_map_tree *em_tree;
1330 em_tree = &BTRFS_I(inode)->extent_tree;
1331 em = alloc_extent_map();
1332 BUG_ON(!em); /* -ENOMEM */
1333 em->start = cur_offset;
1334 em->orig_start = found_key.offset - extent_offset;
1335 em->len = num_bytes;
1336 em->block_len = num_bytes;
1337 em->block_start = disk_bytenr;
1338 em->orig_block_len = disk_num_bytes;
1339 em->ram_bytes = ram_bytes;
1340 em->bdev = root->fs_info->fs_devices->latest_bdev;
1341 em->mod_start = em->start;
1342 em->mod_len = em->len;
1343 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1344 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1345 em->generation = -1;
1347 write_lock(&em_tree->lock);
1348 ret = add_extent_mapping(em_tree, em, 1);
1349 write_unlock(&em_tree->lock);
1350 if (ret != -EEXIST) {
1351 free_extent_map(em);
1354 btrfs_drop_extent_cache(inode, em->start,
1355 em->start + em->len - 1, 0);
1357 type = BTRFS_ORDERED_PREALLOC;
1359 type = BTRFS_ORDERED_NOCOW;
1362 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1363 num_bytes, num_bytes, type);
1364 BUG_ON(ret); /* -ENOMEM */
1366 if (root->root_key.objectid ==
1367 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1368 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1374 extent_clear_unlock_delalloc(inode, cur_offset,
1375 cur_offset + num_bytes - 1,
1376 locked_page, EXTENT_LOCKED |
1377 EXTENT_DELALLOC, PAGE_UNLOCK |
1379 cur_offset = extent_end;
1380 if (cur_offset > end)
1383 btrfs_release_path(path);
1385 if (cur_offset <= end && cow_start == (u64)-1) {
1386 cow_start = cur_offset;
1390 if (cow_start != (u64)-1) {
1391 ret = cow_file_range(inode, locked_page, cow_start, end,
1392 page_started, nr_written, 1);
1398 err = btrfs_end_transaction(trans, root);
1402 if (ret && cur_offset < end)
1403 extent_clear_unlock_delalloc(inode, cur_offset, end,
1404 locked_page, EXTENT_LOCKED |
1405 EXTENT_DELALLOC | EXTENT_DEFRAG |
1406 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1408 PAGE_SET_WRITEBACK |
1409 PAGE_END_WRITEBACK);
1410 btrfs_free_path(path);
1415 * extent_io.c call back to do delayed allocation processing
1417 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1418 u64 start, u64 end, int *page_started,
1419 unsigned long *nr_written)
1422 struct btrfs_root *root = BTRFS_I(inode)->root;
1424 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1425 ret = run_delalloc_nocow(inode, locked_page, start, end,
1426 page_started, 1, nr_written);
1427 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1428 ret = run_delalloc_nocow(inode, locked_page, start, end,
1429 page_started, 0, nr_written);
1430 } else if (!btrfs_test_opt(root, COMPRESS) &&
1431 !(BTRFS_I(inode)->force_compress) &&
1432 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1433 ret = cow_file_range(inode, locked_page, start, end,
1434 page_started, nr_written, 1);
1436 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1437 &BTRFS_I(inode)->runtime_flags);
1438 ret = cow_file_range_async(inode, locked_page, start, end,
1439 page_started, nr_written);
1444 static void btrfs_split_extent_hook(struct inode *inode,
1445 struct extent_state *orig, u64 split)
1447 /* not delalloc, ignore it */
1448 if (!(orig->state & EXTENT_DELALLOC))
1451 spin_lock(&BTRFS_I(inode)->lock);
1452 BTRFS_I(inode)->outstanding_extents++;
1453 spin_unlock(&BTRFS_I(inode)->lock);
1457 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1458 * extents so we can keep track of new extents that are just merged onto old
1459 * extents, such as when we are doing sequential writes, so we can properly
1460 * account for the metadata space we'll need.
1462 static void btrfs_merge_extent_hook(struct inode *inode,
1463 struct extent_state *new,
1464 struct extent_state *other)
1466 /* not delalloc, ignore it */
1467 if (!(other->state & EXTENT_DELALLOC))
1470 spin_lock(&BTRFS_I(inode)->lock);
1471 BTRFS_I(inode)->outstanding_extents--;
1472 spin_unlock(&BTRFS_I(inode)->lock);
1475 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1476 struct inode *inode)
1478 spin_lock(&root->delalloc_lock);
1479 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1480 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1481 &root->delalloc_inodes);
1482 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1483 &BTRFS_I(inode)->runtime_flags);
1484 root->nr_delalloc_inodes++;
1485 if (root->nr_delalloc_inodes == 1) {
1486 spin_lock(&root->fs_info->delalloc_root_lock);
1487 BUG_ON(!list_empty(&root->delalloc_root));
1488 list_add_tail(&root->delalloc_root,
1489 &root->fs_info->delalloc_roots);
1490 spin_unlock(&root->fs_info->delalloc_root_lock);
1493 spin_unlock(&root->delalloc_lock);
1496 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1497 struct inode *inode)
1499 spin_lock(&root->delalloc_lock);
1500 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1501 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1502 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1503 &BTRFS_I(inode)->runtime_flags);
1504 root->nr_delalloc_inodes--;
1505 if (!root->nr_delalloc_inodes) {
1506 spin_lock(&root->fs_info->delalloc_root_lock);
1507 BUG_ON(list_empty(&root->delalloc_root));
1508 list_del_init(&root->delalloc_root);
1509 spin_unlock(&root->fs_info->delalloc_root_lock);
1512 spin_unlock(&root->delalloc_lock);
1516 * extent_io.c set_bit_hook, used to track delayed allocation
1517 * bytes in this file, and to maintain the list of inodes that
1518 * have pending delalloc work to be done.
1520 static void btrfs_set_bit_hook(struct inode *inode,
1521 struct extent_state *state, unsigned long *bits)
1525 * set_bit and clear bit hooks normally require _irqsave/restore
1526 * but in this case, we are only testing for the DELALLOC
1527 * bit, which is only set or cleared with irqs on
1529 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1530 struct btrfs_root *root = BTRFS_I(inode)->root;
1531 u64 len = state->end + 1 - state->start;
1532 bool do_list = !btrfs_is_free_space_inode(inode);
1534 if (*bits & EXTENT_FIRST_DELALLOC) {
1535 *bits &= ~EXTENT_FIRST_DELALLOC;
1537 spin_lock(&BTRFS_I(inode)->lock);
1538 BTRFS_I(inode)->outstanding_extents++;
1539 spin_unlock(&BTRFS_I(inode)->lock);
1542 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1543 root->fs_info->delalloc_batch);
1544 spin_lock(&BTRFS_I(inode)->lock);
1545 BTRFS_I(inode)->delalloc_bytes += len;
1546 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1547 &BTRFS_I(inode)->runtime_flags))
1548 btrfs_add_delalloc_inodes(root, inode);
1549 spin_unlock(&BTRFS_I(inode)->lock);
1554 * extent_io.c clear_bit_hook, see set_bit_hook for why
1556 static void btrfs_clear_bit_hook(struct inode *inode,
1557 struct extent_state *state,
1558 unsigned long *bits)
1561 * set_bit and clear bit hooks normally require _irqsave/restore
1562 * but in this case, we are only testing for the DELALLOC
1563 * bit, which is only set or cleared with irqs on
1565 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1566 struct btrfs_root *root = BTRFS_I(inode)->root;
1567 u64 len = state->end + 1 - state->start;
1568 bool do_list = !btrfs_is_free_space_inode(inode);
1570 if (*bits & EXTENT_FIRST_DELALLOC) {
1571 *bits &= ~EXTENT_FIRST_DELALLOC;
1572 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1573 spin_lock(&BTRFS_I(inode)->lock);
1574 BTRFS_I(inode)->outstanding_extents--;
1575 spin_unlock(&BTRFS_I(inode)->lock);
1579 * We don't reserve metadata space for space cache inodes so we
1580 * don't need to call dellalloc_release_metadata if there is an
1583 if (*bits & EXTENT_DO_ACCOUNTING &&
1584 root != root->fs_info->tree_root)
1585 btrfs_delalloc_release_metadata(inode, len);
1587 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1588 && do_list && !(state->state & EXTENT_NORESERVE))
1589 btrfs_free_reserved_data_space(inode, len);
1591 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1592 root->fs_info->delalloc_batch);
1593 spin_lock(&BTRFS_I(inode)->lock);
1594 BTRFS_I(inode)->delalloc_bytes -= len;
1595 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1596 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1597 &BTRFS_I(inode)->runtime_flags))
1598 btrfs_del_delalloc_inode(root, inode);
1599 spin_unlock(&BTRFS_I(inode)->lock);
1604 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1605 * we don't create bios that span stripes or chunks
1607 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1608 size_t size, struct bio *bio,
1609 unsigned long bio_flags)
1611 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1612 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1617 if (bio_flags & EXTENT_BIO_COMPRESSED)
1620 length = bio->bi_iter.bi_size;
1621 map_length = length;
1622 ret = btrfs_map_block(root->fs_info, rw, logical,
1623 &map_length, NULL, 0);
1624 /* Will always return 0 with map_multi == NULL */
1626 if (map_length < length + size)
1632 * in order to insert checksums into the metadata in large chunks,
1633 * we wait until bio submission time. All the pages in the bio are
1634 * checksummed and sums are attached onto the ordered extent record.
1636 * At IO completion time the cums attached on the ordered extent record
1637 * are inserted into the btree
1639 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1640 struct bio *bio, int mirror_num,
1641 unsigned long bio_flags,
1644 struct btrfs_root *root = BTRFS_I(inode)->root;
1647 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1648 BUG_ON(ret); /* -ENOMEM */
1653 * in order to insert checksums into the metadata in large chunks,
1654 * we wait until bio submission time. All the pages in the bio are
1655 * checksummed and sums are attached onto the ordered extent record.
1657 * At IO completion time the cums attached on the ordered extent record
1658 * are inserted into the btree
1660 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1661 int mirror_num, unsigned long bio_flags,
1664 struct btrfs_root *root = BTRFS_I(inode)->root;
1667 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1669 bio_endio(bio, ret);
1674 * extent_io.c submission hook. This does the right thing for csum calculation
1675 * on write, or reading the csums from the tree before a read
1677 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1678 int mirror_num, unsigned long bio_flags,
1681 struct btrfs_root *root = BTRFS_I(inode)->root;
1685 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1687 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1689 if (btrfs_is_free_space_inode(inode))
1692 if (!(rw & REQ_WRITE)) {
1693 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1697 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1698 ret = btrfs_submit_compressed_read(inode, bio,
1702 } else if (!skip_sum) {
1703 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1708 } else if (async && !skip_sum) {
1709 /* csum items have already been cloned */
1710 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1712 /* we're doing a write, do the async checksumming */
1713 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1714 inode, rw, bio, mirror_num,
1715 bio_flags, bio_offset,
1716 __btrfs_submit_bio_start,
1717 __btrfs_submit_bio_done);
1719 } else if (!skip_sum) {
1720 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1726 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1730 bio_endio(bio, ret);
1735 * given a list of ordered sums record them in the inode. This happens
1736 * at IO completion time based on sums calculated at bio submission time.
1738 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1739 struct inode *inode, u64 file_offset,
1740 struct list_head *list)
1742 struct btrfs_ordered_sum *sum;
1744 list_for_each_entry(sum, list, list) {
1745 trans->adding_csums = 1;
1746 btrfs_csum_file_blocks(trans,
1747 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1748 trans->adding_csums = 0;
1753 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1754 struct extent_state **cached_state)
1756 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1757 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1758 cached_state, GFP_NOFS);
1761 /* see btrfs_writepage_start_hook for details on why this is required */
1762 struct btrfs_writepage_fixup {
1764 struct btrfs_work work;
1767 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1769 struct btrfs_writepage_fixup *fixup;
1770 struct btrfs_ordered_extent *ordered;
1771 struct extent_state *cached_state = NULL;
1773 struct inode *inode;
1778 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1782 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1783 ClearPageChecked(page);
1787 inode = page->mapping->host;
1788 page_start = page_offset(page);
1789 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1791 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1794 /* already ordered? We're done */
1795 if (PagePrivate2(page))
1798 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1800 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1801 page_end, &cached_state, GFP_NOFS);
1803 btrfs_start_ordered_extent(inode, ordered, 1);
1804 btrfs_put_ordered_extent(ordered);
1808 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1810 mapping_set_error(page->mapping, ret);
1811 end_extent_writepage(page, ret, page_start, page_end);
1812 ClearPageChecked(page);
1816 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1817 ClearPageChecked(page);
1818 set_page_dirty(page);
1820 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1821 &cached_state, GFP_NOFS);
1824 page_cache_release(page);
1829 * There are a few paths in the higher layers of the kernel that directly
1830 * set the page dirty bit without asking the filesystem if it is a
1831 * good idea. This causes problems because we want to make sure COW
1832 * properly happens and the data=ordered rules are followed.
1834 * In our case any range that doesn't have the ORDERED bit set
1835 * hasn't been properly setup for IO. We kick off an async process
1836 * to fix it up. The async helper will wait for ordered extents, set
1837 * the delalloc bit and make it safe to write the page.
1839 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1841 struct inode *inode = page->mapping->host;
1842 struct btrfs_writepage_fixup *fixup;
1843 struct btrfs_root *root = BTRFS_I(inode)->root;
1845 /* this page is properly in the ordered list */
1846 if (TestClearPagePrivate2(page))
1849 if (PageChecked(page))
1852 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1856 SetPageChecked(page);
1857 page_cache_get(page);
1858 fixup->work.func = btrfs_writepage_fixup_worker;
1860 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1864 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1865 struct inode *inode, u64 file_pos,
1866 u64 disk_bytenr, u64 disk_num_bytes,
1867 u64 num_bytes, u64 ram_bytes,
1868 u8 compression, u8 encryption,
1869 u16 other_encoding, int extent_type)
1871 struct btrfs_root *root = BTRFS_I(inode)->root;
1872 struct btrfs_file_extent_item *fi;
1873 struct btrfs_path *path;
1874 struct extent_buffer *leaf;
1875 struct btrfs_key ins;
1876 int extent_inserted = 0;
1879 path = btrfs_alloc_path();
1884 * we may be replacing one extent in the tree with another.
1885 * The new extent is pinned in the extent map, and we don't want
1886 * to drop it from the cache until it is completely in the btree.
1888 * So, tell btrfs_drop_extents to leave this extent in the cache.
1889 * the caller is expected to unpin it and allow it to be merged
1892 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
1893 file_pos + num_bytes, NULL, 0,
1894 1, sizeof(*fi), &extent_inserted);
1898 if (!extent_inserted) {
1899 ins.objectid = btrfs_ino(inode);
1900 ins.offset = file_pos;
1901 ins.type = BTRFS_EXTENT_DATA_KEY;
1903 path->leave_spinning = 1;
1904 ret = btrfs_insert_empty_item(trans, root, path, &ins,
1909 leaf = path->nodes[0];
1910 fi = btrfs_item_ptr(leaf, path->slots[0],
1911 struct btrfs_file_extent_item);
1912 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1913 btrfs_set_file_extent_type(leaf, fi, extent_type);
1914 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1915 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1916 btrfs_set_file_extent_offset(leaf, fi, 0);
1917 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1918 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1919 btrfs_set_file_extent_compression(leaf, fi, compression);
1920 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1921 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1923 btrfs_mark_buffer_dirty(leaf);
1924 btrfs_release_path(path);
1926 inode_add_bytes(inode, num_bytes);
1928 ins.objectid = disk_bytenr;
1929 ins.offset = disk_num_bytes;
1930 ins.type = BTRFS_EXTENT_ITEM_KEY;
1931 ret = btrfs_alloc_reserved_file_extent(trans, root,
1932 root->root_key.objectid,
1933 btrfs_ino(inode), file_pos, &ins);
1935 btrfs_free_path(path);
1940 /* snapshot-aware defrag */
1941 struct sa_defrag_extent_backref {
1942 struct rb_node node;
1943 struct old_sa_defrag_extent *old;
1952 struct old_sa_defrag_extent {
1953 struct list_head list;
1954 struct new_sa_defrag_extent *new;
1963 struct new_sa_defrag_extent {
1964 struct rb_root root;
1965 struct list_head head;
1966 struct btrfs_path *path;
1967 struct inode *inode;
1975 static int backref_comp(struct sa_defrag_extent_backref *b1,
1976 struct sa_defrag_extent_backref *b2)
1978 if (b1->root_id < b2->root_id)
1980 else if (b1->root_id > b2->root_id)
1983 if (b1->inum < b2->inum)
1985 else if (b1->inum > b2->inum)
1988 if (b1->file_pos < b2->file_pos)
1990 else if (b1->file_pos > b2->file_pos)
1994 * [------------------------------] ===> (a range of space)
1995 * |<--->| |<---->| =============> (fs/file tree A)
1996 * |<---------------------------->| ===> (fs/file tree B)
1998 * A range of space can refer to two file extents in one tree while
1999 * refer to only one file extent in another tree.
2001 * So we may process a disk offset more than one time(two extents in A)
2002 * and locate at the same extent(one extent in B), then insert two same
2003 * backrefs(both refer to the extent in B).
2008 static void backref_insert(struct rb_root *root,
2009 struct sa_defrag_extent_backref *backref)
2011 struct rb_node **p = &root->rb_node;
2012 struct rb_node *parent = NULL;
2013 struct sa_defrag_extent_backref *entry;
2018 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2020 ret = backref_comp(backref, entry);
2024 p = &(*p)->rb_right;
2027 rb_link_node(&backref->node, parent, p);
2028 rb_insert_color(&backref->node, root);
2032 * Note the backref might has changed, and in this case we just return 0.
2034 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2037 struct btrfs_file_extent_item *extent;
2038 struct btrfs_fs_info *fs_info;
2039 struct old_sa_defrag_extent *old = ctx;
2040 struct new_sa_defrag_extent *new = old->new;
2041 struct btrfs_path *path = new->path;
2042 struct btrfs_key key;
2043 struct btrfs_root *root;
2044 struct sa_defrag_extent_backref *backref;
2045 struct extent_buffer *leaf;
2046 struct inode *inode = new->inode;
2052 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2053 inum == btrfs_ino(inode))
2056 key.objectid = root_id;
2057 key.type = BTRFS_ROOT_ITEM_KEY;
2058 key.offset = (u64)-1;
2060 fs_info = BTRFS_I(inode)->root->fs_info;
2061 root = btrfs_read_fs_root_no_name(fs_info, &key);
2063 if (PTR_ERR(root) == -ENOENT)
2066 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2067 inum, offset, root_id);
2068 return PTR_ERR(root);
2071 key.objectid = inum;
2072 key.type = BTRFS_EXTENT_DATA_KEY;
2073 if (offset > (u64)-1 << 32)
2076 key.offset = offset;
2078 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2079 if (WARN_ON(ret < 0))
2086 leaf = path->nodes[0];
2087 slot = path->slots[0];
2089 if (slot >= btrfs_header_nritems(leaf)) {
2090 ret = btrfs_next_leaf(root, path);
2093 } else if (ret > 0) {
2102 btrfs_item_key_to_cpu(leaf, &key, slot);
2104 if (key.objectid > inum)
2107 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2110 extent = btrfs_item_ptr(leaf, slot,
2111 struct btrfs_file_extent_item);
2113 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2117 * 'offset' refers to the exact key.offset,
2118 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2119 * (key.offset - extent_offset).
2121 if (key.offset != offset)
2124 extent_offset = btrfs_file_extent_offset(leaf, extent);
2125 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2127 if (extent_offset >= old->extent_offset + old->offset +
2128 old->len || extent_offset + num_bytes <=
2129 old->extent_offset + old->offset)
2134 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2140 backref->root_id = root_id;
2141 backref->inum = inum;
2142 backref->file_pos = offset;
2143 backref->num_bytes = num_bytes;
2144 backref->extent_offset = extent_offset;
2145 backref->generation = btrfs_file_extent_generation(leaf, extent);
2147 backref_insert(&new->root, backref);
2150 btrfs_release_path(path);
2155 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2156 struct new_sa_defrag_extent *new)
2158 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2159 struct old_sa_defrag_extent *old, *tmp;
2164 list_for_each_entry_safe(old, tmp, &new->head, list) {
2165 ret = iterate_inodes_from_logical(old->bytenr +
2166 old->extent_offset, fs_info,
2167 path, record_one_backref,
2169 if (ret < 0 && ret != -ENOENT)
2172 /* no backref to be processed for this extent */
2174 list_del(&old->list);
2179 if (list_empty(&new->head))
2185 static int relink_is_mergable(struct extent_buffer *leaf,
2186 struct btrfs_file_extent_item *fi,
2187 struct new_sa_defrag_extent *new)
2189 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2192 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2195 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2198 if (btrfs_file_extent_encryption(leaf, fi) ||
2199 btrfs_file_extent_other_encoding(leaf, fi))
2206 * Note the backref might has changed, and in this case we just return 0.
2208 static noinline int relink_extent_backref(struct btrfs_path *path,
2209 struct sa_defrag_extent_backref *prev,
2210 struct sa_defrag_extent_backref *backref)
2212 struct btrfs_file_extent_item *extent;
2213 struct btrfs_file_extent_item *item;
2214 struct btrfs_ordered_extent *ordered;
2215 struct btrfs_trans_handle *trans;
2216 struct btrfs_fs_info *fs_info;
2217 struct btrfs_root *root;
2218 struct btrfs_key key;
2219 struct extent_buffer *leaf;
2220 struct old_sa_defrag_extent *old = backref->old;
2221 struct new_sa_defrag_extent *new = old->new;
2222 struct inode *src_inode = new->inode;
2223 struct inode *inode;
2224 struct extent_state *cached = NULL;
2233 if (prev && prev->root_id == backref->root_id &&
2234 prev->inum == backref->inum &&
2235 prev->file_pos + prev->num_bytes == backref->file_pos)
2238 /* step 1: get root */
2239 key.objectid = backref->root_id;
2240 key.type = BTRFS_ROOT_ITEM_KEY;
2241 key.offset = (u64)-1;
2243 fs_info = BTRFS_I(src_inode)->root->fs_info;
2244 index = srcu_read_lock(&fs_info->subvol_srcu);
2246 root = btrfs_read_fs_root_no_name(fs_info, &key);
2248 srcu_read_unlock(&fs_info->subvol_srcu, index);
2249 if (PTR_ERR(root) == -ENOENT)
2251 return PTR_ERR(root);
2254 /* step 2: get inode */
2255 key.objectid = backref->inum;
2256 key.type = BTRFS_INODE_ITEM_KEY;
2259 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2260 if (IS_ERR(inode)) {
2261 srcu_read_unlock(&fs_info->subvol_srcu, index);
2265 srcu_read_unlock(&fs_info->subvol_srcu, index);
2267 /* step 3: relink backref */
2268 lock_start = backref->file_pos;
2269 lock_end = backref->file_pos + backref->num_bytes - 1;
2270 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2273 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2275 btrfs_put_ordered_extent(ordered);
2279 trans = btrfs_join_transaction(root);
2280 if (IS_ERR(trans)) {
2281 ret = PTR_ERR(trans);
2285 key.objectid = backref->inum;
2286 key.type = BTRFS_EXTENT_DATA_KEY;
2287 key.offset = backref->file_pos;
2289 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2292 } else if (ret > 0) {
2297 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2298 struct btrfs_file_extent_item);
2300 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2301 backref->generation)
2304 btrfs_release_path(path);
2306 start = backref->file_pos;
2307 if (backref->extent_offset < old->extent_offset + old->offset)
2308 start += old->extent_offset + old->offset -
2309 backref->extent_offset;
2311 len = min(backref->extent_offset + backref->num_bytes,
2312 old->extent_offset + old->offset + old->len);
2313 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2315 ret = btrfs_drop_extents(trans, root, inode, start,
2320 key.objectid = btrfs_ino(inode);
2321 key.type = BTRFS_EXTENT_DATA_KEY;
2324 path->leave_spinning = 1;
2326 struct btrfs_file_extent_item *fi;
2328 struct btrfs_key found_key;
2330 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2335 leaf = path->nodes[0];
2336 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2338 fi = btrfs_item_ptr(leaf, path->slots[0],
2339 struct btrfs_file_extent_item);
2340 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2342 if (extent_len + found_key.offset == start &&
2343 relink_is_mergable(leaf, fi, new)) {
2344 btrfs_set_file_extent_num_bytes(leaf, fi,
2346 btrfs_mark_buffer_dirty(leaf);
2347 inode_add_bytes(inode, len);
2353 btrfs_release_path(path);
2358 ret = btrfs_insert_empty_item(trans, root, path, &key,
2361 btrfs_abort_transaction(trans, root, ret);
2365 leaf = path->nodes[0];
2366 item = btrfs_item_ptr(leaf, path->slots[0],
2367 struct btrfs_file_extent_item);
2368 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2369 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2370 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2371 btrfs_set_file_extent_num_bytes(leaf, item, len);
2372 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2373 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2374 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2375 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2376 btrfs_set_file_extent_encryption(leaf, item, 0);
2377 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2379 btrfs_mark_buffer_dirty(leaf);
2380 inode_add_bytes(inode, len);
2381 btrfs_release_path(path);
2383 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2385 backref->root_id, backref->inum,
2386 new->file_pos, 0); /* start - extent_offset */
2388 btrfs_abort_transaction(trans, root, ret);
2394 btrfs_release_path(path);
2395 path->leave_spinning = 0;
2396 btrfs_end_transaction(trans, root);
2398 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2404 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2406 struct old_sa_defrag_extent *old, *tmp;
2411 list_for_each_entry_safe(old, tmp, &new->head, list) {
2412 list_del(&old->list);
2418 static void relink_file_extents(struct new_sa_defrag_extent *new)
2420 struct btrfs_path *path;
2421 struct sa_defrag_extent_backref *backref;
2422 struct sa_defrag_extent_backref *prev = NULL;
2423 struct inode *inode;
2424 struct btrfs_root *root;
2425 struct rb_node *node;
2429 root = BTRFS_I(inode)->root;
2431 path = btrfs_alloc_path();
2435 if (!record_extent_backrefs(path, new)) {
2436 btrfs_free_path(path);
2439 btrfs_release_path(path);
2442 node = rb_first(&new->root);
2445 rb_erase(node, &new->root);
2447 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2449 ret = relink_extent_backref(path, prev, backref);
2462 btrfs_free_path(path);
2464 free_sa_defrag_extent(new);
2466 atomic_dec(&root->fs_info->defrag_running);
2467 wake_up(&root->fs_info->transaction_wait);
2470 static struct new_sa_defrag_extent *
2471 record_old_file_extents(struct inode *inode,
2472 struct btrfs_ordered_extent *ordered)
2474 struct btrfs_root *root = BTRFS_I(inode)->root;
2475 struct btrfs_path *path;
2476 struct btrfs_key key;
2477 struct old_sa_defrag_extent *old;
2478 struct new_sa_defrag_extent *new;
2481 new = kmalloc(sizeof(*new), GFP_NOFS);
2486 new->file_pos = ordered->file_offset;
2487 new->len = ordered->len;
2488 new->bytenr = ordered->start;
2489 new->disk_len = ordered->disk_len;
2490 new->compress_type = ordered->compress_type;
2491 new->root = RB_ROOT;
2492 INIT_LIST_HEAD(&new->head);
2494 path = btrfs_alloc_path();
2498 key.objectid = btrfs_ino(inode);
2499 key.type = BTRFS_EXTENT_DATA_KEY;
2500 key.offset = new->file_pos;
2502 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2505 if (ret > 0 && path->slots[0] > 0)
2508 /* find out all the old extents for the file range */
2510 struct btrfs_file_extent_item *extent;
2511 struct extent_buffer *l;
2520 slot = path->slots[0];
2522 if (slot >= btrfs_header_nritems(l)) {
2523 ret = btrfs_next_leaf(root, path);
2531 btrfs_item_key_to_cpu(l, &key, slot);
2533 if (key.objectid != btrfs_ino(inode))
2535 if (key.type != BTRFS_EXTENT_DATA_KEY)
2537 if (key.offset >= new->file_pos + new->len)
2540 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2542 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2543 if (key.offset + num_bytes < new->file_pos)
2546 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2550 extent_offset = btrfs_file_extent_offset(l, extent);
2552 old = kmalloc(sizeof(*old), GFP_NOFS);
2556 offset = max(new->file_pos, key.offset);
2557 end = min(new->file_pos + new->len, key.offset + num_bytes);
2559 old->bytenr = disk_bytenr;
2560 old->extent_offset = extent_offset;
2561 old->offset = offset - key.offset;
2562 old->len = end - offset;
2565 list_add_tail(&old->list, &new->head);
2571 btrfs_free_path(path);
2572 atomic_inc(&root->fs_info->defrag_running);
2577 btrfs_free_path(path);
2579 free_sa_defrag_extent(new);
2583 /* as ordered data IO finishes, this gets called so we can finish
2584 * an ordered extent if the range of bytes in the file it covers are
2587 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2589 struct inode *inode = ordered_extent->inode;
2590 struct btrfs_root *root = BTRFS_I(inode)->root;
2591 struct btrfs_trans_handle *trans = NULL;
2592 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2593 struct extent_state *cached_state = NULL;
2594 struct new_sa_defrag_extent *new = NULL;
2595 int compress_type = 0;
2597 u64 logical_len = ordered_extent->len;
2599 bool truncated = false;
2601 nolock = btrfs_is_free_space_inode(inode);
2603 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2608 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2610 logical_len = ordered_extent->truncated_len;
2611 /* Truncated the entire extent, don't bother adding */
2616 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2617 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2618 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2620 trans = btrfs_join_transaction_nolock(root);
2622 trans = btrfs_join_transaction(root);
2623 if (IS_ERR(trans)) {
2624 ret = PTR_ERR(trans);
2628 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2629 ret = btrfs_update_inode_fallback(trans, root, inode);
2630 if (ret) /* -ENOMEM or corruption */
2631 btrfs_abort_transaction(trans, root, ret);
2635 lock_extent_bits(io_tree, ordered_extent->file_offset,
2636 ordered_extent->file_offset + ordered_extent->len - 1,
2639 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2640 ordered_extent->file_offset + ordered_extent->len - 1,
2641 EXTENT_DEFRAG, 1, cached_state);
2643 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2644 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2645 /* the inode is shared */
2646 new = record_old_file_extents(inode, ordered_extent);
2648 clear_extent_bit(io_tree, ordered_extent->file_offset,
2649 ordered_extent->file_offset + ordered_extent->len - 1,
2650 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2654 trans = btrfs_join_transaction_nolock(root);
2656 trans = btrfs_join_transaction(root);
2657 if (IS_ERR(trans)) {
2658 ret = PTR_ERR(trans);
2662 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2664 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2665 compress_type = ordered_extent->compress_type;
2666 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2667 BUG_ON(compress_type);
2668 ret = btrfs_mark_extent_written(trans, inode,
2669 ordered_extent->file_offset,
2670 ordered_extent->file_offset +
2673 BUG_ON(root == root->fs_info->tree_root);
2674 ret = insert_reserved_file_extent(trans, inode,
2675 ordered_extent->file_offset,
2676 ordered_extent->start,
2677 ordered_extent->disk_len,
2678 logical_len, logical_len,
2679 compress_type, 0, 0,
2680 BTRFS_FILE_EXTENT_REG);
2682 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2683 ordered_extent->file_offset, ordered_extent->len,
2686 btrfs_abort_transaction(trans, root, ret);
2690 add_pending_csums(trans, inode, ordered_extent->file_offset,
2691 &ordered_extent->list);
2693 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2694 ret = btrfs_update_inode_fallback(trans, root, inode);
2695 if (ret) { /* -ENOMEM or corruption */
2696 btrfs_abort_transaction(trans, root, ret);
2701 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2702 ordered_extent->file_offset +
2703 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2705 if (root != root->fs_info->tree_root)
2706 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2708 btrfs_end_transaction(trans, root);
2710 if (ret || truncated) {
2714 start = ordered_extent->file_offset + logical_len;
2716 start = ordered_extent->file_offset;
2717 end = ordered_extent->file_offset + ordered_extent->len - 1;
2718 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2720 /* Drop the cache for the part of the extent we didn't write. */
2721 btrfs_drop_extent_cache(inode, start, end, 0);
2724 * If the ordered extent had an IOERR or something else went
2725 * wrong we need to return the space for this ordered extent
2726 * back to the allocator. We only free the extent in the
2727 * truncated case if we didn't write out the extent at all.
2729 if ((ret || !logical_len) &&
2730 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2731 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2732 btrfs_free_reserved_extent(root, ordered_extent->start,
2733 ordered_extent->disk_len);
2738 * This needs to be done to make sure anybody waiting knows we are done
2739 * updating everything for this ordered extent.
2741 btrfs_remove_ordered_extent(inode, ordered_extent);
2743 /* for snapshot-aware defrag */
2746 free_sa_defrag_extent(new);
2747 atomic_dec(&root->fs_info->defrag_running);
2749 relink_file_extents(new);
2754 btrfs_put_ordered_extent(ordered_extent);
2755 /* once for the tree */
2756 btrfs_put_ordered_extent(ordered_extent);
2761 static void finish_ordered_fn(struct btrfs_work *work)
2763 struct btrfs_ordered_extent *ordered_extent;
2764 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2765 btrfs_finish_ordered_io(ordered_extent);
2768 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2769 struct extent_state *state, int uptodate)
2771 struct inode *inode = page->mapping->host;
2772 struct btrfs_root *root = BTRFS_I(inode)->root;
2773 struct btrfs_ordered_extent *ordered_extent = NULL;
2774 struct btrfs_workers *workers;
2776 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2778 ClearPagePrivate2(page);
2779 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2780 end - start + 1, uptodate))
2783 ordered_extent->work.func = finish_ordered_fn;
2784 ordered_extent->work.flags = 0;
2786 if (btrfs_is_free_space_inode(inode))
2787 workers = &root->fs_info->endio_freespace_worker;
2789 workers = &root->fs_info->endio_write_workers;
2790 btrfs_queue_worker(workers, &ordered_extent->work);
2796 * when reads are done, we need to check csums to verify the data is correct
2797 * if there's a match, we allow the bio to finish. If not, the code in
2798 * extent_io.c will try to find good copies for us.
2800 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2801 u64 phy_offset, struct page *page,
2802 u64 start, u64 end, int mirror)
2804 size_t offset = start - page_offset(page);
2805 struct inode *inode = page->mapping->host;
2806 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2808 struct btrfs_root *root = BTRFS_I(inode)->root;
2811 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2812 DEFAULT_RATELIMIT_BURST);
2814 if (PageChecked(page)) {
2815 ClearPageChecked(page);
2819 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2822 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2823 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2824 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2829 phy_offset >>= inode->i_sb->s_blocksize_bits;
2830 csum_expected = *(((u32 *)io_bio->csum) + phy_offset);
2832 kaddr = kmap_atomic(page);
2833 csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
2834 btrfs_csum_final(csum, (char *)&csum);
2835 if (csum != csum_expected)
2838 kunmap_atomic(kaddr);
2843 if (__ratelimit(&_rs))
2844 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
2845 btrfs_ino(page->mapping->host), start, csum, csum_expected);
2846 memset(kaddr + offset, 1, end - start + 1);
2847 flush_dcache_page(page);
2848 kunmap_atomic(kaddr);
2849 if (csum_expected == 0)
2854 struct delayed_iput {
2855 struct list_head list;
2856 struct inode *inode;
2859 /* JDM: If this is fs-wide, why can't we add a pointer to
2860 * btrfs_inode instead and avoid the allocation? */
2861 void btrfs_add_delayed_iput(struct inode *inode)
2863 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2864 struct delayed_iput *delayed;
2866 if (atomic_add_unless(&inode->i_count, -1, 1))
2869 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2870 delayed->inode = inode;
2872 spin_lock(&fs_info->delayed_iput_lock);
2873 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2874 spin_unlock(&fs_info->delayed_iput_lock);
2877 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2880 struct btrfs_fs_info *fs_info = root->fs_info;
2881 struct delayed_iput *delayed;
2884 spin_lock(&fs_info->delayed_iput_lock);
2885 empty = list_empty(&fs_info->delayed_iputs);
2886 spin_unlock(&fs_info->delayed_iput_lock);
2890 spin_lock(&fs_info->delayed_iput_lock);
2891 list_splice_init(&fs_info->delayed_iputs, &list);
2892 spin_unlock(&fs_info->delayed_iput_lock);
2894 while (!list_empty(&list)) {
2895 delayed = list_entry(list.next, struct delayed_iput, list);
2896 list_del(&delayed->list);
2897 iput(delayed->inode);
2903 * This is called in transaction commit time. If there are no orphan
2904 * files in the subvolume, it removes orphan item and frees block_rsv
2907 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2908 struct btrfs_root *root)
2910 struct btrfs_block_rsv *block_rsv;
2913 if (atomic_read(&root->orphan_inodes) ||
2914 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2917 spin_lock(&root->orphan_lock);
2918 if (atomic_read(&root->orphan_inodes)) {
2919 spin_unlock(&root->orphan_lock);
2923 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2924 spin_unlock(&root->orphan_lock);
2928 block_rsv = root->orphan_block_rsv;
2929 root->orphan_block_rsv = NULL;
2930 spin_unlock(&root->orphan_lock);
2932 if (root->orphan_item_inserted &&
2933 btrfs_root_refs(&root->root_item) > 0) {
2934 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2935 root->root_key.objectid);
2937 btrfs_abort_transaction(trans, root, ret);
2939 root->orphan_item_inserted = 0;
2943 WARN_ON(block_rsv->size > 0);
2944 btrfs_free_block_rsv(root, block_rsv);
2949 * This creates an orphan entry for the given inode in case something goes
2950 * wrong in the middle of an unlink/truncate.
2952 * NOTE: caller of this function should reserve 5 units of metadata for
2955 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2957 struct btrfs_root *root = BTRFS_I(inode)->root;
2958 struct btrfs_block_rsv *block_rsv = NULL;
2963 if (!root->orphan_block_rsv) {
2964 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2969 spin_lock(&root->orphan_lock);
2970 if (!root->orphan_block_rsv) {
2971 root->orphan_block_rsv = block_rsv;
2972 } else if (block_rsv) {
2973 btrfs_free_block_rsv(root, block_rsv);
2977 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2978 &BTRFS_I(inode)->runtime_flags)) {
2981 * For proper ENOSPC handling, we should do orphan
2982 * cleanup when mounting. But this introduces backward
2983 * compatibility issue.
2985 if (!xchg(&root->orphan_item_inserted, 1))
2991 atomic_inc(&root->orphan_inodes);
2994 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2995 &BTRFS_I(inode)->runtime_flags))
2997 spin_unlock(&root->orphan_lock);
2999 /* grab metadata reservation from transaction handle */
3001 ret = btrfs_orphan_reserve_metadata(trans, inode);
3002 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3005 /* insert an orphan item to track this unlinked/truncated file */
3007 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3009 atomic_dec(&root->orphan_inodes);
3011 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3012 &BTRFS_I(inode)->runtime_flags);
3013 btrfs_orphan_release_metadata(inode);
3015 if (ret != -EEXIST) {
3016 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3017 &BTRFS_I(inode)->runtime_flags);
3018 btrfs_abort_transaction(trans, root, ret);
3025 /* insert an orphan item to track subvolume contains orphan files */
3027 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3028 root->root_key.objectid);
3029 if (ret && ret != -EEXIST) {
3030 btrfs_abort_transaction(trans, root, ret);
3038 * We have done the truncate/delete so we can go ahead and remove the orphan
3039 * item for this particular inode.
3041 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3042 struct inode *inode)
3044 struct btrfs_root *root = BTRFS_I(inode)->root;
3045 int delete_item = 0;
3046 int release_rsv = 0;
3049 spin_lock(&root->orphan_lock);
3050 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3051 &BTRFS_I(inode)->runtime_flags))
3054 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3055 &BTRFS_I(inode)->runtime_flags))
3057 spin_unlock(&root->orphan_lock);
3060 atomic_dec(&root->orphan_inodes);
3062 ret = btrfs_del_orphan_item(trans, root,
3067 btrfs_orphan_release_metadata(inode);
3073 * this cleans up any orphans that may be left on the list from the last use
3076 int btrfs_orphan_cleanup(struct btrfs_root *root)
3078 struct btrfs_path *path;
3079 struct extent_buffer *leaf;
3080 struct btrfs_key key, found_key;
3081 struct btrfs_trans_handle *trans;
3082 struct inode *inode;
3083 u64 last_objectid = 0;
3084 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3086 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3089 path = btrfs_alloc_path();
3096 key.objectid = BTRFS_ORPHAN_OBJECTID;
3097 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3098 key.offset = (u64)-1;
3101 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3106 * if ret == 0 means we found what we were searching for, which
3107 * is weird, but possible, so only screw with path if we didn't
3108 * find the key and see if we have stuff that matches
3112 if (path->slots[0] == 0)
3117 /* pull out the item */
3118 leaf = path->nodes[0];
3119 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3121 /* make sure the item matches what we want */
3122 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3124 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3127 /* release the path since we're done with it */
3128 btrfs_release_path(path);
3131 * this is where we are basically btrfs_lookup, without the
3132 * crossing root thing. we store the inode number in the
3133 * offset of the orphan item.
3136 if (found_key.offset == last_objectid) {
3137 btrfs_err(root->fs_info,
3138 "Error removing orphan entry, stopping orphan cleanup");
3143 last_objectid = found_key.offset;
3145 found_key.objectid = found_key.offset;
3146 found_key.type = BTRFS_INODE_ITEM_KEY;
3147 found_key.offset = 0;
3148 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3149 ret = PTR_ERR_OR_ZERO(inode);
3150 if (ret && ret != -ESTALE)
3153 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3154 struct btrfs_root *dead_root;
3155 struct btrfs_fs_info *fs_info = root->fs_info;
3156 int is_dead_root = 0;
3159 * this is an orphan in the tree root. Currently these
3160 * could come from 2 sources:
3161 * a) a snapshot deletion in progress
3162 * b) a free space cache inode
3163 * We need to distinguish those two, as the snapshot
3164 * orphan must not get deleted.
3165 * find_dead_roots already ran before us, so if this
3166 * is a snapshot deletion, we should find the root
3167 * in the dead_roots list
3169 spin_lock(&fs_info->trans_lock);
3170 list_for_each_entry(dead_root, &fs_info->dead_roots,
3172 if (dead_root->root_key.objectid ==
3173 found_key.objectid) {
3178 spin_unlock(&fs_info->trans_lock);
3180 /* prevent this orphan from being found again */
3181 key.offset = found_key.objectid - 1;
3186 * Inode is already gone but the orphan item is still there,
3187 * kill the orphan item.
3189 if (ret == -ESTALE) {
3190 trans = btrfs_start_transaction(root, 1);
3191 if (IS_ERR(trans)) {
3192 ret = PTR_ERR(trans);
3195 btrfs_debug(root->fs_info, "auto deleting %Lu",
3196 found_key.objectid);
3197 ret = btrfs_del_orphan_item(trans, root,
3198 found_key.objectid);
3199 btrfs_end_transaction(trans, root);
3206 * add this inode to the orphan list so btrfs_orphan_del does
3207 * the proper thing when we hit it
3209 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3210 &BTRFS_I(inode)->runtime_flags);
3211 atomic_inc(&root->orphan_inodes);
3213 /* if we have links, this was a truncate, lets do that */
3214 if (inode->i_nlink) {
3215 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3221 /* 1 for the orphan item deletion. */
3222 trans = btrfs_start_transaction(root, 1);
3223 if (IS_ERR(trans)) {
3225 ret = PTR_ERR(trans);
3228 ret = btrfs_orphan_add(trans, inode);
3229 btrfs_end_transaction(trans, root);
3235 ret = btrfs_truncate(inode);
3237 btrfs_orphan_del(NULL, inode);
3242 /* this will do delete_inode and everything for us */
3247 /* release the path since we're done with it */
3248 btrfs_release_path(path);
3250 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3252 if (root->orphan_block_rsv)
3253 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3256 if (root->orphan_block_rsv || root->orphan_item_inserted) {
3257 trans = btrfs_join_transaction(root);
3259 btrfs_end_transaction(trans, root);
3263 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3265 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3269 btrfs_crit(root->fs_info,
3270 "could not do orphan cleanup %d", ret);
3271 btrfs_free_path(path);
3276 * very simple check to peek ahead in the leaf looking for xattrs. If we
3277 * don't find any xattrs, we know there can't be any acls.
3279 * slot is the slot the inode is in, objectid is the objectid of the inode
3281 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3282 int slot, u64 objectid,
3283 int *first_xattr_slot)
3285 u32 nritems = btrfs_header_nritems(leaf);
3286 struct btrfs_key found_key;
3287 static u64 xattr_access = 0;
3288 static u64 xattr_default = 0;
3291 if (!xattr_access) {
3292 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3293 strlen(POSIX_ACL_XATTR_ACCESS));
3294 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3295 strlen(POSIX_ACL_XATTR_DEFAULT));
3299 *first_xattr_slot = -1;
3300 while (slot < nritems) {
3301 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3303 /* we found a different objectid, there must not be acls */
3304 if (found_key.objectid != objectid)
3307 /* we found an xattr, assume we've got an acl */
3308 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3309 if (*first_xattr_slot == -1)
3310 *first_xattr_slot = slot;
3311 if (found_key.offset == xattr_access ||
3312 found_key.offset == xattr_default)
3317 * we found a key greater than an xattr key, there can't
3318 * be any acls later on
3320 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3327 * it goes inode, inode backrefs, xattrs, extents,
3328 * so if there are a ton of hard links to an inode there can
3329 * be a lot of backrefs. Don't waste time searching too hard,
3330 * this is just an optimization
3335 /* we hit the end of the leaf before we found an xattr or
3336 * something larger than an xattr. We have to assume the inode
3339 if (*first_xattr_slot == -1)
3340 *first_xattr_slot = slot;
3345 * read an inode from the btree into the in-memory inode
3347 static void btrfs_read_locked_inode(struct inode *inode)
3349 struct btrfs_path *path;
3350 struct extent_buffer *leaf;
3351 struct btrfs_inode_item *inode_item;
3352 struct btrfs_timespec *tspec;
3353 struct btrfs_root *root = BTRFS_I(inode)->root;
3354 struct btrfs_key location;
3359 bool filled = false;
3360 int first_xattr_slot;
3362 ret = btrfs_fill_inode(inode, &rdev);
3366 path = btrfs_alloc_path();
3370 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3372 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3376 leaf = path->nodes[0];
3381 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3382 struct btrfs_inode_item);
3383 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3384 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3385 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3386 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3387 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3389 tspec = btrfs_inode_atime(inode_item);
3390 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3391 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3393 tspec = btrfs_inode_mtime(inode_item);
3394 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3395 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3397 tspec = btrfs_inode_ctime(inode_item);
3398 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3399 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3401 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3402 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3403 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3406 * If we were modified in the current generation and evicted from memory
3407 * and then re-read we need to do a full sync since we don't have any
3408 * idea about which extents were modified before we were evicted from
3411 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3412 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3413 &BTRFS_I(inode)->runtime_flags);
3415 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3416 inode->i_generation = BTRFS_I(inode)->generation;
3418 rdev = btrfs_inode_rdev(leaf, inode_item);
3420 BTRFS_I(inode)->index_cnt = (u64)-1;
3421 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3425 if (inode->i_nlink != 1 ||
3426 path->slots[0] >= btrfs_header_nritems(leaf))
3429 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3430 if (location.objectid != btrfs_ino(inode))
3433 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3434 if (location.type == BTRFS_INODE_REF_KEY) {
3435 struct btrfs_inode_ref *ref;
3437 ref = (struct btrfs_inode_ref *)ptr;
3438 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3439 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3440 struct btrfs_inode_extref *extref;
3442 extref = (struct btrfs_inode_extref *)ptr;
3443 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3448 * try to precache a NULL acl entry for files that don't have
3449 * any xattrs or acls
3451 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3452 btrfs_ino(inode), &first_xattr_slot);
3453 if (first_xattr_slot != -1) {
3454 path->slots[0] = first_xattr_slot;
3455 ret = btrfs_load_inode_props(inode, path);
3457 btrfs_err(root->fs_info,
3458 "error loading props for ino %llu (root %llu): %d\n",
3460 root->root_key.objectid, ret);
3462 btrfs_free_path(path);
3465 cache_no_acl(inode);
3467 switch (inode->i_mode & S_IFMT) {
3469 inode->i_mapping->a_ops = &btrfs_aops;
3470 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3471 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3472 inode->i_fop = &btrfs_file_operations;
3473 inode->i_op = &btrfs_file_inode_operations;
3476 inode->i_fop = &btrfs_dir_file_operations;
3477 if (root == root->fs_info->tree_root)
3478 inode->i_op = &btrfs_dir_ro_inode_operations;
3480 inode->i_op = &btrfs_dir_inode_operations;
3483 inode->i_op = &btrfs_symlink_inode_operations;
3484 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3485 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3488 inode->i_op = &btrfs_special_inode_operations;
3489 init_special_inode(inode, inode->i_mode, rdev);
3493 btrfs_update_iflags(inode);
3497 btrfs_free_path(path);
3498 make_bad_inode(inode);
3502 * given a leaf and an inode, copy the inode fields into the leaf
3504 static void fill_inode_item(struct btrfs_trans_handle *trans,
3505 struct extent_buffer *leaf,
3506 struct btrfs_inode_item *item,
3507 struct inode *inode)
3509 struct btrfs_map_token token;
3511 btrfs_init_map_token(&token);
3513 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3514 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3515 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3517 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3518 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3520 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3521 inode->i_atime.tv_sec, &token);
3522 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3523 inode->i_atime.tv_nsec, &token);
3525 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3526 inode->i_mtime.tv_sec, &token);
3527 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3528 inode->i_mtime.tv_nsec, &token);
3530 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3531 inode->i_ctime.tv_sec, &token);
3532 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3533 inode->i_ctime.tv_nsec, &token);
3535 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3537 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3539 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3540 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3541 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3542 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3543 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3547 * copy everything in the in-memory inode into the btree.
3549 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3550 struct btrfs_root *root, struct inode *inode)
3552 struct btrfs_inode_item *inode_item;
3553 struct btrfs_path *path;
3554 struct extent_buffer *leaf;
3557 path = btrfs_alloc_path();
3561 path->leave_spinning = 1;
3562 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3570 leaf = path->nodes[0];
3571 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3572 struct btrfs_inode_item);
3574 fill_inode_item(trans, leaf, inode_item, inode);
3575 btrfs_mark_buffer_dirty(leaf);
3576 btrfs_set_inode_last_trans(trans, inode);
3579 btrfs_free_path(path);
3584 * copy everything in the in-memory inode into the btree.
3586 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3587 struct btrfs_root *root, struct inode *inode)
3592 * If the inode is a free space inode, we can deadlock during commit
3593 * if we put it into the delayed code.
3595 * The data relocation inode should also be directly updated
3598 if (!btrfs_is_free_space_inode(inode)
3599 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3600 btrfs_update_root_times(trans, root);
3602 ret = btrfs_delayed_update_inode(trans, root, inode);
3604 btrfs_set_inode_last_trans(trans, inode);
3608 return btrfs_update_inode_item(trans, root, inode);
3611 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3612 struct btrfs_root *root,
3613 struct inode *inode)
3617 ret = btrfs_update_inode(trans, root, inode);
3619 return btrfs_update_inode_item(trans, root, inode);
3624 * unlink helper that gets used here in inode.c and in the tree logging
3625 * recovery code. It remove a link in a directory with a given name, and
3626 * also drops the back refs in the inode to the directory
3628 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3629 struct btrfs_root *root,
3630 struct inode *dir, struct inode *inode,
3631 const char *name, int name_len)
3633 struct btrfs_path *path;
3635 struct extent_buffer *leaf;
3636 struct btrfs_dir_item *di;
3637 struct btrfs_key key;
3639 u64 ino = btrfs_ino(inode);
3640 u64 dir_ino = btrfs_ino(dir);
3642 path = btrfs_alloc_path();
3648 path->leave_spinning = 1;
3649 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3650 name, name_len, -1);
3659 leaf = path->nodes[0];
3660 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3661 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3664 btrfs_release_path(path);
3667 * If we don't have dir index, we have to get it by looking up
3668 * the inode ref, since we get the inode ref, remove it directly,
3669 * it is unnecessary to do delayed deletion.
3671 * But if we have dir index, needn't search inode ref to get it.
3672 * Since the inode ref is close to the inode item, it is better
3673 * that we delay to delete it, and just do this deletion when
3674 * we update the inode item.
3676 if (BTRFS_I(inode)->dir_index) {
3677 ret = btrfs_delayed_delete_inode_ref(inode);
3679 index = BTRFS_I(inode)->dir_index;
3684 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3687 btrfs_info(root->fs_info,
3688 "failed to delete reference to %.*s, inode %llu parent %llu",
3689 name_len, name, ino, dir_ino);
3690 btrfs_abort_transaction(trans, root, ret);
3694 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3696 btrfs_abort_transaction(trans, root, ret);
3700 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3702 if (ret != 0 && ret != -ENOENT) {
3703 btrfs_abort_transaction(trans, root, ret);
3707 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3712 btrfs_abort_transaction(trans, root, ret);
3714 btrfs_free_path(path);
3718 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3719 inode_inc_iversion(inode);
3720 inode_inc_iversion(dir);
3721 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3722 ret = btrfs_update_inode(trans, root, dir);
3727 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3728 struct btrfs_root *root,
3729 struct inode *dir, struct inode *inode,
3730 const char *name, int name_len)
3733 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3736 ret = btrfs_update_inode(trans, root, inode);
3742 * helper to start transaction for unlink and rmdir.
3744 * unlink and rmdir are special in btrfs, they do not always free space, so
3745 * if we cannot make our reservations the normal way try and see if there is
3746 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3747 * allow the unlink to occur.
3749 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3751 struct btrfs_trans_handle *trans;
3752 struct btrfs_root *root = BTRFS_I(dir)->root;
3756 * 1 for the possible orphan item
3757 * 1 for the dir item
3758 * 1 for the dir index
3759 * 1 for the inode ref
3762 trans = btrfs_start_transaction(root, 5);
3763 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3766 if (PTR_ERR(trans) == -ENOSPC) {
3767 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3769 trans = btrfs_start_transaction(root, 0);
3772 ret = btrfs_cond_migrate_bytes(root->fs_info,
3773 &root->fs_info->trans_block_rsv,
3776 btrfs_end_transaction(trans, root);
3777 return ERR_PTR(ret);
3779 trans->block_rsv = &root->fs_info->trans_block_rsv;
3780 trans->bytes_reserved = num_bytes;
3785 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3787 struct btrfs_root *root = BTRFS_I(dir)->root;
3788 struct btrfs_trans_handle *trans;
3789 struct inode *inode = dentry->d_inode;
3792 trans = __unlink_start_trans(dir);
3794 return PTR_ERR(trans);
3796 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3798 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3799 dentry->d_name.name, dentry->d_name.len);
3803 if (inode->i_nlink == 0) {
3804 ret = btrfs_orphan_add(trans, inode);
3810 btrfs_end_transaction(trans, root);
3811 btrfs_btree_balance_dirty(root);
3815 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3816 struct btrfs_root *root,
3817 struct inode *dir, u64 objectid,
3818 const char *name, int name_len)
3820 struct btrfs_path *path;
3821 struct extent_buffer *leaf;
3822 struct btrfs_dir_item *di;
3823 struct btrfs_key key;
3826 u64 dir_ino = btrfs_ino(dir);
3828 path = btrfs_alloc_path();
3832 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3833 name, name_len, -1);
3834 if (IS_ERR_OR_NULL(di)) {
3842 leaf = path->nodes[0];
3843 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3844 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3845 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3847 btrfs_abort_transaction(trans, root, ret);
3850 btrfs_release_path(path);
3852 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3853 objectid, root->root_key.objectid,
3854 dir_ino, &index, name, name_len);
3856 if (ret != -ENOENT) {
3857 btrfs_abort_transaction(trans, root, ret);
3860 di = btrfs_search_dir_index_item(root, path, dir_ino,
3862 if (IS_ERR_OR_NULL(di)) {
3867 btrfs_abort_transaction(trans, root, ret);
3871 leaf = path->nodes[0];
3872 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3873 btrfs_release_path(path);
3876 btrfs_release_path(path);
3878 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3880 btrfs_abort_transaction(trans, root, ret);
3884 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3885 inode_inc_iversion(dir);
3886 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3887 ret = btrfs_update_inode_fallback(trans, root, dir);
3889 btrfs_abort_transaction(trans, root, ret);
3891 btrfs_free_path(path);
3895 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3897 struct inode *inode = dentry->d_inode;
3899 struct btrfs_root *root = BTRFS_I(dir)->root;
3900 struct btrfs_trans_handle *trans;
3902 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3904 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3907 trans = __unlink_start_trans(dir);
3909 return PTR_ERR(trans);
3911 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3912 err = btrfs_unlink_subvol(trans, root, dir,
3913 BTRFS_I(inode)->location.objectid,
3914 dentry->d_name.name,
3915 dentry->d_name.len);
3919 err = btrfs_orphan_add(trans, inode);
3923 /* now the directory is empty */
3924 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3925 dentry->d_name.name, dentry->d_name.len);
3927 btrfs_i_size_write(inode, 0);
3929 btrfs_end_transaction(trans, root);
3930 btrfs_btree_balance_dirty(root);
3936 * this can truncate away extent items, csum items and directory items.
3937 * It starts at a high offset and removes keys until it can't find
3938 * any higher than new_size
3940 * csum items that cross the new i_size are truncated to the new size
3943 * min_type is the minimum key type to truncate down to. If set to 0, this
3944 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3946 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3947 struct btrfs_root *root,
3948 struct inode *inode,
3949 u64 new_size, u32 min_type)
3951 struct btrfs_path *path;
3952 struct extent_buffer *leaf;
3953 struct btrfs_file_extent_item *fi;
3954 struct btrfs_key key;
3955 struct btrfs_key found_key;
3956 u64 extent_start = 0;
3957 u64 extent_num_bytes = 0;
3958 u64 extent_offset = 0;
3960 u64 last_size = (u64)-1;
3961 u32 found_type = (u8)-1;
3964 int pending_del_nr = 0;
3965 int pending_del_slot = 0;
3966 int extent_type = -1;
3969 u64 ino = btrfs_ino(inode);
3971 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3973 path = btrfs_alloc_path();
3979 * We want to drop from the next block forward in case this new size is
3980 * not block aligned since we will be keeping the last block of the
3981 * extent just the way it is.
3983 if (root->ref_cows || root == root->fs_info->tree_root)
3984 btrfs_drop_extent_cache(inode, ALIGN(new_size,
3985 root->sectorsize), (u64)-1, 0);
3988 * This function is also used to drop the items in the log tree before
3989 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3990 * it is used to drop the loged items. So we shouldn't kill the delayed
3993 if (min_type == 0 && root == BTRFS_I(inode)->root)
3994 btrfs_kill_delayed_inode_items(inode);
3997 key.offset = (u64)-1;
4001 path->leave_spinning = 1;
4002 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4009 /* there are no items in the tree for us to truncate, we're
4012 if (path->slots[0] == 0)
4019 leaf = path->nodes[0];
4020 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4021 found_type = btrfs_key_type(&found_key);
4023 if (found_key.objectid != ino)
4026 if (found_type < min_type)
4029 item_end = found_key.offset;
4030 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4031 fi = btrfs_item_ptr(leaf, path->slots[0],
4032 struct btrfs_file_extent_item);
4033 extent_type = btrfs_file_extent_type(leaf, fi);
4034 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4036 btrfs_file_extent_num_bytes(leaf, fi);
4037 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4038 item_end += btrfs_file_extent_inline_len(leaf,
4039 path->slots[0], fi);
4043 if (found_type > min_type) {
4046 if (item_end < new_size)
4048 if (found_key.offset >= new_size)
4054 /* FIXME, shrink the extent if the ref count is only 1 */
4055 if (found_type != BTRFS_EXTENT_DATA_KEY)
4059 last_size = found_key.offset;
4061 last_size = new_size;
4063 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4065 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4067 u64 orig_num_bytes =
4068 btrfs_file_extent_num_bytes(leaf, fi);
4069 extent_num_bytes = ALIGN(new_size -
4072 btrfs_set_file_extent_num_bytes(leaf, fi,
4074 num_dec = (orig_num_bytes -
4076 if (root->ref_cows && extent_start != 0)
4077 inode_sub_bytes(inode, num_dec);
4078 btrfs_mark_buffer_dirty(leaf);
4081 btrfs_file_extent_disk_num_bytes(leaf,
4083 extent_offset = found_key.offset -
4084 btrfs_file_extent_offset(leaf, fi);
4086 /* FIXME blocksize != 4096 */
4087 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4088 if (extent_start != 0) {
4091 inode_sub_bytes(inode, num_dec);
4094 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4096 * we can't truncate inline items that have had
4100 btrfs_file_extent_compression(leaf, fi) == 0 &&
4101 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4102 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4103 u32 size = new_size - found_key.offset;
4105 if (root->ref_cows) {
4106 inode_sub_bytes(inode, item_end + 1 -
4111 * update the ram bytes to properly reflect
4112 * the new size of our item
4114 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4116 btrfs_file_extent_calc_inline_size(size);
4117 btrfs_truncate_item(root, path, size, 1);
4118 } else if (root->ref_cows) {
4119 inode_sub_bytes(inode, item_end + 1 -
4125 if (!pending_del_nr) {
4126 /* no pending yet, add ourselves */
4127 pending_del_slot = path->slots[0];
4129 } else if (pending_del_nr &&
4130 path->slots[0] + 1 == pending_del_slot) {
4131 /* hop on the pending chunk */
4133 pending_del_slot = path->slots[0];
4140 if (found_extent && (root->ref_cows ||
4141 root == root->fs_info->tree_root)) {
4142 btrfs_set_path_blocking(path);
4143 ret = btrfs_free_extent(trans, root, extent_start,
4144 extent_num_bytes, 0,
4145 btrfs_header_owner(leaf),
4146 ino, extent_offset, 0);
4150 if (found_type == BTRFS_INODE_ITEM_KEY)
4153 if (path->slots[0] == 0 ||
4154 path->slots[0] != pending_del_slot) {
4155 if (pending_del_nr) {
4156 ret = btrfs_del_items(trans, root, path,
4160 btrfs_abort_transaction(trans,
4166 btrfs_release_path(path);
4173 if (pending_del_nr) {
4174 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4177 btrfs_abort_transaction(trans, root, ret);
4180 if (last_size != (u64)-1)
4181 btrfs_ordered_update_i_size(inode, last_size, NULL);
4182 btrfs_free_path(path);
4187 * btrfs_truncate_page - read, zero a chunk and write a page
4188 * @inode - inode that we're zeroing
4189 * @from - the offset to start zeroing
4190 * @len - the length to zero, 0 to zero the entire range respective to the
4192 * @front - zero up to the offset instead of from the offset on
4194 * This will find the page for the "from" offset and cow the page and zero the
4195 * part we want to zero. This is used with truncate and hole punching.
4197 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4200 struct address_space *mapping = inode->i_mapping;
4201 struct btrfs_root *root = BTRFS_I(inode)->root;
4202 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4203 struct btrfs_ordered_extent *ordered;
4204 struct extent_state *cached_state = NULL;
4206 u32 blocksize = root->sectorsize;
4207 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4208 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4210 gfp_t mask = btrfs_alloc_write_mask(mapping);
4215 if ((offset & (blocksize - 1)) == 0 &&
4216 (!len || ((len & (blocksize - 1)) == 0)))
4218 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4223 page = find_or_create_page(mapping, index, mask);
4225 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4230 page_start = page_offset(page);
4231 page_end = page_start + PAGE_CACHE_SIZE - 1;
4233 if (!PageUptodate(page)) {
4234 ret = btrfs_readpage(NULL, page);
4236 if (page->mapping != mapping) {
4238 page_cache_release(page);
4241 if (!PageUptodate(page)) {
4246 wait_on_page_writeback(page);
4248 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4249 set_page_extent_mapped(page);
4251 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4253 unlock_extent_cached(io_tree, page_start, page_end,
4254 &cached_state, GFP_NOFS);
4256 page_cache_release(page);
4257 btrfs_start_ordered_extent(inode, ordered, 1);
4258 btrfs_put_ordered_extent(ordered);
4262 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4263 EXTENT_DIRTY | EXTENT_DELALLOC |
4264 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4265 0, 0, &cached_state, GFP_NOFS);
4267 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4270 unlock_extent_cached(io_tree, page_start, page_end,
4271 &cached_state, GFP_NOFS);
4275 if (offset != PAGE_CACHE_SIZE) {
4277 len = PAGE_CACHE_SIZE - offset;
4280 memset(kaddr, 0, offset);
4282 memset(kaddr + offset, 0, len);
4283 flush_dcache_page(page);
4286 ClearPageChecked(page);
4287 set_page_dirty(page);
4288 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4293 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4295 page_cache_release(page);
4300 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4301 u64 offset, u64 len)
4303 struct btrfs_trans_handle *trans;
4307 * Still need to make sure the inode looks like it's been updated so
4308 * that any holes get logged if we fsync.
4310 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4311 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4312 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4313 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4318 * 1 - for the one we're dropping
4319 * 1 - for the one we're adding
4320 * 1 - for updating the inode.
4322 trans = btrfs_start_transaction(root, 3);
4324 return PTR_ERR(trans);
4326 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4328 btrfs_abort_transaction(trans, root, ret);
4329 btrfs_end_transaction(trans, root);
4333 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4334 0, 0, len, 0, len, 0, 0, 0);
4336 btrfs_abort_transaction(trans, root, ret);
4338 btrfs_update_inode(trans, root, inode);
4339 btrfs_end_transaction(trans, root);
4344 * This function puts in dummy file extents for the area we're creating a hole
4345 * for. So if we are truncating this file to a larger size we need to insert
4346 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4347 * the range between oldsize and size
4349 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4351 struct btrfs_root *root = BTRFS_I(inode)->root;
4352 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4353 struct extent_map *em = NULL;
4354 struct extent_state *cached_state = NULL;
4355 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4356 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4357 u64 block_end = ALIGN(size, root->sectorsize);
4364 * If our size started in the middle of a page we need to zero out the
4365 * rest of the page before we expand the i_size, otherwise we could
4366 * expose stale data.
4368 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4372 if (size <= hole_start)
4376 struct btrfs_ordered_extent *ordered;
4378 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4380 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4381 block_end - hole_start);
4384 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4385 &cached_state, GFP_NOFS);
4386 btrfs_start_ordered_extent(inode, ordered, 1);
4387 btrfs_put_ordered_extent(ordered);
4390 cur_offset = hole_start;
4392 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4393 block_end - cur_offset, 0);
4399 last_byte = min(extent_map_end(em), block_end);
4400 last_byte = ALIGN(last_byte , root->sectorsize);
4401 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4402 struct extent_map *hole_em;
4403 hole_size = last_byte - cur_offset;
4405 err = maybe_insert_hole(root, inode, cur_offset,
4409 btrfs_drop_extent_cache(inode, cur_offset,
4410 cur_offset + hole_size - 1, 0);
4411 hole_em = alloc_extent_map();
4413 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4414 &BTRFS_I(inode)->runtime_flags);
4417 hole_em->start = cur_offset;
4418 hole_em->len = hole_size;
4419 hole_em->orig_start = cur_offset;
4421 hole_em->block_start = EXTENT_MAP_HOLE;
4422 hole_em->block_len = 0;
4423 hole_em->orig_block_len = 0;
4424 hole_em->ram_bytes = hole_size;
4425 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4426 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4427 hole_em->generation = root->fs_info->generation;
4430 write_lock(&em_tree->lock);
4431 err = add_extent_mapping(em_tree, hole_em, 1);
4432 write_unlock(&em_tree->lock);
4435 btrfs_drop_extent_cache(inode, cur_offset,
4439 free_extent_map(hole_em);
4442 free_extent_map(em);
4444 cur_offset = last_byte;
4445 if (cur_offset >= block_end)
4448 free_extent_map(em);
4449 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4454 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4456 struct btrfs_root *root = BTRFS_I(inode)->root;
4457 struct btrfs_trans_handle *trans;
4458 loff_t oldsize = i_size_read(inode);
4459 loff_t newsize = attr->ia_size;
4460 int mask = attr->ia_valid;
4464 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4465 * special case where we need to update the times despite not having
4466 * these flags set. For all other operations the VFS set these flags
4467 * explicitly if it wants a timestamp update.
4469 if (newsize != oldsize) {
4470 inode_inc_iversion(inode);
4471 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4472 inode->i_ctime = inode->i_mtime =
4473 current_fs_time(inode->i_sb);
4476 if (newsize > oldsize) {
4477 truncate_pagecache(inode, newsize);
4478 ret = btrfs_cont_expand(inode, oldsize, newsize);
4482 trans = btrfs_start_transaction(root, 1);
4484 return PTR_ERR(trans);
4486 i_size_write(inode, newsize);
4487 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4488 ret = btrfs_update_inode(trans, root, inode);
4489 btrfs_end_transaction(trans, root);
4493 * We're truncating a file that used to have good data down to
4494 * zero. Make sure it gets into the ordered flush list so that
4495 * any new writes get down to disk quickly.
4498 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4499 &BTRFS_I(inode)->runtime_flags);
4502 * 1 for the orphan item we're going to add
4503 * 1 for the orphan item deletion.
4505 trans = btrfs_start_transaction(root, 2);
4507 return PTR_ERR(trans);
4510 * We need to do this in case we fail at _any_ point during the
4511 * actual truncate. Once we do the truncate_setsize we could
4512 * invalidate pages which forces any outstanding ordered io to
4513 * be instantly completed which will give us extents that need
4514 * to be truncated. If we fail to get an orphan inode down we
4515 * could have left over extents that were never meant to live,
4516 * so we need to garuntee from this point on that everything
4517 * will be consistent.
4519 ret = btrfs_orphan_add(trans, inode);
4520 btrfs_end_transaction(trans, root);
4524 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4525 truncate_setsize(inode, newsize);
4527 /* Disable nonlocked read DIO to avoid the end less truncate */
4528 btrfs_inode_block_unlocked_dio(inode);
4529 inode_dio_wait(inode);
4530 btrfs_inode_resume_unlocked_dio(inode);
4532 ret = btrfs_truncate(inode);
4533 if (ret && inode->i_nlink) {
4537 * failed to truncate, disk_i_size is only adjusted down
4538 * as we remove extents, so it should represent the true
4539 * size of the inode, so reset the in memory size and
4540 * delete our orphan entry.
4542 trans = btrfs_join_transaction(root);
4543 if (IS_ERR(trans)) {
4544 btrfs_orphan_del(NULL, inode);
4547 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4548 err = btrfs_orphan_del(trans, inode);
4550 btrfs_abort_transaction(trans, root, err);
4551 btrfs_end_transaction(trans, root);
4558 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4560 struct inode *inode = dentry->d_inode;
4561 struct btrfs_root *root = BTRFS_I(inode)->root;
4564 if (btrfs_root_readonly(root))
4567 err = inode_change_ok(inode, attr);
4571 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4572 err = btrfs_setsize(inode, attr);
4577 if (attr->ia_valid) {
4578 setattr_copy(inode, attr);
4579 inode_inc_iversion(inode);
4580 err = btrfs_dirty_inode(inode);
4582 if (!err && attr->ia_valid & ATTR_MODE)
4583 err = posix_acl_chmod(inode, inode->i_mode);
4590 * While truncating the inode pages during eviction, we get the VFS calling
4591 * btrfs_invalidatepage() against each page of the inode. This is slow because
4592 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4593 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4594 * extent_state structures over and over, wasting lots of time.
4596 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4597 * those expensive operations on a per page basis and do only the ordered io
4598 * finishing, while we release here the extent_map and extent_state structures,
4599 * without the excessive merging and splitting.
4601 static void evict_inode_truncate_pages(struct inode *inode)
4603 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4604 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4605 struct rb_node *node;
4607 ASSERT(inode->i_state & I_FREEING);
4608 truncate_inode_pages(&inode->i_data, 0);
4610 write_lock(&map_tree->lock);
4611 while (!RB_EMPTY_ROOT(&map_tree->map)) {
4612 struct extent_map *em;
4614 node = rb_first(&map_tree->map);
4615 em = rb_entry(node, struct extent_map, rb_node);
4616 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4617 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4618 remove_extent_mapping(map_tree, em);
4619 free_extent_map(em);
4621 write_unlock(&map_tree->lock);
4623 spin_lock(&io_tree->lock);
4624 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4625 struct extent_state *state;
4626 struct extent_state *cached_state = NULL;
4628 node = rb_first(&io_tree->state);
4629 state = rb_entry(node, struct extent_state, rb_node);
4630 atomic_inc(&state->refs);
4631 spin_unlock(&io_tree->lock);
4633 lock_extent_bits(io_tree, state->start, state->end,
4635 clear_extent_bit(io_tree, state->start, state->end,
4636 EXTENT_LOCKED | EXTENT_DIRTY |
4637 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
4638 EXTENT_DEFRAG, 1, 1,
4639 &cached_state, GFP_NOFS);
4640 free_extent_state(state);
4642 spin_lock(&io_tree->lock);
4644 spin_unlock(&io_tree->lock);
4647 void btrfs_evict_inode(struct inode *inode)
4649 struct btrfs_trans_handle *trans;
4650 struct btrfs_root *root = BTRFS_I(inode)->root;
4651 struct btrfs_block_rsv *rsv, *global_rsv;
4652 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4655 trace_btrfs_inode_evict(inode);
4657 evict_inode_truncate_pages(inode);
4659 if (inode->i_nlink &&
4660 ((btrfs_root_refs(&root->root_item) != 0 &&
4661 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4662 btrfs_is_free_space_inode(inode)))
4665 if (is_bad_inode(inode)) {
4666 btrfs_orphan_del(NULL, inode);
4669 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4670 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4672 if (root->fs_info->log_root_recovering) {
4673 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4674 &BTRFS_I(inode)->runtime_flags));
4678 if (inode->i_nlink > 0) {
4679 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4680 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4684 ret = btrfs_commit_inode_delayed_inode(inode);
4686 btrfs_orphan_del(NULL, inode);
4690 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4692 btrfs_orphan_del(NULL, inode);
4695 rsv->size = min_size;
4697 global_rsv = &root->fs_info->global_block_rsv;
4699 btrfs_i_size_write(inode, 0);
4702 * This is a bit simpler than btrfs_truncate since we've already
4703 * reserved our space for our orphan item in the unlink, so we just
4704 * need to reserve some slack space in case we add bytes and update
4705 * inode item when doing the truncate.
4708 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4709 BTRFS_RESERVE_FLUSH_LIMIT);
4712 * Try and steal from the global reserve since we will
4713 * likely not use this space anyway, we want to try as
4714 * hard as possible to get this to work.
4717 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4720 btrfs_warn(root->fs_info,
4721 "Could not get space for a delete, will truncate on mount %d",
4723 btrfs_orphan_del(NULL, inode);
4724 btrfs_free_block_rsv(root, rsv);
4728 trans = btrfs_join_transaction(root);
4729 if (IS_ERR(trans)) {
4730 btrfs_orphan_del(NULL, inode);
4731 btrfs_free_block_rsv(root, rsv);
4735 trans->block_rsv = rsv;
4737 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4741 trans->block_rsv = &root->fs_info->trans_block_rsv;
4742 btrfs_end_transaction(trans, root);
4744 btrfs_btree_balance_dirty(root);
4747 btrfs_free_block_rsv(root, rsv);
4750 * Errors here aren't a big deal, it just means we leave orphan items
4751 * in the tree. They will be cleaned up on the next mount.
4754 trans->block_rsv = root->orphan_block_rsv;
4755 btrfs_orphan_del(trans, inode);
4757 btrfs_orphan_del(NULL, inode);
4760 trans->block_rsv = &root->fs_info->trans_block_rsv;
4761 if (!(root == root->fs_info->tree_root ||
4762 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4763 btrfs_return_ino(root, btrfs_ino(inode));
4765 btrfs_end_transaction(trans, root);
4766 btrfs_btree_balance_dirty(root);
4768 btrfs_remove_delayed_node(inode);
4774 * this returns the key found in the dir entry in the location pointer.
4775 * If no dir entries were found, location->objectid is 0.
4777 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4778 struct btrfs_key *location)
4780 const char *name = dentry->d_name.name;
4781 int namelen = dentry->d_name.len;
4782 struct btrfs_dir_item *di;
4783 struct btrfs_path *path;
4784 struct btrfs_root *root = BTRFS_I(dir)->root;
4787 path = btrfs_alloc_path();
4791 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4796 if (IS_ERR_OR_NULL(di))
4799 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4801 btrfs_free_path(path);
4804 location->objectid = 0;
4809 * when we hit a tree root in a directory, the btrfs part of the inode
4810 * needs to be changed to reflect the root directory of the tree root. This
4811 * is kind of like crossing a mount point.
4813 static int fixup_tree_root_location(struct btrfs_root *root,
4815 struct dentry *dentry,
4816 struct btrfs_key *location,
4817 struct btrfs_root **sub_root)
4819 struct btrfs_path *path;
4820 struct btrfs_root *new_root;
4821 struct btrfs_root_ref *ref;
4822 struct extent_buffer *leaf;
4826 path = btrfs_alloc_path();
4833 ret = btrfs_find_item(root->fs_info->tree_root, path,
4834 BTRFS_I(dir)->root->root_key.objectid,
4835 location->objectid, BTRFS_ROOT_REF_KEY, NULL);
4842 leaf = path->nodes[0];
4843 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4844 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4845 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4848 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4849 (unsigned long)(ref + 1),
4850 dentry->d_name.len);
4854 btrfs_release_path(path);
4856 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4857 if (IS_ERR(new_root)) {
4858 err = PTR_ERR(new_root);
4862 *sub_root = new_root;
4863 location->objectid = btrfs_root_dirid(&new_root->root_item);
4864 location->type = BTRFS_INODE_ITEM_KEY;
4865 location->offset = 0;
4868 btrfs_free_path(path);
4872 static void inode_tree_add(struct inode *inode)
4874 struct btrfs_root *root = BTRFS_I(inode)->root;
4875 struct btrfs_inode *entry;
4877 struct rb_node *parent;
4878 struct rb_node *new = &BTRFS_I(inode)->rb_node;
4879 u64 ino = btrfs_ino(inode);
4881 if (inode_unhashed(inode))
4884 spin_lock(&root->inode_lock);
4885 p = &root->inode_tree.rb_node;
4888 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4890 if (ino < btrfs_ino(&entry->vfs_inode))
4891 p = &parent->rb_left;
4892 else if (ino > btrfs_ino(&entry->vfs_inode))
4893 p = &parent->rb_right;
4895 WARN_ON(!(entry->vfs_inode.i_state &
4896 (I_WILL_FREE | I_FREEING)));
4897 rb_replace_node(parent, new, &root->inode_tree);
4898 RB_CLEAR_NODE(parent);
4899 spin_unlock(&root->inode_lock);
4903 rb_link_node(new, parent, p);
4904 rb_insert_color(new, &root->inode_tree);
4905 spin_unlock(&root->inode_lock);
4908 static void inode_tree_del(struct inode *inode)
4910 struct btrfs_root *root = BTRFS_I(inode)->root;
4913 spin_lock(&root->inode_lock);
4914 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4915 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4916 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4917 empty = RB_EMPTY_ROOT(&root->inode_tree);
4919 spin_unlock(&root->inode_lock);
4921 if (empty && btrfs_root_refs(&root->root_item) == 0) {
4922 synchronize_srcu(&root->fs_info->subvol_srcu);
4923 spin_lock(&root->inode_lock);
4924 empty = RB_EMPTY_ROOT(&root->inode_tree);
4925 spin_unlock(&root->inode_lock);
4927 btrfs_add_dead_root(root);
4931 void btrfs_invalidate_inodes(struct btrfs_root *root)
4933 struct rb_node *node;
4934 struct rb_node *prev;
4935 struct btrfs_inode *entry;
4936 struct inode *inode;
4939 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4941 spin_lock(&root->inode_lock);
4943 node = root->inode_tree.rb_node;
4947 entry = rb_entry(node, struct btrfs_inode, rb_node);
4949 if (objectid < btrfs_ino(&entry->vfs_inode))
4950 node = node->rb_left;
4951 else if (objectid > btrfs_ino(&entry->vfs_inode))
4952 node = node->rb_right;
4958 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4959 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4963 prev = rb_next(prev);
4967 entry = rb_entry(node, struct btrfs_inode, rb_node);
4968 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4969 inode = igrab(&entry->vfs_inode);
4971 spin_unlock(&root->inode_lock);
4972 if (atomic_read(&inode->i_count) > 1)
4973 d_prune_aliases(inode);
4975 * btrfs_drop_inode will have it removed from
4976 * the inode cache when its usage count
4981 spin_lock(&root->inode_lock);
4985 if (cond_resched_lock(&root->inode_lock))
4988 node = rb_next(node);
4990 spin_unlock(&root->inode_lock);
4993 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4995 struct btrfs_iget_args *args = p;
4996 inode->i_ino = args->location->objectid;
4997 memcpy(&BTRFS_I(inode)->location, args->location,
4998 sizeof(*args->location));
4999 BTRFS_I(inode)->root = args->root;
5003 static int btrfs_find_actor(struct inode *inode, void *opaque)
5005 struct btrfs_iget_args *args = opaque;
5006 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5007 args->root == BTRFS_I(inode)->root;
5010 static struct inode *btrfs_iget_locked(struct super_block *s,
5011 struct btrfs_key *location,
5012 struct btrfs_root *root)
5014 struct inode *inode;
5015 struct btrfs_iget_args args;
5016 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5018 args.location = location;
5021 inode = iget5_locked(s, hashval, btrfs_find_actor,
5022 btrfs_init_locked_inode,
5027 /* Get an inode object given its location and corresponding root.
5028 * Returns in *is_new if the inode was read from disk
5030 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5031 struct btrfs_root *root, int *new)
5033 struct inode *inode;
5035 inode = btrfs_iget_locked(s, location, root);
5037 return ERR_PTR(-ENOMEM);
5039 if (inode->i_state & I_NEW) {
5040 btrfs_read_locked_inode(inode);
5041 if (!is_bad_inode(inode)) {
5042 inode_tree_add(inode);
5043 unlock_new_inode(inode);
5047 unlock_new_inode(inode);
5049 inode = ERR_PTR(-ESTALE);
5056 static struct inode *new_simple_dir(struct super_block *s,
5057 struct btrfs_key *key,
5058 struct btrfs_root *root)
5060 struct inode *inode = new_inode(s);
5063 return ERR_PTR(-ENOMEM);
5065 BTRFS_I(inode)->root = root;
5066 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5067 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5069 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5070 inode->i_op = &btrfs_dir_ro_inode_operations;
5071 inode->i_fop = &simple_dir_operations;
5072 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5073 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5078 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5080 struct inode *inode;
5081 struct btrfs_root *root = BTRFS_I(dir)->root;
5082 struct btrfs_root *sub_root = root;
5083 struct btrfs_key location;
5087 if (dentry->d_name.len > BTRFS_NAME_LEN)
5088 return ERR_PTR(-ENAMETOOLONG);
5090 ret = btrfs_inode_by_name(dir, dentry, &location);
5092 return ERR_PTR(ret);
5094 if (location.objectid == 0)
5095 return ERR_PTR(-ENOENT);
5097 if (location.type == BTRFS_INODE_ITEM_KEY) {
5098 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5102 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5104 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5105 ret = fixup_tree_root_location(root, dir, dentry,
5106 &location, &sub_root);
5109 inode = ERR_PTR(ret);
5111 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5113 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5115 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5117 if (!IS_ERR(inode) && root != sub_root) {
5118 down_read(&root->fs_info->cleanup_work_sem);
5119 if (!(inode->i_sb->s_flags & MS_RDONLY))
5120 ret = btrfs_orphan_cleanup(sub_root);
5121 up_read(&root->fs_info->cleanup_work_sem);
5124 inode = ERR_PTR(ret);
5131 static int btrfs_dentry_delete(const struct dentry *dentry)
5133 struct btrfs_root *root;
5134 struct inode *inode = dentry->d_inode;
5136 if (!inode && !IS_ROOT(dentry))
5137 inode = dentry->d_parent->d_inode;
5140 root = BTRFS_I(inode)->root;
5141 if (btrfs_root_refs(&root->root_item) == 0)
5144 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5150 static void btrfs_dentry_release(struct dentry *dentry)
5152 if (dentry->d_fsdata)
5153 kfree(dentry->d_fsdata);
5156 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5159 struct inode *inode;
5161 inode = btrfs_lookup_dentry(dir, dentry);
5162 if (IS_ERR(inode)) {
5163 if (PTR_ERR(inode) == -ENOENT)
5166 return ERR_CAST(inode);
5169 return d_materialise_unique(dentry, inode);
5172 unsigned char btrfs_filetype_table[] = {
5173 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5176 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5178 struct inode *inode = file_inode(file);
5179 struct btrfs_root *root = BTRFS_I(inode)->root;
5180 struct btrfs_item *item;
5181 struct btrfs_dir_item *di;
5182 struct btrfs_key key;
5183 struct btrfs_key found_key;
5184 struct btrfs_path *path;
5185 struct list_head ins_list;
5186 struct list_head del_list;
5188 struct extent_buffer *leaf;
5190 unsigned char d_type;
5195 int key_type = BTRFS_DIR_INDEX_KEY;
5199 int is_curr = 0; /* ctx->pos points to the current index? */
5201 /* FIXME, use a real flag for deciding about the key type */
5202 if (root->fs_info->tree_root == root)
5203 key_type = BTRFS_DIR_ITEM_KEY;
5205 if (!dir_emit_dots(file, ctx))
5208 path = btrfs_alloc_path();
5214 if (key_type == BTRFS_DIR_INDEX_KEY) {
5215 INIT_LIST_HEAD(&ins_list);
5216 INIT_LIST_HEAD(&del_list);
5217 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5220 btrfs_set_key_type(&key, key_type);
5221 key.offset = ctx->pos;
5222 key.objectid = btrfs_ino(inode);
5224 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5229 leaf = path->nodes[0];
5230 slot = path->slots[0];
5231 if (slot >= btrfs_header_nritems(leaf)) {
5232 ret = btrfs_next_leaf(root, path);
5240 item = btrfs_item_nr(slot);
5241 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5243 if (found_key.objectid != key.objectid)
5245 if (btrfs_key_type(&found_key) != key_type)
5247 if (found_key.offset < ctx->pos)
5249 if (key_type == BTRFS_DIR_INDEX_KEY &&
5250 btrfs_should_delete_dir_index(&del_list,
5254 ctx->pos = found_key.offset;
5257 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5259 di_total = btrfs_item_size(leaf, item);
5261 while (di_cur < di_total) {
5262 struct btrfs_key location;
5264 if (verify_dir_item(root, leaf, di))
5267 name_len = btrfs_dir_name_len(leaf, di);
5268 if (name_len <= sizeof(tmp_name)) {
5269 name_ptr = tmp_name;
5271 name_ptr = kmalloc(name_len, GFP_NOFS);
5277 read_extent_buffer(leaf, name_ptr,
5278 (unsigned long)(di + 1), name_len);
5280 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5281 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5284 /* is this a reference to our own snapshot? If so
5287 * In contrast to old kernels, we insert the snapshot's
5288 * dir item and dir index after it has been created, so
5289 * we won't find a reference to our own snapshot. We
5290 * still keep the following code for backward
5293 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5294 location.objectid == root->root_key.objectid) {
5298 over = !dir_emit(ctx, name_ptr, name_len,
5299 location.objectid, d_type);
5302 if (name_ptr != tmp_name)
5307 di_len = btrfs_dir_name_len(leaf, di) +
5308 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5310 di = (struct btrfs_dir_item *)((char *)di + di_len);
5316 if (key_type == BTRFS_DIR_INDEX_KEY) {
5319 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5324 /* Reached end of directory/root. Bump pos past the last item. */
5328 * Stop new entries from being returned after we return the last
5331 * New directory entries are assigned a strictly increasing
5332 * offset. This means that new entries created during readdir
5333 * are *guaranteed* to be seen in the future by that readdir.
5334 * This has broken buggy programs which operate on names as
5335 * they're returned by readdir. Until we re-use freed offsets
5336 * we have this hack to stop new entries from being returned
5337 * under the assumption that they'll never reach this huge
5340 * This is being careful not to overflow 32bit loff_t unless the
5341 * last entry requires it because doing so has broken 32bit apps
5344 if (key_type == BTRFS_DIR_INDEX_KEY) {
5345 if (ctx->pos >= INT_MAX)
5346 ctx->pos = LLONG_MAX;
5353 if (key_type == BTRFS_DIR_INDEX_KEY)
5354 btrfs_put_delayed_items(&ins_list, &del_list);
5355 btrfs_free_path(path);
5359 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5361 struct btrfs_root *root = BTRFS_I(inode)->root;
5362 struct btrfs_trans_handle *trans;
5364 bool nolock = false;
5366 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5369 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5372 if (wbc->sync_mode == WB_SYNC_ALL) {
5374 trans = btrfs_join_transaction_nolock(root);
5376 trans = btrfs_join_transaction(root);
5378 return PTR_ERR(trans);
5379 ret = btrfs_commit_transaction(trans, root);
5385 * This is somewhat expensive, updating the tree every time the
5386 * inode changes. But, it is most likely to find the inode in cache.
5387 * FIXME, needs more benchmarking...there are no reasons other than performance
5388 * to keep or drop this code.
5390 static int btrfs_dirty_inode(struct inode *inode)
5392 struct btrfs_root *root = BTRFS_I(inode)->root;
5393 struct btrfs_trans_handle *trans;
5396 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5399 trans = btrfs_join_transaction(root);
5401 return PTR_ERR(trans);
5403 ret = btrfs_update_inode(trans, root, inode);
5404 if (ret && ret == -ENOSPC) {
5405 /* whoops, lets try again with the full transaction */
5406 btrfs_end_transaction(trans, root);
5407 trans = btrfs_start_transaction(root, 1);
5409 return PTR_ERR(trans);
5411 ret = btrfs_update_inode(trans, root, inode);
5413 btrfs_end_transaction(trans, root);
5414 if (BTRFS_I(inode)->delayed_node)
5415 btrfs_balance_delayed_items(root);
5421 * This is a copy of file_update_time. We need this so we can return error on
5422 * ENOSPC for updating the inode in the case of file write and mmap writes.
5424 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5427 struct btrfs_root *root = BTRFS_I(inode)->root;
5429 if (btrfs_root_readonly(root))
5432 if (flags & S_VERSION)
5433 inode_inc_iversion(inode);
5434 if (flags & S_CTIME)
5435 inode->i_ctime = *now;
5436 if (flags & S_MTIME)
5437 inode->i_mtime = *now;
5438 if (flags & S_ATIME)
5439 inode->i_atime = *now;
5440 return btrfs_dirty_inode(inode);
5444 * find the highest existing sequence number in a directory
5445 * and then set the in-memory index_cnt variable to reflect
5446 * free sequence numbers
5448 static int btrfs_set_inode_index_count(struct inode *inode)
5450 struct btrfs_root *root = BTRFS_I(inode)->root;
5451 struct btrfs_key key, found_key;
5452 struct btrfs_path *path;
5453 struct extent_buffer *leaf;
5456 key.objectid = btrfs_ino(inode);
5457 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5458 key.offset = (u64)-1;
5460 path = btrfs_alloc_path();
5464 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5467 /* FIXME: we should be able to handle this */
5473 * MAGIC NUMBER EXPLANATION:
5474 * since we search a directory based on f_pos we have to start at 2
5475 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5476 * else has to start at 2
5478 if (path->slots[0] == 0) {
5479 BTRFS_I(inode)->index_cnt = 2;
5485 leaf = path->nodes[0];
5486 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5488 if (found_key.objectid != btrfs_ino(inode) ||
5489 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5490 BTRFS_I(inode)->index_cnt = 2;
5494 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5496 btrfs_free_path(path);
5501 * helper to find a free sequence number in a given directory. This current
5502 * code is very simple, later versions will do smarter things in the btree
5504 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5508 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5509 ret = btrfs_inode_delayed_dir_index_count(dir);
5511 ret = btrfs_set_inode_index_count(dir);
5517 *index = BTRFS_I(dir)->index_cnt;
5518 BTRFS_I(dir)->index_cnt++;
5523 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5524 struct btrfs_root *root,
5526 const char *name, int name_len,
5527 u64 ref_objectid, u64 objectid,
5528 umode_t mode, u64 *index)
5530 struct inode *inode;
5531 struct btrfs_inode_item *inode_item;
5532 struct btrfs_key *location;
5533 struct btrfs_path *path;
5534 struct btrfs_inode_ref *ref;
5535 struct btrfs_key key[2];
5540 path = btrfs_alloc_path();
5542 return ERR_PTR(-ENOMEM);
5544 inode = new_inode(root->fs_info->sb);
5546 btrfs_free_path(path);
5547 return ERR_PTR(-ENOMEM);
5551 * we have to initialize this early, so we can reclaim the inode
5552 * number if we fail afterwards in this function.
5554 inode->i_ino = objectid;
5557 trace_btrfs_inode_request(dir);
5559 ret = btrfs_set_inode_index(dir, index);
5561 btrfs_free_path(path);
5563 return ERR_PTR(ret);
5567 * index_cnt is ignored for everything but a dir,
5568 * btrfs_get_inode_index_count has an explanation for the magic
5571 BTRFS_I(inode)->index_cnt = 2;
5572 BTRFS_I(inode)->dir_index = *index;
5573 BTRFS_I(inode)->root = root;
5574 BTRFS_I(inode)->generation = trans->transid;
5575 inode->i_generation = BTRFS_I(inode)->generation;
5578 * We could have gotten an inode number from somebody who was fsynced
5579 * and then removed in this same transaction, so let's just set full
5580 * sync since it will be a full sync anyway and this will blow away the
5581 * old info in the log.
5583 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5585 key[0].objectid = objectid;
5586 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5590 * Start new inodes with an inode_ref. This is slightly more
5591 * efficient for small numbers of hard links since they will
5592 * be packed into one item. Extended refs will kick in if we
5593 * add more hard links than can fit in the ref item.
5595 key[1].objectid = objectid;
5596 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5597 key[1].offset = ref_objectid;
5599 sizes[0] = sizeof(struct btrfs_inode_item);
5600 sizes[1] = name_len + sizeof(*ref);
5602 path->leave_spinning = 1;
5603 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
5607 inode_init_owner(inode, dir, mode);
5608 inode_set_bytes(inode, 0);
5609 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5610 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5611 struct btrfs_inode_item);
5612 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5613 sizeof(*inode_item));
5614 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5616 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5617 struct btrfs_inode_ref);
5618 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5619 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5620 ptr = (unsigned long)(ref + 1);
5621 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5623 btrfs_mark_buffer_dirty(path->nodes[0]);
5624 btrfs_free_path(path);
5626 location = &BTRFS_I(inode)->location;
5627 location->objectid = objectid;
5628 location->offset = 0;
5629 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5631 btrfs_inherit_iflags(inode, dir);
5633 if (S_ISREG(mode)) {
5634 if (btrfs_test_opt(root, NODATASUM))
5635 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5636 if (btrfs_test_opt(root, NODATACOW))
5637 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5638 BTRFS_INODE_NODATASUM;
5641 btrfs_insert_inode_hash(inode);
5642 inode_tree_add(inode);
5644 trace_btrfs_inode_new(inode);
5645 btrfs_set_inode_last_trans(trans, inode);
5647 btrfs_update_root_times(trans, root);
5649 ret = btrfs_inode_inherit_props(trans, inode, dir);
5651 btrfs_err(root->fs_info,
5652 "error inheriting props for ino %llu (root %llu): %d",
5653 btrfs_ino(inode), root->root_key.objectid, ret);
5658 BTRFS_I(dir)->index_cnt--;
5659 btrfs_free_path(path);
5661 return ERR_PTR(ret);
5664 static inline u8 btrfs_inode_type(struct inode *inode)
5666 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5670 * utility function to add 'inode' into 'parent_inode' with
5671 * a give name and a given sequence number.
5672 * if 'add_backref' is true, also insert a backref from the
5673 * inode to the parent directory.
5675 int btrfs_add_link(struct btrfs_trans_handle *trans,
5676 struct inode *parent_inode, struct inode *inode,
5677 const char *name, int name_len, int add_backref, u64 index)
5680 struct btrfs_key key;
5681 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5682 u64 ino = btrfs_ino(inode);
5683 u64 parent_ino = btrfs_ino(parent_inode);
5685 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5686 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5689 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5693 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5694 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5695 key.objectid, root->root_key.objectid,
5696 parent_ino, index, name, name_len);
5697 } else if (add_backref) {
5698 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5702 /* Nothing to clean up yet */
5706 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5708 btrfs_inode_type(inode), index);
5709 if (ret == -EEXIST || ret == -EOVERFLOW)
5712 btrfs_abort_transaction(trans, root, ret);
5716 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5718 inode_inc_iversion(parent_inode);
5719 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5720 ret = btrfs_update_inode(trans, root, parent_inode);
5722 btrfs_abort_transaction(trans, root, ret);
5726 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5729 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5730 key.objectid, root->root_key.objectid,
5731 parent_ino, &local_index, name, name_len);
5733 } else if (add_backref) {
5737 err = btrfs_del_inode_ref(trans, root, name, name_len,
5738 ino, parent_ino, &local_index);
5743 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5744 struct inode *dir, struct dentry *dentry,
5745 struct inode *inode, int backref, u64 index)
5747 int err = btrfs_add_link(trans, dir, inode,
5748 dentry->d_name.name, dentry->d_name.len,
5755 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5756 umode_t mode, dev_t rdev)
5758 struct btrfs_trans_handle *trans;
5759 struct btrfs_root *root = BTRFS_I(dir)->root;
5760 struct inode *inode = NULL;
5766 if (!new_valid_dev(rdev))
5770 * 2 for inode item and ref
5772 * 1 for xattr if selinux is on
5774 trans = btrfs_start_transaction(root, 5);
5776 return PTR_ERR(trans);
5778 err = btrfs_find_free_ino(root, &objectid);
5782 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5783 dentry->d_name.len, btrfs_ino(dir), objectid,
5785 if (IS_ERR(inode)) {
5786 err = PTR_ERR(inode);
5790 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5797 * If the active LSM wants to access the inode during
5798 * d_instantiate it needs these. Smack checks to see
5799 * if the filesystem supports xattrs by looking at the
5803 inode->i_op = &btrfs_special_inode_operations;
5804 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5808 init_special_inode(inode, inode->i_mode, rdev);
5809 btrfs_update_inode(trans, root, inode);
5810 d_instantiate(dentry, inode);
5813 btrfs_end_transaction(trans, root);
5814 btrfs_btree_balance_dirty(root);
5816 inode_dec_link_count(inode);
5822 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5823 umode_t mode, bool excl)
5825 struct btrfs_trans_handle *trans;
5826 struct btrfs_root *root = BTRFS_I(dir)->root;
5827 struct inode *inode = NULL;
5828 int drop_inode_on_err = 0;
5834 * 2 for inode item and ref
5836 * 1 for xattr if selinux is on
5838 trans = btrfs_start_transaction(root, 5);
5840 return PTR_ERR(trans);
5842 err = btrfs_find_free_ino(root, &objectid);
5846 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5847 dentry->d_name.len, btrfs_ino(dir), objectid,
5849 if (IS_ERR(inode)) {
5850 err = PTR_ERR(inode);
5853 drop_inode_on_err = 1;
5855 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5859 err = btrfs_update_inode(trans, root, inode);
5864 * If the active LSM wants to access the inode during
5865 * d_instantiate it needs these. Smack checks to see
5866 * if the filesystem supports xattrs by looking at the
5869 inode->i_fop = &btrfs_file_operations;
5870 inode->i_op = &btrfs_file_inode_operations;
5872 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5876 inode->i_mapping->a_ops = &btrfs_aops;
5877 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5878 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5879 d_instantiate(dentry, inode);
5882 btrfs_end_transaction(trans, root);
5883 if (err && drop_inode_on_err) {
5884 inode_dec_link_count(inode);
5887 btrfs_btree_balance_dirty(root);
5891 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5892 struct dentry *dentry)
5894 struct btrfs_trans_handle *trans;
5895 struct btrfs_root *root = BTRFS_I(dir)->root;
5896 struct inode *inode = old_dentry->d_inode;
5901 /* do not allow sys_link's with other subvols of the same device */
5902 if (root->objectid != BTRFS_I(inode)->root->objectid)
5905 if (inode->i_nlink >= BTRFS_LINK_MAX)
5908 err = btrfs_set_inode_index(dir, &index);
5913 * 2 items for inode and inode ref
5914 * 2 items for dir items
5915 * 1 item for parent inode
5917 trans = btrfs_start_transaction(root, 5);
5918 if (IS_ERR(trans)) {
5919 err = PTR_ERR(trans);
5923 /* There are several dir indexes for this inode, clear the cache. */
5924 BTRFS_I(inode)->dir_index = 0ULL;
5926 inode_inc_iversion(inode);
5927 inode->i_ctime = CURRENT_TIME;
5929 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5931 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5936 struct dentry *parent = dentry->d_parent;
5937 err = btrfs_update_inode(trans, root, inode);
5940 d_instantiate(dentry, inode);
5941 btrfs_log_new_name(trans, inode, NULL, parent);
5944 btrfs_end_transaction(trans, root);
5947 inode_dec_link_count(inode);
5950 btrfs_btree_balance_dirty(root);
5954 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5956 struct inode *inode = NULL;
5957 struct btrfs_trans_handle *trans;
5958 struct btrfs_root *root = BTRFS_I(dir)->root;
5960 int drop_on_err = 0;
5965 * 2 items for inode and ref
5966 * 2 items for dir items
5967 * 1 for xattr if selinux is on
5969 trans = btrfs_start_transaction(root, 5);
5971 return PTR_ERR(trans);
5973 err = btrfs_find_free_ino(root, &objectid);
5977 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5978 dentry->d_name.len, btrfs_ino(dir), objectid,
5979 S_IFDIR | mode, &index);
5980 if (IS_ERR(inode)) {
5981 err = PTR_ERR(inode);
5987 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5991 inode->i_op = &btrfs_dir_inode_operations;
5992 inode->i_fop = &btrfs_dir_file_operations;
5994 btrfs_i_size_write(inode, 0);
5995 err = btrfs_update_inode(trans, root, inode);
5999 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6000 dentry->d_name.len, 0, index);
6004 d_instantiate(dentry, inode);
6008 btrfs_end_transaction(trans, root);
6011 btrfs_btree_balance_dirty(root);
6015 /* helper for btfs_get_extent. Given an existing extent in the tree,
6016 * and an extent that you want to insert, deal with overlap and insert
6017 * the new extent into the tree.
6019 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6020 struct extent_map *existing,
6021 struct extent_map *em,
6022 u64 map_start, u64 map_len)
6026 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6027 start_diff = map_start - em->start;
6028 em->start = map_start;
6030 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6031 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6032 em->block_start += start_diff;
6033 em->block_len -= start_diff;
6035 return add_extent_mapping(em_tree, em, 0);
6038 static noinline int uncompress_inline(struct btrfs_path *path,
6039 struct inode *inode, struct page *page,
6040 size_t pg_offset, u64 extent_offset,
6041 struct btrfs_file_extent_item *item)
6044 struct extent_buffer *leaf = path->nodes[0];
6047 unsigned long inline_size;
6051 WARN_ON(pg_offset != 0);
6052 compress_type = btrfs_file_extent_compression(leaf, item);
6053 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6054 inline_size = btrfs_file_extent_inline_item_len(leaf,
6055 btrfs_item_nr(path->slots[0]));
6056 tmp = kmalloc(inline_size, GFP_NOFS);
6059 ptr = btrfs_file_extent_inline_start(item);
6061 read_extent_buffer(leaf, tmp, ptr, inline_size);
6063 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6064 ret = btrfs_decompress(compress_type, tmp, page,
6065 extent_offset, inline_size, max_size);
6067 char *kaddr = kmap_atomic(page);
6068 unsigned long copy_size = min_t(u64,
6069 PAGE_CACHE_SIZE - pg_offset,
6070 max_size - extent_offset);
6071 memset(kaddr + pg_offset, 0, copy_size);
6072 kunmap_atomic(kaddr);
6079 * a bit scary, this does extent mapping from logical file offset to the disk.
6080 * the ugly parts come from merging extents from the disk with the in-ram
6081 * representation. This gets more complex because of the data=ordered code,
6082 * where the in-ram extents might be locked pending data=ordered completion.
6084 * This also copies inline extents directly into the page.
6087 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6088 size_t pg_offset, u64 start, u64 len,
6094 u64 extent_start = 0;
6096 u64 objectid = btrfs_ino(inode);
6098 struct btrfs_path *path = NULL;
6099 struct btrfs_root *root = BTRFS_I(inode)->root;
6100 struct btrfs_file_extent_item *item;
6101 struct extent_buffer *leaf;
6102 struct btrfs_key found_key;
6103 struct extent_map *em = NULL;
6104 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6105 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6106 struct btrfs_trans_handle *trans = NULL;
6110 read_lock(&em_tree->lock);
6111 em = lookup_extent_mapping(em_tree, start, len);
6113 em->bdev = root->fs_info->fs_devices->latest_bdev;
6114 read_unlock(&em_tree->lock);
6117 if (em->start > start || em->start + em->len <= start)
6118 free_extent_map(em);
6119 else if (em->block_start == EXTENT_MAP_INLINE && page)
6120 free_extent_map(em);
6124 em = alloc_extent_map();
6129 em->bdev = root->fs_info->fs_devices->latest_bdev;
6130 em->start = EXTENT_MAP_HOLE;
6131 em->orig_start = EXTENT_MAP_HOLE;
6133 em->block_len = (u64)-1;
6136 path = btrfs_alloc_path();
6142 * Chances are we'll be called again, so go ahead and do
6148 ret = btrfs_lookup_file_extent(trans, root, path,
6149 objectid, start, trans != NULL);
6156 if (path->slots[0] == 0)
6161 leaf = path->nodes[0];
6162 item = btrfs_item_ptr(leaf, path->slots[0],
6163 struct btrfs_file_extent_item);
6164 /* are we inside the extent that was found? */
6165 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6166 found_type = btrfs_key_type(&found_key);
6167 if (found_key.objectid != objectid ||
6168 found_type != BTRFS_EXTENT_DATA_KEY) {
6170 * If we backup past the first extent we want to move forward
6171 * and see if there is an extent in front of us, otherwise we'll
6172 * say there is a hole for our whole search range which can
6179 found_type = btrfs_file_extent_type(leaf, item);
6180 extent_start = found_key.offset;
6181 compress_type = btrfs_file_extent_compression(leaf, item);
6182 if (found_type == BTRFS_FILE_EXTENT_REG ||
6183 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6184 extent_end = extent_start +
6185 btrfs_file_extent_num_bytes(leaf, item);
6186 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6188 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6189 extent_end = ALIGN(extent_start + size, root->sectorsize);
6192 if (start >= extent_end) {
6194 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6195 ret = btrfs_next_leaf(root, path);
6202 leaf = path->nodes[0];
6204 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6205 if (found_key.objectid != objectid ||
6206 found_key.type != BTRFS_EXTENT_DATA_KEY)
6208 if (start + len <= found_key.offset)
6211 em->orig_start = start;
6212 em->len = found_key.offset - start;
6216 em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
6217 if (found_type == BTRFS_FILE_EXTENT_REG ||
6218 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6219 em->start = extent_start;
6220 em->len = extent_end - extent_start;
6221 em->orig_start = extent_start -
6222 btrfs_file_extent_offset(leaf, item);
6223 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6225 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6227 em->block_start = EXTENT_MAP_HOLE;
6230 if (compress_type != BTRFS_COMPRESS_NONE) {
6231 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6232 em->compress_type = compress_type;
6233 em->block_start = bytenr;
6234 em->block_len = em->orig_block_len;
6236 bytenr += btrfs_file_extent_offset(leaf, item);
6237 em->block_start = bytenr;
6238 em->block_len = em->len;
6239 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6240 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6243 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6247 size_t extent_offset;
6250 em->block_start = EXTENT_MAP_INLINE;
6251 if (!page || create) {
6252 em->start = extent_start;
6253 em->len = extent_end - extent_start;
6257 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6258 extent_offset = page_offset(page) + pg_offset - extent_start;
6259 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6260 size - extent_offset);
6261 em->start = extent_start + extent_offset;
6262 em->len = ALIGN(copy_size, root->sectorsize);
6263 em->orig_block_len = em->len;
6264 em->orig_start = em->start;
6265 if (compress_type) {
6266 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6267 em->compress_type = compress_type;
6269 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6270 if (create == 0 && !PageUptodate(page)) {
6271 if (btrfs_file_extent_compression(leaf, item) !=
6272 BTRFS_COMPRESS_NONE) {
6273 ret = uncompress_inline(path, inode, page,
6275 extent_offset, item);
6276 BUG_ON(ret); /* -ENOMEM */
6279 read_extent_buffer(leaf, map + pg_offset, ptr,
6281 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6282 memset(map + pg_offset + copy_size, 0,
6283 PAGE_CACHE_SIZE - pg_offset -
6288 flush_dcache_page(page);
6289 } else if (create && PageUptodate(page)) {
6293 free_extent_map(em);
6296 btrfs_release_path(path);
6297 trans = btrfs_join_transaction(root);
6300 return ERR_CAST(trans);
6304 write_extent_buffer(leaf, map + pg_offset, ptr,
6307 btrfs_mark_buffer_dirty(leaf);
6309 set_extent_uptodate(io_tree, em->start,
6310 extent_map_end(em) - 1, NULL, GFP_NOFS);
6313 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6317 em->orig_start = start;
6320 em->block_start = EXTENT_MAP_HOLE;
6321 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6323 btrfs_release_path(path);
6324 if (em->start > start || extent_map_end(em) <= start) {
6325 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6326 em->start, em->len, start, len);
6332 write_lock(&em_tree->lock);
6333 ret = add_extent_mapping(em_tree, em, 0);
6334 /* it is possible that someone inserted the extent into the tree
6335 * while we had the lock dropped. It is also possible that
6336 * an overlapping map exists in the tree
6338 if (ret == -EEXIST) {
6339 struct extent_map *existing;
6343 existing = lookup_extent_mapping(em_tree, start, len);
6344 if (existing && (existing->start > start ||
6345 existing->start + existing->len <= start)) {
6346 free_extent_map(existing);
6350 existing = lookup_extent_mapping(em_tree, em->start,
6353 err = merge_extent_mapping(em_tree, existing,
6356 free_extent_map(existing);
6358 free_extent_map(em);
6363 free_extent_map(em);
6367 free_extent_map(em);
6372 write_unlock(&em_tree->lock);
6375 trace_btrfs_get_extent(root, em);
6378 btrfs_free_path(path);
6380 ret = btrfs_end_transaction(trans, root);
6385 free_extent_map(em);
6386 return ERR_PTR(err);
6388 BUG_ON(!em); /* Error is always set */
6392 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6393 size_t pg_offset, u64 start, u64 len,
6396 struct extent_map *em;
6397 struct extent_map *hole_em = NULL;
6398 u64 range_start = start;
6404 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6411 * - a pre-alloc extent,
6412 * there might actually be delalloc bytes behind it.
6414 if (em->block_start != EXTENT_MAP_HOLE &&
6415 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6421 /* check to see if we've wrapped (len == -1 or similar) */
6430 /* ok, we didn't find anything, lets look for delalloc */
6431 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6432 end, len, EXTENT_DELALLOC, 1);
6433 found_end = range_start + found;
6434 if (found_end < range_start)
6435 found_end = (u64)-1;
6438 * we didn't find anything useful, return
6439 * the original results from get_extent()
6441 if (range_start > end || found_end <= start) {
6447 /* adjust the range_start to make sure it doesn't
6448 * go backwards from the start they passed in
6450 range_start = max(start, range_start);
6451 found = found_end - range_start;
6454 u64 hole_start = start;
6457 em = alloc_extent_map();
6463 * when btrfs_get_extent can't find anything it
6464 * returns one huge hole
6466 * make sure what it found really fits our range, and
6467 * adjust to make sure it is based on the start from
6471 u64 calc_end = extent_map_end(hole_em);
6473 if (calc_end <= start || (hole_em->start > end)) {
6474 free_extent_map(hole_em);
6477 hole_start = max(hole_em->start, start);
6478 hole_len = calc_end - hole_start;
6482 if (hole_em && range_start > hole_start) {
6483 /* our hole starts before our delalloc, so we
6484 * have to return just the parts of the hole
6485 * that go until the delalloc starts
6487 em->len = min(hole_len,
6488 range_start - hole_start);
6489 em->start = hole_start;
6490 em->orig_start = hole_start;
6492 * don't adjust block start at all,
6493 * it is fixed at EXTENT_MAP_HOLE
6495 em->block_start = hole_em->block_start;
6496 em->block_len = hole_len;
6497 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6498 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6500 em->start = range_start;
6502 em->orig_start = range_start;
6503 em->block_start = EXTENT_MAP_DELALLOC;
6504 em->block_len = found;
6506 } else if (hole_em) {
6511 free_extent_map(hole_em);
6513 free_extent_map(em);
6514 return ERR_PTR(err);
6519 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6522 struct btrfs_root *root = BTRFS_I(inode)->root;
6523 struct extent_map *em;
6524 struct btrfs_key ins;
6528 alloc_hint = get_extent_allocation_hint(inode, start, len);
6529 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
6530 alloc_hint, &ins, 1);
6532 return ERR_PTR(ret);
6534 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6535 ins.offset, ins.offset, ins.offset, 0);
6537 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6541 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6542 ins.offset, ins.offset, 0);
6544 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6545 free_extent_map(em);
6546 return ERR_PTR(ret);
6553 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6554 * block must be cow'd
6556 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6557 u64 *orig_start, u64 *orig_block_len,
6560 struct btrfs_trans_handle *trans;
6561 struct btrfs_path *path;
6563 struct extent_buffer *leaf;
6564 struct btrfs_root *root = BTRFS_I(inode)->root;
6565 struct btrfs_file_extent_item *fi;
6566 struct btrfs_key key;
6573 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6575 path = btrfs_alloc_path();
6579 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
6584 slot = path->slots[0];
6587 /* can't find the item, must cow */
6594 leaf = path->nodes[0];
6595 btrfs_item_key_to_cpu(leaf, &key, slot);
6596 if (key.objectid != btrfs_ino(inode) ||
6597 key.type != BTRFS_EXTENT_DATA_KEY) {
6598 /* not our file or wrong item type, must cow */
6602 if (key.offset > offset) {
6603 /* Wrong offset, must cow */
6607 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6608 found_type = btrfs_file_extent_type(leaf, fi);
6609 if (found_type != BTRFS_FILE_EXTENT_REG &&
6610 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6611 /* not a regular extent, must cow */
6615 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6618 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6619 if (extent_end <= offset)
6622 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6623 if (disk_bytenr == 0)
6626 if (btrfs_file_extent_compression(leaf, fi) ||
6627 btrfs_file_extent_encryption(leaf, fi) ||
6628 btrfs_file_extent_other_encoding(leaf, fi))
6631 backref_offset = btrfs_file_extent_offset(leaf, fi);
6634 *orig_start = key.offset - backref_offset;
6635 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6636 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6639 if (btrfs_extent_readonly(root, disk_bytenr))
6641 btrfs_release_path(path);
6644 * look for other files referencing this extent, if we
6645 * find any we must cow
6647 trans = btrfs_join_transaction(root);
6648 if (IS_ERR(trans)) {
6653 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6654 key.offset - backref_offset, disk_bytenr);
6655 btrfs_end_transaction(trans, root);
6662 * adjust disk_bytenr and num_bytes to cover just the bytes
6663 * in this extent we are about to write. If there
6664 * are any csums in that range we have to cow in order
6665 * to keep the csums correct
6667 disk_bytenr += backref_offset;
6668 disk_bytenr += offset - key.offset;
6669 num_bytes = min(offset + *len, extent_end) - offset;
6670 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6673 * all of the above have passed, it is safe to overwrite this extent
6679 btrfs_free_path(path);
6683 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6684 struct extent_state **cached_state, int writing)
6686 struct btrfs_ordered_extent *ordered;
6690 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6693 * We're concerned with the entire range that we're going to be
6694 * doing DIO to, so we need to make sure theres no ordered
6695 * extents in this range.
6697 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6698 lockend - lockstart + 1);
6701 * We need to make sure there are no buffered pages in this
6702 * range either, we could have raced between the invalidate in
6703 * generic_file_direct_write and locking the extent. The
6704 * invalidate needs to happen so that reads after a write do not
6707 if (!ordered && (!writing ||
6708 !test_range_bit(&BTRFS_I(inode)->io_tree,
6709 lockstart, lockend, EXTENT_UPTODATE, 0,
6713 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6714 cached_state, GFP_NOFS);
6717 btrfs_start_ordered_extent(inode, ordered, 1);
6718 btrfs_put_ordered_extent(ordered);
6720 /* Screw you mmap */
6721 ret = filemap_write_and_wait_range(inode->i_mapping,
6728 * If we found a page that couldn't be invalidated just
6729 * fall back to buffered.
6731 ret = invalidate_inode_pages2_range(inode->i_mapping,
6732 lockstart >> PAGE_CACHE_SHIFT,
6733 lockend >> PAGE_CACHE_SHIFT);
6744 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6745 u64 len, u64 orig_start,
6746 u64 block_start, u64 block_len,
6747 u64 orig_block_len, u64 ram_bytes,
6750 struct extent_map_tree *em_tree;
6751 struct extent_map *em;
6752 struct btrfs_root *root = BTRFS_I(inode)->root;
6755 em_tree = &BTRFS_I(inode)->extent_tree;
6756 em = alloc_extent_map();
6758 return ERR_PTR(-ENOMEM);
6761 em->orig_start = orig_start;
6762 em->mod_start = start;
6765 em->block_len = block_len;
6766 em->block_start = block_start;
6767 em->bdev = root->fs_info->fs_devices->latest_bdev;
6768 em->orig_block_len = orig_block_len;
6769 em->ram_bytes = ram_bytes;
6770 em->generation = -1;
6771 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6772 if (type == BTRFS_ORDERED_PREALLOC)
6773 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6776 btrfs_drop_extent_cache(inode, em->start,
6777 em->start + em->len - 1, 0);
6778 write_lock(&em_tree->lock);
6779 ret = add_extent_mapping(em_tree, em, 1);
6780 write_unlock(&em_tree->lock);
6781 } while (ret == -EEXIST);
6784 free_extent_map(em);
6785 return ERR_PTR(ret);
6792 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6793 struct buffer_head *bh_result, int create)
6795 struct extent_map *em;
6796 struct btrfs_root *root = BTRFS_I(inode)->root;
6797 struct extent_state *cached_state = NULL;
6798 u64 start = iblock << inode->i_blkbits;
6799 u64 lockstart, lockend;
6800 u64 len = bh_result->b_size;
6801 int unlock_bits = EXTENT_LOCKED;
6805 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6807 len = min_t(u64, len, root->sectorsize);
6810 lockend = start + len - 1;
6813 * If this errors out it's because we couldn't invalidate pagecache for
6814 * this range and we need to fallback to buffered.
6816 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6819 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6826 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6827 * io. INLINE is special, and we could probably kludge it in here, but
6828 * it's still buffered so for safety lets just fall back to the generic
6831 * For COMPRESSED we _have_ to read the entire extent in so we can
6832 * decompress it, so there will be buffering required no matter what we
6833 * do, so go ahead and fallback to buffered.
6835 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6836 * to buffered IO. Don't blame me, this is the price we pay for using
6839 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6840 em->block_start == EXTENT_MAP_INLINE) {
6841 free_extent_map(em);
6846 /* Just a good old fashioned hole, return */
6847 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6848 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6849 free_extent_map(em);
6854 * We don't allocate a new extent in the following cases
6856 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6858 * 2) The extent is marked as PREALLOC. We're good to go here and can
6859 * just use the extent.
6863 len = min(len, em->len - (start - em->start));
6864 lockstart = start + len;
6868 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6869 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6870 em->block_start != EXTENT_MAP_HOLE)) {
6873 u64 block_start, orig_start, orig_block_len, ram_bytes;
6875 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6876 type = BTRFS_ORDERED_PREALLOC;
6878 type = BTRFS_ORDERED_NOCOW;
6879 len = min(len, em->len - (start - em->start));
6880 block_start = em->block_start + (start - em->start);
6882 if (can_nocow_extent(inode, start, &len, &orig_start,
6883 &orig_block_len, &ram_bytes) == 1) {
6884 if (type == BTRFS_ORDERED_PREALLOC) {
6885 free_extent_map(em);
6886 em = create_pinned_em(inode, start, len,
6895 ret = btrfs_add_ordered_extent_dio(inode, start,
6896 block_start, len, len, type);
6898 free_extent_map(em);
6906 * this will cow the extent, reset the len in case we changed
6909 len = bh_result->b_size;
6910 free_extent_map(em);
6911 em = btrfs_new_extent_direct(inode, start, len);
6916 len = min(len, em->len - (start - em->start));
6918 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6920 bh_result->b_size = len;
6921 bh_result->b_bdev = em->bdev;
6922 set_buffer_mapped(bh_result);
6924 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6925 set_buffer_new(bh_result);
6928 * Need to update the i_size under the extent lock so buffered
6929 * readers will get the updated i_size when we unlock.
6931 if (start + len > i_size_read(inode))
6932 i_size_write(inode, start + len);
6934 spin_lock(&BTRFS_I(inode)->lock);
6935 BTRFS_I(inode)->outstanding_extents++;
6936 spin_unlock(&BTRFS_I(inode)->lock);
6938 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6939 lockstart + len - 1, EXTENT_DELALLOC, NULL,
6940 &cached_state, GFP_NOFS);
6945 * In the case of write we need to clear and unlock the entire range,
6946 * in the case of read we need to unlock only the end area that we
6947 * aren't using if there is any left over space.
6949 if (lockstart < lockend) {
6950 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6951 lockend, unlock_bits, 1, 0,
6952 &cached_state, GFP_NOFS);
6954 free_extent_state(cached_state);
6957 free_extent_map(em);
6962 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6963 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6967 static void btrfs_endio_direct_read(struct bio *bio, int err)
6969 struct btrfs_dio_private *dip = bio->bi_private;
6970 struct bio_vec *bvec;
6971 struct inode *inode = dip->inode;
6972 struct btrfs_root *root = BTRFS_I(inode)->root;
6973 struct bio *dio_bio;
6974 u32 *csums = (u32 *)dip->csum;
6978 start = dip->logical_offset;
6979 bio_for_each_segment_all(bvec, bio, i) {
6980 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6981 struct page *page = bvec->bv_page;
6984 unsigned long flags;
6986 local_irq_save(flags);
6987 kaddr = kmap_atomic(page);
6988 csum = btrfs_csum_data(kaddr + bvec->bv_offset,
6989 csum, bvec->bv_len);
6990 btrfs_csum_final(csum, (char *)&csum);
6991 kunmap_atomic(kaddr);
6992 local_irq_restore(flags);
6994 flush_dcache_page(bvec->bv_page);
6995 if (csum != csums[i]) {
6996 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
6997 btrfs_ino(inode), start, csum,
7003 start += bvec->bv_len;
7006 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
7007 dip->logical_offset + dip->bytes - 1);
7008 dio_bio = dip->dio_bio;
7012 /* If we had a csum failure make sure to clear the uptodate flag */
7014 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7015 dio_end_io(dio_bio, err);
7019 static void btrfs_endio_direct_write(struct bio *bio, int err)
7021 struct btrfs_dio_private *dip = bio->bi_private;
7022 struct inode *inode = dip->inode;
7023 struct btrfs_root *root = BTRFS_I(inode)->root;
7024 struct btrfs_ordered_extent *ordered = NULL;
7025 u64 ordered_offset = dip->logical_offset;
7026 u64 ordered_bytes = dip->bytes;
7027 struct bio *dio_bio;
7033 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7035 ordered_bytes, !err);
7039 ordered->work.func = finish_ordered_fn;
7040 ordered->work.flags = 0;
7041 btrfs_queue_worker(&root->fs_info->endio_write_workers,
7045 * our bio might span multiple ordered extents. If we haven't
7046 * completed the accounting for the whole dio, go back and try again
7048 if (ordered_offset < dip->logical_offset + dip->bytes) {
7049 ordered_bytes = dip->logical_offset + dip->bytes -
7055 dio_bio = dip->dio_bio;
7059 /* If we had an error make sure to clear the uptodate flag */
7061 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7062 dio_end_io(dio_bio, err);
7066 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7067 struct bio *bio, int mirror_num,
7068 unsigned long bio_flags, u64 offset)
7071 struct btrfs_root *root = BTRFS_I(inode)->root;
7072 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7073 BUG_ON(ret); /* -ENOMEM */
7077 static void btrfs_end_dio_bio(struct bio *bio, int err)
7079 struct btrfs_dio_private *dip = bio->bi_private;
7082 btrfs_err(BTRFS_I(dip->inode)->root->fs_info,
7083 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
7084 btrfs_ino(dip->inode), bio->bi_rw,
7085 (unsigned long long)bio->bi_iter.bi_sector,
7086 bio->bi_iter.bi_size, err);
7090 * before atomic variable goto zero, we must make sure
7091 * dip->errors is perceived to be set.
7093 smp_mb__before_atomic_dec();
7096 /* if there are more bios still pending for this dio, just exit */
7097 if (!atomic_dec_and_test(&dip->pending_bios))
7101 bio_io_error(dip->orig_bio);
7103 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
7104 bio_endio(dip->orig_bio, 0);
7110 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7111 u64 first_sector, gfp_t gfp_flags)
7113 int nr_vecs = bio_get_nr_vecs(bdev);
7114 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7117 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7118 int rw, u64 file_offset, int skip_sum,
7121 struct btrfs_dio_private *dip = bio->bi_private;
7122 int write = rw & REQ_WRITE;
7123 struct btrfs_root *root = BTRFS_I(inode)->root;
7127 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7132 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
7140 if (write && async_submit) {
7141 ret = btrfs_wq_submit_bio(root->fs_info,
7142 inode, rw, bio, 0, 0,
7144 __btrfs_submit_bio_start_direct_io,
7145 __btrfs_submit_bio_done);
7149 * If we aren't doing async submit, calculate the csum of the
7152 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7155 } else if (!skip_sum) {
7156 ret = btrfs_lookup_bio_sums_dio(root, inode, dip, bio,
7163 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7169 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7172 struct inode *inode = dip->inode;
7173 struct btrfs_root *root = BTRFS_I(inode)->root;
7175 struct bio *orig_bio = dip->orig_bio;
7176 struct bio_vec *bvec = orig_bio->bi_io_vec;
7177 u64 start_sector = orig_bio->bi_iter.bi_sector;
7178 u64 file_offset = dip->logical_offset;
7183 int async_submit = 0;
7185 map_length = orig_bio->bi_iter.bi_size;
7186 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7187 &map_length, NULL, 0);
7193 if (map_length >= orig_bio->bi_iter.bi_size) {
7198 /* async crcs make it difficult to collect full stripe writes. */
7199 if (btrfs_get_alloc_profile(root, 1) &
7200 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7205 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7208 bio->bi_private = dip;
7209 bio->bi_end_io = btrfs_end_dio_bio;
7210 atomic_inc(&dip->pending_bios);
7212 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7213 if (unlikely(map_length < submit_len + bvec->bv_len ||
7214 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7215 bvec->bv_offset) < bvec->bv_len)) {
7217 * inc the count before we submit the bio so
7218 * we know the end IO handler won't happen before
7219 * we inc the count. Otherwise, the dip might get freed
7220 * before we're done setting it up
7222 atomic_inc(&dip->pending_bios);
7223 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7224 file_offset, skip_sum,
7228 atomic_dec(&dip->pending_bios);
7232 start_sector += submit_len >> 9;
7233 file_offset += submit_len;
7238 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7239 start_sector, GFP_NOFS);
7242 bio->bi_private = dip;
7243 bio->bi_end_io = btrfs_end_dio_bio;
7245 map_length = orig_bio->bi_iter.bi_size;
7246 ret = btrfs_map_block(root->fs_info, rw,
7248 &map_length, NULL, 0);
7254 submit_len += bvec->bv_len;
7261 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7270 * before atomic variable goto zero, we must
7271 * make sure dip->errors is perceived to be set.
7273 smp_mb__before_atomic_dec();
7274 if (atomic_dec_and_test(&dip->pending_bios))
7275 bio_io_error(dip->orig_bio);
7277 /* bio_end_io() will handle error, so we needn't return it */
7281 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7282 struct inode *inode, loff_t file_offset)
7284 struct btrfs_root *root = BTRFS_I(inode)->root;
7285 struct btrfs_dio_private *dip;
7289 int write = rw & REQ_WRITE;
7293 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7295 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7301 if (!skip_sum && !write) {
7302 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
7303 sum_len = dio_bio->bi_iter.bi_size >>
7304 inode->i_sb->s_blocksize_bits;
7305 sum_len *= csum_size;
7310 dip = kmalloc(sizeof(*dip) + sum_len, GFP_NOFS);
7316 dip->private = dio_bio->bi_private;
7318 dip->logical_offset = file_offset;
7319 dip->bytes = dio_bio->bi_iter.bi_size;
7320 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7321 io_bio->bi_private = dip;
7323 dip->orig_bio = io_bio;
7324 dip->dio_bio = dio_bio;
7325 atomic_set(&dip->pending_bios, 0);
7328 io_bio->bi_end_io = btrfs_endio_direct_write;
7330 io_bio->bi_end_io = btrfs_endio_direct_read;
7332 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7341 * If this is a write, we need to clean up the reserved space and kill
7342 * the ordered extent.
7345 struct btrfs_ordered_extent *ordered;
7346 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7347 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7348 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7349 btrfs_free_reserved_extent(root, ordered->start,
7351 btrfs_put_ordered_extent(ordered);
7352 btrfs_put_ordered_extent(ordered);
7354 bio_endio(dio_bio, ret);
7357 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7358 const struct iovec *iov, loff_t offset,
7359 unsigned long nr_segs)
7365 unsigned blocksize_mask = root->sectorsize - 1;
7366 ssize_t retval = -EINVAL;
7367 loff_t end = offset;
7369 if (offset & blocksize_mask)
7372 /* Check the memory alignment. Blocks cannot straddle pages */
7373 for (seg = 0; seg < nr_segs; seg++) {
7374 addr = (unsigned long)iov[seg].iov_base;
7375 size = iov[seg].iov_len;
7377 if ((addr & blocksize_mask) || (size & blocksize_mask))
7380 /* If this is a write we don't need to check anymore */
7385 * Check to make sure we don't have duplicate iov_base's in this
7386 * iovec, if so return EINVAL, otherwise we'll get csum errors
7387 * when reading back.
7389 for (i = seg + 1; i < nr_segs; i++) {
7390 if (iov[seg].iov_base == iov[i].iov_base)
7399 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7400 const struct iovec *iov, loff_t offset,
7401 unsigned long nr_segs)
7403 struct file *file = iocb->ki_filp;
7404 struct inode *inode = file->f_mapping->host;
7408 bool relock = false;
7411 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7415 atomic_inc(&inode->i_dio_count);
7416 smp_mb__after_atomic_inc();
7419 * The generic stuff only does filemap_write_and_wait_range, which isn't
7420 * enough if we've written compressed pages to this area, so we need to
7421 * call btrfs_wait_ordered_range to make absolutely sure that any
7422 * outstanding dirty pages are on disk.
7424 count = iov_length(iov, nr_segs);
7425 ret = btrfs_wait_ordered_range(inode, offset, count);
7431 * If the write DIO is beyond the EOF, we need update
7432 * the isize, but it is protected by i_mutex. So we can
7433 * not unlock the i_mutex at this case.
7435 if (offset + count <= inode->i_size) {
7436 mutex_unlock(&inode->i_mutex);
7439 ret = btrfs_delalloc_reserve_space(inode, count);
7442 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7443 &BTRFS_I(inode)->runtime_flags))) {
7444 inode_dio_done(inode);
7445 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7449 ret = __blockdev_direct_IO(rw, iocb, inode,
7450 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7451 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7452 btrfs_submit_direct, flags);
7454 if (ret < 0 && ret != -EIOCBQUEUED)
7455 btrfs_delalloc_release_space(inode, count);
7456 else if (ret >= 0 && (size_t)ret < count)
7457 btrfs_delalloc_release_space(inode,
7458 count - (size_t)ret);
7460 btrfs_delalloc_release_metadata(inode, 0);
7464 inode_dio_done(inode);
7466 mutex_lock(&inode->i_mutex);
7471 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7473 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7474 __u64 start, __u64 len)
7478 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7482 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7485 int btrfs_readpage(struct file *file, struct page *page)
7487 struct extent_io_tree *tree;
7488 tree = &BTRFS_I(page->mapping->host)->io_tree;
7489 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7492 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7494 struct extent_io_tree *tree;
7497 if (current->flags & PF_MEMALLOC) {
7498 redirty_page_for_writepage(wbc, page);
7502 tree = &BTRFS_I(page->mapping->host)->io_tree;
7503 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7506 static int btrfs_writepages(struct address_space *mapping,
7507 struct writeback_control *wbc)
7509 struct extent_io_tree *tree;
7511 tree = &BTRFS_I(mapping->host)->io_tree;
7512 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7516 btrfs_readpages(struct file *file, struct address_space *mapping,
7517 struct list_head *pages, unsigned nr_pages)
7519 struct extent_io_tree *tree;
7520 tree = &BTRFS_I(mapping->host)->io_tree;
7521 return extent_readpages(tree, mapping, pages, nr_pages,
7524 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7526 struct extent_io_tree *tree;
7527 struct extent_map_tree *map;
7530 tree = &BTRFS_I(page->mapping->host)->io_tree;
7531 map = &BTRFS_I(page->mapping->host)->extent_tree;
7532 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7534 ClearPagePrivate(page);
7535 set_page_private(page, 0);
7536 page_cache_release(page);
7541 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7543 if (PageWriteback(page) || PageDirty(page))
7545 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7548 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
7549 unsigned int length)
7551 struct inode *inode = page->mapping->host;
7552 struct extent_io_tree *tree;
7553 struct btrfs_ordered_extent *ordered;
7554 struct extent_state *cached_state = NULL;
7555 u64 page_start = page_offset(page);
7556 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7557 int inode_evicting = inode->i_state & I_FREEING;
7560 * we have the page locked, so new writeback can't start,
7561 * and the dirty bit won't be cleared while we are here.
7563 * Wait for IO on this page so that we can safely clear
7564 * the PagePrivate2 bit and do ordered accounting
7566 wait_on_page_writeback(page);
7568 tree = &BTRFS_I(inode)->io_tree;
7570 btrfs_releasepage(page, GFP_NOFS);
7574 if (!inode_evicting)
7575 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7576 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7579 * IO on this page will never be started, so we need
7580 * to account for any ordered extents now
7582 if (!inode_evicting)
7583 clear_extent_bit(tree, page_start, page_end,
7584 EXTENT_DIRTY | EXTENT_DELALLOC |
7585 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7586 EXTENT_DEFRAG, 1, 0, &cached_state,
7589 * whoever cleared the private bit is responsible
7590 * for the finish_ordered_io
7592 if (TestClearPagePrivate2(page)) {
7593 struct btrfs_ordered_inode_tree *tree;
7596 tree = &BTRFS_I(inode)->ordered_tree;
7598 spin_lock_irq(&tree->lock);
7599 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
7600 new_len = page_start - ordered->file_offset;
7601 if (new_len < ordered->truncated_len)
7602 ordered->truncated_len = new_len;
7603 spin_unlock_irq(&tree->lock);
7605 if (btrfs_dec_test_ordered_pending(inode, &ordered,
7607 PAGE_CACHE_SIZE, 1))
7608 btrfs_finish_ordered_io(ordered);
7610 btrfs_put_ordered_extent(ordered);
7611 if (!inode_evicting) {
7612 cached_state = NULL;
7613 lock_extent_bits(tree, page_start, page_end, 0,
7618 if (!inode_evicting) {
7619 clear_extent_bit(tree, page_start, page_end,
7620 EXTENT_LOCKED | EXTENT_DIRTY |
7621 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
7622 EXTENT_DEFRAG, 1, 1,
7623 &cached_state, GFP_NOFS);
7625 __btrfs_releasepage(page, GFP_NOFS);
7628 ClearPageChecked(page);
7629 if (PagePrivate(page)) {
7630 ClearPagePrivate(page);
7631 set_page_private(page, 0);
7632 page_cache_release(page);
7637 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7638 * called from a page fault handler when a page is first dirtied. Hence we must
7639 * be careful to check for EOF conditions here. We set the page up correctly
7640 * for a written page which means we get ENOSPC checking when writing into
7641 * holes and correct delalloc and unwritten extent mapping on filesystems that
7642 * support these features.
7644 * We are not allowed to take the i_mutex here so we have to play games to
7645 * protect against truncate races as the page could now be beyond EOF. Because
7646 * vmtruncate() writes the inode size before removing pages, once we have the
7647 * page lock we can determine safely if the page is beyond EOF. If it is not
7648 * beyond EOF, then the page is guaranteed safe against truncation until we
7651 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7653 struct page *page = vmf->page;
7654 struct inode *inode = file_inode(vma->vm_file);
7655 struct btrfs_root *root = BTRFS_I(inode)->root;
7656 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7657 struct btrfs_ordered_extent *ordered;
7658 struct extent_state *cached_state = NULL;
7660 unsigned long zero_start;
7667 sb_start_pagefault(inode->i_sb);
7668 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7670 ret = file_update_time(vma->vm_file);
7676 else /* -ENOSPC, -EIO, etc */
7677 ret = VM_FAULT_SIGBUS;
7683 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7686 size = i_size_read(inode);
7687 page_start = page_offset(page);
7688 page_end = page_start + PAGE_CACHE_SIZE - 1;
7690 if ((page->mapping != inode->i_mapping) ||
7691 (page_start >= size)) {
7692 /* page got truncated out from underneath us */
7695 wait_on_page_writeback(page);
7697 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7698 set_page_extent_mapped(page);
7701 * we can't set the delalloc bits if there are pending ordered
7702 * extents. Drop our locks and wait for them to finish
7704 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7706 unlock_extent_cached(io_tree, page_start, page_end,
7707 &cached_state, GFP_NOFS);
7709 btrfs_start_ordered_extent(inode, ordered, 1);
7710 btrfs_put_ordered_extent(ordered);
7715 * XXX - page_mkwrite gets called every time the page is dirtied, even
7716 * if it was already dirty, so for space accounting reasons we need to
7717 * clear any delalloc bits for the range we are fixing to save. There
7718 * is probably a better way to do this, but for now keep consistent with
7719 * prepare_pages in the normal write path.
7721 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7722 EXTENT_DIRTY | EXTENT_DELALLOC |
7723 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7724 0, 0, &cached_state, GFP_NOFS);
7726 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7729 unlock_extent_cached(io_tree, page_start, page_end,
7730 &cached_state, GFP_NOFS);
7731 ret = VM_FAULT_SIGBUS;
7736 /* page is wholly or partially inside EOF */
7737 if (page_start + PAGE_CACHE_SIZE > size)
7738 zero_start = size & ~PAGE_CACHE_MASK;
7740 zero_start = PAGE_CACHE_SIZE;
7742 if (zero_start != PAGE_CACHE_SIZE) {
7744 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7745 flush_dcache_page(page);
7748 ClearPageChecked(page);
7749 set_page_dirty(page);
7750 SetPageUptodate(page);
7752 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7753 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7754 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7756 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7760 sb_end_pagefault(inode->i_sb);
7761 return VM_FAULT_LOCKED;
7765 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7767 sb_end_pagefault(inode->i_sb);
7771 static int btrfs_truncate(struct inode *inode)
7773 struct btrfs_root *root = BTRFS_I(inode)->root;
7774 struct btrfs_block_rsv *rsv;
7777 struct btrfs_trans_handle *trans;
7778 u64 mask = root->sectorsize - 1;
7779 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7781 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
7787 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7788 * 3 things going on here
7790 * 1) We need to reserve space for our orphan item and the space to
7791 * delete our orphan item. Lord knows we don't want to have a dangling
7792 * orphan item because we didn't reserve space to remove it.
7794 * 2) We need to reserve space to update our inode.
7796 * 3) We need to have something to cache all the space that is going to
7797 * be free'd up by the truncate operation, but also have some slack
7798 * space reserved in case it uses space during the truncate (thank you
7799 * very much snapshotting).
7801 * And we need these to all be seperate. The fact is we can use alot of
7802 * space doing the truncate, and we have no earthly idea how much space
7803 * we will use, so we need the truncate reservation to be seperate so it
7804 * doesn't end up using space reserved for updating the inode or
7805 * removing the orphan item. We also need to be able to stop the
7806 * transaction and start a new one, which means we need to be able to
7807 * update the inode several times, and we have no idea of knowing how
7808 * many times that will be, so we can't just reserve 1 item for the
7809 * entirety of the opration, so that has to be done seperately as well.
7810 * Then there is the orphan item, which does indeed need to be held on
7811 * to for the whole operation, and we need nobody to touch this reserved
7812 * space except the orphan code.
7814 * So that leaves us with
7816 * 1) root->orphan_block_rsv - for the orphan deletion.
7817 * 2) rsv - for the truncate reservation, which we will steal from the
7818 * transaction reservation.
7819 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7820 * updating the inode.
7822 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7825 rsv->size = min_size;
7829 * 1 for the truncate slack space
7830 * 1 for updating the inode.
7832 trans = btrfs_start_transaction(root, 2);
7833 if (IS_ERR(trans)) {
7834 err = PTR_ERR(trans);
7838 /* Migrate the slack space for the truncate to our reserve */
7839 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7844 * setattr is responsible for setting the ordered_data_close flag,
7845 * but that is only tested during the last file release. That
7846 * could happen well after the next commit, leaving a great big
7847 * window where new writes may get lost if someone chooses to write
7848 * to this file after truncating to zero
7850 * The inode doesn't have any dirty data here, and so if we commit
7851 * this is a noop. If someone immediately starts writing to the inode
7852 * it is very likely we'll catch some of their writes in this
7853 * transaction, and the commit will find this file on the ordered
7854 * data list with good things to send down.
7856 * This is a best effort solution, there is still a window where
7857 * using truncate to replace the contents of the file will
7858 * end up with a zero length file after a crash.
7860 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7861 &BTRFS_I(inode)->runtime_flags))
7862 btrfs_add_ordered_operation(trans, root, inode);
7865 * So if we truncate and then write and fsync we normally would just
7866 * write the extents that changed, which is a problem if we need to
7867 * first truncate that entire inode. So set this flag so we write out
7868 * all of the extents in the inode to the sync log so we're completely
7871 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7872 trans->block_rsv = rsv;
7875 ret = btrfs_truncate_inode_items(trans, root, inode,
7877 BTRFS_EXTENT_DATA_KEY);
7878 if (ret != -ENOSPC) {
7883 trans->block_rsv = &root->fs_info->trans_block_rsv;
7884 ret = btrfs_update_inode(trans, root, inode);
7890 btrfs_end_transaction(trans, root);
7891 btrfs_btree_balance_dirty(root);
7893 trans = btrfs_start_transaction(root, 2);
7894 if (IS_ERR(trans)) {
7895 ret = err = PTR_ERR(trans);
7900 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7902 BUG_ON(ret); /* shouldn't happen */
7903 trans->block_rsv = rsv;
7906 if (ret == 0 && inode->i_nlink > 0) {
7907 trans->block_rsv = root->orphan_block_rsv;
7908 ret = btrfs_orphan_del(trans, inode);
7914 trans->block_rsv = &root->fs_info->trans_block_rsv;
7915 ret = btrfs_update_inode(trans, root, inode);
7919 ret = btrfs_end_transaction(trans, root);
7920 btrfs_btree_balance_dirty(root);
7924 btrfs_free_block_rsv(root, rsv);
7933 * create a new subvolume directory/inode (helper for the ioctl).
7935 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7936 struct btrfs_root *new_root,
7937 struct btrfs_root *parent_root,
7940 struct inode *inode;
7944 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7945 new_dirid, new_dirid,
7946 S_IFDIR | (~current_umask() & S_IRWXUGO),
7949 return PTR_ERR(inode);
7950 inode->i_op = &btrfs_dir_inode_operations;
7951 inode->i_fop = &btrfs_dir_file_operations;
7953 set_nlink(inode, 1);
7954 btrfs_i_size_write(inode, 0);
7956 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
7958 btrfs_err(new_root->fs_info,
7959 "error inheriting subvolume %llu properties: %d\n",
7960 new_root->root_key.objectid, err);
7962 err = btrfs_update_inode(trans, new_root, inode);
7968 struct inode *btrfs_alloc_inode(struct super_block *sb)
7970 struct btrfs_inode *ei;
7971 struct inode *inode;
7973 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7980 ei->last_sub_trans = 0;
7981 ei->logged_trans = 0;
7982 ei->delalloc_bytes = 0;
7983 ei->disk_i_size = 0;
7986 ei->index_cnt = (u64)-1;
7988 ei->last_unlink_trans = 0;
7989 ei->last_log_commit = 0;
7991 spin_lock_init(&ei->lock);
7992 ei->outstanding_extents = 0;
7993 ei->reserved_extents = 0;
7995 ei->runtime_flags = 0;
7996 ei->force_compress = BTRFS_COMPRESS_NONE;
7998 ei->delayed_node = NULL;
8000 inode = &ei->vfs_inode;
8001 extent_map_tree_init(&ei->extent_tree);
8002 extent_io_tree_init(&ei->io_tree, &inode->i_data);
8003 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
8004 ei->io_tree.track_uptodate = 1;
8005 ei->io_failure_tree.track_uptodate = 1;
8006 atomic_set(&ei->sync_writers, 0);
8007 mutex_init(&ei->log_mutex);
8008 mutex_init(&ei->delalloc_mutex);
8009 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8010 INIT_LIST_HEAD(&ei->delalloc_inodes);
8011 INIT_LIST_HEAD(&ei->ordered_operations);
8012 RB_CLEAR_NODE(&ei->rb_node);
8017 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8018 void btrfs_test_destroy_inode(struct inode *inode)
8020 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8021 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8025 static void btrfs_i_callback(struct rcu_head *head)
8027 struct inode *inode = container_of(head, struct inode, i_rcu);
8028 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8031 void btrfs_destroy_inode(struct inode *inode)
8033 struct btrfs_ordered_extent *ordered;
8034 struct btrfs_root *root = BTRFS_I(inode)->root;
8036 WARN_ON(!hlist_empty(&inode->i_dentry));
8037 WARN_ON(inode->i_data.nrpages);
8038 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8039 WARN_ON(BTRFS_I(inode)->reserved_extents);
8040 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8041 WARN_ON(BTRFS_I(inode)->csum_bytes);
8044 * This can happen where we create an inode, but somebody else also
8045 * created the same inode and we need to destroy the one we already
8052 * Make sure we're properly removed from the ordered operation
8056 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
8057 spin_lock(&root->fs_info->ordered_root_lock);
8058 list_del_init(&BTRFS_I(inode)->ordered_operations);
8059 spin_unlock(&root->fs_info->ordered_root_lock);
8062 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8063 &BTRFS_I(inode)->runtime_flags)) {
8064 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
8066 atomic_dec(&root->orphan_inodes);
8070 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8074 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
8075 ordered->file_offset, ordered->len);
8076 btrfs_remove_ordered_extent(inode, ordered);
8077 btrfs_put_ordered_extent(ordered);
8078 btrfs_put_ordered_extent(ordered);
8081 inode_tree_del(inode);
8082 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8084 call_rcu(&inode->i_rcu, btrfs_i_callback);
8087 int btrfs_drop_inode(struct inode *inode)
8089 struct btrfs_root *root = BTRFS_I(inode)->root;
8094 /* the snap/subvol tree is on deleting */
8095 if (btrfs_root_refs(&root->root_item) == 0)
8098 return generic_drop_inode(inode);
8101 static void init_once(void *foo)
8103 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8105 inode_init_once(&ei->vfs_inode);
8108 void btrfs_destroy_cachep(void)
8111 * Make sure all delayed rcu free inodes are flushed before we
8115 if (btrfs_inode_cachep)
8116 kmem_cache_destroy(btrfs_inode_cachep);
8117 if (btrfs_trans_handle_cachep)
8118 kmem_cache_destroy(btrfs_trans_handle_cachep);
8119 if (btrfs_transaction_cachep)
8120 kmem_cache_destroy(btrfs_transaction_cachep);
8121 if (btrfs_path_cachep)
8122 kmem_cache_destroy(btrfs_path_cachep);
8123 if (btrfs_free_space_cachep)
8124 kmem_cache_destroy(btrfs_free_space_cachep);
8125 if (btrfs_delalloc_work_cachep)
8126 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8129 int btrfs_init_cachep(void)
8131 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8132 sizeof(struct btrfs_inode), 0,
8133 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8134 if (!btrfs_inode_cachep)
8137 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8138 sizeof(struct btrfs_trans_handle), 0,
8139 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8140 if (!btrfs_trans_handle_cachep)
8143 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8144 sizeof(struct btrfs_transaction), 0,
8145 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8146 if (!btrfs_transaction_cachep)
8149 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8150 sizeof(struct btrfs_path), 0,
8151 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8152 if (!btrfs_path_cachep)
8155 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8156 sizeof(struct btrfs_free_space), 0,
8157 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8158 if (!btrfs_free_space_cachep)
8161 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8162 sizeof(struct btrfs_delalloc_work), 0,
8163 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8165 if (!btrfs_delalloc_work_cachep)
8170 btrfs_destroy_cachep();
8174 static int btrfs_getattr(struct vfsmount *mnt,
8175 struct dentry *dentry, struct kstat *stat)
8178 struct inode *inode = dentry->d_inode;
8179 u32 blocksize = inode->i_sb->s_blocksize;
8181 generic_fillattr(inode, stat);
8182 stat->dev = BTRFS_I(inode)->root->anon_dev;
8183 stat->blksize = PAGE_CACHE_SIZE;
8185 spin_lock(&BTRFS_I(inode)->lock);
8186 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8187 spin_unlock(&BTRFS_I(inode)->lock);
8188 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8189 ALIGN(delalloc_bytes, blocksize)) >> 9;
8193 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8194 struct inode *new_dir, struct dentry *new_dentry)
8196 struct btrfs_trans_handle *trans;
8197 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8198 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8199 struct inode *new_inode = new_dentry->d_inode;
8200 struct inode *old_inode = old_dentry->d_inode;
8201 struct timespec ctime = CURRENT_TIME;
8205 u64 old_ino = btrfs_ino(old_inode);
8207 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8210 /* we only allow rename subvolume link between subvolumes */
8211 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8214 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8215 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8218 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8219 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8223 /* check for collisions, even if the name isn't there */
8224 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8225 new_dentry->d_name.name,
8226 new_dentry->d_name.len);
8229 if (ret == -EEXIST) {
8231 * eexist without a new_inode */
8232 if (WARN_ON(!new_inode)) {
8236 /* maybe -EOVERFLOW */
8243 * we're using rename to replace one file with another.
8244 * and the replacement file is large. Start IO on it now so
8245 * we don't add too much work to the end of the transaction
8247 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8248 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8249 filemap_flush(old_inode->i_mapping);
8251 /* close the racy window with snapshot create/destroy ioctl */
8252 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8253 down_read(&root->fs_info->subvol_sem);
8255 * We want to reserve the absolute worst case amount of items. So if
8256 * both inodes are subvols and we need to unlink them then that would
8257 * require 4 item modifications, but if they are both normal inodes it
8258 * would require 5 item modifications, so we'll assume their normal
8259 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8260 * should cover the worst case number of items we'll modify.
8262 trans = btrfs_start_transaction(root, 11);
8263 if (IS_ERR(trans)) {
8264 ret = PTR_ERR(trans);
8269 btrfs_record_root_in_trans(trans, dest);
8271 ret = btrfs_set_inode_index(new_dir, &index);
8275 BTRFS_I(old_inode)->dir_index = 0ULL;
8276 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8277 /* force full log commit if subvolume involved. */
8278 root->fs_info->last_trans_log_full_commit = trans->transid;
8280 ret = btrfs_insert_inode_ref(trans, dest,
8281 new_dentry->d_name.name,
8282 new_dentry->d_name.len,
8284 btrfs_ino(new_dir), index);
8288 * this is an ugly little race, but the rename is required
8289 * to make sure that if we crash, the inode is either at the
8290 * old name or the new one. pinning the log transaction lets
8291 * us make sure we don't allow a log commit to come in after
8292 * we unlink the name but before we add the new name back in.
8294 btrfs_pin_log_trans(root);
8297 * make sure the inode gets flushed if it is replacing
8300 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8301 btrfs_add_ordered_operation(trans, root, old_inode);
8303 inode_inc_iversion(old_dir);
8304 inode_inc_iversion(new_dir);
8305 inode_inc_iversion(old_inode);
8306 old_dir->i_ctime = old_dir->i_mtime = ctime;
8307 new_dir->i_ctime = new_dir->i_mtime = ctime;
8308 old_inode->i_ctime = ctime;
8310 if (old_dentry->d_parent != new_dentry->d_parent)
8311 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8313 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8314 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8315 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8316 old_dentry->d_name.name,
8317 old_dentry->d_name.len);
8319 ret = __btrfs_unlink_inode(trans, root, old_dir,
8320 old_dentry->d_inode,
8321 old_dentry->d_name.name,
8322 old_dentry->d_name.len);
8324 ret = btrfs_update_inode(trans, root, old_inode);
8327 btrfs_abort_transaction(trans, root, ret);
8332 inode_inc_iversion(new_inode);
8333 new_inode->i_ctime = CURRENT_TIME;
8334 if (unlikely(btrfs_ino(new_inode) ==
8335 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8336 root_objectid = BTRFS_I(new_inode)->location.objectid;
8337 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8339 new_dentry->d_name.name,
8340 new_dentry->d_name.len);
8341 BUG_ON(new_inode->i_nlink == 0);
8343 ret = btrfs_unlink_inode(trans, dest, new_dir,
8344 new_dentry->d_inode,
8345 new_dentry->d_name.name,
8346 new_dentry->d_name.len);
8348 if (!ret && new_inode->i_nlink == 0)
8349 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8351 btrfs_abort_transaction(trans, root, ret);
8356 ret = btrfs_add_link(trans, new_dir, old_inode,
8357 new_dentry->d_name.name,
8358 new_dentry->d_name.len, 0, index);
8360 btrfs_abort_transaction(trans, root, ret);
8364 if (old_inode->i_nlink == 1)
8365 BTRFS_I(old_inode)->dir_index = index;
8367 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8368 struct dentry *parent = new_dentry->d_parent;
8369 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8370 btrfs_end_log_trans(root);
8373 btrfs_end_transaction(trans, root);
8375 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8376 up_read(&root->fs_info->subvol_sem);
8381 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8383 struct btrfs_delalloc_work *delalloc_work;
8384 struct inode *inode;
8386 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8388 inode = delalloc_work->inode;
8389 if (delalloc_work->wait) {
8390 btrfs_wait_ordered_range(inode, 0, (u64)-1);
8392 filemap_flush(inode->i_mapping);
8393 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8394 &BTRFS_I(inode)->runtime_flags))
8395 filemap_flush(inode->i_mapping);
8398 if (delalloc_work->delay_iput)
8399 btrfs_add_delayed_iput(inode);
8402 complete(&delalloc_work->completion);
8405 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8406 int wait, int delay_iput)
8408 struct btrfs_delalloc_work *work;
8410 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8414 init_completion(&work->completion);
8415 INIT_LIST_HEAD(&work->list);
8416 work->inode = inode;
8418 work->delay_iput = delay_iput;
8419 work->work.func = btrfs_run_delalloc_work;
8424 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8426 wait_for_completion(&work->completion);
8427 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8431 * some fairly slow code that needs optimization. This walks the list
8432 * of all the inodes with pending delalloc and forces them to disk.
8434 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8436 struct btrfs_inode *binode;
8437 struct inode *inode;
8438 struct btrfs_delalloc_work *work, *next;
8439 struct list_head works;
8440 struct list_head splice;
8443 INIT_LIST_HEAD(&works);
8444 INIT_LIST_HEAD(&splice);
8446 spin_lock(&root->delalloc_lock);
8447 list_splice_init(&root->delalloc_inodes, &splice);
8448 while (!list_empty(&splice)) {
8449 binode = list_entry(splice.next, struct btrfs_inode,
8452 list_move_tail(&binode->delalloc_inodes,
8453 &root->delalloc_inodes);
8454 inode = igrab(&binode->vfs_inode);
8456 cond_resched_lock(&root->delalloc_lock);
8459 spin_unlock(&root->delalloc_lock);
8461 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8462 if (unlikely(!work)) {
8464 btrfs_add_delayed_iput(inode);
8470 list_add_tail(&work->list, &works);
8471 btrfs_queue_worker(&root->fs_info->flush_workers,
8475 spin_lock(&root->delalloc_lock);
8477 spin_unlock(&root->delalloc_lock);
8479 list_for_each_entry_safe(work, next, &works, list) {
8480 list_del_init(&work->list);
8481 btrfs_wait_and_free_delalloc_work(work);
8485 list_for_each_entry_safe(work, next, &works, list) {
8486 list_del_init(&work->list);
8487 btrfs_wait_and_free_delalloc_work(work);
8490 if (!list_empty_careful(&splice)) {
8491 spin_lock(&root->delalloc_lock);
8492 list_splice_tail(&splice, &root->delalloc_inodes);
8493 spin_unlock(&root->delalloc_lock);
8498 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8502 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
8505 ret = __start_delalloc_inodes(root, delay_iput);
8507 * the filemap_flush will queue IO into the worker threads, but
8508 * we have to make sure the IO is actually started and that
8509 * ordered extents get created before we return
8511 atomic_inc(&root->fs_info->async_submit_draining);
8512 while (atomic_read(&root->fs_info->nr_async_submits) ||
8513 atomic_read(&root->fs_info->async_delalloc_pages)) {
8514 wait_event(root->fs_info->async_submit_wait,
8515 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8516 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8518 atomic_dec(&root->fs_info->async_submit_draining);
8522 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput)
8524 struct btrfs_root *root;
8525 struct list_head splice;
8528 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
8531 INIT_LIST_HEAD(&splice);
8533 spin_lock(&fs_info->delalloc_root_lock);
8534 list_splice_init(&fs_info->delalloc_roots, &splice);
8535 while (!list_empty(&splice)) {
8536 root = list_first_entry(&splice, struct btrfs_root,
8538 root = btrfs_grab_fs_root(root);
8540 list_move_tail(&root->delalloc_root,
8541 &fs_info->delalloc_roots);
8542 spin_unlock(&fs_info->delalloc_root_lock);
8544 ret = __start_delalloc_inodes(root, delay_iput);
8545 btrfs_put_fs_root(root);
8549 spin_lock(&fs_info->delalloc_root_lock);
8551 spin_unlock(&fs_info->delalloc_root_lock);
8553 atomic_inc(&fs_info->async_submit_draining);
8554 while (atomic_read(&fs_info->nr_async_submits) ||
8555 atomic_read(&fs_info->async_delalloc_pages)) {
8556 wait_event(fs_info->async_submit_wait,
8557 (atomic_read(&fs_info->nr_async_submits) == 0 &&
8558 atomic_read(&fs_info->async_delalloc_pages) == 0));
8560 atomic_dec(&fs_info->async_submit_draining);
8563 if (!list_empty_careful(&splice)) {
8564 spin_lock(&fs_info->delalloc_root_lock);
8565 list_splice_tail(&splice, &fs_info->delalloc_roots);
8566 spin_unlock(&fs_info->delalloc_root_lock);
8571 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8572 const char *symname)
8574 struct btrfs_trans_handle *trans;
8575 struct btrfs_root *root = BTRFS_I(dir)->root;
8576 struct btrfs_path *path;
8577 struct btrfs_key key;
8578 struct inode *inode = NULL;
8586 struct btrfs_file_extent_item *ei;
8587 struct extent_buffer *leaf;
8589 name_len = strlen(symname);
8590 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8591 return -ENAMETOOLONG;
8594 * 2 items for inode item and ref
8595 * 2 items for dir items
8596 * 1 item for xattr if selinux is on
8598 trans = btrfs_start_transaction(root, 5);
8600 return PTR_ERR(trans);
8602 err = btrfs_find_free_ino(root, &objectid);
8606 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8607 dentry->d_name.len, btrfs_ino(dir), objectid,
8608 S_IFLNK|S_IRWXUGO, &index);
8609 if (IS_ERR(inode)) {
8610 err = PTR_ERR(inode);
8614 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8621 * If the active LSM wants to access the inode during
8622 * d_instantiate it needs these. Smack checks to see
8623 * if the filesystem supports xattrs by looking at the
8626 inode->i_fop = &btrfs_file_operations;
8627 inode->i_op = &btrfs_file_inode_operations;
8629 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8633 inode->i_mapping->a_ops = &btrfs_aops;
8634 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8635 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8640 path = btrfs_alloc_path();
8646 key.objectid = btrfs_ino(inode);
8648 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8649 datasize = btrfs_file_extent_calc_inline_size(name_len);
8650 err = btrfs_insert_empty_item(trans, root, path, &key,
8654 btrfs_free_path(path);
8657 leaf = path->nodes[0];
8658 ei = btrfs_item_ptr(leaf, path->slots[0],
8659 struct btrfs_file_extent_item);
8660 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8661 btrfs_set_file_extent_type(leaf, ei,
8662 BTRFS_FILE_EXTENT_INLINE);
8663 btrfs_set_file_extent_encryption(leaf, ei, 0);
8664 btrfs_set_file_extent_compression(leaf, ei, 0);
8665 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8666 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8668 ptr = btrfs_file_extent_inline_start(ei);
8669 write_extent_buffer(leaf, symname, ptr, name_len);
8670 btrfs_mark_buffer_dirty(leaf);
8671 btrfs_free_path(path);
8673 inode->i_op = &btrfs_symlink_inode_operations;
8674 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8675 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8676 inode_set_bytes(inode, name_len);
8677 btrfs_i_size_write(inode, name_len);
8678 err = btrfs_update_inode(trans, root, inode);
8684 d_instantiate(dentry, inode);
8685 btrfs_end_transaction(trans, root);
8687 inode_dec_link_count(inode);
8690 btrfs_btree_balance_dirty(root);
8694 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8695 u64 start, u64 num_bytes, u64 min_size,
8696 loff_t actual_len, u64 *alloc_hint,
8697 struct btrfs_trans_handle *trans)
8699 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8700 struct extent_map *em;
8701 struct btrfs_root *root = BTRFS_I(inode)->root;
8702 struct btrfs_key ins;
8703 u64 cur_offset = start;
8707 bool own_trans = true;
8711 while (num_bytes > 0) {
8713 trans = btrfs_start_transaction(root, 3);
8714 if (IS_ERR(trans)) {
8715 ret = PTR_ERR(trans);
8720 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8721 cur_bytes = max(cur_bytes, min_size);
8722 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
8723 *alloc_hint, &ins, 1);
8726 btrfs_end_transaction(trans, root);
8730 ret = insert_reserved_file_extent(trans, inode,
8731 cur_offset, ins.objectid,
8732 ins.offset, ins.offset,
8733 ins.offset, 0, 0, 0,
8734 BTRFS_FILE_EXTENT_PREALLOC);
8736 btrfs_free_reserved_extent(root, ins.objectid,
8738 btrfs_abort_transaction(trans, root, ret);
8740 btrfs_end_transaction(trans, root);
8743 btrfs_drop_extent_cache(inode, cur_offset,
8744 cur_offset + ins.offset -1, 0);
8746 em = alloc_extent_map();
8748 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8749 &BTRFS_I(inode)->runtime_flags);
8753 em->start = cur_offset;
8754 em->orig_start = cur_offset;
8755 em->len = ins.offset;
8756 em->block_start = ins.objectid;
8757 em->block_len = ins.offset;
8758 em->orig_block_len = ins.offset;
8759 em->ram_bytes = ins.offset;
8760 em->bdev = root->fs_info->fs_devices->latest_bdev;
8761 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8762 em->generation = trans->transid;
8765 write_lock(&em_tree->lock);
8766 ret = add_extent_mapping(em_tree, em, 1);
8767 write_unlock(&em_tree->lock);
8770 btrfs_drop_extent_cache(inode, cur_offset,
8771 cur_offset + ins.offset - 1,
8774 free_extent_map(em);
8776 num_bytes -= ins.offset;
8777 cur_offset += ins.offset;
8778 *alloc_hint = ins.objectid + ins.offset;
8780 inode_inc_iversion(inode);
8781 inode->i_ctime = CURRENT_TIME;
8782 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8783 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8784 (actual_len > inode->i_size) &&
8785 (cur_offset > inode->i_size)) {
8786 if (cur_offset > actual_len)
8787 i_size = actual_len;
8789 i_size = cur_offset;
8790 i_size_write(inode, i_size);
8791 btrfs_ordered_update_i_size(inode, i_size, NULL);
8794 ret = btrfs_update_inode(trans, root, inode);
8797 btrfs_abort_transaction(trans, root, ret);
8799 btrfs_end_transaction(trans, root);
8804 btrfs_end_transaction(trans, root);
8809 int btrfs_prealloc_file_range(struct inode *inode, 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,
8818 int btrfs_prealloc_file_range_trans(struct inode *inode,
8819 struct btrfs_trans_handle *trans, int mode,
8820 u64 start, u64 num_bytes, u64 min_size,
8821 loff_t actual_len, u64 *alloc_hint)
8823 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8824 min_size, actual_len, alloc_hint, trans);
8827 static int btrfs_set_page_dirty(struct page *page)
8829 return __set_page_dirty_nobuffers(page);
8832 static int btrfs_permission(struct inode *inode, int mask)
8834 struct btrfs_root *root = BTRFS_I(inode)->root;
8835 umode_t mode = inode->i_mode;
8837 if (mask & MAY_WRITE &&
8838 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8839 if (btrfs_root_readonly(root))
8841 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8844 return generic_permission(inode, mask);
8847 static const struct inode_operations btrfs_dir_inode_operations = {
8848 .getattr = btrfs_getattr,
8849 .lookup = btrfs_lookup,
8850 .create = btrfs_create,
8851 .unlink = btrfs_unlink,
8853 .mkdir = btrfs_mkdir,
8854 .rmdir = btrfs_rmdir,
8855 .rename = btrfs_rename,
8856 .symlink = btrfs_symlink,
8857 .setattr = btrfs_setattr,
8858 .mknod = btrfs_mknod,
8859 .setxattr = btrfs_setxattr,
8860 .getxattr = btrfs_getxattr,
8861 .listxattr = btrfs_listxattr,
8862 .removexattr = btrfs_removexattr,
8863 .permission = btrfs_permission,
8864 .get_acl = btrfs_get_acl,
8865 .set_acl = btrfs_set_acl,
8866 .update_time = btrfs_update_time,
8868 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8869 .lookup = btrfs_lookup,
8870 .permission = btrfs_permission,
8871 .get_acl = btrfs_get_acl,
8872 .set_acl = btrfs_set_acl,
8873 .update_time = btrfs_update_time,
8876 static const struct file_operations btrfs_dir_file_operations = {
8877 .llseek = generic_file_llseek,
8878 .read = generic_read_dir,
8879 .iterate = btrfs_real_readdir,
8880 .unlocked_ioctl = btrfs_ioctl,
8881 #ifdef CONFIG_COMPAT
8882 .compat_ioctl = btrfs_ioctl,
8884 .release = btrfs_release_file,
8885 .fsync = btrfs_sync_file,
8888 static struct extent_io_ops btrfs_extent_io_ops = {
8889 .fill_delalloc = run_delalloc_range,
8890 .submit_bio_hook = btrfs_submit_bio_hook,
8891 .merge_bio_hook = btrfs_merge_bio_hook,
8892 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8893 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8894 .writepage_start_hook = btrfs_writepage_start_hook,
8895 .set_bit_hook = btrfs_set_bit_hook,
8896 .clear_bit_hook = btrfs_clear_bit_hook,
8897 .merge_extent_hook = btrfs_merge_extent_hook,
8898 .split_extent_hook = btrfs_split_extent_hook,
8902 * btrfs doesn't support the bmap operation because swapfiles
8903 * use bmap to make a mapping of extents in the file. They assume
8904 * these extents won't change over the life of the file and they
8905 * use the bmap result to do IO directly to the drive.
8907 * the btrfs bmap call would return logical addresses that aren't
8908 * suitable for IO and they also will change frequently as COW
8909 * operations happen. So, swapfile + btrfs == corruption.
8911 * For now we're avoiding this by dropping bmap.
8913 static const struct address_space_operations btrfs_aops = {
8914 .readpage = btrfs_readpage,
8915 .writepage = btrfs_writepage,
8916 .writepages = btrfs_writepages,
8917 .readpages = btrfs_readpages,
8918 .direct_IO = btrfs_direct_IO,
8919 .invalidatepage = btrfs_invalidatepage,
8920 .releasepage = btrfs_releasepage,
8921 .set_page_dirty = btrfs_set_page_dirty,
8922 .error_remove_page = generic_error_remove_page,
8925 static const struct address_space_operations btrfs_symlink_aops = {
8926 .readpage = btrfs_readpage,
8927 .writepage = btrfs_writepage,
8928 .invalidatepage = btrfs_invalidatepage,
8929 .releasepage = btrfs_releasepage,
8932 static const struct inode_operations btrfs_file_inode_operations = {
8933 .getattr = btrfs_getattr,
8934 .setattr = btrfs_setattr,
8935 .setxattr = btrfs_setxattr,
8936 .getxattr = btrfs_getxattr,
8937 .listxattr = btrfs_listxattr,
8938 .removexattr = btrfs_removexattr,
8939 .permission = btrfs_permission,
8940 .fiemap = btrfs_fiemap,
8941 .get_acl = btrfs_get_acl,
8942 .set_acl = btrfs_set_acl,
8943 .update_time = btrfs_update_time,
8945 static const struct inode_operations btrfs_special_inode_operations = {
8946 .getattr = btrfs_getattr,
8947 .setattr = btrfs_setattr,
8948 .permission = btrfs_permission,
8949 .setxattr = btrfs_setxattr,
8950 .getxattr = btrfs_getxattr,
8951 .listxattr = btrfs_listxattr,
8952 .removexattr = btrfs_removexattr,
8953 .get_acl = btrfs_get_acl,
8954 .set_acl = btrfs_set_acl,
8955 .update_time = btrfs_update_time,
8957 static const struct inode_operations btrfs_symlink_inode_operations = {
8958 .readlink = generic_readlink,
8959 .follow_link = page_follow_link_light,
8960 .put_link = page_put_link,
8961 .getattr = btrfs_getattr,
8962 .setattr = btrfs_setattr,
8963 .permission = btrfs_permission,
8964 .setxattr = btrfs_setxattr,
8965 .getxattr = btrfs_getxattr,
8966 .listxattr = btrfs_listxattr,
8967 .removexattr = btrfs_removexattr,
8968 .update_time = btrfs_update_time,
8971 const struct dentry_operations btrfs_dentry_operations = {
8972 .d_delete = btrfs_dentry_delete,
8973 .d_release = btrfs_dentry_release,