2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
41 #include <linux/mount.h>
42 #include <linux/btrfs.h>
43 #include <linux/blkdev.h>
44 #include <linux/posix_acl_xattr.h>
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"
62 struct btrfs_iget_args {
64 struct btrfs_root *root;
67 static const struct inode_operations btrfs_dir_inode_operations;
68 static const struct inode_operations btrfs_symlink_inode_operations;
69 static const struct inode_operations btrfs_dir_ro_inode_operations;
70 static const struct inode_operations btrfs_special_inode_operations;
71 static const struct inode_operations btrfs_file_inode_operations;
72 static const struct address_space_operations btrfs_aops;
73 static const struct address_space_operations btrfs_symlink_aops;
74 static const struct file_operations btrfs_dir_file_operations;
75 static struct extent_io_ops btrfs_extent_io_ops;
77 static struct kmem_cache *btrfs_inode_cachep;
78 static struct kmem_cache *btrfs_delalloc_work_cachep;
79 struct kmem_cache *btrfs_trans_handle_cachep;
80 struct kmem_cache *btrfs_transaction_cachep;
81 struct kmem_cache *btrfs_path_cachep;
82 struct kmem_cache *btrfs_free_space_cachep;
85 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
86 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
87 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
88 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
89 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
90 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
91 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
92 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
95 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
96 static int btrfs_truncate(struct inode *inode);
97 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
98 static noinline int cow_file_range(struct inode *inode,
99 struct page *locked_page,
100 u64 start, u64 end, int *page_started,
101 unsigned long *nr_written, int unlock);
102 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
103 u64 len, u64 orig_start,
104 u64 block_start, u64 block_len,
105 u64 orig_block_len, u64 ram_bytes,
108 static int btrfs_dirty_inode(struct inode *inode);
110 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
111 struct inode *inode, struct inode *dir,
112 const struct qstr *qstr)
116 err = btrfs_init_acl(trans, inode, dir);
118 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
123 * this does all the hard work for inserting an inline extent into
124 * the btree. The caller should have done a btrfs_drop_extents so that
125 * no overlapping inline items exist in the btree
127 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
128 struct btrfs_root *root, struct inode *inode,
129 u64 start, size_t size, size_t compressed_size,
131 struct page **compressed_pages)
133 struct btrfs_key key;
134 struct btrfs_path *path;
135 struct extent_buffer *leaf;
136 struct page *page = NULL;
139 struct btrfs_file_extent_item *ei;
142 size_t cur_size = size;
144 unsigned long offset;
146 if (compressed_size && compressed_pages)
147 cur_size = compressed_size;
149 path = btrfs_alloc_path();
153 path->leave_spinning = 1;
155 key.objectid = btrfs_ino(inode);
157 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
158 datasize = btrfs_file_extent_calc_inline_size(cur_size);
160 inode_add_bytes(inode, size);
161 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_free_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);
222 btrfs_free_path(path);
228 * conditionally insert an inline extent into the file. This
229 * does the checks required to make sure the data is small enough
230 * to fit as an inline extent.
232 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
233 struct btrfs_root *root,
234 struct inode *inode, u64 start, u64 end,
235 size_t compressed_size, int compress_type,
236 struct page **compressed_pages)
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;
246 data_len = compressed_size;
249 actual_end >= PAGE_CACHE_SIZE ||
250 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
252 (actual_end & (root->sectorsize - 1)) == 0) ||
254 data_len > root->fs_info->max_inline) {
258 ret = btrfs_drop_extents(trans, root, inode, start, aligned_end, 1);
262 if (isize > actual_end)
263 inline_len = min_t(u64, isize, actual_end);
264 ret = insert_inline_extent(trans, root, inode, start,
265 inline_len, compressed_size,
266 compress_type, compressed_pages);
267 if (ret && ret != -ENOSPC) {
268 btrfs_abort_transaction(trans, root, ret);
270 } else if (ret == -ENOSPC) {
274 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
275 btrfs_delalloc_release_metadata(inode, end + 1 - start);
276 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
280 struct async_extent {
285 unsigned long nr_pages;
287 struct list_head list;
292 struct btrfs_root *root;
293 struct page *locked_page;
296 struct list_head extents;
297 struct btrfs_work work;
300 static noinline int add_async_extent(struct async_cow *cow,
301 u64 start, u64 ram_size,
304 unsigned long nr_pages,
307 struct async_extent *async_extent;
309 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
310 BUG_ON(!async_extent); /* -ENOMEM */
311 async_extent->start = start;
312 async_extent->ram_size = ram_size;
313 async_extent->compressed_size = compressed_size;
314 async_extent->pages = pages;
315 async_extent->nr_pages = nr_pages;
316 async_extent->compress_type = compress_type;
317 list_add_tail(&async_extent->list, &cow->extents);
322 * we create compressed extents in two phases. The first
323 * phase compresses a range of pages that have already been
324 * locked (both pages and state bits are locked).
326 * This is done inside an ordered work queue, and the compression
327 * is spread across many cpus. The actual IO submission is step
328 * two, and the ordered work queue takes care of making sure that
329 * happens in the same order things were put onto the queue by
330 * writepages and friends.
332 * If this code finds it can't get good compression, it puts an
333 * entry onto the work queue to write the uncompressed bytes. This
334 * makes sure that both compressed inodes and uncompressed inodes
335 * are written in the same order that the flusher thread sent them
338 static noinline int compress_file_range(struct inode *inode,
339 struct page *locked_page,
341 struct async_cow *async_cow,
344 struct btrfs_root *root = BTRFS_I(inode)->root;
345 struct btrfs_trans_handle *trans;
347 u64 blocksize = root->sectorsize;
349 u64 isize = i_size_read(inode);
351 struct page **pages = NULL;
352 unsigned long nr_pages;
353 unsigned long nr_pages_ret = 0;
354 unsigned long total_compressed = 0;
355 unsigned long total_in = 0;
356 unsigned long max_compressed = 128 * 1024;
357 unsigned long max_uncompressed = 128 * 1024;
360 int compress_type = root->fs_info->compress_type;
363 /* if this is a small write inside eof, kick off a defrag */
364 if ((end - start + 1) < 16 * 1024 &&
365 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
366 btrfs_add_inode_defrag(NULL, inode);
368 actual_end = min_t(u64, isize, end + 1);
371 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
372 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
375 * we don't want to send crud past the end of i_size through
376 * compression, that's just a waste of CPU time. So, if the
377 * end of the file is before the start of our current
378 * requested range of bytes, we bail out to the uncompressed
379 * cleanup code that can deal with all of this.
381 * It isn't really the fastest way to fix things, but this is a
382 * very uncommon corner.
384 if (actual_end <= start)
385 goto cleanup_and_bail_uncompressed;
387 total_compressed = actual_end - start;
389 /* we want to make sure that amount of ram required to uncompress
390 * an extent is reasonable, so we limit the total size in ram
391 * of a compressed extent to 128k. This is a crucial number
392 * because it also controls how easily we can spread reads across
393 * cpus for decompression.
395 * We also want to make sure the amount of IO required to do
396 * a random read is reasonably small, so we limit the size of
397 * a compressed extent to 128k.
399 total_compressed = min(total_compressed, max_uncompressed);
400 num_bytes = ALIGN(end - start + 1, blocksize);
401 num_bytes = max(blocksize, num_bytes);
406 * we do compression for mount -o compress and when the
407 * inode has not been flagged as nocompress. This flag can
408 * change at any time if we discover bad compression ratios.
410 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
411 (btrfs_test_opt(root, COMPRESS) ||
412 (BTRFS_I(inode)->force_compress) ||
413 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
415 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
417 /* just bail out to the uncompressed code */
421 if (BTRFS_I(inode)->force_compress)
422 compress_type = BTRFS_I(inode)->force_compress;
425 * we need to call clear_page_dirty_for_io on each
426 * page in the range. Otherwise applications with the file
427 * mmap'd can wander in and change the page contents while
428 * we are compressing them.
430 * If the compression fails for any reason, we set the pages
431 * dirty again later on.
433 extent_range_clear_dirty_for_io(inode, start, end);
435 ret = btrfs_compress_pages(compress_type,
436 inode->i_mapping, start,
437 total_compressed, pages,
438 nr_pages, &nr_pages_ret,
444 unsigned long offset = total_compressed &
445 (PAGE_CACHE_SIZE - 1);
446 struct page *page = pages[nr_pages_ret - 1];
449 /* zero the tail end of the last page, we might be
450 * sending it down to disk
453 kaddr = kmap_atomic(page);
454 memset(kaddr + offset, 0,
455 PAGE_CACHE_SIZE - offset);
456 kunmap_atomic(kaddr);
463 trans = btrfs_join_transaction(root);
465 ret = PTR_ERR(trans);
467 goto cleanup_and_out;
469 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
471 /* lets try to make an inline extent */
472 if (ret || total_in < (actual_end - start)) {
473 /* we didn't compress the entire range, try
474 * to make an uncompressed inline extent.
476 ret = cow_file_range_inline(trans, root, inode,
477 start, end, 0, 0, NULL);
479 /* try making a compressed inline extent */
480 ret = cow_file_range_inline(trans, root, inode,
483 compress_type, pages);
487 * inline extent creation worked or returned error,
488 * we don't need to create any more async work items.
489 * Unlock and free up our temp pages.
491 extent_clear_unlock_delalloc(inode,
492 &BTRFS_I(inode)->io_tree,
494 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
495 EXTENT_CLEAR_DELALLOC |
496 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
498 btrfs_end_transaction(trans, root);
501 btrfs_end_transaction(trans, root);
506 * we aren't doing an inline extent round the compressed size
507 * up to a block size boundary so the allocator does sane
510 total_compressed = ALIGN(total_compressed, blocksize);
513 * one last check to make sure the compression is really a
514 * win, compare the page count read with the blocks on disk
516 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
517 if (total_compressed >= total_in) {
520 num_bytes = total_in;
523 if (!will_compress && pages) {
525 * the compression code ran but failed to make things smaller,
526 * free any pages it allocated and our page pointer array
528 for (i = 0; i < nr_pages_ret; i++) {
529 WARN_ON(pages[i]->mapping);
530 page_cache_release(pages[i]);
534 total_compressed = 0;
537 /* flag the file so we don't compress in the future */
538 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
539 !(BTRFS_I(inode)->force_compress)) {
540 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
546 /* the async work queues will take care of doing actual
547 * allocation on disk for these compressed pages,
548 * and will submit them to the elevator.
550 add_async_extent(async_cow, start, num_bytes,
551 total_compressed, pages, nr_pages_ret,
554 if (start + num_bytes < end) {
561 cleanup_and_bail_uncompressed:
563 * No compression, but we still need to write the pages in
564 * the file we've been given so far. redirty the locked
565 * page if it corresponds to our extent and set things up
566 * for the async work queue to run cow_file_range to do
567 * the normal delalloc dance
569 if (page_offset(locked_page) >= start &&
570 page_offset(locked_page) <= end) {
571 __set_page_dirty_nobuffers(locked_page);
572 /* unlocked later on in the async handlers */
575 extent_range_redirty_for_io(inode, start, end);
576 add_async_extent(async_cow, start, end - start + 1,
577 0, NULL, 0, BTRFS_COMPRESS_NONE);
585 for (i = 0; i < nr_pages_ret; i++) {
586 WARN_ON(pages[i]->mapping);
587 page_cache_release(pages[i]);
594 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
596 EXTENT_CLEAR_UNLOCK_PAGE |
598 EXTENT_CLEAR_DELALLOC |
599 EXTENT_SET_WRITEBACK |
600 EXTENT_END_WRITEBACK);
601 if (!trans || IS_ERR(trans))
602 btrfs_error(root->fs_info, ret, "Failed to join transaction");
604 btrfs_abort_transaction(trans, root, ret);
609 * phase two of compressed writeback. This is the ordered portion
610 * of the code, which only gets called in the order the work was
611 * queued. We walk all the async extents created by compress_file_range
612 * and send them down to the disk.
614 static noinline int submit_compressed_extents(struct inode *inode,
615 struct async_cow *async_cow)
617 struct async_extent *async_extent;
619 struct btrfs_trans_handle *trans;
620 struct btrfs_key ins;
621 struct extent_map *em;
622 struct btrfs_root *root = BTRFS_I(inode)->root;
623 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
624 struct extent_io_tree *io_tree;
627 if (list_empty(&async_cow->extents))
631 while (!list_empty(&async_cow->extents)) {
632 async_extent = list_entry(async_cow->extents.next,
633 struct async_extent, list);
634 list_del(&async_extent->list);
636 io_tree = &BTRFS_I(inode)->io_tree;
639 /* did the compression code fall back to uncompressed IO? */
640 if (!async_extent->pages) {
641 int page_started = 0;
642 unsigned long nr_written = 0;
644 lock_extent(io_tree, async_extent->start,
645 async_extent->start +
646 async_extent->ram_size - 1);
648 /* allocate blocks */
649 ret = cow_file_range(inode, async_cow->locked_page,
651 async_extent->start +
652 async_extent->ram_size - 1,
653 &page_started, &nr_written, 0);
658 * if page_started, cow_file_range inserted an
659 * inline extent and took care of all the unlocking
660 * and IO for us. Otherwise, we need to submit
661 * all those pages down to the drive.
663 if (!page_started && !ret)
664 extent_write_locked_range(io_tree,
665 inode, async_extent->start,
666 async_extent->start +
667 async_extent->ram_size - 1,
671 unlock_page(async_cow->locked_page);
677 lock_extent(io_tree, async_extent->start,
678 async_extent->start + async_extent->ram_size - 1);
680 trans = btrfs_join_transaction(root);
682 ret = PTR_ERR(trans);
684 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
685 ret = btrfs_reserve_extent(trans, root,
686 async_extent->compressed_size,
687 async_extent->compressed_size,
688 0, alloc_hint, &ins, 1);
689 if (ret && ret != -ENOSPC)
690 btrfs_abort_transaction(trans, root, ret);
691 btrfs_end_transaction(trans, root);
697 for (i = 0; i < async_extent->nr_pages; i++) {
698 WARN_ON(async_extent->pages[i]->mapping);
699 page_cache_release(async_extent->pages[i]);
701 kfree(async_extent->pages);
702 async_extent->nr_pages = 0;
703 async_extent->pages = NULL;
705 if (ret == -ENOSPC) {
706 unlock_extent(io_tree, async_extent->start,
707 async_extent->start +
708 async_extent->ram_size - 1);
715 * here we're doing allocation and writeback of the
718 btrfs_drop_extent_cache(inode, async_extent->start,
719 async_extent->start +
720 async_extent->ram_size - 1, 0);
722 em = alloc_extent_map();
725 goto out_free_reserve;
727 em->start = async_extent->start;
728 em->len = async_extent->ram_size;
729 em->orig_start = em->start;
730 em->mod_start = em->start;
731 em->mod_len = em->len;
733 em->block_start = ins.objectid;
734 em->block_len = ins.offset;
735 em->orig_block_len = ins.offset;
736 em->ram_bytes = async_extent->ram_size;
737 em->bdev = root->fs_info->fs_devices->latest_bdev;
738 em->compress_type = async_extent->compress_type;
739 set_bit(EXTENT_FLAG_PINNED, &em->flags);
740 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
744 write_lock(&em_tree->lock);
745 ret = add_extent_mapping(em_tree, em, 1);
746 write_unlock(&em_tree->lock);
747 if (ret != -EEXIST) {
751 btrfs_drop_extent_cache(inode, async_extent->start,
752 async_extent->start +
753 async_extent->ram_size - 1, 0);
757 goto out_free_reserve;
759 ret = btrfs_add_ordered_extent_compress(inode,
762 async_extent->ram_size,
764 BTRFS_ORDERED_COMPRESSED,
765 async_extent->compress_type);
767 goto out_free_reserve;
770 * clear dirty, set writeback and unlock the pages.
772 extent_clear_unlock_delalloc(inode,
773 &BTRFS_I(inode)->io_tree,
775 async_extent->start +
776 async_extent->ram_size - 1,
777 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
778 EXTENT_CLEAR_UNLOCK |
779 EXTENT_CLEAR_DELALLOC |
780 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
782 ret = btrfs_submit_compressed_write(inode,
784 async_extent->ram_size,
786 ins.offset, async_extent->pages,
787 async_extent->nr_pages);
788 alloc_hint = ins.objectid + ins.offset;
798 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
800 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
802 async_extent->start +
803 async_extent->ram_size - 1,
804 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
805 EXTENT_CLEAR_UNLOCK |
806 EXTENT_CLEAR_DELALLOC |
808 EXTENT_SET_WRITEBACK |
809 EXTENT_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 btrfs_trans_handle *trans,
861 struct btrfs_root *root,
862 struct page *locked_page,
863 u64 start, u64 end, int *page_started,
864 unsigned long *nr_written,
869 unsigned long ram_size;
872 u64 blocksize = root->sectorsize;
873 struct btrfs_key ins;
874 struct extent_map *em;
875 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
878 BUG_ON(btrfs_is_free_space_inode(inode));
880 num_bytes = ALIGN(end - start + 1, blocksize);
881 num_bytes = max(blocksize, num_bytes);
882 disk_num_bytes = num_bytes;
884 /* if this is a small write inside eof, kick off defrag */
885 if (num_bytes < 64 * 1024 &&
886 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
887 btrfs_add_inode_defrag(trans, inode);
890 /* lets try to make an inline extent */
891 ret = cow_file_range_inline(trans, root, inode,
892 start, end, 0, 0, NULL);
894 extent_clear_unlock_delalloc(inode,
895 &BTRFS_I(inode)->io_tree,
897 EXTENT_CLEAR_UNLOCK_PAGE |
898 EXTENT_CLEAR_UNLOCK |
899 EXTENT_CLEAR_DELALLOC |
901 EXTENT_SET_WRITEBACK |
902 EXTENT_END_WRITEBACK);
904 *nr_written = *nr_written +
905 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
908 } else if (ret < 0) {
909 btrfs_abort_transaction(trans, root, ret);
914 BUG_ON(disk_num_bytes >
915 btrfs_super_total_bytes(root->fs_info->super_copy));
917 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
918 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
920 while (disk_num_bytes > 0) {
923 cur_alloc_size = disk_num_bytes;
924 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
925 root->sectorsize, 0, alloc_hint,
928 btrfs_abort_transaction(trans, root, ret);
932 em = alloc_extent_map();
938 em->orig_start = em->start;
939 ram_size = ins.offset;
940 em->len = ins.offset;
941 em->mod_start = em->start;
942 em->mod_len = em->len;
944 em->block_start = ins.objectid;
945 em->block_len = ins.offset;
946 em->orig_block_len = ins.offset;
947 em->ram_bytes = ram_size;
948 em->bdev = root->fs_info->fs_devices->latest_bdev;
949 set_bit(EXTENT_FLAG_PINNED, &em->flags);
953 write_lock(&em_tree->lock);
954 ret = add_extent_mapping(em_tree, em, 1);
955 write_unlock(&em_tree->lock);
956 if (ret != -EEXIST) {
960 btrfs_drop_extent_cache(inode, start,
961 start + ram_size - 1, 0);
966 cur_alloc_size = ins.offset;
967 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
968 ram_size, cur_alloc_size, 0);
972 if (root->root_key.objectid ==
973 BTRFS_DATA_RELOC_TREE_OBJECTID) {
974 ret = btrfs_reloc_clone_csums(inode, start,
977 btrfs_abort_transaction(trans, root, ret);
982 if (disk_num_bytes < cur_alloc_size)
985 /* we're not doing compressed IO, don't unlock the first
986 * page (which the caller expects to stay locked), don't
987 * clear any dirty bits and don't set any writeback bits
989 * Do set the Private2 bit so we know this page was properly
990 * setup for writepage
992 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
993 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
996 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
997 start, start + ram_size - 1,
999 disk_num_bytes -= cur_alloc_size;
1000 num_bytes -= cur_alloc_size;
1001 alloc_hint = ins.objectid + ins.offset;
1002 start += cur_alloc_size;
1008 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
1010 extent_clear_unlock_delalloc(inode,
1011 &BTRFS_I(inode)->io_tree,
1012 start, end, locked_page,
1013 EXTENT_CLEAR_UNLOCK_PAGE |
1014 EXTENT_CLEAR_UNLOCK |
1015 EXTENT_CLEAR_DELALLOC |
1016 EXTENT_CLEAR_DIRTY |
1017 EXTENT_SET_WRITEBACK |
1018 EXTENT_END_WRITEBACK);
1023 static noinline int cow_file_range(struct inode *inode,
1024 struct page *locked_page,
1025 u64 start, u64 end, int *page_started,
1026 unsigned long *nr_written,
1029 struct btrfs_trans_handle *trans;
1030 struct btrfs_root *root = BTRFS_I(inode)->root;
1033 trans = btrfs_join_transaction(root);
1034 if (IS_ERR(trans)) {
1035 extent_clear_unlock_delalloc(inode,
1036 &BTRFS_I(inode)->io_tree,
1037 start, end, locked_page,
1038 EXTENT_CLEAR_UNLOCK_PAGE |
1039 EXTENT_CLEAR_UNLOCK |
1040 EXTENT_CLEAR_DELALLOC |
1041 EXTENT_CLEAR_DIRTY |
1042 EXTENT_SET_WRITEBACK |
1043 EXTENT_END_WRITEBACK);
1044 return PTR_ERR(trans);
1046 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1048 ret = __cow_file_range(trans, inode, root, locked_page, start, end,
1049 page_started, nr_written, unlock);
1051 btrfs_end_transaction(trans, root);
1057 * work queue call back to started compression on a file and pages
1059 static noinline void async_cow_start(struct btrfs_work *work)
1061 struct async_cow *async_cow;
1063 async_cow = container_of(work, struct async_cow, work);
1065 compress_file_range(async_cow->inode, async_cow->locked_page,
1066 async_cow->start, async_cow->end, async_cow,
1068 if (num_added == 0) {
1069 btrfs_add_delayed_iput(async_cow->inode);
1070 async_cow->inode = NULL;
1075 * work queue call back to submit previously compressed pages
1077 static noinline void async_cow_submit(struct btrfs_work *work)
1079 struct async_cow *async_cow;
1080 struct btrfs_root *root;
1081 unsigned long nr_pages;
1083 async_cow = container_of(work, struct async_cow, work);
1085 root = async_cow->root;
1086 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1089 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1091 waitqueue_active(&root->fs_info->async_submit_wait))
1092 wake_up(&root->fs_info->async_submit_wait);
1094 if (async_cow->inode)
1095 submit_compressed_extents(async_cow->inode, async_cow);
1098 static noinline void async_cow_free(struct btrfs_work *work)
1100 struct async_cow *async_cow;
1101 async_cow = container_of(work, struct async_cow, work);
1102 if (async_cow->inode)
1103 btrfs_add_delayed_iput(async_cow->inode);
1107 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1108 u64 start, u64 end, int *page_started,
1109 unsigned long *nr_written)
1111 struct async_cow *async_cow;
1112 struct btrfs_root *root = BTRFS_I(inode)->root;
1113 unsigned long nr_pages;
1115 int limit = 10 * 1024 * 1024;
1117 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1118 1, 0, NULL, GFP_NOFS);
1119 while (start < end) {
1120 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1121 BUG_ON(!async_cow); /* -ENOMEM */
1122 async_cow->inode = igrab(inode);
1123 async_cow->root = root;
1124 async_cow->locked_page = locked_page;
1125 async_cow->start = start;
1127 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1130 cur_end = min(end, start + 512 * 1024 - 1);
1132 async_cow->end = cur_end;
1133 INIT_LIST_HEAD(&async_cow->extents);
1135 async_cow->work.func = async_cow_start;
1136 async_cow->work.ordered_func = async_cow_submit;
1137 async_cow->work.ordered_free = async_cow_free;
1138 async_cow->work.flags = 0;
1140 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1142 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1144 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1147 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1148 wait_event(root->fs_info->async_submit_wait,
1149 (atomic_read(&root->fs_info->async_delalloc_pages) <
1153 while (atomic_read(&root->fs_info->async_submit_draining) &&
1154 atomic_read(&root->fs_info->async_delalloc_pages)) {
1155 wait_event(root->fs_info->async_submit_wait,
1156 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1160 *nr_written += nr_pages;
1161 start = cur_end + 1;
1167 static noinline int csum_exist_in_range(struct btrfs_root *root,
1168 u64 bytenr, u64 num_bytes)
1171 struct btrfs_ordered_sum *sums;
1174 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1175 bytenr + num_bytes - 1, &list, 0);
1176 if (ret == 0 && list_empty(&list))
1179 while (!list_empty(&list)) {
1180 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1181 list_del(&sums->list);
1188 * when nowcow writeback call back. This checks for snapshots or COW copies
1189 * of the extents that exist in the file, and COWs the file as required.
1191 * If no cow copies or snapshots exist, we write directly to the existing
1194 static noinline int run_delalloc_nocow(struct inode *inode,
1195 struct page *locked_page,
1196 u64 start, u64 end, int *page_started, int force,
1197 unsigned long *nr_written)
1199 struct btrfs_root *root = BTRFS_I(inode)->root;
1200 struct btrfs_trans_handle *trans;
1201 struct extent_buffer *leaf;
1202 struct btrfs_path *path;
1203 struct btrfs_file_extent_item *fi;
1204 struct btrfs_key found_key;
1219 u64 ino = btrfs_ino(inode);
1221 path = btrfs_alloc_path();
1223 extent_clear_unlock_delalloc(inode,
1224 &BTRFS_I(inode)->io_tree,
1225 start, end, locked_page,
1226 EXTENT_CLEAR_UNLOCK_PAGE |
1227 EXTENT_CLEAR_UNLOCK |
1228 EXTENT_CLEAR_DELALLOC |
1229 EXTENT_CLEAR_DIRTY |
1230 EXTENT_SET_WRITEBACK |
1231 EXTENT_END_WRITEBACK);
1235 nolock = btrfs_is_free_space_inode(inode);
1238 trans = btrfs_join_transaction_nolock(root);
1240 trans = btrfs_join_transaction(root);
1242 if (IS_ERR(trans)) {
1243 extent_clear_unlock_delalloc(inode,
1244 &BTRFS_I(inode)->io_tree,
1245 start, end, locked_page,
1246 EXTENT_CLEAR_UNLOCK_PAGE |
1247 EXTENT_CLEAR_UNLOCK |
1248 EXTENT_CLEAR_DELALLOC |
1249 EXTENT_CLEAR_DIRTY |
1250 EXTENT_SET_WRITEBACK |
1251 EXTENT_END_WRITEBACK);
1252 btrfs_free_path(path);
1253 return PTR_ERR(trans);
1256 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1258 cow_start = (u64)-1;
1261 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1264 btrfs_abort_transaction(trans, root, ret);
1267 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1268 leaf = path->nodes[0];
1269 btrfs_item_key_to_cpu(leaf, &found_key,
1270 path->slots[0] - 1);
1271 if (found_key.objectid == ino &&
1272 found_key.type == BTRFS_EXTENT_DATA_KEY)
1277 leaf = path->nodes[0];
1278 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1279 ret = btrfs_next_leaf(root, path);
1281 btrfs_abort_transaction(trans, root, ret);
1286 leaf = path->nodes[0];
1292 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1294 if (found_key.objectid > ino ||
1295 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1296 found_key.offset > end)
1299 if (found_key.offset > cur_offset) {
1300 extent_end = found_key.offset;
1305 fi = btrfs_item_ptr(leaf, path->slots[0],
1306 struct btrfs_file_extent_item);
1307 extent_type = btrfs_file_extent_type(leaf, fi);
1309 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1310 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1311 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1312 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1313 extent_offset = btrfs_file_extent_offset(leaf, fi);
1314 extent_end = found_key.offset +
1315 btrfs_file_extent_num_bytes(leaf, fi);
1317 btrfs_file_extent_disk_num_bytes(leaf, fi);
1318 if (extent_end <= start) {
1322 if (disk_bytenr == 0)
1324 if (btrfs_file_extent_compression(leaf, fi) ||
1325 btrfs_file_extent_encryption(leaf, fi) ||
1326 btrfs_file_extent_other_encoding(leaf, fi))
1328 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1330 if (btrfs_extent_readonly(root, disk_bytenr))
1332 if (btrfs_cross_ref_exist(trans, root, ino,
1334 extent_offset, disk_bytenr))
1336 disk_bytenr += extent_offset;
1337 disk_bytenr += cur_offset - found_key.offset;
1338 num_bytes = min(end + 1, extent_end) - cur_offset;
1340 * force cow if csum exists in the range.
1341 * this ensure that csum for a given extent are
1342 * either valid or do not exist.
1344 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1347 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1348 extent_end = found_key.offset +
1349 btrfs_file_extent_inline_len(leaf, fi);
1350 extent_end = ALIGN(extent_end, root->sectorsize);
1355 if (extent_end <= start) {
1360 if (cow_start == (u64)-1)
1361 cow_start = cur_offset;
1362 cur_offset = extent_end;
1363 if (cur_offset > end)
1369 btrfs_release_path(path);
1370 if (cow_start != (u64)-1) {
1371 ret = __cow_file_range(trans, inode, root, locked_page,
1372 cow_start, found_key.offset - 1,
1373 page_started, nr_written, 1);
1375 btrfs_abort_transaction(trans, root, ret);
1378 cow_start = (u64)-1;
1381 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1382 struct extent_map *em;
1383 struct extent_map_tree *em_tree;
1384 em_tree = &BTRFS_I(inode)->extent_tree;
1385 em = alloc_extent_map();
1386 BUG_ON(!em); /* -ENOMEM */
1387 em->start = cur_offset;
1388 em->orig_start = found_key.offset - extent_offset;
1389 em->len = num_bytes;
1390 em->block_len = num_bytes;
1391 em->block_start = disk_bytenr;
1392 em->orig_block_len = disk_num_bytes;
1393 em->ram_bytes = ram_bytes;
1394 em->bdev = root->fs_info->fs_devices->latest_bdev;
1395 em->mod_start = em->start;
1396 em->mod_len = em->len;
1397 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1398 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1399 em->generation = -1;
1401 write_lock(&em_tree->lock);
1402 ret = add_extent_mapping(em_tree, em, 1);
1403 write_unlock(&em_tree->lock);
1404 if (ret != -EEXIST) {
1405 free_extent_map(em);
1408 btrfs_drop_extent_cache(inode, em->start,
1409 em->start + em->len - 1, 0);
1411 type = BTRFS_ORDERED_PREALLOC;
1413 type = BTRFS_ORDERED_NOCOW;
1416 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1417 num_bytes, num_bytes, type);
1418 BUG_ON(ret); /* -ENOMEM */
1420 if (root->root_key.objectid ==
1421 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1422 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1425 btrfs_abort_transaction(trans, root, ret);
1430 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1431 cur_offset, cur_offset + num_bytes - 1,
1432 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1433 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1434 EXTENT_SET_PRIVATE2);
1435 cur_offset = extent_end;
1436 if (cur_offset > end)
1439 btrfs_release_path(path);
1441 if (cur_offset <= end && cow_start == (u64)-1) {
1442 cow_start = cur_offset;
1446 if (cow_start != (u64)-1) {
1447 ret = __cow_file_range(trans, inode, root, locked_page,
1449 page_started, nr_written, 1);
1451 btrfs_abort_transaction(trans, root, ret);
1457 err = btrfs_end_transaction(trans, root);
1461 if (ret && cur_offset < end)
1462 extent_clear_unlock_delalloc(inode,
1463 &BTRFS_I(inode)->io_tree,
1464 cur_offset, end, locked_page,
1465 EXTENT_CLEAR_UNLOCK_PAGE |
1466 EXTENT_CLEAR_UNLOCK |
1467 EXTENT_CLEAR_DELALLOC |
1468 EXTENT_CLEAR_DIRTY |
1469 EXTENT_SET_WRITEBACK |
1470 EXTENT_END_WRITEBACK);
1472 btrfs_free_path(path);
1477 * extent_io.c call back to do delayed allocation processing
1479 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1480 u64 start, u64 end, int *page_started,
1481 unsigned long *nr_written)
1484 struct btrfs_root *root = BTRFS_I(inode)->root;
1486 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1487 ret = run_delalloc_nocow(inode, locked_page, start, end,
1488 page_started, 1, nr_written);
1489 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1490 ret = run_delalloc_nocow(inode, locked_page, start, end,
1491 page_started, 0, nr_written);
1492 } else if (!btrfs_test_opt(root, COMPRESS) &&
1493 !(BTRFS_I(inode)->force_compress) &&
1494 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1495 ret = cow_file_range(inode, locked_page, start, end,
1496 page_started, nr_written, 1);
1498 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1499 &BTRFS_I(inode)->runtime_flags);
1500 ret = cow_file_range_async(inode, locked_page, start, end,
1501 page_started, nr_written);
1506 static void btrfs_split_extent_hook(struct inode *inode,
1507 struct extent_state *orig, u64 split)
1509 /* not delalloc, ignore it */
1510 if (!(orig->state & EXTENT_DELALLOC))
1513 spin_lock(&BTRFS_I(inode)->lock);
1514 BTRFS_I(inode)->outstanding_extents++;
1515 spin_unlock(&BTRFS_I(inode)->lock);
1519 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1520 * extents so we can keep track of new extents that are just merged onto old
1521 * extents, such as when we are doing sequential writes, so we can properly
1522 * account for the metadata space we'll need.
1524 static void btrfs_merge_extent_hook(struct inode *inode,
1525 struct extent_state *new,
1526 struct extent_state *other)
1528 /* not delalloc, ignore it */
1529 if (!(other->state & EXTENT_DELALLOC))
1532 spin_lock(&BTRFS_I(inode)->lock);
1533 BTRFS_I(inode)->outstanding_extents--;
1534 spin_unlock(&BTRFS_I(inode)->lock);
1537 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1538 struct inode *inode)
1540 spin_lock(&root->delalloc_lock);
1541 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1542 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1543 &root->delalloc_inodes);
1544 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1545 &BTRFS_I(inode)->runtime_flags);
1546 root->nr_delalloc_inodes++;
1547 if (root->nr_delalloc_inodes == 1) {
1548 spin_lock(&root->fs_info->delalloc_root_lock);
1549 BUG_ON(!list_empty(&root->delalloc_root));
1550 list_add_tail(&root->delalloc_root,
1551 &root->fs_info->delalloc_roots);
1552 spin_unlock(&root->fs_info->delalloc_root_lock);
1555 spin_unlock(&root->delalloc_lock);
1558 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1559 struct inode *inode)
1561 spin_lock(&root->delalloc_lock);
1562 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1563 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1564 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1565 &BTRFS_I(inode)->runtime_flags);
1566 root->nr_delalloc_inodes--;
1567 if (!root->nr_delalloc_inodes) {
1568 spin_lock(&root->fs_info->delalloc_root_lock);
1569 BUG_ON(list_empty(&root->delalloc_root));
1570 list_del_init(&root->delalloc_root);
1571 spin_unlock(&root->fs_info->delalloc_root_lock);
1574 spin_unlock(&root->delalloc_lock);
1578 * extent_io.c set_bit_hook, used to track delayed allocation
1579 * bytes in this file, and to maintain the list of inodes that
1580 * have pending delalloc work to be done.
1582 static void btrfs_set_bit_hook(struct inode *inode,
1583 struct extent_state *state, unsigned long *bits)
1587 * set_bit and clear bit hooks normally require _irqsave/restore
1588 * but in this case, we are only testing for the DELALLOC
1589 * bit, which is only set or cleared with irqs on
1591 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1592 struct btrfs_root *root = BTRFS_I(inode)->root;
1593 u64 len = state->end + 1 - state->start;
1594 bool do_list = !btrfs_is_free_space_inode(inode);
1596 if (*bits & EXTENT_FIRST_DELALLOC) {
1597 *bits &= ~EXTENT_FIRST_DELALLOC;
1599 spin_lock(&BTRFS_I(inode)->lock);
1600 BTRFS_I(inode)->outstanding_extents++;
1601 spin_unlock(&BTRFS_I(inode)->lock);
1604 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1605 root->fs_info->delalloc_batch);
1606 spin_lock(&BTRFS_I(inode)->lock);
1607 BTRFS_I(inode)->delalloc_bytes += len;
1608 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1609 &BTRFS_I(inode)->runtime_flags))
1610 btrfs_add_delalloc_inodes(root, inode);
1611 spin_unlock(&BTRFS_I(inode)->lock);
1616 * extent_io.c clear_bit_hook, see set_bit_hook for why
1618 static void btrfs_clear_bit_hook(struct inode *inode,
1619 struct extent_state *state,
1620 unsigned long *bits)
1623 * set_bit and clear bit hooks normally require _irqsave/restore
1624 * but in this case, we are only testing for the DELALLOC
1625 * bit, which is only set or cleared with irqs on
1627 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1628 struct btrfs_root *root = BTRFS_I(inode)->root;
1629 u64 len = state->end + 1 - state->start;
1630 bool do_list = !btrfs_is_free_space_inode(inode);
1632 if (*bits & EXTENT_FIRST_DELALLOC) {
1633 *bits &= ~EXTENT_FIRST_DELALLOC;
1634 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1635 spin_lock(&BTRFS_I(inode)->lock);
1636 BTRFS_I(inode)->outstanding_extents--;
1637 spin_unlock(&BTRFS_I(inode)->lock);
1640 if (*bits & EXTENT_DO_ACCOUNTING)
1641 btrfs_delalloc_release_metadata(inode, len);
1643 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1644 && do_list && !(state->state & EXTENT_NORESERVE))
1645 btrfs_free_reserved_data_space(inode, len);
1647 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1648 root->fs_info->delalloc_batch);
1649 spin_lock(&BTRFS_I(inode)->lock);
1650 BTRFS_I(inode)->delalloc_bytes -= len;
1651 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1652 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1653 &BTRFS_I(inode)->runtime_flags))
1654 btrfs_del_delalloc_inode(root, inode);
1655 spin_unlock(&BTRFS_I(inode)->lock);
1660 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1661 * we don't create bios that span stripes or chunks
1663 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1664 size_t size, struct bio *bio,
1665 unsigned long bio_flags)
1667 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1668 u64 logical = (u64)bio->bi_sector << 9;
1673 if (bio_flags & EXTENT_BIO_COMPRESSED)
1676 length = bio->bi_size;
1677 map_length = length;
1678 ret = btrfs_map_block(root->fs_info, rw, logical,
1679 &map_length, NULL, 0);
1680 /* Will always return 0 with map_multi == NULL */
1682 if (map_length < length + size)
1688 * in order to insert checksums into the metadata in large chunks,
1689 * we wait until bio submission time. All the pages in the bio are
1690 * checksummed and sums are attached onto the ordered extent record.
1692 * At IO completion time the cums attached on the ordered extent record
1693 * are inserted into the btree
1695 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1696 struct bio *bio, int mirror_num,
1697 unsigned long bio_flags,
1700 struct btrfs_root *root = BTRFS_I(inode)->root;
1703 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1704 BUG_ON(ret); /* -ENOMEM */
1709 * in order to insert checksums into the metadata in large chunks,
1710 * we wait until bio submission time. All the pages in the bio are
1711 * checksummed and sums are attached onto the ordered extent record.
1713 * At IO completion time the cums attached on the ordered extent record
1714 * are inserted into the btree
1716 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1717 int mirror_num, unsigned long bio_flags,
1720 struct btrfs_root *root = BTRFS_I(inode)->root;
1723 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1725 bio_endio(bio, ret);
1730 * extent_io.c submission hook. This does the right thing for csum calculation
1731 * on write, or reading the csums from the tree before a read
1733 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1734 int mirror_num, unsigned long bio_flags,
1737 struct btrfs_root *root = BTRFS_I(inode)->root;
1741 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1743 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1745 if (btrfs_is_free_space_inode(inode))
1748 if (!(rw & REQ_WRITE)) {
1749 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1753 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1754 ret = btrfs_submit_compressed_read(inode, bio,
1758 } else if (!skip_sum) {
1759 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1764 } else if (async && !skip_sum) {
1765 /* csum items have already been cloned */
1766 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1768 /* we're doing a write, do the async checksumming */
1769 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1770 inode, rw, bio, mirror_num,
1771 bio_flags, bio_offset,
1772 __btrfs_submit_bio_start,
1773 __btrfs_submit_bio_done);
1775 } else if (!skip_sum) {
1776 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1782 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1786 bio_endio(bio, ret);
1791 * given a list of ordered sums record them in the inode. This happens
1792 * at IO completion time based on sums calculated at bio submission time.
1794 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1795 struct inode *inode, u64 file_offset,
1796 struct list_head *list)
1798 struct btrfs_ordered_sum *sum;
1800 list_for_each_entry(sum, list, list) {
1801 trans->adding_csums = 1;
1802 btrfs_csum_file_blocks(trans,
1803 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1804 trans->adding_csums = 0;
1809 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1810 struct extent_state **cached_state)
1812 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1813 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1814 cached_state, GFP_NOFS);
1817 /* see btrfs_writepage_start_hook for details on why this is required */
1818 struct btrfs_writepage_fixup {
1820 struct btrfs_work work;
1823 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1825 struct btrfs_writepage_fixup *fixup;
1826 struct btrfs_ordered_extent *ordered;
1827 struct extent_state *cached_state = NULL;
1829 struct inode *inode;
1834 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1838 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1839 ClearPageChecked(page);
1843 inode = page->mapping->host;
1844 page_start = page_offset(page);
1845 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1847 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1850 /* already ordered? We're done */
1851 if (PagePrivate2(page))
1854 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1856 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1857 page_end, &cached_state, GFP_NOFS);
1859 btrfs_start_ordered_extent(inode, ordered, 1);
1860 btrfs_put_ordered_extent(ordered);
1864 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1866 mapping_set_error(page->mapping, ret);
1867 end_extent_writepage(page, ret, page_start, page_end);
1868 ClearPageChecked(page);
1872 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1873 ClearPageChecked(page);
1874 set_page_dirty(page);
1876 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1877 &cached_state, GFP_NOFS);
1880 page_cache_release(page);
1885 * There are a few paths in the higher layers of the kernel that directly
1886 * set the page dirty bit without asking the filesystem if it is a
1887 * good idea. This causes problems because we want to make sure COW
1888 * properly happens and the data=ordered rules are followed.
1890 * In our case any range that doesn't have the ORDERED bit set
1891 * hasn't been properly setup for IO. We kick off an async process
1892 * to fix it up. The async helper will wait for ordered extents, set
1893 * the delalloc bit and make it safe to write the page.
1895 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1897 struct inode *inode = page->mapping->host;
1898 struct btrfs_writepage_fixup *fixup;
1899 struct btrfs_root *root = BTRFS_I(inode)->root;
1901 /* this page is properly in the ordered list */
1902 if (TestClearPagePrivate2(page))
1905 if (PageChecked(page))
1908 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1912 SetPageChecked(page);
1913 page_cache_get(page);
1914 fixup->work.func = btrfs_writepage_fixup_worker;
1916 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1920 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1921 struct inode *inode, u64 file_pos,
1922 u64 disk_bytenr, u64 disk_num_bytes,
1923 u64 num_bytes, u64 ram_bytes,
1924 u8 compression, u8 encryption,
1925 u16 other_encoding, int extent_type)
1927 struct btrfs_root *root = BTRFS_I(inode)->root;
1928 struct btrfs_file_extent_item *fi;
1929 struct btrfs_path *path;
1930 struct extent_buffer *leaf;
1931 struct btrfs_key ins;
1934 path = btrfs_alloc_path();
1938 path->leave_spinning = 1;
1941 * we may be replacing one extent in the tree with another.
1942 * The new extent is pinned in the extent map, and we don't want
1943 * to drop it from the cache until it is completely in the btree.
1945 * So, tell btrfs_drop_extents to leave this extent in the cache.
1946 * the caller is expected to unpin it and allow it to be merged
1949 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1950 file_pos + num_bytes, 0);
1954 ins.objectid = btrfs_ino(inode);
1955 ins.offset = file_pos;
1956 ins.type = BTRFS_EXTENT_DATA_KEY;
1957 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1960 leaf = path->nodes[0];
1961 fi = btrfs_item_ptr(leaf, path->slots[0],
1962 struct btrfs_file_extent_item);
1963 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1964 btrfs_set_file_extent_type(leaf, fi, extent_type);
1965 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1966 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1967 btrfs_set_file_extent_offset(leaf, fi, 0);
1968 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1969 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1970 btrfs_set_file_extent_compression(leaf, fi, compression);
1971 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1972 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1974 btrfs_mark_buffer_dirty(leaf);
1975 btrfs_release_path(path);
1977 inode_add_bytes(inode, num_bytes);
1979 ins.objectid = disk_bytenr;
1980 ins.offset = disk_num_bytes;
1981 ins.type = BTRFS_EXTENT_ITEM_KEY;
1982 ret = btrfs_alloc_reserved_file_extent(trans, root,
1983 root->root_key.objectid,
1984 btrfs_ino(inode), file_pos, &ins);
1986 btrfs_free_path(path);
1991 /* snapshot-aware defrag */
1992 struct sa_defrag_extent_backref {
1993 struct rb_node node;
1994 struct old_sa_defrag_extent *old;
2003 struct old_sa_defrag_extent {
2004 struct list_head list;
2005 struct new_sa_defrag_extent *new;
2014 struct new_sa_defrag_extent {
2015 struct rb_root root;
2016 struct list_head head;
2017 struct btrfs_path *path;
2018 struct inode *inode;
2026 static int backref_comp(struct sa_defrag_extent_backref *b1,
2027 struct sa_defrag_extent_backref *b2)
2029 if (b1->root_id < b2->root_id)
2031 else if (b1->root_id > b2->root_id)
2034 if (b1->inum < b2->inum)
2036 else if (b1->inum > b2->inum)
2039 if (b1->file_pos < b2->file_pos)
2041 else if (b1->file_pos > b2->file_pos)
2045 * [------------------------------] ===> (a range of space)
2046 * |<--->| |<---->| =============> (fs/file tree A)
2047 * |<---------------------------->| ===> (fs/file tree B)
2049 * A range of space can refer to two file extents in one tree while
2050 * refer to only one file extent in another tree.
2052 * So we may process a disk offset more than one time(two extents in A)
2053 * and locate at the same extent(one extent in B), then insert two same
2054 * backrefs(both refer to the extent in B).
2059 static void backref_insert(struct rb_root *root,
2060 struct sa_defrag_extent_backref *backref)
2062 struct rb_node **p = &root->rb_node;
2063 struct rb_node *parent = NULL;
2064 struct sa_defrag_extent_backref *entry;
2069 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2071 ret = backref_comp(backref, entry);
2075 p = &(*p)->rb_right;
2078 rb_link_node(&backref->node, parent, p);
2079 rb_insert_color(&backref->node, root);
2083 * Note the backref might has changed, and in this case we just return 0.
2085 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2088 struct btrfs_file_extent_item *extent;
2089 struct btrfs_fs_info *fs_info;
2090 struct old_sa_defrag_extent *old = ctx;
2091 struct new_sa_defrag_extent *new = old->new;
2092 struct btrfs_path *path = new->path;
2093 struct btrfs_key key;
2094 struct btrfs_root *root;
2095 struct sa_defrag_extent_backref *backref;
2096 struct extent_buffer *leaf;
2097 struct inode *inode = new->inode;
2103 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2104 inum == btrfs_ino(inode))
2107 key.objectid = root_id;
2108 key.type = BTRFS_ROOT_ITEM_KEY;
2109 key.offset = (u64)-1;
2111 fs_info = BTRFS_I(inode)->root->fs_info;
2112 root = btrfs_read_fs_root_no_name(fs_info, &key);
2114 if (PTR_ERR(root) == -ENOENT)
2117 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2118 inum, offset, root_id);
2119 return PTR_ERR(root);
2122 key.objectid = inum;
2123 key.type = BTRFS_EXTENT_DATA_KEY;
2124 if (offset > (u64)-1 << 32)
2127 key.offset = offset;
2129 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2138 leaf = path->nodes[0];
2139 slot = path->slots[0];
2141 if (slot >= btrfs_header_nritems(leaf)) {
2142 ret = btrfs_next_leaf(root, path);
2145 } else if (ret > 0) {
2154 btrfs_item_key_to_cpu(leaf, &key, slot);
2156 if (key.objectid > inum)
2159 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2162 extent = btrfs_item_ptr(leaf, slot,
2163 struct btrfs_file_extent_item);
2165 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2168 extent_offset = btrfs_file_extent_offset(leaf, extent);
2169 if (key.offset - extent_offset != offset)
2172 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2173 if (extent_offset >= old->extent_offset + old->offset +
2174 old->len || extent_offset + num_bytes <=
2175 old->extent_offset + old->offset)
2181 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2187 backref->root_id = root_id;
2188 backref->inum = inum;
2189 backref->file_pos = offset + extent_offset;
2190 backref->num_bytes = num_bytes;
2191 backref->extent_offset = extent_offset;
2192 backref->generation = btrfs_file_extent_generation(leaf, extent);
2194 backref_insert(&new->root, backref);
2197 btrfs_release_path(path);
2202 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2203 struct new_sa_defrag_extent *new)
2205 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2206 struct old_sa_defrag_extent *old, *tmp;
2211 list_for_each_entry_safe(old, tmp, &new->head, list) {
2212 ret = iterate_inodes_from_logical(old->bytenr, fs_info,
2213 path, record_one_backref,
2215 BUG_ON(ret < 0 && ret != -ENOENT);
2217 /* no backref to be processed for this extent */
2219 list_del(&old->list);
2224 if (list_empty(&new->head))
2230 static int relink_is_mergable(struct extent_buffer *leaf,
2231 struct btrfs_file_extent_item *fi,
2234 if (btrfs_file_extent_disk_bytenr(leaf, fi) != disk_bytenr)
2237 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2240 if (btrfs_file_extent_compression(leaf, fi) ||
2241 btrfs_file_extent_encryption(leaf, fi) ||
2242 btrfs_file_extent_other_encoding(leaf, fi))
2249 * Note the backref might has changed, and in this case we just return 0.
2251 static noinline int relink_extent_backref(struct btrfs_path *path,
2252 struct sa_defrag_extent_backref *prev,
2253 struct sa_defrag_extent_backref *backref)
2255 struct btrfs_file_extent_item *extent;
2256 struct btrfs_file_extent_item *item;
2257 struct btrfs_ordered_extent *ordered;
2258 struct btrfs_trans_handle *trans;
2259 struct btrfs_fs_info *fs_info;
2260 struct btrfs_root *root;
2261 struct btrfs_key key;
2262 struct extent_buffer *leaf;
2263 struct old_sa_defrag_extent *old = backref->old;
2264 struct new_sa_defrag_extent *new = old->new;
2265 struct inode *src_inode = new->inode;
2266 struct inode *inode;
2267 struct extent_state *cached = NULL;
2276 if (prev && prev->root_id == backref->root_id &&
2277 prev->inum == backref->inum &&
2278 prev->file_pos + prev->num_bytes == backref->file_pos)
2281 /* step 1: get root */
2282 key.objectid = backref->root_id;
2283 key.type = BTRFS_ROOT_ITEM_KEY;
2284 key.offset = (u64)-1;
2286 fs_info = BTRFS_I(src_inode)->root->fs_info;
2287 index = srcu_read_lock(&fs_info->subvol_srcu);
2289 root = btrfs_read_fs_root_no_name(fs_info, &key);
2291 srcu_read_unlock(&fs_info->subvol_srcu, index);
2292 if (PTR_ERR(root) == -ENOENT)
2294 return PTR_ERR(root);
2297 /* step 2: get inode */
2298 key.objectid = backref->inum;
2299 key.type = BTRFS_INODE_ITEM_KEY;
2302 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2303 if (IS_ERR(inode)) {
2304 srcu_read_unlock(&fs_info->subvol_srcu, index);
2308 srcu_read_unlock(&fs_info->subvol_srcu, index);
2310 /* step 3: relink backref */
2311 lock_start = backref->file_pos;
2312 lock_end = backref->file_pos + backref->num_bytes - 1;
2313 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2316 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2318 btrfs_put_ordered_extent(ordered);
2322 trans = btrfs_join_transaction(root);
2323 if (IS_ERR(trans)) {
2324 ret = PTR_ERR(trans);
2328 key.objectid = backref->inum;
2329 key.type = BTRFS_EXTENT_DATA_KEY;
2330 key.offset = backref->file_pos;
2332 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2335 } else if (ret > 0) {
2340 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2341 struct btrfs_file_extent_item);
2343 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2344 backref->generation)
2347 btrfs_release_path(path);
2349 start = backref->file_pos;
2350 if (backref->extent_offset < old->extent_offset + old->offset)
2351 start += old->extent_offset + old->offset -
2352 backref->extent_offset;
2354 len = min(backref->extent_offset + backref->num_bytes,
2355 old->extent_offset + old->offset + old->len);
2356 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2358 ret = btrfs_drop_extents(trans, root, inode, start,
2363 key.objectid = btrfs_ino(inode);
2364 key.type = BTRFS_EXTENT_DATA_KEY;
2367 path->leave_spinning = 1;
2369 struct btrfs_file_extent_item *fi;
2371 struct btrfs_key found_key;
2373 ret = btrfs_search_slot(trans, root, &key, path, 1, 1);
2378 leaf = path->nodes[0];
2379 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2381 fi = btrfs_item_ptr(leaf, path->slots[0],
2382 struct btrfs_file_extent_item);
2383 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2385 if (relink_is_mergable(leaf, fi, new->bytenr) &&
2386 extent_len + found_key.offset == start) {
2387 btrfs_set_file_extent_num_bytes(leaf, fi,
2389 btrfs_mark_buffer_dirty(leaf);
2390 inode_add_bytes(inode, len);
2396 btrfs_release_path(path);
2401 ret = btrfs_insert_empty_item(trans, root, path, &key,
2404 btrfs_abort_transaction(trans, root, ret);
2408 leaf = path->nodes[0];
2409 item = btrfs_item_ptr(leaf, path->slots[0],
2410 struct btrfs_file_extent_item);
2411 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2412 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2413 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2414 btrfs_set_file_extent_num_bytes(leaf, item, len);
2415 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2416 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2417 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2418 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2419 btrfs_set_file_extent_encryption(leaf, item, 0);
2420 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2422 btrfs_mark_buffer_dirty(leaf);
2423 inode_add_bytes(inode, len);
2424 btrfs_release_path(path);
2426 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2428 backref->root_id, backref->inum,
2429 new->file_pos, 0); /* start - extent_offset */
2431 btrfs_abort_transaction(trans, root, ret);
2437 btrfs_release_path(path);
2438 path->leave_spinning = 0;
2439 btrfs_end_transaction(trans, root);
2441 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2447 static void relink_file_extents(struct new_sa_defrag_extent *new)
2449 struct btrfs_path *path;
2450 struct old_sa_defrag_extent *old, *tmp;
2451 struct sa_defrag_extent_backref *backref;
2452 struct sa_defrag_extent_backref *prev = NULL;
2453 struct inode *inode;
2454 struct btrfs_root *root;
2455 struct rb_node *node;
2459 root = BTRFS_I(inode)->root;
2461 path = btrfs_alloc_path();
2465 if (!record_extent_backrefs(path, new)) {
2466 btrfs_free_path(path);
2469 btrfs_release_path(path);
2472 node = rb_first(&new->root);
2475 rb_erase(node, &new->root);
2477 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2479 ret = relink_extent_backref(path, prev, backref);
2492 btrfs_free_path(path);
2494 list_for_each_entry_safe(old, tmp, &new->head, list) {
2495 list_del(&old->list);
2499 atomic_dec(&root->fs_info->defrag_running);
2500 wake_up(&root->fs_info->transaction_wait);
2505 static struct new_sa_defrag_extent *
2506 record_old_file_extents(struct inode *inode,
2507 struct btrfs_ordered_extent *ordered)
2509 struct btrfs_root *root = BTRFS_I(inode)->root;
2510 struct btrfs_path *path;
2511 struct btrfs_key key;
2512 struct old_sa_defrag_extent *old, *tmp;
2513 struct new_sa_defrag_extent *new;
2516 new = kmalloc(sizeof(*new), GFP_NOFS);
2521 new->file_pos = ordered->file_offset;
2522 new->len = ordered->len;
2523 new->bytenr = ordered->start;
2524 new->disk_len = ordered->disk_len;
2525 new->compress_type = ordered->compress_type;
2526 new->root = RB_ROOT;
2527 INIT_LIST_HEAD(&new->head);
2529 path = btrfs_alloc_path();
2533 key.objectid = btrfs_ino(inode);
2534 key.type = BTRFS_EXTENT_DATA_KEY;
2535 key.offset = new->file_pos;
2537 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2540 if (ret > 0 && path->slots[0] > 0)
2543 /* find out all the old extents for the file range */
2545 struct btrfs_file_extent_item *extent;
2546 struct extent_buffer *l;
2555 slot = path->slots[0];
2557 if (slot >= btrfs_header_nritems(l)) {
2558 ret = btrfs_next_leaf(root, path);
2566 btrfs_item_key_to_cpu(l, &key, slot);
2568 if (key.objectid != btrfs_ino(inode))
2570 if (key.type != BTRFS_EXTENT_DATA_KEY)
2572 if (key.offset >= new->file_pos + new->len)
2575 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2577 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2578 if (key.offset + num_bytes < new->file_pos)
2581 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2585 extent_offset = btrfs_file_extent_offset(l, extent);
2587 old = kmalloc(sizeof(*old), GFP_NOFS);
2591 offset = max(new->file_pos, key.offset);
2592 end = min(new->file_pos + new->len, key.offset + num_bytes);
2594 old->bytenr = disk_bytenr;
2595 old->extent_offset = extent_offset;
2596 old->offset = offset - key.offset;
2597 old->len = end - offset;
2600 list_add_tail(&old->list, &new->head);
2606 btrfs_free_path(path);
2607 atomic_inc(&root->fs_info->defrag_running);
2612 list_for_each_entry_safe(old, tmp, &new->head, list) {
2613 list_del(&old->list);
2617 btrfs_free_path(path);
2624 * helper function for btrfs_finish_ordered_io, this
2625 * just reads in some of the csum leaves to prime them into ram
2626 * before we start the transaction. It limits the amount of btree
2627 * reads required while inside the transaction.
2629 /* as ordered data IO finishes, this gets called so we can finish
2630 * an ordered extent if the range of bytes in the file it covers are
2633 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2635 struct inode *inode = ordered_extent->inode;
2636 struct btrfs_root *root = BTRFS_I(inode)->root;
2637 struct btrfs_trans_handle *trans = NULL;
2638 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2639 struct extent_state *cached_state = NULL;
2640 struct new_sa_defrag_extent *new = NULL;
2641 int compress_type = 0;
2645 nolock = btrfs_is_free_space_inode(inode);
2647 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2652 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2653 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2654 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2656 trans = btrfs_join_transaction_nolock(root);
2658 trans = btrfs_join_transaction(root);
2659 if (IS_ERR(trans)) {
2660 ret = PTR_ERR(trans);
2664 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2665 ret = btrfs_update_inode_fallback(trans, root, inode);
2666 if (ret) /* -ENOMEM or corruption */
2667 btrfs_abort_transaction(trans, root, ret);
2671 lock_extent_bits(io_tree, ordered_extent->file_offset,
2672 ordered_extent->file_offset + ordered_extent->len - 1,
2675 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2676 ordered_extent->file_offset + ordered_extent->len - 1,
2677 EXTENT_DEFRAG, 1, cached_state);
2679 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2680 if (last_snapshot >= BTRFS_I(inode)->generation)
2681 /* the inode is shared */
2682 new = record_old_file_extents(inode, ordered_extent);
2684 clear_extent_bit(io_tree, ordered_extent->file_offset,
2685 ordered_extent->file_offset + ordered_extent->len - 1,
2686 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2690 trans = btrfs_join_transaction_nolock(root);
2692 trans = btrfs_join_transaction(root);
2693 if (IS_ERR(trans)) {
2694 ret = PTR_ERR(trans);
2698 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2700 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2701 compress_type = ordered_extent->compress_type;
2702 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2703 BUG_ON(compress_type);
2704 ret = btrfs_mark_extent_written(trans, inode,
2705 ordered_extent->file_offset,
2706 ordered_extent->file_offset +
2707 ordered_extent->len);
2709 BUG_ON(root == root->fs_info->tree_root);
2710 ret = insert_reserved_file_extent(trans, inode,
2711 ordered_extent->file_offset,
2712 ordered_extent->start,
2713 ordered_extent->disk_len,
2714 ordered_extent->len,
2715 ordered_extent->len,
2716 compress_type, 0, 0,
2717 BTRFS_FILE_EXTENT_REG);
2719 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2720 ordered_extent->file_offset, ordered_extent->len,
2723 btrfs_abort_transaction(trans, root, ret);
2727 add_pending_csums(trans, inode, ordered_extent->file_offset,
2728 &ordered_extent->list);
2730 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2731 ret = btrfs_update_inode_fallback(trans, root, inode);
2732 if (ret) { /* -ENOMEM or corruption */
2733 btrfs_abort_transaction(trans, root, ret);
2738 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2739 ordered_extent->file_offset +
2740 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2742 if (root != root->fs_info->tree_root)
2743 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2745 btrfs_end_transaction(trans, root);
2748 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
2749 ordered_extent->file_offset +
2750 ordered_extent->len - 1, NULL, GFP_NOFS);
2753 * If the ordered extent had an IOERR or something else went
2754 * wrong we need to return the space for this ordered extent
2755 * back to the allocator.
2757 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2758 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2759 btrfs_free_reserved_extent(root, ordered_extent->start,
2760 ordered_extent->disk_len);
2765 * This needs to be done to make sure anybody waiting knows we are done
2766 * updating everything for this ordered extent.
2768 btrfs_remove_ordered_extent(inode, ordered_extent);
2770 /* for snapshot-aware defrag */
2772 relink_file_extents(new);
2775 btrfs_put_ordered_extent(ordered_extent);
2776 /* once for the tree */
2777 btrfs_put_ordered_extent(ordered_extent);
2782 static void finish_ordered_fn(struct btrfs_work *work)
2784 struct btrfs_ordered_extent *ordered_extent;
2785 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2786 btrfs_finish_ordered_io(ordered_extent);
2789 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2790 struct extent_state *state, int uptodate)
2792 struct inode *inode = page->mapping->host;
2793 struct btrfs_root *root = BTRFS_I(inode)->root;
2794 struct btrfs_ordered_extent *ordered_extent = NULL;
2795 struct btrfs_workers *workers;
2797 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2799 ClearPagePrivate2(page);
2800 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2801 end - start + 1, uptodate))
2804 ordered_extent->work.func = finish_ordered_fn;
2805 ordered_extent->work.flags = 0;
2807 if (btrfs_is_free_space_inode(inode))
2808 workers = &root->fs_info->endio_freespace_worker;
2810 workers = &root->fs_info->endio_write_workers;
2811 btrfs_queue_worker(workers, &ordered_extent->work);
2817 * when reads are done, we need to check csums to verify the data is correct
2818 * if there's a match, we allow the bio to finish. If not, the code in
2819 * extent_io.c will try to find good copies for us.
2821 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
2822 struct extent_state *state, int mirror)
2824 size_t offset = start - page_offset(page);
2825 struct inode *inode = page->mapping->host;
2826 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2828 u64 private = ~(u32)0;
2830 struct btrfs_root *root = BTRFS_I(inode)->root;
2832 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2833 DEFAULT_RATELIMIT_BURST);
2835 if (PageChecked(page)) {
2836 ClearPageChecked(page);
2840 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2843 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2844 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2845 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2850 if (state && state->start == start) {
2851 private = state->private;
2854 ret = get_state_private(io_tree, start, &private);
2856 kaddr = kmap_atomic(page);
2860 csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
2861 btrfs_csum_final(csum, (char *)&csum);
2862 if (csum != private)
2865 kunmap_atomic(kaddr);
2870 if (__ratelimit(&_rs))
2871 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u private %llu",
2872 (unsigned long long)btrfs_ino(page->mapping->host),
2873 (unsigned long long)start, csum,
2874 (unsigned long long)private);
2875 memset(kaddr + offset, 1, end - start + 1);
2876 flush_dcache_page(page);
2877 kunmap_atomic(kaddr);
2883 struct delayed_iput {
2884 struct list_head list;
2885 struct inode *inode;
2888 /* JDM: If this is fs-wide, why can't we add a pointer to
2889 * btrfs_inode instead and avoid the allocation? */
2890 void btrfs_add_delayed_iput(struct inode *inode)
2892 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2893 struct delayed_iput *delayed;
2895 if (atomic_add_unless(&inode->i_count, -1, 1))
2898 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2899 delayed->inode = inode;
2901 spin_lock(&fs_info->delayed_iput_lock);
2902 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2903 spin_unlock(&fs_info->delayed_iput_lock);
2906 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2909 struct btrfs_fs_info *fs_info = root->fs_info;
2910 struct delayed_iput *delayed;
2913 spin_lock(&fs_info->delayed_iput_lock);
2914 empty = list_empty(&fs_info->delayed_iputs);
2915 spin_unlock(&fs_info->delayed_iput_lock);
2919 spin_lock(&fs_info->delayed_iput_lock);
2920 list_splice_init(&fs_info->delayed_iputs, &list);
2921 spin_unlock(&fs_info->delayed_iput_lock);
2923 while (!list_empty(&list)) {
2924 delayed = list_entry(list.next, struct delayed_iput, list);
2925 list_del(&delayed->list);
2926 iput(delayed->inode);
2932 * This is called in transaction commit time. If there are no orphan
2933 * files in the subvolume, it removes orphan item and frees block_rsv
2936 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2937 struct btrfs_root *root)
2939 struct btrfs_block_rsv *block_rsv;
2942 if (atomic_read(&root->orphan_inodes) ||
2943 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2946 spin_lock(&root->orphan_lock);
2947 if (atomic_read(&root->orphan_inodes)) {
2948 spin_unlock(&root->orphan_lock);
2952 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2953 spin_unlock(&root->orphan_lock);
2957 block_rsv = root->orphan_block_rsv;
2958 root->orphan_block_rsv = NULL;
2959 spin_unlock(&root->orphan_lock);
2961 if (root->orphan_item_inserted &&
2962 btrfs_root_refs(&root->root_item) > 0) {
2963 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2964 root->root_key.objectid);
2966 root->orphan_item_inserted = 0;
2970 WARN_ON(block_rsv->size > 0);
2971 btrfs_free_block_rsv(root, block_rsv);
2976 * This creates an orphan entry for the given inode in case something goes
2977 * wrong in the middle of an unlink/truncate.
2979 * NOTE: caller of this function should reserve 5 units of metadata for
2982 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2984 struct btrfs_root *root = BTRFS_I(inode)->root;
2985 struct btrfs_block_rsv *block_rsv = NULL;
2990 if (!root->orphan_block_rsv) {
2991 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2996 spin_lock(&root->orphan_lock);
2997 if (!root->orphan_block_rsv) {
2998 root->orphan_block_rsv = block_rsv;
2999 } else if (block_rsv) {
3000 btrfs_free_block_rsv(root, block_rsv);
3004 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3005 &BTRFS_I(inode)->runtime_flags)) {
3008 * For proper ENOSPC handling, we should do orphan
3009 * cleanup when mounting. But this introduces backward
3010 * compatibility issue.
3012 if (!xchg(&root->orphan_item_inserted, 1))
3018 atomic_inc(&root->orphan_inodes);
3021 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3022 &BTRFS_I(inode)->runtime_flags))
3024 spin_unlock(&root->orphan_lock);
3026 /* grab metadata reservation from transaction handle */
3028 ret = btrfs_orphan_reserve_metadata(trans, inode);
3029 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3032 /* insert an orphan item to track this unlinked/truncated file */
3034 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3035 if (ret && ret != -EEXIST) {
3036 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3037 &BTRFS_I(inode)->runtime_flags);
3038 btrfs_abort_transaction(trans, root, ret);
3044 /* insert an orphan item to track subvolume contains orphan files */
3046 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3047 root->root_key.objectid);
3048 if (ret && ret != -EEXIST) {
3049 btrfs_abort_transaction(trans, root, ret);
3057 * We have done the truncate/delete so we can go ahead and remove the orphan
3058 * item for this particular inode.
3060 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3061 struct inode *inode)
3063 struct btrfs_root *root = BTRFS_I(inode)->root;
3064 int delete_item = 0;
3065 int release_rsv = 0;
3068 spin_lock(&root->orphan_lock);
3069 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3070 &BTRFS_I(inode)->runtime_flags))
3073 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3074 &BTRFS_I(inode)->runtime_flags))
3076 spin_unlock(&root->orphan_lock);
3078 if (trans && delete_item) {
3079 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3080 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3084 btrfs_orphan_release_metadata(inode);
3085 atomic_dec(&root->orphan_inodes);
3092 * this cleans up any orphans that may be left on the list from the last use
3095 int btrfs_orphan_cleanup(struct btrfs_root *root)
3097 struct btrfs_path *path;
3098 struct extent_buffer *leaf;
3099 struct btrfs_key key, found_key;
3100 struct btrfs_trans_handle *trans;
3101 struct inode *inode;
3102 u64 last_objectid = 0;
3103 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3105 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3108 path = btrfs_alloc_path();
3115 key.objectid = BTRFS_ORPHAN_OBJECTID;
3116 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3117 key.offset = (u64)-1;
3120 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3125 * if ret == 0 means we found what we were searching for, which
3126 * is weird, but possible, so only screw with path if we didn't
3127 * find the key and see if we have stuff that matches
3131 if (path->slots[0] == 0)
3136 /* pull out the item */
3137 leaf = path->nodes[0];
3138 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3140 /* make sure the item matches what we want */
3141 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3143 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3146 /* release the path since we're done with it */
3147 btrfs_release_path(path);
3150 * this is where we are basically btrfs_lookup, without the
3151 * crossing root thing. we store the inode number in the
3152 * offset of the orphan item.
3155 if (found_key.offset == last_objectid) {
3156 btrfs_err(root->fs_info,
3157 "Error removing orphan entry, stopping orphan cleanup");
3162 last_objectid = found_key.offset;
3164 found_key.objectid = found_key.offset;
3165 found_key.type = BTRFS_INODE_ITEM_KEY;
3166 found_key.offset = 0;
3167 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3168 ret = PTR_RET(inode);
3169 if (ret && ret != -ESTALE)
3172 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3173 struct btrfs_root *dead_root;
3174 struct btrfs_fs_info *fs_info = root->fs_info;
3175 int is_dead_root = 0;
3178 * this is an orphan in the tree root. Currently these
3179 * could come from 2 sources:
3180 * a) a snapshot deletion in progress
3181 * b) a free space cache inode
3182 * We need to distinguish those two, as the snapshot
3183 * orphan must not get deleted.
3184 * find_dead_roots already ran before us, so if this
3185 * is a snapshot deletion, we should find the root
3186 * in the dead_roots list
3188 spin_lock(&fs_info->trans_lock);
3189 list_for_each_entry(dead_root, &fs_info->dead_roots,
3191 if (dead_root->root_key.objectid ==
3192 found_key.objectid) {
3197 spin_unlock(&fs_info->trans_lock);
3199 /* prevent this orphan from being found again */
3200 key.offset = found_key.objectid - 1;
3205 * Inode is already gone but the orphan item is still there,
3206 * kill the orphan item.
3208 if (ret == -ESTALE) {
3209 trans = btrfs_start_transaction(root, 1);
3210 if (IS_ERR(trans)) {
3211 ret = PTR_ERR(trans);
3214 btrfs_debug(root->fs_info, "auto deleting %Lu",
3215 found_key.objectid);
3216 ret = btrfs_del_orphan_item(trans, root,
3217 found_key.objectid);
3218 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3219 btrfs_end_transaction(trans, root);
3224 * add this inode to the orphan list so btrfs_orphan_del does
3225 * the proper thing when we hit it
3227 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3228 &BTRFS_I(inode)->runtime_flags);
3229 atomic_inc(&root->orphan_inodes);
3231 /* if we have links, this was a truncate, lets do that */
3232 if (inode->i_nlink) {
3233 if (!S_ISREG(inode->i_mode)) {
3240 /* 1 for the orphan item deletion. */
3241 trans = btrfs_start_transaction(root, 1);
3242 if (IS_ERR(trans)) {
3244 ret = PTR_ERR(trans);
3247 ret = btrfs_orphan_add(trans, inode);
3248 btrfs_end_transaction(trans, root);
3254 ret = btrfs_truncate(inode);
3256 btrfs_orphan_del(NULL, inode);
3261 /* this will do delete_inode and everything for us */
3266 /* release the path since we're done with it */
3267 btrfs_release_path(path);
3269 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3271 if (root->orphan_block_rsv)
3272 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3275 if (root->orphan_block_rsv || root->orphan_item_inserted) {
3276 trans = btrfs_join_transaction(root);
3278 btrfs_end_transaction(trans, root);
3282 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3284 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3288 btrfs_crit(root->fs_info,
3289 "could not do orphan cleanup %d", ret);
3290 btrfs_free_path(path);
3295 * very simple check to peek ahead in the leaf looking for xattrs. If we
3296 * don't find any xattrs, we know there can't be any acls.
3298 * slot is the slot the inode is in, objectid is the objectid of the inode
3300 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3301 int slot, u64 objectid)
3303 u32 nritems = btrfs_header_nritems(leaf);
3304 struct btrfs_key found_key;
3305 static u64 xattr_access = 0;
3306 static u64 xattr_default = 0;
3309 if (!xattr_access) {
3310 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3311 strlen(POSIX_ACL_XATTR_ACCESS));
3312 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3313 strlen(POSIX_ACL_XATTR_DEFAULT));
3317 while (slot < nritems) {
3318 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3320 /* we found a different objectid, there must not be acls */
3321 if (found_key.objectid != objectid)
3324 /* we found an xattr, assume we've got an acl */
3325 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3326 if (found_key.offset == xattr_access ||
3327 found_key.offset == xattr_default)
3332 * we found a key greater than an xattr key, there can't
3333 * be any acls later on
3335 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3342 * it goes inode, inode backrefs, xattrs, extents,
3343 * so if there are a ton of hard links to an inode there can
3344 * be a lot of backrefs. Don't waste time searching too hard,
3345 * this is just an optimization
3350 /* we hit the end of the leaf before we found an xattr or
3351 * something larger than an xattr. We have to assume the inode
3358 * read an inode from the btree into the in-memory inode
3360 static void btrfs_read_locked_inode(struct inode *inode)
3362 struct btrfs_path *path;
3363 struct extent_buffer *leaf;
3364 struct btrfs_inode_item *inode_item;
3365 struct btrfs_timespec *tspec;
3366 struct btrfs_root *root = BTRFS_I(inode)->root;
3367 struct btrfs_key location;
3371 bool filled = false;
3373 ret = btrfs_fill_inode(inode, &rdev);
3377 path = btrfs_alloc_path();
3381 path->leave_spinning = 1;
3382 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3384 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3388 leaf = path->nodes[0];
3393 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3394 struct btrfs_inode_item);
3395 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3396 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3397 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3398 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3399 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3401 tspec = btrfs_inode_atime(inode_item);
3402 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3403 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3405 tspec = btrfs_inode_mtime(inode_item);
3406 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3407 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3409 tspec = btrfs_inode_ctime(inode_item);
3410 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3411 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3413 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3414 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3415 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3418 * If we were modified in the current generation and evicted from memory
3419 * and then re-read we need to do a full sync since we don't have any
3420 * idea about which extents were modified before we were evicted from
3423 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3424 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3425 &BTRFS_I(inode)->runtime_flags);
3427 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3428 inode->i_generation = BTRFS_I(inode)->generation;
3430 rdev = btrfs_inode_rdev(leaf, inode_item);
3432 BTRFS_I(inode)->index_cnt = (u64)-1;
3433 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3436 * try to precache a NULL acl entry for files that don't have
3437 * any xattrs or acls
3439 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3442 cache_no_acl(inode);
3444 btrfs_free_path(path);
3446 switch (inode->i_mode & S_IFMT) {
3448 inode->i_mapping->a_ops = &btrfs_aops;
3449 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3450 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3451 inode->i_fop = &btrfs_file_operations;
3452 inode->i_op = &btrfs_file_inode_operations;
3455 inode->i_fop = &btrfs_dir_file_operations;
3456 if (root == root->fs_info->tree_root)
3457 inode->i_op = &btrfs_dir_ro_inode_operations;
3459 inode->i_op = &btrfs_dir_inode_operations;
3462 inode->i_op = &btrfs_symlink_inode_operations;
3463 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3464 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3467 inode->i_op = &btrfs_special_inode_operations;
3468 init_special_inode(inode, inode->i_mode, rdev);
3472 btrfs_update_iflags(inode);
3476 btrfs_free_path(path);
3477 make_bad_inode(inode);
3481 * given a leaf and an inode, copy the inode fields into the leaf
3483 static void fill_inode_item(struct btrfs_trans_handle *trans,
3484 struct extent_buffer *leaf,
3485 struct btrfs_inode_item *item,
3486 struct inode *inode)
3488 struct btrfs_map_token token;
3490 btrfs_init_map_token(&token);
3492 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3493 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3494 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3496 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3497 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3499 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3500 inode->i_atime.tv_sec, &token);
3501 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3502 inode->i_atime.tv_nsec, &token);
3504 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3505 inode->i_mtime.tv_sec, &token);
3506 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3507 inode->i_mtime.tv_nsec, &token);
3509 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3510 inode->i_ctime.tv_sec, &token);
3511 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3512 inode->i_ctime.tv_nsec, &token);
3514 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3516 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3518 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3519 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3520 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3521 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3522 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3526 * copy everything in the in-memory inode into the btree.
3528 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3529 struct btrfs_root *root, struct inode *inode)
3531 struct btrfs_inode_item *inode_item;
3532 struct btrfs_path *path;
3533 struct extent_buffer *leaf;
3536 path = btrfs_alloc_path();
3540 path->leave_spinning = 1;
3541 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3549 btrfs_unlock_up_safe(path, 1);
3550 leaf = path->nodes[0];
3551 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3552 struct btrfs_inode_item);
3554 fill_inode_item(trans, leaf, inode_item, inode);
3555 btrfs_mark_buffer_dirty(leaf);
3556 btrfs_set_inode_last_trans(trans, inode);
3559 btrfs_free_path(path);
3564 * copy everything in the in-memory inode into the btree.
3566 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3567 struct btrfs_root *root, struct inode *inode)
3572 * If the inode is a free space inode, we can deadlock during commit
3573 * if we put it into the delayed code.
3575 * The data relocation inode should also be directly updated
3578 if (!btrfs_is_free_space_inode(inode)
3579 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3580 btrfs_update_root_times(trans, root);
3582 ret = btrfs_delayed_update_inode(trans, root, inode);
3584 btrfs_set_inode_last_trans(trans, inode);
3588 return btrfs_update_inode_item(trans, root, inode);
3591 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3592 struct btrfs_root *root,
3593 struct inode *inode)
3597 ret = btrfs_update_inode(trans, root, inode);
3599 return btrfs_update_inode_item(trans, root, inode);
3604 * unlink helper that gets used here in inode.c and in the tree logging
3605 * recovery code. It remove a link in a directory with a given name, and
3606 * also drops the back refs in the inode to the directory
3608 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3609 struct btrfs_root *root,
3610 struct inode *dir, struct inode *inode,
3611 const char *name, int name_len)
3613 struct btrfs_path *path;
3615 struct extent_buffer *leaf;
3616 struct btrfs_dir_item *di;
3617 struct btrfs_key key;
3619 u64 ino = btrfs_ino(inode);
3620 u64 dir_ino = btrfs_ino(dir);
3622 path = btrfs_alloc_path();
3628 path->leave_spinning = 1;
3629 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3630 name, name_len, -1);
3639 leaf = path->nodes[0];
3640 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3641 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3644 btrfs_release_path(path);
3646 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3649 btrfs_info(root->fs_info,
3650 "failed to delete reference to %.*s, inode %llu parent %llu",
3652 (unsigned long long)ino, (unsigned long long)dir_ino);
3653 btrfs_abort_transaction(trans, root, ret);
3657 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3659 btrfs_abort_transaction(trans, root, ret);
3663 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3665 if (ret != 0 && ret != -ENOENT) {
3666 btrfs_abort_transaction(trans, root, ret);
3670 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3675 btrfs_abort_transaction(trans, root, ret);
3677 btrfs_free_path(path);
3681 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3682 inode_inc_iversion(inode);
3683 inode_inc_iversion(dir);
3684 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3685 ret = btrfs_update_inode(trans, root, dir);
3690 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3691 struct btrfs_root *root,
3692 struct inode *dir, struct inode *inode,
3693 const char *name, int name_len)
3696 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3698 btrfs_drop_nlink(inode);
3699 ret = btrfs_update_inode(trans, root, inode);
3705 * helper to start transaction for unlink and rmdir.
3707 * unlink and rmdir are special in btrfs, they do not always free space, so
3708 * if we cannot make our reservations the normal way try and see if there is
3709 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3710 * allow the unlink to occur.
3712 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3714 struct btrfs_trans_handle *trans;
3715 struct btrfs_root *root = BTRFS_I(dir)->root;
3719 * 1 for the possible orphan item
3720 * 1 for the dir item
3721 * 1 for the dir index
3722 * 1 for the inode ref
3725 trans = btrfs_start_transaction(root, 5);
3726 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3729 if (PTR_ERR(trans) == -ENOSPC) {
3730 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3732 trans = btrfs_start_transaction(root, 0);
3735 ret = btrfs_cond_migrate_bytes(root->fs_info,
3736 &root->fs_info->trans_block_rsv,
3739 btrfs_end_transaction(trans, root);
3740 return ERR_PTR(ret);
3742 trans->block_rsv = &root->fs_info->trans_block_rsv;
3743 trans->bytes_reserved = num_bytes;
3748 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3750 struct btrfs_root *root = BTRFS_I(dir)->root;
3751 struct btrfs_trans_handle *trans;
3752 struct inode *inode = dentry->d_inode;
3755 trans = __unlink_start_trans(dir);
3757 return PTR_ERR(trans);
3759 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3761 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3762 dentry->d_name.name, dentry->d_name.len);
3766 if (inode->i_nlink == 0) {
3767 ret = btrfs_orphan_add(trans, inode);
3773 btrfs_end_transaction(trans, root);
3774 btrfs_btree_balance_dirty(root);
3778 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3779 struct btrfs_root *root,
3780 struct inode *dir, u64 objectid,
3781 const char *name, int name_len)
3783 struct btrfs_path *path;
3784 struct extent_buffer *leaf;
3785 struct btrfs_dir_item *di;
3786 struct btrfs_key key;
3789 u64 dir_ino = btrfs_ino(dir);
3791 path = btrfs_alloc_path();
3795 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3796 name, name_len, -1);
3797 if (IS_ERR_OR_NULL(di)) {
3805 leaf = path->nodes[0];
3806 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3807 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3808 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3810 btrfs_abort_transaction(trans, root, ret);
3813 btrfs_release_path(path);
3815 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3816 objectid, root->root_key.objectid,
3817 dir_ino, &index, name, name_len);
3819 if (ret != -ENOENT) {
3820 btrfs_abort_transaction(trans, root, ret);
3823 di = btrfs_search_dir_index_item(root, path, dir_ino,
3825 if (IS_ERR_OR_NULL(di)) {
3830 btrfs_abort_transaction(trans, root, ret);
3834 leaf = path->nodes[0];
3835 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3836 btrfs_release_path(path);
3839 btrfs_release_path(path);
3841 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3843 btrfs_abort_transaction(trans, root, ret);
3847 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3848 inode_inc_iversion(dir);
3849 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3850 ret = btrfs_update_inode_fallback(trans, root, dir);
3852 btrfs_abort_transaction(trans, root, ret);
3854 btrfs_free_path(path);
3858 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3860 struct inode *inode = dentry->d_inode;
3862 struct btrfs_root *root = BTRFS_I(dir)->root;
3863 struct btrfs_trans_handle *trans;
3865 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3867 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3870 trans = __unlink_start_trans(dir);
3872 return PTR_ERR(trans);
3874 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3875 err = btrfs_unlink_subvol(trans, root, dir,
3876 BTRFS_I(inode)->location.objectid,
3877 dentry->d_name.name,
3878 dentry->d_name.len);
3882 err = btrfs_orphan_add(trans, inode);
3886 /* now the directory is empty */
3887 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3888 dentry->d_name.name, dentry->d_name.len);
3890 btrfs_i_size_write(inode, 0);
3892 btrfs_end_transaction(trans, root);
3893 btrfs_btree_balance_dirty(root);
3899 * this can truncate away extent items, csum items and directory items.
3900 * It starts at a high offset and removes keys until it can't find
3901 * any higher than new_size
3903 * csum items that cross the new i_size are truncated to the new size
3906 * min_type is the minimum key type to truncate down to. If set to 0, this
3907 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3909 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3910 struct btrfs_root *root,
3911 struct inode *inode,
3912 u64 new_size, u32 min_type)
3914 struct btrfs_path *path;
3915 struct extent_buffer *leaf;
3916 struct btrfs_file_extent_item *fi;
3917 struct btrfs_key key;
3918 struct btrfs_key found_key;
3919 u64 extent_start = 0;
3920 u64 extent_num_bytes = 0;
3921 u64 extent_offset = 0;
3923 u32 found_type = (u8)-1;
3926 int pending_del_nr = 0;
3927 int pending_del_slot = 0;
3928 int extent_type = -1;
3931 u64 ino = btrfs_ino(inode);
3933 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3935 path = btrfs_alloc_path();
3941 * We want to drop from the next block forward in case this new size is
3942 * not block aligned since we will be keeping the last block of the
3943 * extent just the way it is.
3945 if (root->ref_cows || root == root->fs_info->tree_root)
3946 btrfs_drop_extent_cache(inode, ALIGN(new_size,
3947 root->sectorsize), (u64)-1, 0);
3950 * This function is also used to drop the items in the log tree before
3951 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3952 * it is used to drop the loged items. So we shouldn't kill the delayed
3955 if (min_type == 0 && root == BTRFS_I(inode)->root)
3956 btrfs_kill_delayed_inode_items(inode);
3959 key.offset = (u64)-1;
3963 path->leave_spinning = 1;
3964 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3971 /* there are no items in the tree for us to truncate, we're
3974 if (path->slots[0] == 0)
3981 leaf = path->nodes[0];
3982 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3983 found_type = btrfs_key_type(&found_key);
3985 if (found_key.objectid != ino)
3988 if (found_type < min_type)
3991 item_end = found_key.offset;
3992 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3993 fi = btrfs_item_ptr(leaf, path->slots[0],
3994 struct btrfs_file_extent_item);
3995 extent_type = btrfs_file_extent_type(leaf, fi);
3996 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3998 btrfs_file_extent_num_bytes(leaf, fi);
3999 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4000 item_end += btrfs_file_extent_inline_len(leaf,
4005 if (found_type > min_type) {
4008 if (item_end < new_size)
4010 if (found_key.offset >= new_size)
4016 /* FIXME, shrink the extent if the ref count is only 1 */
4017 if (found_type != BTRFS_EXTENT_DATA_KEY)
4020 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4022 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4024 u64 orig_num_bytes =
4025 btrfs_file_extent_num_bytes(leaf, fi);
4026 extent_num_bytes = ALIGN(new_size -
4029 btrfs_set_file_extent_num_bytes(leaf, fi,
4031 num_dec = (orig_num_bytes -
4033 if (root->ref_cows && extent_start != 0)
4034 inode_sub_bytes(inode, num_dec);
4035 btrfs_mark_buffer_dirty(leaf);
4038 btrfs_file_extent_disk_num_bytes(leaf,
4040 extent_offset = found_key.offset -
4041 btrfs_file_extent_offset(leaf, fi);
4043 /* FIXME blocksize != 4096 */
4044 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4045 if (extent_start != 0) {
4048 inode_sub_bytes(inode, num_dec);
4051 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4053 * we can't truncate inline items that have had
4057 btrfs_file_extent_compression(leaf, fi) == 0 &&
4058 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4059 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4060 u32 size = new_size - found_key.offset;
4062 if (root->ref_cows) {
4063 inode_sub_bytes(inode, item_end + 1 -
4067 btrfs_file_extent_calc_inline_size(size);
4068 btrfs_truncate_item(root, path, size, 1);
4069 } else if (root->ref_cows) {
4070 inode_sub_bytes(inode, item_end + 1 -
4076 if (!pending_del_nr) {
4077 /* no pending yet, add ourselves */
4078 pending_del_slot = path->slots[0];
4080 } else if (pending_del_nr &&
4081 path->slots[0] + 1 == pending_del_slot) {
4082 /* hop on the pending chunk */
4084 pending_del_slot = path->slots[0];
4091 if (found_extent && (root->ref_cows ||
4092 root == root->fs_info->tree_root)) {
4093 btrfs_set_path_blocking(path);
4094 ret = btrfs_free_extent(trans, root, extent_start,
4095 extent_num_bytes, 0,
4096 btrfs_header_owner(leaf),
4097 ino, extent_offset, 0);
4101 if (found_type == BTRFS_INODE_ITEM_KEY)
4104 if (path->slots[0] == 0 ||
4105 path->slots[0] != pending_del_slot) {
4106 if (pending_del_nr) {
4107 ret = btrfs_del_items(trans, root, path,
4111 btrfs_abort_transaction(trans,
4117 btrfs_release_path(path);
4124 if (pending_del_nr) {
4125 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4128 btrfs_abort_transaction(trans, root, ret);
4131 btrfs_free_path(path);
4136 * btrfs_truncate_page - read, zero a chunk and write a page
4137 * @inode - inode that we're zeroing
4138 * @from - the offset to start zeroing
4139 * @len - the length to zero, 0 to zero the entire range respective to the
4141 * @front - zero up to the offset instead of from the offset on
4143 * This will find the page for the "from" offset and cow the page and zero the
4144 * part we want to zero. This is used with truncate and hole punching.
4146 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4149 struct address_space *mapping = inode->i_mapping;
4150 struct btrfs_root *root = BTRFS_I(inode)->root;
4151 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4152 struct btrfs_ordered_extent *ordered;
4153 struct extent_state *cached_state = NULL;
4155 u32 blocksize = root->sectorsize;
4156 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4157 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4159 gfp_t mask = btrfs_alloc_write_mask(mapping);
4164 if ((offset & (blocksize - 1)) == 0 &&
4165 (!len || ((len & (blocksize - 1)) == 0)))
4167 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4172 page = find_or_create_page(mapping, index, mask);
4174 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4179 page_start = page_offset(page);
4180 page_end = page_start + PAGE_CACHE_SIZE - 1;
4182 if (!PageUptodate(page)) {
4183 ret = btrfs_readpage(NULL, page);
4185 if (page->mapping != mapping) {
4187 page_cache_release(page);
4190 if (!PageUptodate(page)) {
4195 wait_on_page_writeback(page);
4197 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4198 set_page_extent_mapped(page);
4200 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4202 unlock_extent_cached(io_tree, page_start, page_end,
4203 &cached_state, GFP_NOFS);
4205 page_cache_release(page);
4206 btrfs_start_ordered_extent(inode, ordered, 1);
4207 btrfs_put_ordered_extent(ordered);
4211 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4212 EXTENT_DIRTY | EXTENT_DELALLOC |
4213 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4214 0, 0, &cached_state, GFP_NOFS);
4216 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4219 unlock_extent_cached(io_tree, page_start, page_end,
4220 &cached_state, GFP_NOFS);
4224 if (offset != PAGE_CACHE_SIZE) {
4226 len = PAGE_CACHE_SIZE - offset;
4229 memset(kaddr, 0, offset);
4231 memset(kaddr + offset, 0, len);
4232 flush_dcache_page(page);
4235 ClearPageChecked(page);
4236 set_page_dirty(page);
4237 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4242 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4244 page_cache_release(page);
4250 * This function puts in dummy file extents for the area we're creating a hole
4251 * for. So if we are truncating this file to a larger size we need to insert
4252 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4253 * the range between oldsize and size
4255 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4257 struct btrfs_trans_handle *trans;
4258 struct btrfs_root *root = BTRFS_I(inode)->root;
4259 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4260 struct extent_map *em = NULL;
4261 struct extent_state *cached_state = NULL;
4262 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4263 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4264 u64 block_end = ALIGN(size, root->sectorsize);
4271 * If our size started in the middle of a page we need to zero out the
4272 * rest of the page before we expand the i_size, otherwise we could
4273 * expose stale data.
4275 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4279 if (size <= hole_start)
4283 struct btrfs_ordered_extent *ordered;
4284 btrfs_wait_ordered_range(inode, hole_start,
4285 block_end - hole_start);
4286 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4288 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
4291 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4292 &cached_state, GFP_NOFS);
4293 btrfs_put_ordered_extent(ordered);
4296 cur_offset = hole_start;
4298 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4299 block_end - cur_offset, 0);
4305 last_byte = min(extent_map_end(em), block_end);
4306 last_byte = ALIGN(last_byte , root->sectorsize);
4307 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4308 struct extent_map *hole_em;
4309 hole_size = last_byte - cur_offset;
4311 trans = btrfs_start_transaction(root, 3);
4312 if (IS_ERR(trans)) {
4313 err = PTR_ERR(trans);
4317 err = btrfs_drop_extents(trans, root, inode,
4319 cur_offset + hole_size, 1);
4321 btrfs_abort_transaction(trans, root, err);
4322 btrfs_end_transaction(trans, root);
4326 err = btrfs_insert_file_extent(trans, root,
4327 btrfs_ino(inode), cur_offset, 0,
4328 0, hole_size, 0, hole_size,
4331 btrfs_abort_transaction(trans, root, err);
4332 btrfs_end_transaction(trans, root);
4336 btrfs_drop_extent_cache(inode, cur_offset,
4337 cur_offset + hole_size - 1, 0);
4338 hole_em = alloc_extent_map();
4340 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4341 &BTRFS_I(inode)->runtime_flags);
4344 hole_em->start = cur_offset;
4345 hole_em->len = hole_size;
4346 hole_em->orig_start = cur_offset;
4348 hole_em->block_start = EXTENT_MAP_HOLE;
4349 hole_em->block_len = 0;
4350 hole_em->orig_block_len = 0;
4351 hole_em->ram_bytes = hole_size;
4352 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4353 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4354 hole_em->generation = trans->transid;
4357 write_lock(&em_tree->lock);
4358 err = add_extent_mapping(em_tree, hole_em, 1);
4359 write_unlock(&em_tree->lock);
4362 btrfs_drop_extent_cache(inode, cur_offset,
4366 free_extent_map(hole_em);
4368 btrfs_update_inode(trans, root, inode);
4369 btrfs_end_transaction(trans, root);
4371 free_extent_map(em);
4373 cur_offset = last_byte;
4374 if (cur_offset >= block_end)
4378 free_extent_map(em);
4379 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4384 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4386 struct btrfs_root *root = BTRFS_I(inode)->root;
4387 struct btrfs_trans_handle *trans;
4388 loff_t oldsize = i_size_read(inode);
4389 loff_t newsize = attr->ia_size;
4390 int mask = attr->ia_valid;
4393 if (newsize == oldsize)
4397 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4398 * special case where we need to update the times despite not having
4399 * these flags set. For all other operations the VFS set these flags
4400 * explicitly if it wants a timestamp update.
4402 if (newsize != oldsize && (!(mask & (ATTR_CTIME | ATTR_MTIME))))
4403 inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb);
4405 if (newsize > oldsize) {
4406 truncate_pagecache(inode, oldsize, newsize);
4407 ret = btrfs_cont_expand(inode, oldsize, newsize);
4411 trans = btrfs_start_transaction(root, 1);
4413 return PTR_ERR(trans);
4415 i_size_write(inode, newsize);
4416 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4417 ret = btrfs_update_inode(trans, root, inode);
4418 btrfs_end_transaction(trans, root);
4422 * We're truncating a file that used to have good data down to
4423 * zero. Make sure it gets into the ordered flush list so that
4424 * any new writes get down to disk quickly.
4427 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4428 &BTRFS_I(inode)->runtime_flags);
4431 * 1 for the orphan item we're going to add
4432 * 1 for the orphan item deletion.
4434 trans = btrfs_start_transaction(root, 2);
4436 return PTR_ERR(trans);
4439 * We need to do this in case we fail at _any_ point during the
4440 * actual truncate. Once we do the truncate_setsize we could
4441 * invalidate pages which forces any outstanding ordered io to
4442 * be instantly completed which will give us extents that need
4443 * to be truncated. If we fail to get an orphan inode down we
4444 * could have left over extents that were never meant to live,
4445 * so we need to garuntee from this point on that everything
4446 * will be consistent.
4448 ret = btrfs_orphan_add(trans, inode);
4449 btrfs_end_transaction(trans, root);
4453 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4454 truncate_setsize(inode, newsize);
4456 /* Disable nonlocked read DIO to avoid the end less truncate */
4457 btrfs_inode_block_unlocked_dio(inode);
4458 inode_dio_wait(inode);
4459 btrfs_inode_resume_unlocked_dio(inode);
4461 ret = btrfs_truncate(inode);
4462 if (ret && inode->i_nlink)
4463 btrfs_orphan_del(NULL, inode);
4469 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4471 struct inode *inode = dentry->d_inode;
4472 struct btrfs_root *root = BTRFS_I(inode)->root;
4475 if (btrfs_root_readonly(root))
4478 err = inode_change_ok(inode, attr);
4482 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4483 err = btrfs_setsize(inode, attr);
4488 if (attr->ia_valid) {
4489 setattr_copy(inode, attr);
4490 inode_inc_iversion(inode);
4491 err = btrfs_dirty_inode(inode);
4493 if (!err && attr->ia_valid & ATTR_MODE)
4494 err = btrfs_acl_chmod(inode);
4500 void btrfs_evict_inode(struct inode *inode)
4502 struct btrfs_trans_handle *trans;
4503 struct btrfs_root *root = BTRFS_I(inode)->root;
4504 struct btrfs_block_rsv *rsv, *global_rsv;
4505 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4508 trace_btrfs_inode_evict(inode);
4510 truncate_inode_pages(&inode->i_data, 0);
4511 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
4512 btrfs_is_free_space_inode(inode)))
4515 if (is_bad_inode(inode)) {
4516 btrfs_orphan_del(NULL, inode);
4519 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4520 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4522 if (root->fs_info->log_root_recovering) {
4523 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4524 &BTRFS_I(inode)->runtime_flags));
4528 if (inode->i_nlink > 0) {
4529 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
4533 ret = btrfs_commit_inode_delayed_inode(inode);
4535 btrfs_orphan_del(NULL, inode);
4539 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4541 btrfs_orphan_del(NULL, inode);
4544 rsv->size = min_size;
4546 global_rsv = &root->fs_info->global_block_rsv;
4548 btrfs_i_size_write(inode, 0);
4551 * This is a bit simpler than btrfs_truncate since we've already
4552 * reserved our space for our orphan item in the unlink, so we just
4553 * need to reserve some slack space in case we add bytes and update
4554 * inode item when doing the truncate.
4557 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4558 BTRFS_RESERVE_FLUSH_LIMIT);
4561 * Try and steal from the global reserve since we will
4562 * likely not use this space anyway, we want to try as
4563 * hard as possible to get this to work.
4566 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4569 btrfs_warn(root->fs_info,
4570 "Could not get space for a delete, will truncate on mount %d",
4572 btrfs_orphan_del(NULL, inode);
4573 btrfs_free_block_rsv(root, rsv);
4577 trans = btrfs_join_transaction(root);
4578 if (IS_ERR(trans)) {
4579 btrfs_orphan_del(NULL, inode);
4580 btrfs_free_block_rsv(root, rsv);
4584 trans->block_rsv = rsv;
4586 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4590 trans->block_rsv = &root->fs_info->trans_block_rsv;
4591 btrfs_end_transaction(trans, root);
4593 btrfs_btree_balance_dirty(root);
4596 btrfs_free_block_rsv(root, rsv);
4599 trans->block_rsv = root->orphan_block_rsv;
4600 ret = btrfs_orphan_del(trans, inode);
4604 trans->block_rsv = &root->fs_info->trans_block_rsv;
4605 if (!(root == root->fs_info->tree_root ||
4606 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4607 btrfs_return_ino(root, btrfs_ino(inode));
4609 btrfs_end_transaction(trans, root);
4610 btrfs_btree_balance_dirty(root);
4612 btrfs_remove_delayed_node(inode);
4618 * this returns the key found in the dir entry in the location pointer.
4619 * If no dir entries were found, location->objectid is 0.
4621 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4622 struct btrfs_key *location)
4624 const char *name = dentry->d_name.name;
4625 int namelen = dentry->d_name.len;
4626 struct btrfs_dir_item *di;
4627 struct btrfs_path *path;
4628 struct btrfs_root *root = BTRFS_I(dir)->root;
4631 path = btrfs_alloc_path();
4635 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4640 if (IS_ERR_OR_NULL(di))
4643 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4645 btrfs_free_path(path);
4648 location->objectid = 0;
4653 * when we hit a tree root in a directory, the btrfs part of the inode
4654 * needs to be changed to reflect the root directory of the tree root. This
4655 * is kind of like crossing a mount point.
4657 static int fixup_tree_root_location(struct btrfs_root *root,
4659 struct dentry *dentry,
4660 struct btrfs_key *location,
4661 struct btrfs_root **sub_root)
4663 struct btrfs_path *path;
4664 struct btrfs_root *new_root;
4665 struct btrfs_root_ref *ref;
4666 struct extent_buffer *leaf;
4670 path = btrfs_alloc_path();
4677 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
4678 BTRFS_I(dir)->root->root_key.objectid,
4679 location->objectid);
4686 leaf = path->nodes[0];
4687 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4688 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4689 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4692 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4693 (unsigned long)(ref + 1),
4694 dentry->d_name.len);
4698 btrfs_release_path(path);
4700 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4701 if (IS_ERR(new_root)) {
4702 err = PTR_ERR(new_root);
4706 *sub_root = new_root;
4707 location->objectid = btrfs_root_dirid(&new_root->root_item);
4708 location->type = BTRFS_INODE_ITEM_KEY;
4709 location->offset = 0;
4712 btrfs_free_path(path);
4716 static void inode_tree_add(struct inode *inode)
4718 struct btrfs_root *root = BTRFS_I(inode)->root;
4719 struct btrfs_inode *entry;
4721 struct rb_node *parent;
4722 u64 ino = btrfs_ino(inode);
4724 if (inode_unhashed(inode))
4728 spin_lock(&root->inode_lock);
4729 p = &root->inode_tree.rb_node;
4732 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4734 if (ino < btrfs_ino(&entry->vfs_inode))
4735 p = &parent->rb_left;
4736 else if (ino > btrfs_ino(&entry->vfs_inode))
4737 p = &parent->rb_right;
4739 WARN_ON(!(entry->vfs_inode.i_state &
4740 (I_WILL_FREE | I_FREEING)));
4741 rb_erase(parent, &root->inode_tree);
4742 RB_CLEAR_NODE(parent);
4743 spin_unlock(&root->inode_lock);
4747 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
4748 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4749 spin_unlock(&root->inode_lock);
4752 static void inode_tree_del(struct inode *inode)
4754 struct btrfs_root *root = BTRFS_I(inode)->root;
4757 spin_lock(&root->inode_lock);
4758 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4759 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4760 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4761 empty = RB_EMPTY_ROOT(&root->inode_tree);
4763 spin_unlock(&root->inode_lock);
4766 * Free space cache has inodes in the tree root, but the tree root has a
4767 * root_refs of 0, so this could end up dropping the tree root as a
4768 * snapshot, so we need the extra !root->fs_info->tree_root check to
4769 * make sure we don't drop it.
4771 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4772 root != root->fs_info->tree_root) {
4773 synchronize_srcu(&root->fs_info->subvol_srcu);
4774 spin_lock(&root->inode_lock);
4775 empty = RB_EMPTY_ROOT(&root->inode_tree);
4776 spin_unlock(&root->inode_lock);
4778 btrfs_add_dead_root(root);
4782 void btrfs_invalidate_inodes(struct btrfs_root *root)
4784 struct rb_node *node;
4785 struct rb_node *prev;
4786 struct btrfs_inode *entry;
4787 struct inode *inode;
4790 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4792 spin_lock(&root->inode_lock);
4794 node = root->inode_tree.rb_node;
4798 entry = rb_entry(node, struct btrfs_inode, rb_node);
4800 if (objectid < btrfs_ino(&entry->vfs_inode))
4801 node = node->rb_left;
4802 else if (objectid > btrfs_ino(&entry->vfs_inode))
4803 node = node->rb_right;
4809 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4810 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4814 prev = rb_next(prev);
4818 entry = rb_entry(node, struct btrfs_inode, rb_node);
4819 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4820 inode = igrab(&entry->vfs_inode);
4822 spin_unlock(&root->inode_lock);
4823 if (atomic_read(&inode->i_count) > 1)
4824 d_prune_aliases(inode);
4826 * btrfs_drop_inode will have it removed from
4827 * the inode cache when its usage count
4832 spin_lock(&root->inode_lock);
4836 if (cond_resched_lock(&root->inode_lock))
4839 node = rb_next(node);
4841 spin_unlock(&root->inode_lock);
4844 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4846 struct btrfs_iget_args *args = p;
4847 inode->i_ino = args->ino;
4848 BTRFS_I(inode)->root = args->root;
4852 static int btrfs_find_actor(struct inode *inode, void *opaque)
4854 struct btrfs_iget_args *args = opaque;
4855 return args->ino == btrfs_ino(inode) &&
4856 args->root == BTRFS_I(inode)->root;
4859 static struct inode *btrfs_iget_locked(struct super_block *s,
4861 struct btrfs_root *root)
4863 struct inode *inode;
4864 struct btrfs_iget_args args;
4865 args.ino = objectid;
4868 inode = iget5_locked(s, objectid, btrfs_find_actor,
4869 btrfs_init_locked_inode,
4874 /* Get an inode object given its location and corresponding root.
4875 * Returns in *is_new if the inode was read from disk
4877 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4878 struct btrfs_root *root, int *new)
4880 struct inode *inode;
4882 inode = btrfs_iget_locked(s, location->objectid, root);
4884 return ERR_PTR(-ENOMEM);
4886 if (inode->i_state & I_NEW) {
4887 BTRFS_I(inode)->root = root;
4888 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4889 btrfs_read_locked_inode(inode);
4890 if (!is_bad_inode(inode)) {
4891 inode_tree_add(inode);
4892 unlock_new_inode(inode);
4896 unlock_new_inode(inode);
4898 inode = ERR_PTR(-ESTALE);
4905 static struct inode *new_simple_dir(struct super_block *s,
4906 struct btrfs_key *key,
4907 struct btrfs_root *root)
4909 struct inode *inode = new_inode(s);
4912 return ERR_PTR(-ENOMEM);
4914 BTRFS_I(inode)->root = root;
4915 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4916 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4918 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4919 inode->i_op = &btrfs_dir_ro_inode_operations;
4920 inode->i_fop = &simple_dir_operations;
4921 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4922 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4927 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4929 struct inode *inode;
4930 struct btrfs_root *root = BTRFS_I(dir)->root;
4931 struct btrfs_root *sub_root = root;
4932 struct btrfs_key location;
4936 if (dentry->d_name.len > BTRFS_NAME_LEN)
4937 return ERR_PTR(-ENAMETOOLONG);
4939 ret = btrfs_inode_by_name(dir, dentry, &location);
4941 return ERR_PTR(ret);
4943 if (location.objectid == 0)
4946 if (location.type == BTRFS_INODE_ITEM_KEY) {
4947 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4951 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4953 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4954 ret = fixup_tree_root_location(root, dir, dentry,
4955 &location, &sub_root);
4958 inode = ERR_PTR(ret);
4960 inode = new_simple_dir(dir->i_sb, &location, sub_root);
4962 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4964 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4966 if (!IS_ERR(inode) && root != sub_root) {
4967 down_read(&root->fs_info->cleanup_work_sem);
4968 if (!(inode->i_sb->s_flags & MS_RDONLY))
4969 ret = btrfs_orphan_cleanup(sub_root);
4970 up_read(&root->fs_info->cleanup_work_sem);
4973 inode = ERR_PTR(ret);
4980 static int btrfs_dentry_delete(const struct dentry *dentry)
4982 struct btrfs_root *root;
4983 struct inode *inode = dentry->d_inode;
4985 if (!inode && !IS_ROOT(dentry))
4986 inode = dentry->d_parent->d_inode;
4989 root = BTRFS_I(inode)->root;
4990 if (btrfs_root_refs(&root->root_item) == 0)
4993 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
4999 static void btrfs_dentry_release(struct dentry *dentry)
5001 if (dentry->d_fsdata)
5002 kfree(dentry->d_fsdata);
5005 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5010 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
5014 unsigned char btrfs_filetype_table[] = {
5015 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5018 static int btrfs_real_readdir(struct file *filp, void *dirent,
5021 struct inode *inode = file_inode(filp);
5022 struct btrfs_root *root = BTRFS_I(inode)->root;
5023 struct btrfs_item *item;
5024 struct btrfs_dir_item *di;
5025 struct btrfs_key key;
5026 struct btrfs_key found_key;
5027 struct btrfs_path *path;
5028 struct list_head ins_list;
5029 struct list_head del_list;
5031 struct extent_buffer *leaf;
5033 unsigned char d_type;
5038 int key_type = BTRFS_DIR_INDEX_KEY;
5042 int is_curr = 0; /* filp->f_pos points to the current index? */
5044 /* FIXME, use a real flag for deciding about the key type */
5045 if (root->fs_info->tree_root == root)
5046 key_type = BTRFS_DIR_ITEM_KEY;
5048 /* special case for "." */
5049 if (filp->f_pos == 0) {
5050 over = filldir(dirent, ".", 1,
5051 filp->f_pos, btrfs_ino(inode), DT_DIR);
5056 /* special case for .., just use the back ref */
5057 if (filp->f_pos == 1) {
5058 u64 pino = parent_ino(filp->f_path.dentry);
5059 over = filldir(dirent, "..", 2,
5060 filp->f_pos, pino, DT_DIR);
5065 path = btrfs_alloc_path();
5071 if (key_type == BTRFS_DIR_INDEX_KEY) {
5072 INIT_LIST_HEAD(&ins_list);
5073 INIT_LIST_HEAD(&del_list);
5074 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5077 btrfs_set_key_type(&key, key_type);
5078 key.offset = filp->f_pos;
5079 key.objectid = btrfs_ino(inode);
5081 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5086 leaf = path->nodes[0];
5087 slot = path->slots[0];
5088 if (slot >= btrfs_header_nritems(leaf)) {
5089 ret = btrfs_next_leaf(root, path);
5097 item = btrfs_item_nr(leaf, slot);
5098 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5100 if (found_key.objectid != key.objectid)
5102 if (btrfs_key_type(&found_key) != key_type)
5104 if (found_key.offset < filp->f_pos)
5106 if (key_type == BTRFS_DIR_INDEX_KEY &&
5107 btrfs_should_delete_dir_index(&del_list,
5111 filp->f_pos = found_key.offset;
5114 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5116 di_total = btrfs_item_size(leaf, item);
5118 while (di_cur < di_total) {
5119 struct btrfs_key location;
5121 if (verify_dir_item(root, leaf, di))
5124 name_len = btrfs_dir_name_len(leaf, di);
5125 if (name_len <= sizeof(tmp_name)) {
5126 name_ptr = tmp_name;
5128 name_ptr = kmalloc(name_len, GFP_NOFS);
5134 read_extent_buffer(leaf, name_ptr,
5135 (unsigned long)(di + 1), name_len);
5137 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5138 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5141 /* is this a reference to our own snapshot? If so
5144 * In contrast to old kernels, we insert the snapshot's
5145 * dir item and dir index after it has been created, so
5146 * we won't find a reference to our own snapshot. We
5147 * still keep the following code for backward
5150 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5151 location.objectid == root->root_key.objectid) {
5155 over = filldir(dirent, name_ptr, name_len,
5156 found_key.offset, location.objectid,
5160 if (name_ptr != tmp_name)
5165 di_len = btrfs_dir_name_len(leaf, di) +
5166 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5168 di = (struct btrfs_dir_item *)((char *)di + di_len);
5174 if (key_type == BTRFS_DIR_INDEX_KEY) {
5177 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
5183 /* Reached end of directory/root. Bump pos past the last item. */
5184 if (key_type == BTRFS_DIR_INDEX_KEY)
5186 * 32-bit glibc will use getdents64, but then strtol -
5187 * so the last number we can serve is this.
5189 filp->f_pos = 0x7fffffff;
5195 if (key_type == BTRFS_DIR_INDEX_KEY)
5196 btrfs_put_delayed_items(&ins_list, &del_list);
5197 btrfs_free_path(path);
5201 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5203 struct btrfs_root *root = BTRFS_I(inode)->root;
5204 struct btrfs_trans_handle *trans;
5206 bool nolock = false;
5208 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5211 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5214 if (wbc->sync_mode == WB_SYNC_ALL) {
5216 trans = btrfs_join_transaction_nolock(root);
5218 trans = btrfs_join_transaction(root);
5220 return PTR_ERR(trans);
5221 ret = btrfs_commit_transaction(trans, root);
5227 * This is somewhat expensive, updating the tree every time the
5228 * inode changes. But, it is most likely to find the inode in cache.
5229 * FIXME, needs more benchmarking...there are no reasons other than performance
5230 * to keep or drop this code.
5232 static int btrfs_dirty_inode(struct inode *inode)
5234 struct btrfs_root *root = BTRFS_I(inode)->root;
5235 struct btrfs_trans_handle *trans;
5238 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5241 trans = btrfs_join_transaction(root);
5243 return PTR_ERR(trans);
5245 ret = btrfs_update_inode(trans, root, inode);
5246 if (ret && ret == -ENOSPC) {
5247 /* whoops, lets try again with the full transaction */
5248 btrfs_end_transaction(trans, root);
5249 trans = btrfs_start_transaction(root, 1);
5251 return PTR_ERR(trans);
5253 ret = btrfs_update_inode(trans, root, inode);
5255 btrfs_end_transaction(trans, root);
5256 if (BTRFS_I(inode)->delayed_node)
5257 btrfs_balance_delayed_items(root);
5263 * This is a copy of file_update_time. We need this so we can return error on
5264 * ENOSPC for updating the inode in the case of file write and mmap writes.
5266 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5269 struct btrfs_root *root = BTRFS_I(inode)->root;
5271 if (btrfs_root_readonly(root))
5274 if (flags & S_VERSION)
5275 inode_inc_iversion(inode);
5276 if (flags & S_CTIME)
5277 inode->i_ctime = *now;
5278 if (flags & S_MTIME)
5279 inode->i_mtime = *now;
5280 if (flags & S_ATIME)
5281 inode->i_atime = *now;
5282 return btrfs_dirty_inode(inode);
5286 * find the highest existing sequence number in a directory
5287 * and then set the in-memory index_cnt variable to reflect
5288 * free sequence numbers
5290 static int btrfs_set_inode_index_count(struct inode *inode)
5292 struct btrfs_root *root = BTRFS_I(inode)->root;
5293 struct btrfs_key key, found_key;
5294 struct btrfs_path *path;
5295 struct extent_buffer *leaf;
5298 key.objectid = btrfs_ino(inode);
5299 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5300 key.offset = (u64)-1;
5302 path = btrfs_alloc_path();
5306 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5309 /* FIXME: we should be able to handle this */
5315 * MAGIC NUMBER EXPLANATION:
5316 * since we search a directory based on f_pos we have to start at 2
5317 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5318 * else has to start at 2
5320 if (path->slots[0] == 0) {
5321 BTRFS_I(inode)->index_cnt = 2;
5327 leaf = path->nodes[0];
5328 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5330 if (found_key.objectid != btrfs_ino(inode) ||
5331 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5332 BTRFS_I(inode)->index_cnt = 2;
5336 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5338 btrfs_free_path(path);
5343 * helper to find a free sequence number in a given directory. This current
5344 * code is very simple, later versions will do smarter things in the btree
5346 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5350 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5351 ret = btrfs_inode_delayed_dir_index_count(dir);
5353 ret = btrfs_set_inode_index_count(dir);
5359 *index = BTRFS_I(dir)->index_cnt;
5360 BTRFS_I(dir)->index_cnt++;
5365 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5366 struct btrfs_root *root,
5368 const char *name, int name_len,
5369 u64 ref_objectid, u64 objectid,
5370 umode_t mode, u64 *index)
5372 struct inode *inode;
5373 struct btrfs_inode_item *inode_item;
5374 struct btrfs_key *location;
5375 struct btrfs_path *path;
5376 struct btrfs_inode_ref *ref;
5377 struct btrfs_key key[2];
5383 path = btrfs_alloc_path();
5385 return ERR_PTR(-ENOMEM);
5387 inode = new_inode(root->fs_info->sb);
5389 btrfs_free_path(path);
5390 return ERR_PTR(-ENOMEM);
5394 * we have to initialize this early, so we can reclaim the inode
5395 * number if we fail afterwards in this function.
5397 inode->i_ino = objectid;
5400 trace_btrfs_inode_request(dir);
5402 ret = btrfs_set_inode_index(dir, index);
5404 btrfs_free_path(path);
5406 return ERR_PTR(ret);
5410 * index_cnt is ignored for everything but a dir,
5411 * btrfs_get_inode_index_count has an explanation for the magic
5414 BTRFS_I(inode)->index_cnt = 2;
5415 BTRFS_I(inode)->root = root;
5416 BTRFS_I(inode)->generation = trans->transid;
5417 inode->i_generation = BTRFS_I(inode)->generation;
5420 * We could have gotten an inode number from somebody who was fsynced
5421 * and then removed in this same transaction, so let's just set full
5422 * sync since it will be a full sync anyway and this will blow away the
5423 * old info in the log.
5425 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5432 key[0].objectid = objectid;
5433 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5437 * Start new inodes with an inode_ref. This is slightly more
5438 * efficient for small numbers of hard links since they will
5439 * be packed into one item. Extended refs will kick in if we
5440 * add more hard links than can fit in the ref item.
5442 key[1].objectid = objectid;
5443 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5444 key[1].offset = ref_objectid;
5446 sizes[0] = sizeof(struct btrfs_inode_item);
5447 sizes[1] = name_len + sizeof(*ref);
5449 path->leave_spinning = 1;
5450 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
5454 inode_init_owner(inode, dir, mode);
5455 inode_set_bytes(inode, 0);
5456 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5457 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5458 struct btrfs_inode_item);
5459 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5460 sizeof(*inode_item));
5461 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5463 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5464 struct btrfs_inode_ref);
5465 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5466 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5467 ptr = (unsigned long)(ref + 1);
5468 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5470 btrfs_mark_buffer_dirty(path->nodes[0]);
5471 btrfs_free_path(path);
5473 location = &BTRFS_I(inode)->location;
5474 location->objectid = objectid;
5475 location->offset = 0;
5476 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5478 btrfs_inherit_iflags(inode, dir);
5480 if (S_ISREG(mode)) {
5481 if (btrfs_test_opt(root, NODATASUM))
5482 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5483 if (btrfs_test_opt(root, NODATACOW))
5484 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5485 BTRFS_INODE_NODATASUM;
5488 insert_inode_hash(inode);
5489 inode_tree_add(inode);
5491 trace_btrfs_inode_new(inode);
5492 btrfs_set_inode_last_trans(trans, inode);
5494 btrfs_update_root_times(trans, root);
5499 BTRFS_I(dir)->index_cnt--;
5500 btrfs_free_path(path);
5502 return ERR_PTR(ret);
5505 static inline u8 btrfs_inode_type(struct inode *inode)
5507 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5511 * utility function to add 'inode' into 'parent_inode' with
5512 * a give name and a given sequence number.
5513 * if 'add_backref' is true, also insert a backref from the
5514 * inode to the parent directory.
5516 int btrfs_add_link(struct btrfs_trans_handle *trans,
5517 struct inode *parent_inode, struct inode *inode,
5518 const char *name, int name_len, int add_backref, u64 index)
5521 struct btrfs_key key;
5522 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5523 u64 ino = btrfs_ino(inode);
5524 u64 parent_ino = btrfs_ino(parent_inode);
5526 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5527 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5530 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5534 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5535 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5536 key.objectid, root->root_key.objectid,
5537 parent_ino, index, name, name_len);
5538 } else if (add_backref) {
5539 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5543 /* Nothing to clean up yet */
5547 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5549 btrfs_inode_type(inode), index);
5550 if (ret == -EEXIST || ret == -EOVERFLOW)
5553 btrfs_abort_transaction(trans, root, ret);
5557 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5559 inode_inc_iversion(parent_inode);
5560 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5561 ret = btrfs_update_inode(trans, root, parent_inode);
5563 btrfs_abort_transaction(trans, root, ret);
5567 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5570 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5571 key.objectid, root->root_key.objectid,
5572 parent_ino, &local_index, name, name_len);
5574 } else if (add_backref) {
5578 err = btrfs_del_inode_ref(trans, root, name, name_len,
5579 ino, parent_ino, &local_index);
5584 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5585 struct inode *dir, struct dentry *dentry,
5586 struct inode *inode, int backref, u64 index)
5588 int err = btrfs_add_link(trans, dir, inode,
5589 dentry->d_name.name, dentry->d_name.len,
5596 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5597 umode_t mode, dev_t rdev)
5599 struct btrfs_trans_handle *trans;
5600 struct btrfs_root *root = BTRFS_I(dir)->root;
5601 struct inode *inode = NULL;
5607 if (!new_valid_dev(rdev))
5611 * 2 for inode item and ref
5613 * 1 for xattr if selinux is on
5615 trans = btrfs_start_transaction(root, 5);
5617 return PTR_ERR(trans);
5619 err = btrfs_find_free_ino(root, &objectid);
5623 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5624 dentry->d_name.len, btrfs_ino(dir), objectid,
5626 if (IS_ERR(inode)) {
5627 err = PTR_ERR(inode);
5631 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5638 * If the active LSM wants to access the inode during
5639 * d_instantiate it needs these. Smack checks to see
5640 * if the filesystem supports xattrs by looking at the
5644 inode->i_op = &btrfs_special_inode_operations;
5645 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5649 init_special_inode(inode, inode->i_mode, rdev);
5650 btrfs_update_inode(trans, root, inode);
5651 d_instantiate(dentry, inode);
5654 btrfs_end_transaction(trans, root);
5655 btrfs_btree_balance_dirty(root);
5657 inode_dec_link_count(inode);
5663 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5664 umode_t mode, bool excl)
5666 struct btrfs_trans_handle *trans;
5667 struct btrfs_root *root = BTRFS_I(dir)->root;
5668 struct inode *inode = NULL;
5669 int drop_inode_on_err = 0;
5675 * 2 for inode item and ref
5677 * 1 for xattr if selinux is on
5679 trans = btrfs_start_transaction(root, 5);
5681 return PTR_ERR(trans);
5683 err = btrfs_find_free_ino(root, &objectid);
5687 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5688 dentry->d_name.len, btrfs_ino(dir), objectid,
5690 if (IS_ERR(inode)) {
5691 err = PTR_ERR(inode);
5694 drop_inode_on_err = 1;
5696 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5700 err = btrfs_update_inode(trans, root, inode);
5705 * If the active LSM wants to access the inode during
5706 * d_instantiate it needs these. Smack checks to see
5707 * if the filesystem supports xattrs by looking at the
5710 inode->i_fop = &btrfs_file_operations;
5711 inode->i_op = &btrfs_file_inode_operations;
5713 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5717 inode->i_mapping->a_ops = &btrfs_aops;
5718 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5719 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5720 d_instantiate(dentry, inode);
5723 btrfs_end_transaction(trans, root);
5724 if (err && drop_inode_on_err) {
5725 inode_dec_link_count(inode);
5728 btrfs_btree_balance_dirty(root);
5732 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5733 struct dentry *dentry)
5735 struct btrfs_trans_handle *trans;
5736 struct btrfs_root *root = BTRFS_I(dir)->root;
5737 struct inode *inode = old_dentry->d_inode;
5742 /* do not allow sys_link's with other subvols of the same device */
5743 if (root->objectid != BTRFS_I(inode)->root->objectid)
5746 if (inode->i_nlink >= BTRFS_LINK_MAX)
5749 err = btrfs_set_inode_index(dir, &index);
5754 * 2 items for inode and inode ref
5755 * 2 items for dir items
5756 * 1 item for parent inode
5758 trans = btrfs_start_transaction(root, 5);
5759 if (IS_ERR(trans)) {
5760 err = PTR_ERR(trans);
5764 btrfs_inc_nlink(inode);
5765 inode_inc_iversion(inode);
5766 inode->i_ctime = CURRENT_TIME;
5768 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5770 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5775 struct dentry *parent = dentry->d_parent;
5776 err = btrfs_update_inode(trans, root, inode);
5779 d_instantiate(dentry, inode);
5780 btrfs_log_new_name(trans, inode, NULL, parent);
5783 btrfs_end_transaction(trans, root);
5786 inode_dec_link_count(inode);
5789 btrfs_btree_balance_dirty(root);
5793 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5795 struct inode *inode = NULL;
5796 struct btrfs_trans_handle *trans;
5797 struct btrfs_root *root = BTRFS_I(dir)->root;
5799 int drop_on_err = 0;
5804 * 2 items for inode and ref
5805 * 2 items for dir items
5806 * 1 for xattr if selinux is on
5808 trans = btrfs_start_transaction(root, 5);
5810 return PTR_ERR(trans);
5812 err = btrfs_find_free_ino(root, &objectid);
5816 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5817 dentry->d_name.len, btrfs_ino(dir), objectid,
5818 S_IFDIR | mode, &index);
5819 if (IS_ERR(inode)) {
5820 err = PTR_ERR(inode);
5826 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5830 inode->i_op = &btrfs_dir_inode_operations;
5831 inode->i_fop = &btrfs_dir_file_operations;
5833 btrfs_i_size_write(inode, 0);
5834 err = btrfs_update_inode(trans, root, inode);
5838 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5839 dentry->d_name.len, 0, index);
5843 d_instantiate(dentry, inode);
5847 btrfs_end_transaction(trans, root);
5850 btrfs_btree_balance_dirty(root);
5854 /* helper for btfs_get_extent. Given an existing extent in the tree,
5855 * and an extent that you want to insert, deal with overlap and insert
5856 * the new extent into the tree.
5858 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5859 struct extent_map *existing,
5860 struct extent_map *em,
5861 u64 map_start, u64 map_len)
5865 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5866 start_diff = map_start - em->start;
5867 em->start = map_start;
5869 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5870 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5871 em->block_start += start_diff;
5872 em->block_len -= start_diff;
5874 return add_extent_mapping(em_tree, em, 0);
5877 static noinline int uncompress_inline(struct btrfs_path *path,
5878 struct inode *inode, struct page *page,
5879 size_t pg_offset, u64 extent_offset,
5880 struct btrfs_file_extent_item *item)
5883 struct extent_buffer *leaf = path->nodes[0];
5886 unsigned long inline_size;
5890 WARN_ON(pg_offset != 0);
5891 compress_type = btrfs_file_extent_compression(leaf, item);
5892 max_size = btrfs_file_extent_ram_bytes(leaf, item);
5893 inline_size = btrfs_file_extent_inline_item_len(leaf,
5894 btrfs_item_nr(leaf, path->slots[0]));
5895 tmp = kmalloc(inline_size, GFP_NOFS);
5898 ptr = btrfs_file_extent_inline_start(item);
5900 read_extent_buffer(leaf, tmp, ptr, inline_size);
5902 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
5903 ret = btrfs_decompress(compress_type, tmp, page,
5904 extent_offset, inline_size, max_size);
5906 char *kaddr = kmap_atomic(page);
5907 unsigned long copy_size = min_t(u64,
5908 PAGE_CACHE_SIZE - pg_offset,
5909 max_size - extent_offset);
5910 memset(kaddr + pg_offset, 0, copy_size);
5911 kunmap_atomic(kaddr);
5918 * a bit scary, this does extent mapping from logical file offset to the disk.
5919 * the ugly parts come from merging extents from the disk with the in-ram
5920 * representation. This gets more complex because of the data=ordered code,
5921 * where the in-ram extents might be locked pending data=ordered completion.
5923 * This also copies inline extents directly into the page.
5926 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
5927 size_t pg_offset, u64 start, u64 len,
5933 u64 extent_start = 0;
5935 u64 objectid = btrfs_ino(inode);
5937 struct btrfs_path *path = NULL;
5938 struct btrfs_root *root = BTRFS_I(inode)->root;
5939 struct btrfs_file_extent_item *item;
5940 struct extent_buffer *leaf;
5941 struct btrfs_key found_key;
5942 struct extent_map *em = NULL;
5943 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5944 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5945 struct btrfs_trans_handle *trans = NULL;
5949 read_lock(&em_tree->lock);
5950 em = lookup_extent_mapping(em_tree, start, len);
5952 em->bdev = root->fs_info->fs_devices->latest_bdev;
5953 read_unlock(&em_tree->lock);
5956 if (em->start > start || em->start + em->len <= start)
5957 free_extent_map(em);
5958 else if (em->block_start == EXTENT_MAP_INLINE && page)
5959 free_extent_map(em);
5963 em = alloc_extent_map();
5968 em->bdev = root->fs_info->fs_devices->latest_bdev;
5969 em->start = EXTENT_MAP_HOLE;
5970 em->orig_start = EXTENT_MAP_HOLE;
5972 em->block_len = (u64)-1;
5975 path = btrfs_alloc_path();
5981 * Chances are we'll be called again, so go ahead and do
5987 ret = btrfs_lookup_file_extent(trans, root, path,
5988 objectid, start, trans != NULL);
5995 if (path->slots[0] == 0)
6000 leaf = path->nodes[0];
6001 item = btrfs_item_ptr(leaf, path->slots[0],
6002 struct btrfs_file_extent_item);
6003 /* are we inside the extent that was found? */
6004 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6005 found_type = btrfs_key_type(&found_key);
6006 if (found_key.objectid != objectid ||
6007 found_type != BTRFS_EXTENT_DATA_KEY) {
6011 found_type = btrfs_file_extent_type(leaf, item);
6012 extent_start = found_key.offset;
6013 compress_type = btrfs_file_extent_compression(leaf, item);
6014 if (found_type == BTRFS_FILE_EXTENT_REG ||
6015 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6016 extent_end = extent_start +
6017 btrfs_file_extent_num_bytes(leaf, item);
6018 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6020 size = btrfs_file_extent_inline_len(leaf, item);
6021 extent_end = ALIGN(extent_start + size, root->sectorsize);
6024 if (start >= extent_end) {
6026 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6027 ret = btrfs_next_leaf(root, path);
6034 leaf = path->nodes[0];
6036 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6037 if (found_key.objectid != objectid ||
6038 found_key.type != BTRFS_EXTENT_DATA_KEY)
6040 if (start + len <= found_key.offset)
6043 em->orig_start = start;
6044 em->len = found_key.offset - start;
6048 em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
6049 if (found_type == BTRFS_FILE_EXTENT_REG ||
6050 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6051 em->start = extent_start;
6052 em->len = extent_end - extent_start;
6053 em->orig_start = extent_start -
6054 btrfs_file_extent_offset(leaf, item);
6055 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6057 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6059 em->block_start = EXTENT_MAP_HOLE;
6062 if (compress_type != BTRFS_COMPRESS_NONE) {
6063 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6064 em->compress_type = compress_type;
6065 em->block_start = bytenr;
6066 em->block_len = em->orig_block_len;
6068 bytenr += btrfs_file_extent_offset(leaf, item);
6069 em->block_start = bytenr;
6070 em->block_len = em->len;
6071 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6072 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6075 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6079 size_t extent_offset;
6082 em->block_start = EXTENT_MAP_INLINE;
6083 if (!page || create) {
6084 em->start = extent_start;
6085 em->len = extent_end - extent_start;
6089 size = btrfs_file_extent_inline_len(leaf, item);
6090 extent_offset = page_offset(page) + pg_offset - extent_start;
6091 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6092 size - extent_offset);
6093 em->start = extent_start + extent_offset;
6094 em->len = ALIGN(copy_size, root->sectorsize);
6095 em->orig_block_len = em->len;
6096 em->orig_start = em->start;
6097 if (compress_type) {
6098 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6099 em->compress_type = compress_type;
6101 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6102 if (create == 0 && !PageUptodate(page)) {
6103 if (btrfs_file_extent_compression(leaf, item) !=
6104 BTRFS_COMPRESS_NONE) {
6105 ret = uncompress_inline(path, inode, page,
6107 extent_offset, item);
6108 BUG_ON(ret); /* -ENOMEM */
6111 read_extent_buffer(leaf, map + pg_offset, ptr,
6113 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6114 memset(map + pg_offset + copy_size, 0,
6115 PAGE_CACHE_SIZE - pg_offset -
6120 flush_dcache_page(page);
6121 } else if (create && PageUptodate(page)) {
6125 free_extent_map(em);
6128 btrfs_release_path(path);
6129 trans = btrfs_join_transaction(root);
6132 return ERR_CAST(trans);
6136 write_extent_buffer(leaf, map + pg_offset, ptr,
6139 btrfs_mark_buffer_dirty(leaf);
6141 set_extent_uptodate(io_tree, em->start,
6142 extent_map_end(em) - 1, NULL, GFP_NOFS);
6145 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6149 em->orig_start = start;
6152 em->block_start = EXTENT_MAP_HOLE;
6153 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6155 btrfs_release_path(path);
6156 if (em->start > start || extent_map_end(em) <= start) {
6157 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6158 (unsigned long long)em->start,
6159 (unsigned long long)em->len,
6160 (unsigned long long)start,
6161 (unsigned long long)len);
6167 write_lock(&em_tree->lock);
6168 ret = add_extent_mapping(em_tree, em, 0);
6169 /* it is possible that someone inserted the extent into the tree
6170 * while we had the lock dropped. It is also possible that
6171 * an overlapping map exists in the tree
6173 if (ret == -EEXIST) {
6174 struct extent_map *existing;
6178 existing = lookup_extent_mapping(em_tree, start, len);
6179 if (existing && (existing->start > start ||
6180 existing->start + existing->len <= start)) {
6181 free_extent_map(existing);
6185 existing = lookup_extent_mapping(em_tree, em->start,
6188 err = merge_extent_mapping(em_tree, existing,
6191 free_extent_map(existing);
6193 free_extent_map(em);
6198 free_extent_map(em);
6202 free_extent_map(em);
6207 write_unlock(&em_tree->lock);
6211 trace_btrfs_get_extent(root, em);
6214 btrfs_free_path(path);
6216 ret = btrfs_end_transaction(trans, root);
6221 free_extent_map(em);
6222 return ERR_PTR(err);
6224 BUG_ON(!em); /* Error is always set */
6228 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6229 size_t pg_offset, u64 start, u64 len,
6232 struct extent_map *em;
6233 struct extent_map *hole_em = NULL;
6234 u64 range_start = start;
6240 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6247 * - a pre-alloc extent,
6248 * there might actually be delalloc bytes behind it.
6250 if (em->block_start != EXTENT_MAP_HOLE &&
6251 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6257 /* check to see if we've wrapped (len == -1 or similar) */
6266 /* ok, we didn't find anything, lets look for delalloc */
6267 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6268 end, len, EXTENT_DELALLOC, 1);
6269 found_end = range_start + found;
6270 if (found_end < range_start)
6271 found_end = (u64)-1;
6274 * we didn't find anything useful, return
6275 * the original results from get_extent()
6277 if (range_start > end || found_end <= start) {
6283 /* adjust the range_start to make sure it doesn't
6284 * go backwards from the start they passed in
6286 range_start = max(start,range_start);
6287 found = found_end - range_start;
6290 u64 hole_start = start;
6293 em = alloc_extent_map();
6299 * when btrfs_get_extent can't find anything it
6300 * returns one huge hole
6302 * make sure what it found really fits our range, and
6303 * adjust to make sure it is based on the start from
6307 u64 calc_end = extent_map_end(hole_em);
6309 if (calc_end <= start || (hole_em->start > end)) {
6310 free_extent_map(hole_em);
6313 hole_start = max(hole_em->start, start);
6314 hole_len = calc_end - hole_start;
6318 if (hole_em && range_start > hole_start) {
6319 /* our hole starts before our delalloc, so we
6320 * have to return just the parts of the hole
6321 * that go until the delalloc starts
6323 em->len = min(hole_len,
6324 range_start - hole_start);
6325 em->start = hole_start;
6326 em->orig_start = hole_start;
6328 * don't adjust block start at all,
6329 * it is fixed at EXTENT_MAP_HOLE
6331 em->block_start = hole_em->block_start;
6332 em->block_len = hole_len;
6333 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6334 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6336 em->start = range_start;
6338 em->orig_start = range_start;
6339 em->block_start = EXTENT_MAP_DELALLOC;
6340 em->block_len = found;
6342 } else if (hole_em) {
6347 free_extent_map(hole_em);
6349 free_extent_map(em);
6350 return ERR_PTR(err);
6355 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6358 struct btrfs_root *root = BTRFS_I(inode)->root;
6359 struct btrfs_trans_handle *trans;
6360 struct extent_map *em;
6361 struct btrfs_key ins;
6365 trans = btrfs_join_transaction(root);
6367 return ERR_CAST(trans);
6369 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
6371 alloc_hint = get_extent_allocation_hint(inode, start, len);
6372 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
6373 alloc_hint, &ins, 1);
6379 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6380 ins.offset, ins.offset, ins.offset, 0);
6384 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6385 ins.offset, ins.offset, 0);
6387 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6391 btrfs_end_transaction(trans, root);
6396 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6397 * block must be cow'd
6399 noinline int can_nocow_extent(struct btrfs_trans_handle *trans,
6400 struct inode *inode, u64 offset, u64 *len,
6401 u64 *orig_start, u64 *orig_block_len,
6404 struct btrfs_path *path;
6406 struct extent_buffer *leaf;
6407 struct btrfs_root *root = BTRFS_I(inode)->root;
6408 struct btrfs_file_extent_item *fi;
6409 struct btrfs_key key;
6416 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6417 path = btrfs_alloc_path();
6421 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
6426 slot = path->slots[0];
6429 /* can't find the item, must cow */
6436 leaf = path->nodes[0];
6437 btrfs_item_key_to_cpu(leaf, &key, slot);
6438 if (key.objectid != btrfs_ino(inode) ||
6439 key.type != BTRFS_EXTENT_DATA_KEY) {
6440 /* not our file or wrong item type, must cow */
6444 if (key.offset > offset) {
6445 /* Wrong offset, must cow */
6449 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6450 found_type = btrfs_file_extent_type(leaf, fi);
6451 if (found_type != BTRFS_FILE_EXTENT_REG &&
6452 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6453 /* not a regular extent, must cow */
6457 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6460 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6461 if (disk_bytenr == 0)
6464 if (btrfs_file_extent_compression(leaf, fi) ||
6465 btrfs_file_extent_encryption(leaf, fi) ||
6466 btrfs_file_extent_other_encoding(leaf, fi))
6469 backref_offset = btrfs_file_extent_offset(leaf, fi);
6472 *orig_start = key.offset - backref_offset;
6473 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6474 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6477 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6479 if (btrfs_extent_readonly(root, disk_bytenr))
6483 * look for other files referencing this extent, if we
6484 * find any we must cow
6486 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6487 key.offset - backref_offset, disk_bytenr))
6491 * adjust disk_bytenr and num_bytes to cover just the bytes
6492 * in this extent we are about to write. If there
6493 * are any csums in that range we have to cow in order
6494 * to keep the csums correct
6496 disk_bytenr += backref_offset;
6497 disk_bytenr += offset - key.offset;
6498 num_bytes = min(offset + *len, extent_end) - offset;
6499 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6502 * all of the above have passed, it is safe to overwrite this extent
6508 btrfs_free_path(path);
6512 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6513 struct extent_state **cached_state, int writing)
6515 struct btrfs_ordered_extent *ordered;
6519 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6522 * We're concerned with the entire range that we're going to be
6523 * doing DIO to, so we need to make sure theres no ordered
6524 * extents in this range.
6526 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6527 lockend - lockstart + 1);
6530 * We need to make sure there are no buffered pages in this
6531 * range either, we could have raced between the invalidate in
6532 * generic_file_direct_write and locking the extent. The
6533 * invalidate needs to happen so that reads after a write do not
6536 if (!ordered && (!writing ||
6537 !test_range_bit(&BTRFS_I(inode)->io_tree,
6538 lockstart, lockend, EXTENT_UPTODATE, 0,
6542 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6543 cached_state, GFP_NOFS);
6546 btrfs_start_ordered_extent(inode, ordered, 1);
6547 btrfs_put_ordered_extent(ordered);
6549 /* Screw you mmap */
6550 ret = filemap_write_and_wait_range(inode->i_mapping,
6557 * If we found a page that couldn't be invalidated just
6558 * fall back to buffered.
6560 ret = invalidate_inode_pages2_range(inode->i_mapping,
6561 lockstart >> PAGE_CACHE_SHIFT,
6562 lockend >> PAGE_CACHE_SHIFT);
6573 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6574 u64 len, u64 orig_start,
6575 u64 block_start, u64 block_len,
6576 u64 orig_block_len, u64 ram_bytes,
6579 struct extent_map_tree *em_tree;
6580 struct extent_map *em;
6581 struct btrfs_root *root = BTRFS_I(inode)->root;
6584 em_tree = &BTRFS_I(inode)->extent_tree;
6585 em = alloc_extent_map();
6587 return ERR_PTR(-ENOMEM);
6590 em->orig_start = orig_start;
6591 em->mod_start = start;
6594 em->block_len = block_len;
6595 em->block_start = block_start;
6596 em->bdev = root->fs_info->fs_devices->latest_bdev;
6597 em->orig_block_len = orig_block_len;
6598 em->ram_bytes = ram_bytes;
6599 em->generation = -1;
6600 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6601 if (type == BTRFS_ORDERED_PREALLOC)
6602 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6605 btrfs_drop_extent_cache(inode, em->start,
6606 em->start + em->len - 1, 0);
6607 write_lock(&em_tree->lock);
6608 ret = add_extent_mapping(em_tree, em, 1);
6609 write_unlock(&em_tree->lock);
6610 } while (ret == -EEXIST);
6613 free_extent_map(em);
6614 return ERR_PTR(ret);
6621 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6622 struct buffer_head *bh_result, int create)
6624 struct extent_map *em;
6625 struct btrfs_root *root = BTRFS_I(inode)->root;
6626 struct extent_state *cached_state = NULL;
6627 u64 start = iblock << inode->i_blkbits;
6628 u64 lockstart, lockend;
6629 u64 len = bh_result->b_size;
6630 struct btrfs_trans_handle *trans;
6631 int unlock_bits = EXTENT_LOCKED;
6635 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6637 len = min_t(u64, len, root->sectorsize);
6640 lockend = start + len - 1;
6643 * If this errors out it's because we couldn't invalidate pagecache for
6644 * this range and we need to fallback to buffered.
6646 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6649 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6656 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6657 * io. INLINE is special, and we could probably kludge it in here, but
6658 * it's still buffered so for safety lets just fall back to the generic
6661 * For COMPRESSED we _have_ to read the entire extent in so we can
6662 * decompress it, so there will be buffering required no matter what we
6663 * do, so go ahead and fallback to buffered.
6665 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6666 * to buffered IO. Don't blame me, this is the price we pay for using
6669 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6670 em->block_start == EXTENT_MAP_INLINE) {
6671 free_extent_map(em);
6676 /* Just a good old fashioned hole, return */
6677 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6678 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6679 free_extent_map(em);
6684 * We don't allocate a new extent in the following cases
6686 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6688 * 2) The extent is marked as PREALLOC. We're good to go here and can
6689 * just use the extent.
6693 len = min(len, em->len - (start - em->start));
6694 lockstart = start + len;
6698 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6699 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6700 em->block_start != EXTENT_MAP_HOLE)) {
6703 u64 block_start, orig_start, orig_block_len, ram_bytes;
6705 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6706 type = BTRFS_ORDERED_PREALLOC;
6708 type = BTRFS_ORDERED_NOCOW;
6709 len = min(len, em->len - (start - em->start));
6710 block_start = em->block_start + (start - em->start);
6713 * we're not going to log anything, but we do need
6714 * to make sure the current transaction stays open
6715 * while we look for nocow cross refs
6717 trans = btrfs_join_transaction(root);
6721 if (can_nocow_extent(trans, inode, start, &len, &orig_start,
6722 &orig_block_len, &ram_bytes) == 1) {
6723 if (type == BTRFS_ORDERED_PREALLOC) {
6724 free_extent_map(em);
6725 em = create_pinned_em(inode, start, len,
6731 btrfs_end_transaction(trans, root);
6736 ret = btrfs_add_ordered_extent_dio(inode, start,
6737 block_start, len, len, type);
6738 btrfs_end_transaction(trans, root);
6740 free_extent_map(em);
6745 btrfs_end_transaction(trans, root);
6749 * this will cow the extent, reset the len in case we changed
6752 len = bh_result->b_size;
6753 free_extent_map(em);
6754 em = btrfs_new_extent_direct(inode, start, len);
6759 len = min(len, em->len - (start - em->start));
6761 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6763 bh_result->b_size = len;
6764 bh_result->b_bdev = em->bdev;
6765 set_buffer_mapped(bh_result);
6767 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6768 set_buffer_new(bh_result);
6771 * Need to update the i_size under the extent lock so buffered
6772 * readers will get the updated i_size when we unlock.
6774 if (start + len > i_size_read(inode))
6775 i_size_write(inode, start + len);
6777 spin_lock(&BTRFS_I(inode)->lock);
6778 BTRFS_I(inode)->outstanding_extents++;
6779 spin_unlock(&BTRFS_I(inode)->lock);
6781 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6782 lockstart + len - 1, EXTENT_DELALLOC, NULL,
6783 &cached_state, GFP_NOFS);
6788 * In the case of write we need to clear and unlock the entire range,
6789 * in the case of read we need to unlock only the end area that we
6790 * aren't using if there is any left over space.
6792 if (lockstart < lockend) {
6793 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6794 lockend, unlock_bits, 1, 0,
6795 &cached_state, GFP_NOFS);
6797 free_extent_state(cached_state);
6800 free_extent_map(em);
6805 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6806 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6810 struct btrfs_dio_private {
6811 struct inode *inode;
6817 /* number of bios pending for this dio */
6818 atomic_t pending_bios;
6823 /* orig_bio is our btrfs_io_bio */
6824 struct bio *orig_bio;
6826 /* dio_bio came from fs/direct-io.c */
6827 struct bio *dio_bio;
6830 static void btrfs_endio_direct_read(struct bio *bio, int err)
6832 struct btrfs_dio_private *dip = bio->bi_private;
6833 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6834 struct bio_vec *bvec = bio->bi_io_vec;
6835 struct inode *inode = dip->inode;
6836 struct btrfs_root *root = BTRFS_I(inode)->root;
6837 struct bio *dio_bio;
6840 start = dip->logical_offset;
6842 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6843 struct page *page = bvec->bv_page;
6846 u64 private = ~(u32)0;
6847 unsigned long flags;
6849 if (get_state_private(&BTRFS_I(inode)->io_tree,
6852 local_irq_save(flags);
6853 kaddr = kmap_atomic(page);
6854 csum = btrfs_csum_data(kaddr + bvec->bv_offset,
6855 csum, bvec->bv_len);
6856 btrfs_csum_final(csum, (char *)&csum);
6857 kunmap_atomic(kaddr);
6858 local_irq_restore(flags);
6860 flush_dcache_page(bvec->bv_page);
6861 if (csum != private) {
6863 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u private %u",
6864 (unsigned long long)btrfs_ino(inode),
6865 (unsigned long long)start,
6866 csum, (unsigned)private);
6871 start += bvec->bv_len;
6873 } while (bvec <= bvec_end);
6875 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6876 dip->logical_offset + dip->bytes - 1);
6877 dio_bio = dip->dio_bio;
6881 /* If we had a csum failure make sure to clear the uptodate flag */
6883 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
6884 dio_end_io(dio_bio, err);
6888 static void btrfs_endio_direct_write(struct bio *bio, int err)
6890 struct btrfs_dio_private *dip = bio->bi_private;
6891 struct inode *inode = dip->inode;
6892 struct btrfs_root *root = BTRFS_I(inode)->root;
6893 struct btrfs_ordered_extent *ordered = NULL;
6894 u64 ordered_offset = dip->logical_offset;
6895 u64 ordered_bytes = dip->bytes;
6896 struct bio *dio_bio;
6902 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
6904 ordered_bytes, !err);
6908 ordered->work.func = finish_ordered_fn;
6909 ordered->work.flags = 0;
6910 btrfs_queue_worker(&root->fs_info->endio_write_workers,
6914 * our bio might span multiple ordered extents. If we haven't
6915 * completed the accounting for the whole dio, go back and try again
6917 if (ordered_offset < dip->logical_offset + dip->bytes) {
6918 ordered_bytes = dip->logical_offset + dip->bytes -
6924 dio_bio = dip->dio_bio;
6928 /* If we had an error make sure to clear the uptodate flag */
6930 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
6931 dio_end_io(dio_bio, err);
6935 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
6936 struct bio *bio, int mirror_num,
6937 unsigned long bio_flags, u64 offset)
6940 struct btrfs_root *root = BTRFS_I(inode)->root;
6941 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
6942 BUG_ON(ret); /* -ENOMEM */
6946 static void btrfs_end_dio_bio(struct bio *bio, int err)
6948 struct btrfs_dio_private *dip = bio->bi_private;
6951 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
6952 "sector %#Lx len %u err no %d\n",
6953 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
6954 (unsigned long long)bio->bi_sector, bio->bi_size, err);
6958 * before atomic variable goto zero, we must make sure
6959 * dip->errors is perceived to be set.
6961 smp_mb__before_atomic_dec();
6964 /* if there are more bios still pending for this dio, just exit */
6965 if (!atomic_dec_and_test(&dip->pending_bios))
6969 bio_io_error(dip->orig_bio);
6971 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
6972 bio_endio(dip->orig_bio, 0);
6978 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
6979 u64 first_sector, gfp_t gfp_flags)
6981 int nr_vecs = bio_get_nr_vecs(bdev);
6982 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
6985 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
6986 int rw, u64 file_offset, int skip_sum,
6989 int write = rw & REQ_WRITE;
6990 struct btrfs_root *root = BTRFS_I(inode)->root;
6994 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
6999 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
7007 if (write && async_submit) {
7008 ret = btrfs_wq_submit_bio(root->fs_info,
7009 inode, rw, bio, 0, 0,
7011 __btrfs_submit_bio_start_direct_io,
7012 __btrfs_submit_bio_done);
7016 * If we aren't doing async submit, calculate the csum of the
7019 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7022 } else if (!skip_sum) {
7023 ret = btrfs_lookup_bio_sums_dio(root, inode, bio, file_offset);
7029 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7035 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7038 struct inode *inode = dip->inode;
7039 struct btrfs_root *root = BTRFS_I(inode)->root;
7041 struct bio *orig_bio = dip->orig_bio;
7042 struct bio_vec *bvec = orig_bio->bi_io_vec;
7043 u64 start_sector = orig_bio->bi_sector;
7044 u64 file_offset = dip->logical_offset;
7049 int async_submit = 0;
7051 map_length = orig_bio->bi_size;
7052 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7053 &map_length, NULL, 0);
7058 if (map_length >= orig_bio->bi_size) {
7063 /* async crcs make it difficult to collect full stripe writes. */
7064 if (btrfs_get_alloc_profile(root, 1) &
7065 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7070 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7073 bio->bi_private = dip;
7074 bio->bi_end_io = btrfs_end_dio_bio;
7075 atomic_inc(&dip->pending_bios);
7077 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7078 if (unlikely(map_length < submit_len + bvec->bv_len ||
7079 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7080 bvec->bv_offset) < bvec->bv_len)) {
7082 * inc the count before we submit the bio so
7083 * we know the end IO handler won't happen before
7084 * we inc the count. Otherwise, the dip might get freed
7085 * before we're done setting it up
7087 atomic_inc(&dip->pending_bios);
7088 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7089 file_offset, skip_sum,
7093 atomic_dec(&dip->pending_bios);
7097 start_sector += submit_len >> 9;
7098 file_offset += submit_len;
7103 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7104 start_sector, GFP_NOFS);
7107 bio->bi_private = dip;
7108 bio->bi_end_io = btrfs_end_dio_bio;
7110 map_length = orig_bio->bi_size;
7111 ret = btrfs_map_block(root->fs_info, rw,
7113 &map_length, NULL, 0);
7119 submit_len += bvec->bv_len;
7126 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7135 * before atomic variable goto zero, we must
7136 * make sure dip->errors is perceived to be set.
7138 smp_mb__before_atomic_dec();
7139 if (atomic_dec_and_test(&dip->pending_bios))
7140 bio_io_error(dip->orig_bio);
7142 /* bio_end_io() will handle error, so we needn't return it */
7146 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7147 struct inode *inode, loff_t file_offset)
7149 struct btrfs_root *root = BTRFS_I(inode)->root;
7150 struct btrfs_dio_private *dip;
7151 struct bio_vec *bvec = dio_bio->bi_io_vec;
7154 int write = rw & REQ_WRITE;
7157 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7159 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7166 dip = kmalloc(sizeof(*dip), GFP_NOFS);
7172 dip->private = dio_bio->bi_private;
7173 io_bio->bi_private = dio_bio->bi_private;
7175 dip->logical_offset = file_offset;
7179 dip->bytes += bvec->bv_len;
7181 } while (bvec <= (dio_bio->bi_io_vec + dio_bio->bi_vcnt - 1));
7183 dip->disk_bytenr = (u64)dio_bio->bi_sector << 9;
7184 io_bio->bi_private = dip;
7186 dip->orig_bio = io_bio;
7187 dip->dio_bio = dio_bio;
7188 atomic_set(&dip->pending_bios, 0);
7191 io_bio->bi_end_io = btrfs_endio_direct_write;
7193 io_bio->bi_end_io = btrfs_endio_direct_read;
7195 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7204 * If this is a write, we need to clean up the reserved space and kill
7205 * the ordered extent.
7208 struct btrfs_ordered_extent *ordered;
7209 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7210 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7211 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7212 btrfs_free_reserved_extent(root, ordered->start,
7214 btrfs_put_ordered_extent(ordered);
7215 btrfs_put_ordered_extent(ordered);
7217 bio_endio(dio_bio, ret);
7220 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7221 const struct iovec *iov, loff_t offset,
7222 unsigned long nr_segs)
7228 unsigned blocksize_mask = root->sectorsize - 1;
7229 ssize_t retval = -EINVAL;
7230 loff_t end = offset;
7232 if (offset & blocksize_mask)
7235 /* Check the memory alignment. Blocks cannot straddle pages */
7236 for (seg = 0; seg < nr_segs; seg++) {
7237 addr = (unsigned long)iov[seg].iov_base;
7238 size = iov[seg].iov_len;
7240 if ((addr & blocksize_mask) || (size & blocksize_mask))
7243 /* If this is a write we don't need to check anymore */
7248 * Check to make sure we don't have duplicate iov_base's in this
7249 * iovec, if so return EINVAL, otherwise we'll get csum errors
7250 * when reading back.
7252 for (i = seg + 1; i < nr_segs; i++) {
7253 if (iov[seg].iov_base == iov[i].iov_base)
7262 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7263 const struct iovec *iov, loff_t offset,
7264 unsigned long nr_segs)
7266 struct file *file = iocb->ki_filp;
7267 struct inode *inode = file->f_mapping->host;
7271 bool relock = false;
7274 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7278 atomic_inc(&inode->i_dio_count);
7279 smp_mb__after_atomic_inc();
7282 count = iov_length(iov, nr_segs);
7284 * If the write DIO is beyond the EOF, we need update
7285 * the isize, but it is protected by i_mutex. So we can
7286 * not unlock the i_mutex at this case.
7288 if (offset + count <= inode->i_size) {
7289 mutex_unlock(&inode->i_mutex);
7292 ret = btrfs_delalloc_reserve_space(inode, count);
7295 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7296 &BTRFS_I(inode)->runtime_flags))) {
7297 inode_dio_done(inode);
7298 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7302 ret = __blockdev_direct_IO(rw, iocb, inode,
7303 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7304 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7305 btrfs_submit_direct, flags);
7307 if (ret < 0 && ret != -EIOCBQUEUED)
7308 btrfs_delalloc_release_space(inode, count);
7309 else if (ret >= 0 && (size_t)ret < count)
7310 btrfs_delalloc_release_space(inode,
7311 count - (size_t)ret);
7313 btrfs_delalloc_release_metadata(inode, 0);
7317 inode_dio_done(inode);
7319 mutex_lock(&inode->i_mutex);
7324 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7326 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7327 __u64 start, __u64 len)
7331 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7335 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7338 int btrfs_readpage(struct file *file, struct page *page)
7340 struct extent_io_tree *tree;
7341 tree = &BTRFS_I(page->mapping->host)->io_tree;
7342 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7345 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7347 struct extent_io_tree *tree;
7350 if (current->flags & PF_MEMALLOC) {
7351 redirty_page_for_writepage(wbc, page);
7355 tree = &BTRFS_I(page->mapping->host)->io_tree;
7356 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7359 static int btrfs_writepages(struct address_space *mapping,
7360 struct writeback_control *wbc)
7362 struct extent_io_tree *tree;
7364 tree = &BTRFS_I(mapping->host)->io_tree;
7365 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7369 btrfs_readpages(struct file *file, struct address_space *mapping,
7370 struct list_head *pages, unsigned nr_pages)
7372 struct extent_io_tree *tree;
7373 tree = &BTRFS_I(mapping->host)->io_tree;
7374 return extent_readpages(tree, mapping, pages, nr_pages,
7377 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7379 struct extent_io_tree *tree;
7380 struct extent_map_tree *map;
7383 tree = &BTRFS_I(page->mapping->host)->io_tree;
7384 map = &BTRFS_I(page->mapping->host)->extent_tree;
7385 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7387 ClearPagePrivate(page);
7388 set_page_private(page, 0);
7389 page_cache_release(page);
7394 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7396 if (PageWriteback(page) || PageDirty(page))
7398 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7401 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
7403 struct inode *inode = page->mapping->host;
7404 struct extent_io_tree *tree;
7405 struct btrfs_ordered_extent *ordered;
7406 struct extent_state *cached_state = NULL;
7407 u64 page_start = page_offset(page);
7408 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7411 * we have the page locked, so new writeback can't start,
7412 * and the dirty bit won't be cleared while we are here.
7414 * Wait for IO on this page so that we can safely clear
7415 * the PagePrivate2 bit and do ordered accounting
7417 wait_on_page_writeback(page);
7419 tree = &BTRFS_I(inode)->io_tree;
7421 btrfs_releasepage(page, GFP_NOFS);
7424 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7425 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
7428 * IO on this page will never be started, so we need
7429 * to account for any ordered extents now
7431 clear_extent_bit(tree, page_start, page_end,
7432 EXTENT_DIRTY | EXTENT_DELALLOC |
7433 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7434 EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS);
7436 * whoever cleared the private bit is responsible
7437 * for the finish_ordered_io
7439 if (TestClearPagePrivate2(page) &&
7440 btrfs_dec_test_ordered_pending(inode, &ordered, page_start,
7441 PAGE_CACHE_SIZE, 1)) {
7442 btrfs_finish_ordered_io(ordered);
7444 btrfs_put_ordered_extent(ordered);
7445 cached_state = NULL;
7446 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7448 clear_extent_bit(tree, page_start, page_end,
7449 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
7450 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
7451 &cached_state, GFP_NOFS);
7452 __btrfs_releasepage(page, GFP_NOFS);
7454 ClearPageChecked(page);
7455 if (PagePrivate(page)) {
7456 ClearPagePrivate(page);
7457 set_page_private(page, 0);
7458 page_cache_release(page);
7463 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7464 * called from a page fault handler when a page is first dirtied. Hence we must
7465 * be careful to check for EOF conditions here. We set the page up correctly
7466 * for a written page which means we get ENOSPC checking when writing into
7467 * holes and correct delalloc and unwritten extent mapping on filesystems that
7468 * support these features.
7470 * We are not allowed to take the i_mutex here so we have to play games to
7471 * protect against truncate races as the page could now be beyond EOF. Because
7472 * vmtruncate() writes the inode size before removing pages, once we have the
7473 * page lock we can determine safely if the page is beyond EOF. If it is not
7474 * beyond EOF, then the page is guaranteed safe against truncation until we
7477 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7479 struct page *page = vmf->page;
7480 struct inode *inode = file_inode(vma->vm_file);
7481 struct btrfs_root *root = BTRFS_I(inode)->root;
7482 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7483 struct btrfs_ordered_extent *ordered;
7484 struct extent_state *cached_state = NULL;
7486 unsigned long zero_start;
7493 sb_start_pagefault(inode->i_sb);
7494 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7496 ret = file_update_time(vma->vm_file);
7502 else /* -ENOSPC, -EIO, etc */
7503 ret = VM_FAULT_SIGBUS;
7509 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7512 size = i_size_read(inode);
7513 page_start = page_offset(page);
7514 page_end = page_start + PAGE_CACHE_SIZE - 1;
7516 if ((page->mapping != inode->i_mapping) ||
7517 (page_start >= size)) {
7518 /* page got truncated out from underneath us */
7521 wait_on_page_writeback(page);
7523 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7524 set_page_extent_mapped(page);
7527 * we can't set the delalloc bits if there are pending ordered
7528 * extents. Drop our locks and wait for them to finish
7530 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7532 unlock_extent_cached(io_tree, page_start, page_end,
7533 &cached_state, GFP_NOFS);
7535 btrfs_start_ordered_extent(inode, ordered, 1);
7536 btrfs_put_ordered_extent(ordered);
7541 * XXX - page_mkwrite gets called every time the page is dirtied, even
7542 * if it was already dirty, so for space accounting reasons we need to
7543 * clear any delalloc bits for the range we are fixing to save. There
7544 * is probably a better way to do this, but for now keep consistent with
7545 * prepare_pages in the normal write path.
7547 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7548 EXTENT_DIRTY | EXTENT_DELALLOC |
7549 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7550 0, 0, &cached_state, GFP_NOFS);
7552 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7555 unlock_extent_cached(io_tree, page_start, page_end,
7556 &cached_state, GFP_NOFS);
7557 ret = VM_FAULT_SIGBUS;
7562 /* page is wholly or partially inside EOF */
7563 if (page_start + PAGE_CACHE_SIZE > size)
7564 zero_start = size & ~PAGE_CACHE_MASK;
7566 zero_start = PAGE_CACHE_SIZE;
7568 if (zero_start != PAGE_CACHE_SIZE) {
7570 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7571 flush_dcache_page(page);
7574 ClearPageChecked(page);
7575 set_page_dirty(page);
7576 SetPageUptodate(page);
7578 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7579 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7580 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7582 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7586 sb_end_pagefault(inode->i_sb);
7587 return VM_FAULT_LOCKED;
7591 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7593 sb_end_pagefault(inode->i_sb);
7597 static int btrfs_truncate(struct inode *inode)
7599 struct btrfs_root *root = BTRFS_I(inode)->root;
7600 struct btrfs_block_rsv *rsv;
7603 struct btrfs_trans_handle *trans;
7604 u64 mask = root->sectorsize - 1;
7605 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7607 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
7608 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
7611 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7612 * 3 things going on here
7614 * 1) We need to reserve space for our orphan item and the space to
7615 * delete our orphan item. Lord knows we don't want to have a dangling
7616 * orphan item because we didn't reserve space to remove it.
7618 * 2) We need to reserve space to update our inode.
7620 * 3) We need to have something to cache all the space that is going to
7621 * be free'd up by the truncate operation, but also have some slack
7622 * space reserved in case it uses space during the truncate (thank you
7623 * very much snapshotting).
7625 * And we need these to all be seperate. The fact is we can use alot of
7626 * space doing the truncate, and we have no earthly idea how much space
7627 * we will use, so we need the truncate reservation to be seperate so it
7628 * doesn't end up using space reserved for updating the inode or
7629 * removing the orphan item. We also need to be able to stop the
7630 * transaction and start a new one, which means we need to be able to
7631 * update the inode several times, and we have no idea of knowing how
7632 * many times that will be, so we can't just reserve 1 item for the
7633 * entirety of the opration, so that has to be done seperately as well.
7634 * Then there is the orphan item, which does indeed need to be held on
7635 * to for the whole operation, and we need nobody to touch this reserved
7636 * space except the orphan code.
7638 * So that leaves us with
7640 * 1) root->orphan_block_rsv - for the orphan deletion.
7641 * 2) rsv - for the truncate reservation, which we will steal from the
7642 * transaction reservation.
7643 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7644 * updating the inode.
7646 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7649 rsv->size = min_size;
7653 * 1 for the truncate slack space
7654 * 1 for updating the inode.
7656 trans = btrfs_start_transaction(root, 2);
7657 if (IS_ERR(trans)) {
7658 err = PTR_ERR(trans);
7662 /* Migrate the slack space for the truncate to our reserve */
7663 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7668 * setattr is responsible for setting the ordered_data_close flag,
7669 * but that is only tested during the last file release. That
7670 * could happen well after the next commit, leaving a great big
7671 * window where new writes may get lost if someone chooses to write
7672 * to this file after truncating to zero
7674 * The inode doesn't have any dirty data here, and so if we commit
7675 * this is a noop. If someone immediately starts writing to the inode
7676 * it is very likely we'll catch some of their writes in this
7677 * transaction, and the commit will find this file on the ordered
7678 * data list with good things to send down.
7680 * This is a best effort solution, there is still a window where
7681 * using truncate to replace the contents of the file will
7682 * end up with a zero length file after a crash.
7684 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7685 &BTRFS_I(inode)->runtime_flags))
7686 btrfs_add_ordered_operation(trans, root, inode);
7689 * So if we truncate and then write and fsync we normally would just
7690 * write the extents that changed, which is a problem if we need to
7691 * first truncate that entire inode. So set this flag so we write out
7692 * all of the extents in the inode to the sync log so we're completely
7695 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7696 trans->block_rsv = rsv;
7699 ret = btrfs_truncate_inode_items(trans, root, inode,
7701 BTRFS_EXTENT_DATA_KEY);
7702 if (ret != -ENOSPC) {
7707 trans->block_rsv = &root->fs_info->trans_block_rsv;
7708 ret = btrfs_update_inode(trans, root, inode);
7714 btrfs_end_transaction(trans, root);
7715 btrfs_btree_balance_dirty(root);
7717 trans = btrfs_start_transaction(root, 2);
7718 if (IS_ERR(trans)) {
7719 ret = err = PTR_ERR(trans);
7724 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7726 BUG_ON(ret); /* shouldn't happen */
7727 trans->block_rsv = rsv;
7730 if (ret == 0 && inode->i_nlink > 0) {
7731 trans->block_rsv = root->orphan_block_rsv;
7732 ret = btrfs_orphan_del(trans, inode);
7738 trans->block_rsv = &root->fs_info->trans_block_rsv;
7739 ret = btrfs_update_inode(trans, root, inode);
7743 ret = btrfs_end_transaction(trans, root);
7744 btrfs_btree_balance_dirty(root);
7748 btrfs_free_block_rsv(root, rsv);
7757 * create a new subvolume directory/inode (helper for the ioctl).
7759 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7760 struct btrfs_root *new_root, u64 new_dirid)
7762 struct inode *inode;
7766 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7767 new_dirid, new_dirid,
7768 S_IFDIR | (~current_umask() & S_IRWXUGO),
7771 return PTR_ERR(inode);
7772 inode->i_op = &btrfs_dir_inode_operations;
7773 inode->i_fop = &btrfs_dir_file_operations;
7775 set_nlink(inode, 1);
7776 btrfs_i_size_write(inode, 0);
7778 err = btrfs_update_inode(trans, new_root, inode);
7784 struct inode *btrfs_alloc_inode(struct super_block *sb)
7786 struct btrfs_inode *ei;
7787 struct inode *inode;
7789 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7796 ei->last_sub_trans = 0;
7797 ei->logged_trans = 0;
7798 ei->delalloc_bytes = 0;
7799 ei->disk_i_size = 0;
7802 ei->index_cnt = (u64)-1;
7803 ei->last_unlink_trans = 0;
7804 ei->last_log_commit = 0;
7806 spin_lock_init(&ei->lock);
7807 ei->outstanding_extents = 0;
7808 ei->reserved_extents = 0;
7810 ei->runtime_flags = 0;
7811 ei->force_compress = BTRFS_COMPRESS_NONE;
7813 ei->delayed_node = NULL;
7815 inode = &ei->vfs_inode;
7816 extent_map_tree_init(&ei->extent_tree);
7817 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7818 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7819 ei->io_tree.track_uptodate = 1;
7820 ei->io_failure_tree.track_uptodate = 1;
7821 atomic_set(&ei->sync_writers, 0);
7822 mutex_init(&ei->log_mutex);
7823 mutex_init(&ei->delalloc_mutex);
7824 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7825 INIT_LIST_HEAD(&ei->delalloc_inodes);
7826 INIT_LIST_HEAD(&ei->ordered_operations);
7827 RB_CLEAR_NODE(&ei->rb_node);
7832 static void btrfs_i_callback(struct rcu_head *head)
7834 struct inode *inode = container_of(head, struct inode, i_rcu);
7835 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7838 void btrfs_destroy_inode(struct inode *inode)
7840 struct btrfs_ordered_extent *ordered;
7841 struct btrfs_root *root = BTRFS_I(inode)->root;
7843 WARN_ON(!hlist_empty(&inode->i_dentry));
7844 WARN_ON(inode->i_data.nrpages);
7845 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7846 WARN_ON(BTRFS_I(inode)->reserved_extents);
7847 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7848 WARN_ON(BTRFS_I(inode)->csum_bytes);
7851 * This can happen where we create an inode, but somebody else also
7852 * created the same inode and we need to destroy the one we already
7859 * Make sure we're properly removed from the ordered operation
7863 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7864 spin_lock(&root->fs_info->ordered_root_lock);
7865 list_del_init(&BTRFS_I(inode)->ordered_operations);
7866 spin_unlock(&root->fs_info->ordered_root_lock);
7869 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7870 &BTRFS_I(inode)->runtime_flags)) {
7871 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
7872 (unsigned long long)btrfs_ino(inode));
7873 atomic_dec(&root->orphan_inodes);
7877 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7881 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
7882 (unsigned long long)ordered->file_offset,
7883 (unsigned long long)ordered->len);
7884 btrfs_remove_ordered_extent(inode, ordered);
7885 btrfs_put_ordered_extent(ordered);
7886 btrfs_put_ordered_extent(ordered);
7889 inode_tree_del(inode);
7890 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7892 call_rcu(&inode->i_rcu, btrfs_i_callback);
7895 int btrfs_drop_inode(struct inode *inode)
7897 struct btrfs_root *root = BTRFS_I(inode)->root;
7902 /* the snap/subvol tree is on deleting */
7903 if (btrfs_root_refs(&root->root_item) == 0 &&
7904 root != root->fs_info->tree_root)
7907 return generic_drop_inode(inode);
7910 static void init_once(void *foo)
7912 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
7914 inode_init_once(&ei->vfs_inode);
7917 void btrfs_destroy_cachep(void)
7920 * Make sure all delayed rcu free inodes are flushed before we
7924 if (btrfs_inode_cachep)
7925 kmem_cache_destroy(btrfs_inode_cachep);
7926 if (btrfs_trans_handle_cachep)
7927 kmem_cache_destroy(btrfs_trans_handle_cachep);
7928 if (btrfs_transaction_cachep)
7929 kmem_cache_destroy(btrfs_transaction_cachep);
7930 if (btrfs_path_cachep)
7931 kmem_cache_destroy(btrfs_path_cachep);
7932 if (btrfs_free_space_cachep)
7933 kmem_cache_destroy(btrfs_free_space_cachep);
7934 if (btrfs_delalloc_work_cachep)
7935 kmem_cache_destroy(btrfs_delalloc_work_cachep);
7938 int btrfs_init_cachep(void)
7940 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
7941 sizeof(struct btrfs_inode), 0,
7942 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
7943 if (!btrfs_inode_cachep)
7946 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
7947 sizeof(struct btrfs_trans_handle), 0,
7948 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7949 if (!btrfs_trans_handle_cachep)
7952 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
7953 sizeof(struct btrfs_transaction), 0,
7954 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7955 if (!btrfs_transaction_cachep)
7958 btrfs_path_cachep = kmem_cache_create("btrfs_path",
7959 sizeof(struct btrfs_path), 0,
7960 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7961 if (!btrfs_path_cachep)
7964 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
7965 sizeof(struct btrfs_free_space), 0,
7966 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7967 if (!btrfs_free_space_cachep)
7970 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
7971 sizeof(struct btrfs_delalloc_work), 0,
7972 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
7974 if (!btrfs_delalloc_work_cachep)
7979 btrfs_destroy_cachep();
7983 static int btrfs_getattr(struct vfsmount *mnt,
7984 struct dentry *dentry, struct kstat *stat)
7987 struct inode *inode = dentry->d_inode;
7988 u32 blocksize = inode->i_sb->s_blocksize;
7990 generic_fillattr(inode, stat);
7991 stat->dev = BTRFS_I(inode)->root->anon_dev;
7992 stat->blksize = PAGE_CACHE_SIZE;
7994 spin_lock(&BTRFS_I(inode)->lock);
7995 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
7996 spin_unlock(&BTRFS_I(inode)->lock);
7997 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
7998 ALIGN(delalloc_bytes, blocksize)) >> 9;
8002 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8003 struct inode *new_dir, struct dentry *new_dentry)
8005 struct btrfs_trans_handle *trans;
8006 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8007 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8008 struct inode *new_inode = new_dentry->d_inode;
8009 struct inode *old_inode = old_dentry->d_inode;
8010 struct timespec ctime = CURRENT_TIME;
8014 u64 old_ino = btrfs_ino(old_inode);
8016 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8019 /* we only allow rename subvolume link between subvolumes */
8020 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8023 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8024 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8027 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8028 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8032 /* check for collisions, even if the name isn't there */
8033 ret = btrfs_check_dir_item_collision(root, new_dir->i_ino,
8034 new_dentry->d_name.name,
8035 new_dentry->d_name.len);
8038 if (ret == -EEXIST) {
8040 * eexist without a new_inode */
8046 /* maybe -EOVERFLOW */
8053 * we're using rename to replace one file with another.
8054 * and the replacement file is large. Start IO on it now so
8055 * we don't add too much work to the end of the transaction
8057 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8058 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8059 filemap_flush(old_inode->i_mapping);
8061 /* close the racy window with snapshot create/destroy ioctl */
8062 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8063 down_read(&root->fs_info->subvol_sem);
8065 * We want to reserve the absolute worst case amount of items. So if
8066 * both inodes are subvols and we need to unlink them then that would
8067 * require 4 item modifications, but if they are both normal inodes it
8068 * would require 5 item modifications, so we'll assume their normal
8069 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8070 * should cover the worst case number of items we'll modify.
8072 trans = btrfs_start_transaction(root, 11);
8073 if (IS_ERR(trans)) {
8074 ret = PTR_ERR(trans);
8079 btrfs_record_root_in_trans(trans, dest);
8081 ret = btrfs_set_inode_index(new_dir, &index);
8085 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8086 /* force full log commit if subvolume involved. */
8087 root->fs_info->last_trans_log_full_commit = trans->transid;
8089 ret = btrfs_insert_inode_ref(trans, dest,
8090 new_dentry->d_name.name,
8091 new_dentry->d_name.len,
8093 btrfs_ino(new_dir), index);
8097 * this is an ugly little race, but the rename is required
8098 * to make sure that if we crash, the inode is either at the
8099 * old name or the new one. pinning the log transaction lets
8100 * us make sure we don't allow a log commit to come in after
8101 * we unlink the name but before we add the new name back in.
8103 btrfs_pin_log_trans(root);
8106 * make sure the inode gets flushed if it is replacing
8109 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8110 btrfs_add_ordered_operation(trans, root, old_inode);
8112 inode_inc_iversion(old_dir);
8113 inode_inc_iversion(new_dir);
8114 inode_inc_iversion(old_inode);
8115 old_dir->i_ctime = old_dir->i_mtime = ctime;
8116 new_dir->i_ctime = new_dir->i_mtime = ctime;
8117 old_inode->i_ctime = ctime;
8119 if (old_dentry->d_parent != new_dentry->d_parent)
8120 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8122 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8123 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8124 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8125 old_dentry->d_name.name,
8126 old_dentry->d_name.len);
8128 ret = __btrfs_unlink_inode(trans, root, old_dir,
8129 old_dentry->d_inode,
8130 old_dentry->d_name.name,
8131 old_dentry->d_name.len);
8133 ret = btrfs_update_inode(trans, root, old_inode);
8136 btrfs_abort_transaction(trans, root, ret);
8141 inode_inc_iversion(new_inode);
8142 new_inode->i_ctime = CURRENT_TIME;
8143 if (unlikely(btrfs_ino(new_inode) ==
8144 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8145 root_objectid = BTRFS_I(new_inode)->location.objectid;
8146 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8148 new_dentry->d_name.name,
8149 new_dentry->d_name.len);
8150 BUG_ON(new_inode->i_nlink == 0);
8152 ret = btrfs_unlink_inode(trans, dest, new_dir,
8153 new_dentry->d_inode,
8154 new_dentry->d_name.name,
8155 new_dentry->d_name.len);
8157 if (!ret && new_inode->i_nlink == 0) {
8158 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8162 btrfs_abort_transaction(trans, root, ret);
8167 ret = btrfs_add_link(trans, new_dir, old_inode,
8168 new_dentry->d_name.name,
8169 new_dentry->d_name.len, 0, index);
8171 btrfs_abort_transaction(trans, root, ret);
8175 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8176 struct dentry *parent = new_dentry->d_parent;
8177 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8178 btrfs_end_log_trans(root);
8181 btrfs_end_transaction(trans, root);
8183 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8184 up_read(&root->fs_info->subvol_sem);
8189 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8191 struct btrfs_delalloc_work *delalloc_work;
8193 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8195 if (delalloc_work->wait)
8196 btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1);
8198 filemap_flush(delalloc_work->inode->i_mapping);
8200 if (delalloc_work->delay_iput)
8201 btrfs_add_delayed_iput(delalloc_work->inode);
8203 iput(delalloc_work->inode);
8204 complete(&delalloc_work->completion);
8207 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8208 int wait, int delay_iput)
8210 struct btrfs_delalloc_work *work;
8212 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8216 init_completion(&work->completion);
8217 INIT_LIST_HEAD(&work->list);
8218 work->inode = inode;
8220 work->delay_iput = delay_iput;
8221 work->work.func = btrfs_run_delalloc_work;
8226 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8228 wait_for_completion(&work->completion);
8229 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8233 * some fairly slow code that needs optimization. This walks the list
8234 * of all the inodes with pending delalloc and forces them to disk.
8236 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8238 struct btrfs_inode *binode;
8239 struct inode *inode;
8240 struct btrfs_delalloc_work *work, *next;
8241 struct list_head works;
8242 struct list_head splice;
8245 INIT_LIST_HEAD(&works);
8246 INIT_LIST_HEAD(&splice);
8248 spin_lock(&root->delalloc_lock);
8249 list_splice_init(&root->delalloc_inodes, &splice);
8250 while (!list_empty(&splice)) {
8251 binode = list_entry(splice.next, struct btrfs_inode,
8254 list_move_tail(&binode->delalloc_inodes,
8255 &root->delalloc_inodes);
8256 inode = igrab(&binode->vfs_inode);
8258 cond_resched_lock(&root->delalloc_lock);
8261 spin_unlock(&root->delalloc_lock);
8263 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8264 if (unlikely(!work)) {
8268 list_add_tail(&work->list, &works);
8269 btrfs_queue_worker(&root->fs_info->flush_workers,
8273 spin_lock(&root->delalloc_lock);
8275 spin_unlock(&root->delalloc_lock);
8277 list_for_each_entry_safe(work, next, &works, list) {
8278 list_del_init(&work->list);
8279 btrfs_wait_and_free_delalloc_work(work);
8283 list_for_each_entry_safe(work, next, &works, list) {
8284 list_del_init(&work->list);
8285 btrfs_wait_and_free_delalloc_work(work);
8288 if (!list_empty_careful(&splice)) {
8289 spin_lock(&root->delalloc_lock);
8290 list_splice_tail(&splice, &root->delalloc_inodes);
8291 spin_unlock(&root->delalloc_lock);
8296 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8300 if (root->fs_info->sb->s_flags & MS_RDONLY)
8303 ret = __start_delalloc_inodes(root, delay_iput);
8305 * the filemap_flush will queue IO into the worker threads, but
8306 * we have to make sure the IO is actually started and that
8307 * ordered extents get created before we return
8309 atomic_inc(&root->fs_info->async_submit_draining);
8310 while (atomic_read(&root->fs_info->nr_async_submits) ||
8311 atomic_read(&root->fs_info->async_delalloc_pages)) {
8312 wait_event(root->fs_info->async_submit_wait,
8313 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8314 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8316 atomic_dec(&root->fs_info->async_submit_draining);
8320 int btrfs_start_all_delalloc_inodes(struct btrfs_fs_info *fs_info,
8323 struct btrfs_root *root;
8324 struct list_head splice;
8327 if (fs_info->sb->s_flags & MS_RDONLY)
8330 INIT_LIST_HEAD(&splice);
8332 spin_lock(&fs_info->delalloc_root_lock);
8333 list_splice_init(&fs_info->delalloc_roots, &splice);
8334 while (!list_empty(&splice)) {
8335 root = list_first_entry(&splice, struct btrfs_root,
8337 root = btrfs_grab_fs_root(root);
8339 list_move_tail(&root->delalloc_root,
8340 &fs_info->delalloc_roots);
8341 spin_unlock(&fs_info->delalloc_root_lock);
8343 ret = __start_delalloc_inodes(root, delay_iput);
8344 btrfs_put_fs_root(root);
8348 spin_lock(&fs_info->delalloc_root_lock);
8350 spin_unlock(&fs_info->delalloc_root_lock);
8352 atomic_inc(&fs_info->async_submit_draining);
8353 while (atomic_read(&fs_info->nr_async_submits) ||
8354 atomic_read(&fs_info->async_delalloc_pages)) {
8355 wait_event(fs_info->async_submit_wait,
8356 (atomic_read(&fs_info->nr_async_submits) == 0 &&
8357 atomic_read(&fs_info->async_delalloc_pages) == 0));
8359 atomic_dec(&fs_info->async_submit_draining);
8362 if (!list_empty_careful(&splice)) {
8363 spin_lock(&fs_info->delalloc_root_lock);
8364 list_splice_tail(&splice, &fs_info->delalloc_roots);
8365 spin_unlock(&fs_info->delalloc_root_lock);
8370 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8371 const char *symname)
8373 struct btrfs_trans_handle *trans;
8374 struct btrfs_root *root = BTRFS_I(dir)->root;
8375 struct btrfs_path *path;
8376 struct btrfs_key key;
8377 struct inode *inode = NULL;
8385 struct btrfs_file_extent_item *ei;
8386 struct extent_buffer *leaf;
8388 name_len = strlen(symname) + 1;
8389 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8390 return -ENAMETOOLONG;
8393 * 2 items for inode item and ref
8394 * 2 items for dir items
8395 * 1 item for xattr if selinux is on
8397 trans = btrfs_start_transaction(root, 5);
8399 return PTR_ERR(trans);
8401 err = btrfs_find_free_ino(root, &objectid);
8405 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8406 dentry->d_name.len, btrfs_ino(dir), objectid,
8407 S_IFLNK|S_IRWXUGO, &index);
8408 if (IS_ERR(inode)) {
8409 err = PTR_ERR(inode);
8413 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8420 * If the active LSM wants to access the inode during
8421 * d_instantiate it needs these. Smack checks to see
8422 * if the filesystem supports xattrs by looking at the
8425 inode->i_fop = &btrfs_file_operations;
8426 inode->i_op = &btrfs_file_inode_operations;
8428 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8432 inode->i_mapping->a_ops = &btrfs_aops;
8433 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8434 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8439 path = btrfs_alloc_path();
8445 key.objectid = btrfs_ino(inode);
8447 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8448 datasize = btrfs_file_extent_calc_inline_size(name_len);
8449 err = btrfs_insert_empty_item(trans, root, path, &key,
8453 btrfs_free_path(path);
8456 leaf = path->nodes[0];
8457 ei = btrfs_item_ptr(leaf, path->slots[0],
8458 struct btrfs_file_extent_item);
8459 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8460 btrfs_set_file_extent_type(leaf, ei,
8461 BTRFS_FILE_EXTENT_INLINE);
8462 btrfs_set_file_extent_encryption(leaf, ei, 0);
8463 btrfs_set_file_extent_compression(leaf, ei, 0);
8464 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8465 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8467 ptr = btrfs_file_extent_inline_start(ei);
8468 write_extent_buffer(leaf, symname, ptr, name_len);
8469 btrfs_mark_buffer_dirty(leaf);
8470 btrfs_free_path(path);
8472 inode->i_op = &btrfs_symlink_inode_operations;
8473 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8474 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8475 inode_set_bytes(inode, name_len);
8476 btrfs_i_size_write(inode, name_len - 1);
8477 err = btrfs_update_inode(trans, root, inode);
8483 d_instantiate(dentry, inode);
8484 btrfs_end_transaction(trans, root);
8486 inode_dec_link_count(inode);
8489 btrfs_btree_balance_dirty(root);
8493 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8494 u64 start, u64 num_bytes, u64 min_size,
8495 loff_t actual_len, u64 *alloc_hint,
8496 struct btrfs_trans_handle *trans)
8498 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8499 struct extent_map *em;
8500 struct btrfs_root *root = BTRFS_I(inode)->root;
8501 struct btrfs_key ins;
8502 u64 cur_offset = start;
8506 bool own_trans = true;
8510 while (num_bytes > 0) {
8512 trans = btrfs_start_transaction(root, 3);
8513 if (IS_ERR(trans)) {
8514 ret = PTR_ERR(trans);
8519 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8520 cur_bytes = max(cur_bytes, min_size);
8521 ret = btrfs_reserve_extent(trans, root, cur_bytes,
8522 min_size, 0, *alloc_hint, &ins, 1);
8525 btrfs_end_transaction(trans, root);
8529 ret = insert_reserved_file_extent(trans, inode,
8530 cur_offset, ins.objectid,
8531 ins.offset, ins.offset,
8532 ins.offset, 0, 0, 0,
8533 BTRFS_FILE_EXTENT_PREALLOC);
8535 btrfs_abort_transaction(trans, root, ret);
8537 btrfs_end_transaction(trans, root);
8540 btrfs_drop_extent_cache(inode, cur_offset,
8541 cur_offset + ins.offset -1, 0);
8543 em = alloc_extent_map();
8545 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8546 &BTRFS_I(inode)->runtime_flags);
8550 em->start = cur_offset;
8551 em->orig_start = cur_offset;
8552 em->len = ins.offset;
8553 em->block_start = ins.objectid;
8554 em->block_len = ins.offset;
8555 em->orig_block_len = ins.offset;
8556 em->ram_bytes = ins.offset;
8557 em->bdev = root->fs_info->fs_devices->latest_bdev;
8558 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8559 em->generation = trans->transid;
8562 write_lock(&em_tree->lock);
8563 ret = add_extent_mapping(em_tree, em, 1);
8564 write_unlock(&em_tree->lock);
8567 btrfs_drop_extent_cache(inode, cur_offset,
8568 cur_offset + ins.offset - 1,
8571 free_extent_map(em);
8573 num_bytes -= ins.offset;
8574 cur_offset += ins.offset;
8575 *alloc_hint = ins.objectid + ins.offset;
8577 inode_inc_iversion(inode);
8578 inode->i_ctime = CURRENT_TIME;
8579 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8580 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8581 (actual_len > inode->i_size) &&
8582 (cur_offset > inode->i_size)) {
8583 if (cur_offset > actual_len)
8584 i_size = actual_len;
8586 i_size = cur_offset;
8587 i_size_write(inode, i_size);
8588 btrfs_ordered_update_i_size(inode, i_size, NULL);
8591 ret = btrfs_update_inode(trans, root, inode);
8594 btrfs_abort_transaction(trans, root, ret);
8596 btrfs_end_transaction(trans, root);
8601 btrfs_end_transaction(trans, root);
8606 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8607 u64 start, u64 num_bytes, u64 min_size,
8608 loff_t actual_len, u64 *alloc_hint)
8610 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8611 min_size, actual_len, alloc_hint,
8615 int btrfs_prealloc_file_range_trans(struct inode *inode,
8616 struct btrfs_trans_handle *trans, int mode,
8617 u64 start, u64 num_bytes, u64 min_size,
8618 loff_t actual_len, u64 *alloc_hint)
8620 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8621 min_size, actual_len, alloc_hint, trans);
8624 static int btrfs_set_page_dirty(struct page *page)
8626 return __set_page_dirty_nobuffers(page);
8629 static int btrfs_permission(struct inode *inode, int mask)
8631 struct btrfs_root *root = BTRFS_I(inode)->root;
8632 umode_t mode = inode->i_mode;
8634 if (mask & MAY_WRITE &&
8635 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8636 if (btrfs_root_readonly(root))
8638 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8641 return generic_permission(inode, mask);
8644 static const struct inode_operations btrfs_dir_inode_operations = {
8645 .getattr = btrfs_getattr,
8646 .lookup = btrfs_lookup,
8647 .create = btrfs_create,
8648 .unlink = btrfs_unlink,
8650 .mkdir = btrfs_mkdir,
8651 .rmdir = btrfs_rmdir,
8652 .rename = btrfs_rename,
8653 .symlink = btrfs_symlink,
8654 .setattr = btrfs_setattr,
8655 .mknod = btrfs_mknod,
8656 .setxattr = btrfs_setxattr,
8657 .getxattr = btrfs_getxattr,
8658 .listxattr = btrfs_listxattr,
8659 .removexattr = btrfs_removexattr,
8660 .permission = btrfs_permission,
8661 .get_acl = btrfs_get_acl,
8663 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8664 .lookup = btrfs_lookup,
8665 .permission = btrfs_permission,
8666 .get_acl = btrfs_get_acl,
8669 static const struct file_operations btrfs_dir_file_operations = {
8670 .llseek = generic_file_llseek,
8671 .read = generic_read_dir,
8672 .readdir = btrfs_real_readdir,
8673 .unlocked_ioctl = btrfs_ioctl,
8674 #ifdef CONFIG_COMPAT
8675 .compat_ioctl = btrfs_ioctl,
8677 .release = btrfs_release_file,
8678 .fsync = btrfs_sync_file,
8681 static struct extent_io_ops btrfs_extent_io_ops = {
8682 .fill_delalloc = run_delalloc_range,
8683 .submit_bio_hook = btrfs_submit_bio_hook,
8684 .merge_bio_hook = btrfs_merge_bio_hook,
8685 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8686 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8687 .writepage_start_hook = btrfs_writepage_start_hook,
8688 .set_bit_hook = btrfs_set_bit_hook,
8689 .clear_bit_hook = btrfs_clear_bit_hook,
8690 .merge_extent_hook = btrfs_merge_extent_hook,
8691 .split_extent_hook = btrfs_split_extent_hook,
8695 * btrfs doesn't support the bmap operation because swapfiles
8696 * use bmap to make a mapping of extents in the file. They assume
8697 * these extents won't change over the life of the file and they
8698 * use the bmap result to do IO directly to the drive.
8700 * the btrfs bmap call would return logical addresses that aren't
8701 * suitable for IO and they also will change frequently as COW
8702 * operations happen. So, swapfile + btrfs == corruption.
8704 * For now we're avoiding this by dropping bmap.
8706 static const struct address_space_operations btrfs_aops = {
8707 .readpage = btrfs_readpage,
8708 .writepage = btrfs_writepage,
8709 .writepages = btrfs_writepages,
8710 .readpages = btrfs_readpages,
8711 .direct_IO = btrfs_direct_IO,
8712 .invalidatepage = btrfs_invalidatepage,
8713 .releasepage = btrfs_releasepage,
8714 .set_page_dirty = btrfs_set_page_dirty,
8715 .error_remove_page = generic_error_remove_page,
8718 static const struct address_space_operations btrfs_symlink_aops = {
8719 .readpage = btrfs_readpage,
8720 .writepage = btrfs_writepage,
8721 .invalidatepage = btrfs_invalidatepage,
8722 .releasepage = btrfs_releasepage,
8725 static const struct inode_operations btrfs_file_inode_operations = {
8726 .getattr = btrfs_getattr,
8727 .setattr = btrfs_setattr,
8728 .setxattr = btrfs_setxattr,
8729 .getxattr = btrfs_getxattr,
8730 .listxattr = btrfs_listxattr,
8731 .removexattr = btrfs_removexattr,
8732 .permission = btrfs_permission,
8733 .fiemap = btrfs_fiemap,
8734 .get_acl = btrfs_get_acl,
8735 .update_time = btrfs_update_time,
8737 static const struct inode_operations btrfs_special_inode_operations = {
8738 .getattr = btrfs_getattr,
8739 .setattr = btrfs_setattr,
8740 .permission = btrfs_permission,
8741 .setxattr = btrfs_setxattr,
8742 .getxattr = btrfs_getxattr,
8743 .listxattr = btrfs_listxattr,
8744 .removexattr = btrfs_removexattr,
8745 .get_acl = btrfs_get_acl,
8746 .update_time = btrfs_update_time,
8748 static const struct inode_operations btrfs_symlink_inode_operations = {
8749 .readlink = generic_readlink,
8750 .follow_link = page_follow_link_light,
8751 .put_link = page_put_link,
8752 .getattr = btrfs_getattr,
8753 .setattr = btrfs_setattr,
8754 .permission = btrfs_permission,
8755 .setxattr = btrfs_setxattr,
8756 .getxattr = btrfs_getxattr,
8757 .listxattr = btrfs_listxattr,
8758 .removexattr = btrfs_removexattr,
8759 .get_acl = btrfs_get_acl,
8760 .update_time = btrfs_update_time,
8763 const struct dentry_operations btrfs_dentry_operations = {
8764 .d_delete = btrfs_dentry_delete,
8765 .d_release = btrfs_dentry_release,