2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/aio.h>
36 #include <linux/bit_spinlock.h>
37 #include <linux/xattr.h>
38 #include <linux/posix_acl.h>
39 #include <linux/falloc.h>
40 #include <linux/slab.h>
41 #include <linux/ratelimit.h>
42 #include <linux/mount.h>
43 #include <linux/btrfs.h>
44 #include <linux/blkdev.h>
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"
61 struct btrfs_iget_args {
63 struct btrfs_root *root;
66 static const struct inode_operations btrfs_dir_inode_operations;
67 static const struct inode_operations btrfs_symlink_inode_operations;
68 static const struct inode_operations btrfs_dir_ro_inode_operations;
69 static const struct inode_operations btrfs_special_inode_operations;
70 static const struct inode_operations btrfs_file_inode_operations;
71 static const struct address_space_operations btrfs_aops;
72 static const struct address_space_operations btrfs_symlink_aops;
73 static const struct file_operations btrfs_dir_file_operations;
74 static struct extent_io_ops btrfs_extent_io_ops;
76 static struct kmem_cache *btrfs_inode_cachep;
77 static struct kmem_cache *btrfs_delalloc_work_cachep;
78 struct kmem_cache *btrfs_trans_handle_cachep;
79 struct kmem_cache *btrfs_transaction_cachep;
80 struct kmem_cache *btrfs_path_cachep;
81 struct kmem_cache *btrfs_free_space_cachep;
84 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
85 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
86 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
87 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
88 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
89 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
90 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
91 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
94 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
95 static int btrfs_truncate(struct inode *inode);
96 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
97 static noinline int cow_file_range(struct inode *inode,
98 struct page *locked_page,
99 u64 start, u64 end, int *page_started,
100 unsigned long *nr_written, int unlock);
101 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
102 u64 len, u64 orig_start,
103 u64 block_start, u64 block_len,
104 u64 orig_block_len, u64 ram_bytes,
107 static int btrfs_dirty_inode(struct inode *inode);
109 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
110 struct inode *inode, struct inode *dir,
111 const struct qstr *qstr)
115 err = btrfs_init_acl(trans, inode, dir);
117 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
122 * this does all the hard work for inserting an inline extent into
123 * the btree. The caller should have done a btrfs_drop_extents so that
124 * no overlapping inline items exist in the btree
126 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
127 struct btrfs_root *root, struct inode *inode,
128 u64 start, size_t size, size_t compressed_size,
130 struct page **compressed_pages)
132 struct btrfs_key key;
133 struct btrfs_path *path;
134 struct extent_buffer *leaf;
135 struct page *page = NULL;
138 struct btrfs_file_extent_item *ei;
141 size_t cur_size = size;
143 unsigned long offset;
145 if (compressed_size && compressed_pages)
146 cur_size = compressed_size;
148 path = btrfs_alloc_path();
152 path->leave_spinning = 1;
154 key.objectid = btrfs_ino(inode);
156 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
157 datasize = btrfs_file_extent_calc_inline_size(cur_size);
159 inode_add_bytes(inode, size);
160 ret = btrfs_insert_empty_item(trans, root, path, &key,
166 leaf = path->nodes[0];
167 ei = btrfs_item_ptr(leaf, path->slots[0],
168 struct btrfs_file_extent_item);
169 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
170 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
171 btrfs_set_file_extent_encryption(leaf, ei, 0);
172 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
173 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
174 ptr = btrfs_file_extent_inline_start(ei);
176 if (compress_type != BTRFS_COMPRESS_NONE) {
179 while (compressed_size > 0) {
180 cpage = compressed_pages[i];
181 cur_size = min_t(unsigned long, compressed_size,
184 kaddr = kmap_atomic(cpage);
185 write_extent_buffer(leaf, kaddr, ptr, cur_size);
186 kunmap_atomic(kaddr);
190 compressed_size -= cur_size;
192 btrfs_set_file_extent_compression(leaf, ei,
195 page = find_get_page(inode->i_mapping,
196 start >> PAGE_CACHE_SHIFT);
197 btrfs_set_file_extent_compression(leaf, ei, 0);
198 kaddr = kmap_atomic(page);
199 offset = start & (PAGE_CACHE_SIZE - 1);
200 write_extent_buffer(leaf, kaddr + offset, ptr, size);
201 kunmap_atomic(kaddr);
202 page_cache_release(page);
204 btrfs_mark_buffer_dirty(leaf);
205 btrfs_free_path(path);
208 * we're an inline extent, so nobody can
209 * extend the file past i_size without locking
210 * a page we already have locked.
212 * We must do any isize and inode updates
213 * before we unlock the pages. Otherwise we
214 * could end up racing with unlink.
216 BTRFS_I(inode)->disk_i_size = inode->i_size;
217 ret = btrfs_update_inode(trans, root, inode);
221 btrfs_free_path(path);
227 * conditionally insert an inline extent into the file. This
228 * does the checks required to make sure the data is small enough
229 * to fit as an inline extent.
231 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
232 struct btrfs_root *root,
233 struct inode *inode, u64 start, u64 end,
234 size_t compressed_size, int compress_type,
235 struct page **compressed_pages)
237 u64 isize = i_size_read(inode);
238 u64 actual_end = min(end + 1, isize);
239 u64 inline_len = actual_end - start;
240 u64 aligned_end = ALIGN(end, root->sectorsize);
241 u64 data_len = inline_len;
245 data_len = compressed_size;
248 actual_end >= PAGE_CACHE_SIZE ||
249 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
251 (actual_end & (root->sectorsize - 1)) == 0) ||
253 data_len > root->fs_info->max_inline) {
257 ret = btrfs_drop_extents(trans, root, inode, start, aligned_end, 1);
261 if (isize > actual_end)
262 inline_len = min_t(u64, isize, actual_end);
263 ret = insert_inline_extent(trans, root, inode, start,
264 inline_len, compressed_size,
265 compress_type, compressed_pages);
266 if (ret && ret != -ENOSPC) {
267 btrfs_abort_transaction(trans, root, ret);
269 } else if (ret == -ENOSPC) {
273 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
274 btrfs_delalloc_release_metadata(inode, end + 1 - start);
275 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
279 struct async_extent {
284 unsigned long nr_pages;
286 struct list_head list;
291 struct btrfs_root *root;
292 struct page *locked_page;
295 struct list_head extents;
296 struct btrfs_work work;
299 static noinline int add_async_extent(struct async_cow *cow,
300 u64 start, u64 ram_size,
303 unsigned long nr_pages,
306 struct async_extent *async_extent;
308 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
309 BUG_ON(!async_extent); /* -ENOMEM */
310 async_extent->start = start;
311 async_extent->ram_size = ram_size;
312 async_extent->compressed_size = compressed_size;
313 async_extent->pages = pages;
314 async_extent->nr_pages = nr_pages;
315 async_extent->compress_type = compress_type;
316 list_add_tail(&async_extent->list, &cow->extents);
321 * we create compressed extents in two phases. The first
322 * phase compresses a range of pages that have already been
323 * locked (both pages and state bits are locked).
325 * This is done inside an ordered work queue, and the compression
326 * is spread across many cpus. The actual IO submission is step
327 * two, and the ordered work queue takes care of making sure that
328 * happens in the same order things were put onto the queue by
329 * writepages and friends.
331 * If this code finds it can't get good compression, it puts an
332 * entry onto the work queue to write the uncompressed bytes. This
333 * makes sure that both compressed inodes and uncompressed inodes
334 * are written in the same order that the flusher thread sent them
337 static noinline int compress_file_range(struct inode *inode,
338 struct page *locked_page,
340 struct async_cow *async_cow,
343 struct btrfs_root *root = BTRFS_I(inode)->root;
344 struct btrfs_trans_handle *trans;
346 u64 blocksize = root->sectorsize;
348 u64 isize = i_size_read(inode);
350 struct page **pages = NULL;
351 unsigned long nr_pages;
352 unsigned long nr_pages_ret = 0;
353 unsigned long total_compressed = 0;
354 unsigned long total_in = 0;
355 unsigned long max_compressed = 128 * 1024;
356 unsigned long max_uncompressed = 128 * 1024;
359 int compress_type = root->fs_info->compress_type;
362 /* if this is a small write inside eof, kick off a defrag */
363 if ((end - start + 1) < 16 * 1024 &&
364 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
365 btrfs_add_inode_defrag(NULL, inode);
367 actual_end = min_t(u64, isize, end + 1);
370 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
371 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
374 * we don't want to send crud past the end of i_size through
375 * compression, that's just a waste of CPU time. So, if the
376 * end of the file is before the start of our current
377 * requested range of bytes, we bail out to the uncompressed
378 * cleanup code that can deal with all of this.
380 * It isn't really the fastest way to fix things, but this is a
381 * very uncommon corner.
383 if (actual_end <= start)
384 goto cleanup_and_bail_uncompressed;
386 total_compressed = actual_end - start;
388 /* we want to make sure that amount of ram required to uncompress
389 * an extent is reasonable, so we limit the total size in ram
390 * of a compressed extent to 128k. This is a crucial number
391 * because it also controls how easily we can spread reads across
392 * cpus for decompression.
394 * We also want to make sure the amount of IO required to do
395 * a random read is reasonably small, so we limit the size of
396 * a compressed extent to 128k.
398 total_compressed = min(total_compressed, max_uncompressed);
399 num_bytes = ALIGN(end - start + 1, blocksize);
400 num_bytes = max(blocksize, num_bytes);
405 * we do compression for mount -o compress and when the
406 * inode has not been flagged as nocompress. This flag can
407 * change at any time if we discover bad compression ratios.
409 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
410 (btrfs_test_opt(root, COMPRESS) ||
411 (BTRFS_I(inode)->force_compress) ||
412 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
414 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
416 /* just bail out to the uncompressed code */
420 if (BTRFS_I(inode)->force_compress)
421 compress_type = BTRFS_I(inode)->force_compress;
424 * we need to call clear_page_dirty_for_io on each
425 * page in the range. Otherwise applications with the file
426 * mmap'd can wander in and change the page contents while
427 * we are compressing them.
429 * If the compression fails for any reason, we set the pages
430 * dirty again later on.
432 extent_range_clear_dirty_for_io(inode, start, end);
434 ret = btrfs_compress_pages(compress_type,
435 inode->i_mapping, start,
436 total_compressed, pages,
437 nr_pages, &nr_pages_ret,
443 unsigned long offset = total_compressed &
444 (PAGE_CACHE_SIZE - 1);
445 struct page *page = pages[nr_pages_ret - 1];
448 /* zero the tail end of the last page, we might be
449 * sending it down to disk
452 kaddr = kmap_atomic(page);
453 memset(kaddr + offset, 0,
454 PAGE_CACHE_SIZE - offset);
455 kunmap_atomic(kaddr);
462 trans = btrfs_join_transaction(root);
464 ret = PTR_ERR(trans);
466 goto cleanup_and_out;
468 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
470 /* lets try to make an inline extent */
471 if (ret || total_in < (actual_end - start)) {
472 /* we didn't compress the entire range, try
473 * to make an uncompressed inline extent.
475 ret = cow_file_range_inline(trans, root, inode,
476 start, end, 0, 0, NULL);
478 /* try making a compressed inline extent */
479 ret = cow_file_range_inline(trans, root, inode,
482 compress_type, pages);
486 * inline extent creation worked or returned error,
487 * we don't need to create any more async work items.
488 * Unlock and free up our temp pages.
490 extent_clear_unlock_delalloc(inode,
491 &BTRFS_I(inode)->io_tree,
493 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
494 EXTENT_CLEAR_DELALLOC |
495 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
497 btrfs_end_transaction(trans, root);
500 btrfs_end_transaction(trans, root);
505 * we aren't doing an inline extent round the compressed size
506 * up to a block size boundary so the allocator does sane
509 total_compressed = ALIGN(total_compressed, blocksize);
512 * one last check to make sure the compression is really a
513 * win, compare the page count read with the blocks on disk
515 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
516 if (total_compressed >= total_in) {
519 num_bytes = total_in;
522 if (!will_compress && pages) {
524 * the compression code ran but failed to make things smaller,
525 * free any pages it allocated and our page pointer array
527 for (i = 0; i < nr_pages_ret; i++) {
528 WARN_ON(pages[i]->mapping);
529 page_cache_release(pages[i]);
533 total_compressed = 0;
536 /* flag the file so we don't compress in the future */
537 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
538 !(BTRFS_I(inode)->force_compress)) {
539 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
545 /* the async work queues will take care of doing actual
546 * allocation on disk for these compressed pages,
547 * and will submit them to the elevator.
549 add_async_extent(async_cow, start, num_bytes,
550 total_compressed, pages, nr_pages_ret,
553 if (start + num_bytes < end) {
560 cleanup_and_bail_uncompressed:
562 * No compression, but we still need to write the pages in
563 * the file we've been given so far. redirty the locked
564 * page if it corresponds to our extent and set things up
565 * for the async work queue to run cow_file_range to do
566 * the normal delalloc dance
568 if (page_offset(locked_page) >= start &&
569 page_offset(locked_page) <= end) {
570 __set_page_dirty_nobuffers(locked_page);
571 /* unlocked later on in the async handlers */
574 extent_range_redirty_for_io(inode, start, end);
575 add_async_extent(async_cow, start, end - start + 1,
576 0, NULL, 0, BTRFS_COMPRESS_NONE);
584 for (i = 0; i < nr_pages_ret; i++) {
585 WARN_ON(pages[i]->mapping);
586 page_cache_release(pages[i]);
593 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
595 EXTENT_CLEAR_UNLOCK_PAGE |
597 EXTENT_CLEAR_DELALLOC |
598 EXTENT_SET_WRITEBACK |
599 EXTENT_END_WRITEBACK);
600 if (!trans || IS_ERR(trans))
601 btrfs_error(root->fs_info, ret, "Failed to join transaction");
603 btrfs_abort_transaction(trans, root, ret);
608 * phase two of compressed writeback. This is the ordered portion
609 * of the code, which only gets called in the order the work was
610 * queued. We walk all the async extents created by compress_file_range
611 * and send them down to the disk.
613 static noinline int submit_compressed_extents(struct inode *inode,
614 struct async_cow *async_cow)
616 struct async_extent *async_extent;
618 struct btrfs_trans_handle *trans;
619 struct btrfs_key ins;
620 struct extent_map *em;
621 struct btrfs_root *root = BTRFS_I(inode)->root;
622 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
623 struct extent_io_tree *io_tree;
626 if (list_empty(&async_cow->extents))
630 while (!list_empty(&async_cow->extents)) {
631 async_extent = list_entry(async_cow->extents.next,
632 struct async_extent, list);
633 list_del(&async_extent->list);
635 io_tree = &BTRFS_I(inode)->io_tree;
638 /* did the compression code fall back to uncompressed IO? */
639 if (!async_extent->pages) {
640 int page_started = 0;
641 unsigned long nr_written = 0;
643 lock_extent(io_tree, async_extent->start,
644 async_extent->start +
645 async_extent->ram_size - 1);
647 /* allocate blocks */
648 ret = cow_file_range(inode, async_cow->locked_page,
650 async_extent->start +
651 async_extent->ram_size - 1,
652 &page_started, &nr_written, 0);
657 * if page_started, cow_file_range inserted an
658 * inline extent and took care of all the unlocking
659 * and IO for us. Otherwise, we need to submit
660 * all those pages down to the drive.
662 if (!page_started && !ret)
663 extent_write_locked_range(io_tree,
664 inode, async_extent->start,
665 async_extent->start +
666 async_extent->ram_size - 1,
670 unlock_page(async_cow->locked_page);
676 lock_extent(io_tree, async_extent->start,
677 async_extent->start + async_extent->ram_size - 1);
679 trans = btrfs_join_transaction(root);
681 ret = PTR_ERR(trans);
683 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
684 ret = btrfs_reserve_extent(trans, root,
685 async_extent->compressed_size,
686 async_extent->compressed_size,
687 0, alloc_hint, &ins, 1);
688 if (ret && ret != -ENOSPC)
689 btrfs_abort_transaction(trans, root, ret);
690 btrfs_end_transaction(trans, root);
696 for (i = 0; i < async_extent->nr_pages; i++) {
697 WARN_ON(async_extent->pages[i]->mapping);
698 page_cache_release(async_extent->pages[i]);
700 kfree(async_extent->pages);
701 async_extent->nr_pages = 0;
702 async_extent->pages = NULL;
710 * here we're doing allocation and writeback of the
713 btrfs_drop_extent_cache(inode, async_extent->start,
714 async_extent->start +
715 async_extent->ram_size - 1, 0);
717 em = alloc_extent_map();
720 goto out_free_reserve;
722 em->start = async_extent->start;
723 em->len = async_extent->ram_size;
724 em->orig_start = em->start;
725 em->mod_start = em->start;
726 em->mod_len = em->len;
728 em->block_start = ins.objectid;
729 em->block_len = ins.offset;
730 em->orig_block_len = ins.offset;
731 em->ram_bytes = async_extent->ram_size;
732 em->bdev = root->fs_info->fs_devices->latest_bdev;
733 em->compress_type = async_extent->compress_type;
734 set_bit(EXTENT_FLAG_PINNED, &em->flags);
735 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
739 write_lock(&em_tree->lock);
740 ret = add_extent_mapping(em_tree, em, 1);
741 write_unlock(&em_tree->lock);
742 if (ret != -EEXIST) {
746 btrfs_drop_extent_cache(inode, async_extent->start,
747 async_extent->start +
748 async_extent->ram_size - 1, 0);
752 goto out_free_reserve;
754 ret = btrfs_add_ordered_extent_compress(inode,
757 async_extent->ram_size,
759 BTRFS_ORDERED_COMPRESSED,
760 async_extent->compress_type);
762 goto out_free_reserve;
765 * clear dirty, set writeback and unlock the pages.
767 extent_clear_unlock_delalloc(inode,
768 &BTRFS_I(inode)->io_tree,
770 async_extent->start +
771 async_extent->ram_size - 1,
772 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
773 EXTENT_CLEAR_UNLOCK |
774 EXTENT_CLEAR_DELALLOC |
775 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
777 ret = btrfs_submit_compressed_write(inode,
779 async_extent->ram_size,
781 ins.offset, async_extent->pages,
782 async_extent->nr_pages);
783 alloc_hint = ins.objectid + ins.offset;
793 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
795 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
797 async_extent->start +
798 async_extent->ram_size - 1,
799 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
800 EXTENT_CLEAR_UNLOCK |
801 EXTENT_CLEAR_DELALLOC |
803 EXTENT_SET_WRITEBACK |
804 EXTENT_END_WRITEBACK);
809 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
812 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
813 struct extent_map *em;
816 read_lock(&em_tree->lock);
817 em = search_extent_mapping(em_tree, start, num_bytes);
820 * if block start isn't an actual block number then find the
821 * first block in this inode and use that as a hint. If that
822 * block is also bogus then just don't worry about it.
824 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
826 em = search_extent_mapping(em_tree, 0, 0);
827 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
828 alloc_hint = em->block_start;
832 alloc_hint = em->block_start;
836 read_unlock(&em_tree->lock);
842 * when extent_io.c finds a delayed allocation range in the file,
843 * the call backs end up in this code. The basic idea is to
844 * allocate extents on disk for the range, and create ordered data structs
845 * in ram to track those extents.
847 * locked_page is the page that writepage had locked already. We use
848 * it to make sure we don't do extra locks or unlocks.
850 * *page_started is set to one if we unlock locked_page and do everything
851 * required to start IO on it. It may be clean and already done with
854 static noinline int __cow_file_range(struct btrfs_trans_handle *trans,
856 struct btrfs_root *root,
857 struct page *locked_page,
858 u64 start, u64 end, int *page_started,
859 unsigned long *nr_written,
864 unsigned long ram_size;
867 u64 blocksize = root->sectorsize;
868 struct btrfs_key ins;
869 struct extent_map *em;
870 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
873 BUG_ON(btrfs_is_free_space_inode(inode));
875 num_bytes = ALIGN(end - start + 1, blocksize);
876 num_bytes = max(blocksize, num_bytes);
877 disk_num_bytes = num_bytes;
879 /* if this is a small write inside eof, kick off defrag */
880 if (num_bytes < 64 * 1024 &&
881 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
882 btrfs_add_inode_defrag(trans, inode);
885 /* lets try to make an inline extent */
886 ret = cow_file_range_inline(trans, root, inode,
887 start, end, 0, 0, NULL);
889 extent_clear_unlock_delalloc(inode,
890 &BTRFS_I(inode)->io_tree,
892 EXTENT_CLEAR_UNLOCK_PAGE |
893 EXTENT_CLEAR_UNLOCK |
894 EXTENT_CLEAR_DELALLOC |
896 EXTENT_SET_WRITEBACK |
897 EXTENT_END_WRITEBACK);
899 *nr_written = *nr_written +
900 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
903 } else if (ret < 0) {
904 btrfs_abort_transaction(trans, root, ret);
909 BUG_ON(disk_num_bytes >
910 btrfs_super_total_bytes(root->fs_info->super_copy));
912 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
913 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
915 while (disk_num_bytes > 0) {
918 cur_alloc_size = disk_num_bytes;
919 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
920 root->sectorsize, 0, alloc_hint,
923 btrfs_abort_transaction(trans, root, ret);
927 em = alloc_extent_map();
933 em->orig_start = em->start;
934 ram_size = ins.offset;
935 em->len = ins.offset;
936 em->mod_start = em->start;
937 em->mod_len = em->len;
939 em->block_start = ins.objectid;
940 em->block_len = ins.offset;
941 em->orig_block_len = ins.offset;
942 em->ram_bytes = ram_size;
943 em->bdev = root->fs_info->fs_devices->latest_bdev;
944 set_bit(EXTENT_FLAG_PINNED, &em->flags);
948 write_lock(&em_tree->lock);
949 ret = add_extent_mapping(em_tree, em, 1);
950 write_unlock(&em_tree->lock);
951 if (ret != -EEXIST) {
955 btrfs_drop_extent_cache(inode, start,
956 start + ram_size - 1, 0);
961 cur_alloc_size = ins.offset;
962 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
963 ram_size, cur_alloc_size, 0);
967 if (root->root_key.objectid ==
968 BTRFS_DATA_RELOC_TREE_OBJECTID) {
969 ret = btrfs_reloc_clone_csums(inode, start,
972 btrfs_abort_transaction(trans, root, ret);
977 if (disk_num_bytes < cur_alloc_size)
980 /* we're not doing compressed IO, don't unlock the first
981 * page (which the caller expects to stay locked), don't
982 * clear any dirty bits and don't set any writeback bits
984 * Do set the Private2 bit so we know this page was properly
985 * setup for writepage
987 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
988 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
991 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
992 start, start + ram_size - 1,
994 disk_num_bytes -= cur_alloc_size;
995 num_bytes -= cur_alloc_size;
996 alloc_hint = ins.objectid + ins.offset;
997 start += cur_alloc_size;
1003 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
1005 extent_clear_unlock_delalloc(inode,
1006 &BTRFS_I(inode)->io_tree,
1007 start, end, locked_page,
1008 EXTENT_CLEAR_UNLOCK_PAGE |
1009 EXTENT_CLEAR_UNLOCK |
1010 EXTENT_CLEAR_DELALLOC |
1011 EXTENT_CLEAR_DIRTY |
1012 EXTENT_SET_WRITEBACK |
1013 EXTENT_END_WRITEBACK);
1018 static noinline int cow_file_range(struct inode *inode,
1019 struct page *locked_page,
1020 u64 start, u64 end, int *page_started,
1021 unsigned long *nr_written,
1024 struct btrfs_trans_handle *trans;
1025 struct btrfs_root *root = BTRFS_I(inode)->root;
1028 trans = btrfs_join_transaction(root);
1029 if (IS_ERR(trans)) {
1030 extent_clear_unlock_delalloc(inode,
1031 &BTRFS_I(inode)->io_tree,
1032 start, end, locked_page,
1033 EXTENT_CLEAR_UNLOCK_PAGE |
1034 EXTENT_CLEAR_UNLOCK |
1035 EXTENT_CLEAR_DELALLOC |
1036 EXTENT_CLEAR_DIRTY |
1037 EXTENT_SET_WRITEBACK |
1038 EXTENT_END_WRITEBACK);
1039 return PTR_ERR(trans);
1041 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1043 ret = __cow_file_range(trans, inode, root, locked_page, start, end,
1044 page_started, nr_written, unlock);
1046 btrfs_end_transaction(trans, root);
1052 * work queue call back to started compression on a file and pages
1054 static noinline void async_cow_start(struct btrfs_work *work)
1056 struct async_cow *async_cow;
1058 async_cow = container_of(work, struct async_cow, work);
1060 compress_file_range(async_cow->inode, async_cow->locked_page,
1061 async_cow->start, async_cow->end, async_cow,
1063 if (num_added == 0) {
1064 btrfs_add_delayed_iput(async_cow->inode);
1065 async_cow->inode = NULL;
1070 * work queue call back to submit previously compressed pages
1072 static noinline void async_cow_submit(struct btrfs_work *work)
1074 struct async_cow *async_cow;
1075 struct btrfs_root *root;
1076 unsigned long nr_pages;
1078 async_cow = container_of(work, struct async_cow, work);
1080 root = async_cow->root;
1081 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1084 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1086 waitqueue_active(&root->fs_info->async_submit_wait))
1087 wake_up(&root->fs_info->async_submit_wait);
1089 if (async_cow->inode)
1090 submit_compressed_extents(async_cow->inode, async_cow);
1093 static noinline void async_cow_free(struct btrfs_work *work)
1095 struct async_cow *async_cow;
1096 async_cow = container_of(work, struct async_cow, work);
1097 if (async_cow->inode)
1098 btrfs_add_delayed_iput(async_cow->inode);
1102 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1103 u64 start, u64 end, int *page_started,
1104 unsigned long *nr_written)
1106 struct async_cow *async_cow;
1107 struct btrfs_root *root = BTRFS_I(inode)->root;
1108 unsigned long nr_pages;
1110 int limit = 10 * 1024 * 1024;
1112 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1113 1, 0, NULL, GFP_NOFS);
1114 while (start < end) {
1115 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1116 BUG_ON(!async_cow); /* -ENOMEM */
1117 async_cow->inode = igrab(inode);
1118 async_cow->root = root;
1119 async_cow->locked_page = locked_page;
1120 async_cow->start = start;
1122 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1125 cur_end = min(end, start + 512 * 1024 - 1);
1127 async_cow->end = cur_end;
1128 INIT_LIST_HEAD(&async_cow->extents);
1130 async_cow->work.func = async_cow_start;
1131 async_cow->work.ordered_func = async_cow_submit;
1132 async_cow->work.ordered_free = async_cow_free;
1133 async_cow->work.flags = 0;
1135 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1137 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1139 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1142 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1143 wait_event(root->fs_info->async_submit_wait,
1144 (atomic_read(&root->fs_info->async_delalloc_pages) <
1148 while (atomic_read(&root->fs_info->async_submit_draining) &&
1149 atomic_read(&root->fs_info->async_delalloc_pages)) {
1150 wait_event(root->fs_info->async_submit_wait,
1151 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1155 *nr_written += nr_pages;
1156 start = cur_end + 1;
1162 static noinline int csum_exist_in_range(struct btrfs_root *root,
1163 u64 bytenr, u64 num_bytes)
1166 struct btrfs_ordered_sum *sums;
1169 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1170 bytenr + num_bytes - 1, &list, 0);
1171 if (ret == 0 && list_empty(&list))
1174 while (!list_empty(&list)) {
1175 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1176 list_del(&sums->list);
1183 * when nowcow writeback call back. This checks for snapshots or COW copies
1184 * of the extents that exist in the file, and COWs the file as required.
1186 * If no cow copies or snapshots exist, we write directly to the existing
1189 static noinline int run_delalloc_nocow(struct inode *inode,
1190 struct page *locked_page,
1191 u64 start, u64 end, int *page_started, int force,
1192 unsigned long *nr_written)
1194 struct btrfs_root *root = BTRFS_I(inode)->root;
1195 struct btrfs_trans_handle *trans;
1196 struct extent_buffer *leaf;
1197 struct btrfs_path *path;
1198 struct btrfs_file_extent_item *fi;
1199 struct btrfs_key found_key;
1214 u64 ino = btrfs_ino(inode);
1216 path = btrfs_alloc_path();
1218 extent_clear_unlock_delalloc(inode,
1219 &BTRFS_I(inode)->io_tree,
1220 start, end, locked_page,
1221 EXTENT_CLEAR_UNLOCK_PAGE |
1222 EXTENT_CLEAR_UNLOCK |
1223 EXTENT_CLEAR_DELALLOC |
1224 EXTENT_CLEAR_DIRTY |
1225 EXTENT_SET_WRITEBACK |
1226 EXTENT_END_WRITEBACK);
1230 nolock = btrfs_is_free_space_inode(inode);
1233 trans = btrfs_join_transaction_nolock(root);
1235 trans = btrfs_join_transaction(root);
1237 if (IS_ERR(trans)) {
1238 extent_clear_unlock_delalloc(inode,
1239 &BTRFS_I(inode)->io_tree,
1240 start, end, locked_page,
1241 EXTENT_CLEAR_UNLOCK_PAGE |
1242 EXTENT_CLEAR_UNLOCK |
1243 EXTENT_CLEAR_DELALLOC |
1244 EXTENT_CLEAR_DIRTY |
1245 EXTENT_SET_WRITEBACK |
1246 EXTENT_END_WRITEBACK);
1247 btrfs_free_path(path);
1248 return PTR_ERR(trans);
1251 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1253 cow_start = (u64)-1;
1256 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1259 btrfs_abort_transaction(trans, root, ret);
1262 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1263 leaf = path->nodes[0];
1264 btrfs_item_key_to_cpu(leaf, &found_key,
1265 path->slots[0] - 1);
1266 if (found_key.objectid == ino &&
1267 found_key.type == BTRFS_EXTENT_DATA_KEY)
1272 leaf = path->nodes[0];
1273 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1274 ret = btrfs_next_leaf(root, path);
1276 btrfs_abort_transaction(trans, root, ret);
1281 leaf = path->nodes[0];
1287 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1289 if (found_key.objectid > ino ||
1290 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1291 found_key.offset > end)
1294 if (found_key.offset > cur_offset) {
1295 extent_end = found_key.offset;
1300 fi = btrfs_item_ptr(leaf, path->slots[0],
1301 struct btrfs_file_extent_item);
1302 extent_type = btrfs_file_extent_type(leaf, fi);
1304 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1305 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1306 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1307 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1308 extent_offset = btrfs_file_extent_offset(leaf, fi);
1309 extent_end = found_key.offset +
1310 btrfs_file_extent_num_bytes(leaf, fi);
1312 btrfs_file_extent_disk_num_bytes(leaf, fi);
1313 if (extent_end <= start) {
1317 if (disk_bytenr == 0)
1319 if (btrfs_file_extent_compression(leaf, fi) ||
1320 btrfs_file_extent_encryption(leaf, fi) ||
1321 btrfs_file_extent_other_encoding(leaf, fi))
1323 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1325 if (btrfs_extent_readonly(root, disk_bytenr))
1327 if (btrfs_cross_ref_exist(trans, root, ino,
1329 extent_offset, disk_bytenr))
1331 disk_bytenr += extent_offset;
1332 disk_bytenr += cur_offset - found_key.offset;
1333 num_bytes = min(end + 1, extent_end) - cur_offset;
1335 * force cow if csum exists in the range.
1336 * this ensure that csum for a given extent are
1337 * either valid or do not exist.
1339 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1342 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1343 extent_end = found_key.offset +
1344 btrfs_file_extent_inline_len(leaf, fi);
1345 extent_end = ALIGN(extent_end, root->sectorsize);
1350 if (extent_end <= start) {
1355 if (cow_start == (u64)-1)
1356 cow_start = cur_offset;
1357 cur_offset = extent_end;
1358 if (cur_offset > end)
1364 btrfs_release_path(path);
1365 if (cow_start != (u64)-1) {
1366 ret = __cow_file_range(trans, inode, root, locked_page,
1367 cow_start, found_key.offset - 1,
1368 page_started, nr_written, 1);
1370 btrfs_abort_transaction(trans, root, ret);
1373 cow_start = (u64)-1;
1376 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1377 struct extent_map *em;
1378 struct extent_map_tree *em_tree;
1379 em_tree = &BTRFS_I(inode)->extent_tree;
1380 em = alloc_extent_map();
1381 BUG_ON(!em); /* -ENOMEM */
1382 em->start = cur_offset;
1383 em->orig_start = found_key.offset - extent_offset;
1384 em->len = num_bytes;
1385 em->block_len = num_bytes;
1386 em->block_start = disk_bytenr;
1387 em->orig_block_len = disk_num_bytes;
1388 em->ram_bytes = ram_bytes;
1389 em->bdev = root->fs_info->fs_devices->latest_bdev;
1390 em->mod_start = em->start;
1391 em->mod_len = em->len;
1392 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1393 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1394 em->generation = -1;
1396 write_lock(&em_tree->lock);
1397 ret = add_extent_mapping(em_tree, em, 1);
1398 write_unlock(&em_tree->lock);
1399 if (ret != -EEXIST) {
1400 free_extent_map(em);
1403 btrfs_drop_extent_cache(inode, em->start,
1404 em->start + em->len - 1, 0);
1406 type = BTRFS_ORDERED_PREALLOC;
1408 type = BTRFS_ORDERED_NOCOW;
1411 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1412 num_bytes, num_bytes, type);
1413 BUG_ON(ret); /* -ENOMEM */
1415 if (root->root_key.objectid ==
1416 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1417 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1420 btrfs_abort_transaction(trans, root, ret);
1425 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1426 cur_offset, cur_offset + num_bytes - 1,
1427 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1428 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1429 EXTENT_SET_PRIVATE2);
1430 cur_offset = extent_end;
1431 if (cur_offset > end)
1434 btrfs_release_path(path);
1436 if (cur_offset <= end && cow_start == (u64)-1) {
1437 cow_start = cur_offset;
1441 if (cow_start != (u64)-1) {
1442 ret = __cow_file_range(trans, inode, root, locked_page,
1444 page_started, nr_written, 1);
1446 btrfs_abort_transaction(trans, root, ret);
1452 err = btrfs_end_transaction(trans, root);
1456 if (ret && cur_offset < end)
1457 extent_clear_unlock_delalloc(inode,
1458 &BTRFS_I(inode)->io_tree,
1459 cur_offset, end, locked_page,
1460 EXTENT_CLEAR_UNLOCK_PAGE |
1461 EXTENT_CLEAR_UNLOCK |
1462 EXTENT_CLEAR_DELALLOC |
1463 EXTENT_CLEAR_DIRTY |
1464 EXTENT_SET_WRITEBACK |
1465 EXTENT_END_WRITEBACK);
1467 btrfs_free_path(path);
1472 * extent_io.c call back to do delayed allocation processing
1474 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1475 u64 start, u64 end, int *page_started,
1476 unsigned long *nr_written)
1479 struct btrfs_root *root = BTRFS_I(inode)->root;
1481 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1482 ret = run_delalloc_nocow(inode, locked_page, start, end,
1483 page_started, 1, nr_written);
1484 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1485 ret = run_delalloc_nocow(inode, locked_page, start, end,
1486 page_started, 0, nr_written);
1487 } else if (!btrfs_test_opt(root, COMPRESS) &&
1488 !(BTRFS_I(inode)->force_compress) &&
1489 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1490 ret = cow_file_range(inode, locked_page, start, end,
1491 page_started, nr_written, 1);
1493 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1494 &BTRFS_I(inode)->runtime_flags);
1495 ret = cow_file_range_async(inode, locked_page, start, end,
1496 page_started, nr_written);
1501 static void btrfs_split_extent_hook(struct inode *inode,
1502 struct extent_state *orig, u64 split)
1504 /* not delalloc, ignore it */
1505 if (!(orig->state & EXTENT_DELALLOC))
1508 spin_lock(&BTRFS_I(inode)->lock);
1509 BTRFS_I(inode)->outstanding_extents++;
1510 spin_unlock(&BTRFS_I(inode)->lock);
1514 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1515 * extents so we can keep track of new extents that are just merged onto old
1516 * extents, such as when we are doing sequential writes, so we can properly
1517 * account for the metadata space we'll need.
1519 static void btrfs_merge_extent_hook(struct inode *inode,
1520 struct extent_state *new,
1521 struct extent_state *other)
1523 /* not delalloc, ignore it */
1524 if (!(other->state & EXTENT_DELALLOC))
1527 spin_lock(&BTRFS_I(inode)->lock);
1528 BTRFS_I(inode)->outstanding_extents--;
1529 spin_unlock(&BTRFS_I(inode)->lock);
1533 * extent_io.c set_bit_hook, used to track delayed allocation
1534 * bytes in this file, and to maintain the list of inodes that
1535 * have pending delalloc work to be done.
1537 static void btrfs_set_bit_hook(struct inode *inode,
1538 struct extent_state *state, unsigned long *bits)
1542 * set_bit and clear bit hooks normally require _irqsave/restore
1543 * but in this case, we are only testing for the DELALLOC
1544 * bit, which is only set or cleared with irqs on
1546 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1547 struct btrfs_root *root = BTRFS_I(inode)->root;
1548 u64 len = state->end + 1 - state->start;
1549 bool do_list = !btrfs_is_free_space_inode(inode);
1551 if (*bits & EXTENT_FIRST_DELALLOC) {
1552 *bits &= ~EXTENT_FIRST_DELALLOC;
1554 spin_lock(&BTRFS_I(inode)->lock);
1555 BTRFS_I(inode)->outstanding_extents++;
1556 spin_unlock(&BTRFS_I(inode)->lock);
1559 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1560 root->fs_info->delalloc_batch);
1561 spin_lock(&BTRFS_I(inode)->lock);
1562 BTRFS_I(inode)->delalloc_bytes += len;
1563 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1564 &BTRFS_I(inode)->runtime_flags)) {
1565 spin_lock(&root->fs_info->delalloc_lock);
1566 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1567 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1568 &root->fs_info->delalloc_inodes);
1569 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1570 &BTRFS_I(inode)->runtime_flags);
1572 spin_unlock(&root->fs_info->delalloc_lock);
1574 spin_unlock(&BTRFS_I(inode)->lock);
1579 * extent_io.c clear_bit_hook, see set_bit_hook for why
1581 static void btrfs_clear_bit_hook(struct inode *inode,
1582 struct extent_state *state,
1583 unsigned long *bits)
1586 * set_bit and clear bit hooks normally require _irqsave/restore
1587 * but in this case, we are only testing for the DELALLOC
1588 * bit, which is only set or cleared with irqs on
1590 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1591 struct btrfs_root *root = BTRFS_I(inode)->root;
1592 u64 len = state->end + 1 - state->start;
1593 bool do_list = !btrfs_is_free_space_inode(inode);
1595 if (*bits & EXTENT_FIRST_DELALLOC) {
1596 *bits &= ~EXTENT_FIRST_DELALLOC;
1597 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1598 spin_lock(&BTRFS_I(inode)->lock);
1599 BTRFS_I(inode)->outstanding_extents--;
1600 spin_unlock(&BTRFS_I(inode)->lock);
1603 if (*bits & EXTENT_DO_ACCOUNTING)
1604 btrfs_delalloc_release_metadata(inode, len);
1606 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1608 btrfs_free_reserved_data_space(inode, len);
1610 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1611 root->fs_info->delalloc_batch);
1612 spin_lock(&BTRFS_I(inode)->lock);
1613 BTRFS_I(inode)->delalloc_bytes -= len;
1614 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1615 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1616 &BTRFS_I(inode)->runtime_flags)) {
1617 spin_lock(&root->fs_info->delalloc_lock);
1618 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1619 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1620 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1621 &BTRFS_I(inode)->runtime_flags);
1623 spin_unlock(&root->fs_info->delalloc_lock);
1625 spin_unlock(&BTRFS_I(inode)->lock);
1630 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1631 * we don't create bios that span stripes or chunks
1633 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1634 size_t size, struct bio *bio,
1635 unsigned long bio_flags)
1637 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1638 u64 logical = (u64)bio->bi_sector << 9;
1643 if (bio_flags & EXTENT_BIO_COMPRESSED)
1646 length = bio->bi_size;
1647 map_length = length;
1648 ret = btrfs_map_block(root->fs_info, rw, logical,
1649 &map_length, NULL, 0);
1650 /* Will always return 0 with map_multi == NULL */
1652 if (map_length < length + size)
1658 * in order to insert checksums into the metadata in large chunks,
1659 * we wait until bio submission time. All the pages in the bio are
1660 * checksummed and sums are attached onto the ordered extent record.
1662 * At IO completion time the cums attached on the ordered extent record
1663 * are inserted into the btree
1665 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1666 struct bio *bio, int mirror_num,
1667 unsigned long bio_flags,
1670 struct btrfs_root *root = BTRFS_I(inode)->root;
1673 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1674 BUG_ON(ret); /* -ENOMEM */
1679 * in order to insert checksums into the metadata in large chunks,
1680 * we wait until bio submission time. All the pages in the bio are
1681 * checksummed and sums are attached onto the ordered extent record.
1683 * At IO completion time the cums attached on the ordered extent record
1684 * are inserted into the btree
1686 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1687 int mirror_num, unsigned long bio_flags,
1690 struct btrfs_root *root = BTRFS_I(inode)->root;
1693 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1695 bio_endio(bio, ret);
1700 * extent_io.c submission hook. This does the right thing for csum calculation
1701 * on write, or reading the csums from the tree before a read
1703 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1704 int mirror_num, unsigned long bio_flags,
1707 struct btrfs_root *root = BTRFS_I(inode)->root;
1711 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1713 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1715 if (btrfs_is_free_space_inode(inode))
1718 if (!(rw & REQ_WRITE)) {
1719 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1723 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1724 ret = btrfs_submit_compressed_read(inode, bio,
1728 } else if (!skip_sum) {
1729 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1734 } else if (async && !skip_sum) {
1735 /* csum items have already been cloned */
1736 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1738 /* we're doing a write, do the async checksumming */
1739 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1740 inode, rw, bio, mirror_num,
1741 bio_flags, bio_offset,
1742 __btrfs_submit_bio_start,
1743 __btrfs_submit_bio_done);
1745 } else if (!skip_sum) {
1746 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1752 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1756 bio_endio(bio, ret);
1761 * given a list of ordered sums record them in the inode. This happens
1762 * at IO completion time based on sums calculated at bio submission time.
1764 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1765 struct inode *inode, u64 file_offset,
1766 struct list_head *list)
1768 struct btrfs_ordered_sum *sum;
1770 list_for_each_entry(sum, list, list) {
1771 trans->adding_csums = 1;
1772 btrfs_csum_file_blocks(trans,
1773 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1774 trans->adding_csums = 0;
1779 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1780 struct extent_state **cached_state)
1782 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1783 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1784 cached_state, GFP_NOFS);
1787 /* see btrfs_writepage_start_hook for details on why this is required */
1788 struct btrfs_writepage_fixup {
1790 struct btrfs_work work;
1793 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1795 struct btrfs_writepage_fixup *fixup;
1796 struct btrfs_ordered_extent *ordered;
1797 struct extent_state *cached_state = NULL;
1799 struct inode *inode;
1804 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1808 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1809 ClearPageChecked(page);
1813 inode = page->mapping->host;
1814 page_start = page_offset(page);
1815 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1817 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1820 /* already ordered? We're done */
1821 if (PagePrivate2(page))
1824 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1826 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1827 page_end, &cached_state, GFP_NOFS);
1829 btrfs_start_ordered_extent(inode, ordered, 1);
1830 btrfs_put_ordered_extent(ordered);
1834 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1836 mapping_set_error(page->mapping, ret);
1837 end_extent_writepage(page, ret, page_start, page_end);
1838 ClearPageChecked(page);
1842 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1843 ClearPageChecked(page);
1844 set_page_dirty(page);
1846 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1847 &cached_state, GFP_NOFS);
1850 page_cache_release(page);
1855 * There are a few paths in the higher layers of the kernel that directly
1856 * set the page dirty bit without asking the filesystem if it is a
1857 * good idea. This causes problems because we want to make sure COW
1858 * properly happens and the data=ordered rules are followed.
1860 * In our case any range that doesn't have the ORDERED bit set
1861 * hasn't been properly setup for IO. We kick off an async process
1862 * to fix it up. The async helper will wait for ordered extents, set
1863 * the delalloc bit and make it safe to write the page.
1865 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1867 struct inode *inode = page->mapping->host;
1868 struct btrfs_writepage_fixup *fixup;
1869 struct btrfs_root *root = BTRFS_I(inode)->root;
1871 /* this page is properly in the ordered list */
1872 if (TestClearPagePrivate2(page))
1875 if (PageChecked(page))
1878 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1882 SetPageChecked(page);
1883 page_cache_get(page);
1884 fixup->work.func = btrfs_writepage_fixup_worker;
1886 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1890 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1891 struct inode *inode, u64 file_pos,
1892 u64 disk_bytenr, u64 disk_num_bytes,
1893 u64 num_bytes, u64 ram_bytes,
1894 u8 compression, u8 encryption,
1895 u16 other_encoding, int extent_type)
1897 struct btrfs_root *root = BTRFS_I(inode)->root;
1898 struct btrfs_file_extent_item *fi;
1899 struct btrfs_path *path;
1900 struct extent_buffer *leaf;
1901 struct btrfs_key ins;
1904 path = btrfs_alloc_path();
1908 path->leave_spinning = 1;
1911 * we may be replacing one extent in the tree with another.
1912 * The new extent is pinned in the extent map, and we don't want
1913 * to drop it from the cache until it is completely in the btree.
1915 * So, tell btrfs_drop_extents to leave this extent in the cache.
1916 * the caller is expected to unpin it and allow it to be merged
1919 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1920 file_pos + num_bytes, 0);
1924 ins.objectid = btrfs_ino(inode);
1925 ins.offset = file_pos;
1926 ins.type = BTRFS_EXTENT_DATA_KEY;
1927 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1930 leaf = path->nodes[0];
1931 fi = btrfs_item_ptr(leaf, path->slots[0],
1932 struct btrfs_file_extent_item);
1933 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1934 btrfs_set_file_extent_type(leaf, fi, extent_type);
1935 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1936 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1937 btrfs_set_file_extent_offset(leaf, fi, 0);
1938 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1939 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1940 btrfs_set_file_extent_compression(leaf, fi, compression);
1941 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1942 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1944 btrfs_mark_buffer_dirty(leaf);
1945 btrfs_release_path(path);
1947 inode_add_bytes(inode, num_bytes);
1949 ins.objectid = disk_bytenr;
1950 ins.offset = disk_num_bytes;
1951 ins.type = BTRFS_EXTENT_ITEM_KEY;
1952 ret = btrfs_alloc_reserved_file_extent(trans, root,
1953 root->root_key.objectid,
1954 btrfs_ino(inode), file_pos, &ins);
1956 btrfs_free_path(path);
1961 /* snapshot-aware defrag */
1962 struct sa_defrag_extent_backref {
1963 struct rb_node node;
1964 struct old_sa_defrag_extent *old;
1973 struct old_sa_defrag_extent {
1974 struct list_head list;
1975 struct new_sa_defrag_extent *new;
1984 struct new_sa_defrag_extent {
1985 struct rb_root root;
1986 struct list_head head;
1987 struct btrfs_path *path;
1988 struct inode *inode;
1996 static int backref_comp(struct sa_defrag_extent_backref *b1,
1997 struct sa_defrag_extent_backref *b2)
1999 if (b1->root_id < b2->root_id)
2001 else if (b1->root_id > b2->root_id)
2004 if (b1->inum < b2->inum)
2006 else if (b1->inum > b2->inum)
2009 if (b1->file_pos < b2->file_pos)
2011 else if (b1->file_pos > b2->file_pos)
2015 * [------------------------------] ===> (a range of space)
2016 * |<--->| |<---->| =============> (fs/file tree A)
2017 * |<---------------------------->| ===> (fs/file tree B)
2019 * A range of space can refer to two file extents in one tree while
2020 * refer to only one file extent in another tree.
2022 * So we may process a disk offset more than one time(two extents in A)
2023 * and locate at the same extent(one extent in B), then insert two same
2024 * backrefs(both refer to the extent in B).
2029 static void backref_insert(struct rb_root *root,
2030 struct sa_defrag_extent_backref *backref)
2032 struct rb_node **p = &root->rb_node;
2033 struct rb_node *parent = NULL;
2034 struct sa_defrag_extent_backref *entry;
2039 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2041 ret = backref_comp(backref, entry);
2045 p = &(*p)->rb_right;
2048 rb_link_node(&backref->node, parent, p);
2049 rb_insert_color(&backref->node, root);
2053 * Note the backref might has changed, and in this case we just return 0.
2055 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2058 struct btrfs_file_extent_item *extent;
2059 struct btrfs_fs_info *fs_info;
2060 struct old_sa_defrag_extent *old = ctx;
2061 struct new_sa_defrag_extent *new = old->new;
2062 struct btrfs_path *path = new->path;
2063 struct btrfs_key key;
2064 struct btrfs_root *root;
2065 struct sa_defrag_extent_backref *backref;
2066 struct extent_buffer *leaf;
2067 struct inode *inode = new->inode;
2073 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2074 inum == btrfs_ino(inode))
2077 key.objectid = root_id;
2078 key.type = BTRFS_ROOT_ITEM_KEY;
2079 key.offset = (u64)-1;
2081 fs_info = BTRFS_I(inode)->root->fs_info;
2082 root = btrfs_read_fs_root_no_name(fs_info, &key);
2084 if (PTR_ERR(root) == -ENOENT)
2087 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2088 inum, offset, root_id);
2089 return PTR_ERR(root);
2092 key.objectid = inum;
2093 key.type = BTRFS_EXTENT_DATA_KEY;
2094 if (offset > (u64)-1 << 32)
2097 key.offset = offset;
2099 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2108 leaf = path->nodes[0];
2109 slot = path->slots[0];
2111 if (slot >= btrfs_header_nritems(leaf)) {
2112 ret = btrfs_next_leaf(root, path);
2115 } else if (ret > 0) {
2124 btrfs_item_key_to_cpu(leaf, &key, slot);
2126 if (key.objectid > inum)
2129 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2132 extent = btrfs_item_ptr(leaf, slot,
2133 struct btrfs_file_extent_item);
2135 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2138 extent_offset = btrfs_file_extent_offset(leaf, extent);
2139 if (key.offset - extent_offset != offset)
2142 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2143 if (extent_offset >= old->extent_offset + old->offset +
2144 old->len || extent_offset + num_bytes <=
2145 old->extent_offset + old->offset)
2151 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2157 backref->root_id = root_id;
2158 backref->inum = inum;
2159 backref->file_pos = offset + extent_offset;
2160 backref->num_bytes = num_bytes;
2161 backref->extent_offset = extent_offset;
2162 backref->generation = btrfs_file_extent_generation(leaf, extent);
2164 backref_insert(&new->root, backref);
2167 btrfs_release_path(path);
2172 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2173 struct new_sa_defrag_extent *new)
2175 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2176 struct old_sa_defrag_extent *old, *tmp;
2181 list_for_each_entry_safe(old, tmp, &new->head, list) {
2182 ret = iterate_inodes_from_logical(old->bytenr, fs_info,
2183 path, record_one_backref,
2185 BUG_ON(ret < 0 && ret != -ENOENT);
2187 /* no backref to be processed for this extent */
2189 list_del(&old->list);
2194 if (list_empty(&new->head))
2200 static int relink_is_mergable(struct extent_buffer *leaf,
2201 struct btrfs_file_extent_item *fi,
2204 if (btrfs_file_extent_disk_bytenr(leaf, fi) != disk_bytenr)
2207 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2210 if (btrfs_file_extent_compression(leaf, fi) ||
2211 btrfs_file_extent_encryption(leaf, fi) ||
2212 btrfs_file_extent_other_encoding(leaf, fi))
2219 * Note the backref might has changed, and in this case we just return 0.
2221 static noinline int relink_extent_backref(struct btrfs_path *path,
2222 struct sa_defrag_extent_backref *prev,
2223 struct sa_defrag_extent_backref *backref)
2225 struct btrfs_file_extent_item *extent;
2226 struct btrfs_file_extent_item *item;
2227 struct btrfs_ordered_extent *ordered;
2228 struct btrfs_trans_handle *trans;
2229 struct btrfs_fs_info *fs_info;
2230 struct btrfs_root *root;
2231 struct btrfs_key key;
2232 struct extent_buffer *leaf;
2233 struct old_sa_defrag_extent *old = backref->old;
2234 struct new_sa_defrag_extent *new = old->new;
2235 struct inode *src_inode = new->inode;
2236 struct inode *inode;
2237 struct extent_state *cached = NULL;
2246 if (prev && prev->root_id == backref->root_id &&
2247 prev->inum == backref->inum &&
2248 prev->file_pos + prev->num_bytes == backref->file_pos)
2251 /* step 1: get root */
2252 key.objectid = backref->root_id;
2253 key.type = BTRFS_ROOT_ITEM_KEY;
2254 key.offset = (u64)-1;
2256 fs_info = BTRFS_I(src_inode)->root->fs_info;
2257 index = srcu_read_lock(&fs_info->subvol_srcu);
2259 root = btrfs_read_fs_root_no_name(fs_info, &key);
2261 srcu_read_unlock(&fs_info->subvol_srcu, index);
2262 if (PTR_ERR(root) == -ENOENT)
2264 return PTR_ERR(root);
2266 if (btrfs_root_refs(&root->root_item) == 0) {
2267 srcu_read_unlock(&fs_info->subvol_srcu, index);
2268 /* parse ENOENT to 0 */
2272 /* step 2: get inode */
2273 key.objectid = backref->inum;
2274 key.type = BTRFS_INODE_ITEM_KEY;
2277 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2278 if (IS_ERR(inode)) {
2279 srcu_read_unlock(&fs_info->subvol_srcu, index);
2283 srcu_read_unlock(&fs_info->subvol_srcu, index);
2285 /* step 3: relink backref */
2286 lock_start = backref->file_pos;
2287 lock_end = backref->file_pos + backref->num_bytes - 1;
2288 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2291 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2293 btrfs_put_ordered_extent(ordered);
2297 trans = btrfs_join_transaction(root);
2298 if (IS_ERR(trans)) {
2299 ret = PTR_ERR(trans);
2303 key.objectid = backref->inum;
2304 key.type = BTRFS_EXTENT_DATA_KEY;
2305 key.offset = backref->file_pos;
2307 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2310 } else if (ret > 0) {
2315 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2316 struct btrfs_file_extent_item);
2318 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2319 backref->generation)
2322 btrfs_release_path(path);
2324 start = backref->file_pos;
2325 if (backref->extent_offset < old->extent_offset + old->offset)
2326 start += old->extent_offset + old->offset -
2327 backref->extent_offset;
2329 len = min(backref->extent_offset + backref->num_bytes,
2330 old->extent_offset + old->offset + old->len);
2331 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2333 ret = btrfs_drop_extents(trans, root, inode, start,
2338 key.objectid = btrfs_ino(inode);
2339 key.type = BTRFS_EXTENT_DATA_KEY;
2342 path->leave_spinning = 1;
2344 struct btrfs_file_extent_item *fi;
2346 struct btrfs_key found_key;
2348 ret = btrfs_search_slot(trans, root, &key, path, 1, 1);
2353 leaf = path->nodes[0];
2354 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2356 fi = btrfs_item_ptr(leaf, path->slots[0],
2357 struct btrfs_file_extent_item);
2358 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2360 if (relink_is_mergable(leaf, fi, new->bytenr) &&
2361 extent_len + found_key.offset == start) {
2362 btrfs_set_file_extent_num_bytes(leaf, fi,
2364 btrfs_mark_buffer_dirty(leaf);
2365 inode_add_bytes(inode, len);
2371 btrfs_release_path(path);
2376 ret = btrfs_insert_empty_item(trans, root, path, &key,
2379 btrfs_abort_transaction(trans, root, ret);
2383 leaf = path->nodes[0];
2384 item = btrfs_item_ptr(leaf, path->slots[0],
2385 struct btrfs_file_extent_item);
2386 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2387 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2388 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2389 btrfs_set_file_extent_num_bytes(leaf, item, len);
2390 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2391 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2392 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2393 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2394 btrfs_set_file_extent_encryption(leaf, item, 0);
2395 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2397 btrfs_mark_buffer_dirty(leaf);
2398 inode_add_bytes(inode, len);
2399 btrfs_release_path(path);
2401 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2403 backref->root_id, backref->inum,
2404 new->file_pos, 0); /* start - extent_offset */
2406 btrfs_abort_transaction(trans, root, ret);
2412 btrfs_release_path(path);
2413 path->leave_spinning = 0;
2414 btrfs_end_transaction(trans, root);
2416 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2422 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2424 struct old_sa_defrag_extent *old, *tmp;
2429 list_for_each_entry_safe(old, tmp, &new->head, list) {
2430 list_del(&old->list);
2436 static void relink_file_extents(struct new_sa_defrag_extent *new)
2438 struct btrfs_path *path;
2439 struct sa_defrag_extent_backref *backref;
2440 struct sa_defrag_extent_backref *prev = NULL;
2441 struct inode *inode;
2442 struct btrfs_root *root;
2443 struct rb_node *node;
2447 root = BTRFS_I(inode)->root;
2449 path = btrfs_alloc_path();
2453 if (!record_extent_backrefs(path, new)) {
2454 btrfs_free_path(path);
2457 btrfs_release_path(path);
2460 node = rb_first(&new->root);
2463 rb_erase(node, &new->root);
2465 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2467 ret = relink_extent_backref(path, prev, backref);
2480 btrfs_free_path(path);
2482 free_sa_defrag_extent(new);
2484 atomic_dec(&root->fs_info->defrag_running);
2485 wake_up(&root->fs_info->transaction_wait);
2488 static struct new_sa_defrag_extent *
2489 record_old_file_extents(struct inode *inode,
2490 struct btrfs_ordered_extent *ordered)
2492 struct btrfs_root *root = BTRFS_I(inode)->root;
2493 struct btrfs_path *path;
2494 struct btrfs_key key;
2495 struct old_sa_defrag_extent *old;
2496 struct new_sa_defrag_extent *new;
2499 new = kmalloc(sizeof(*new), GFP_NOFS);
2504 new->file_pos = ordered->file_offset;
2505 new->len = ordered->len;
2506 new->bytenr = ordered->start;
2507 new->disk_len = ordered->disk_len;
2508 new->compress_type = ordered->compress_type;
2509 new->root = RB_ROOT;
2510 INIT_LIST_HEAD(&new->head);
2512 path = btrfs_alloc_path();
2516 key.objectid = btrfs_ino(inode);
2517 key.type = BTRFS_EXTENT_DATA_KEY;
2518 key.offset = new->file_pos;
2520 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2523 if (ret > 0 && path->slots[0] > 0)
2526 /* find out all the old extents for the file range */
2528 struct btrfs_file_extent_item *extent;
2529 struct extent_buffer *l;
2538 slot = path->slots[0];
2540 if (slot >= btrfs_header_nritems(l)) {
2541 ret = btrfs_next_leaf(root, path);
2549 btrfs_item_key_to_cpu(l, &key, slot);
2551 if (key.objectid != btrfs_ino(inode))
2553 if (key.type != BTRFS_EXTENT_DATA_KEY)
2555 if (key.offset >= new->file_pos + new->len)
2558 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2560 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2561 if (key.offset + num_bytes < new->file_pos)
2564 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2568 extent_offset = btrfs_file_extent_offset(l, extent);
2570 old = kmalloc(sizeof(*old), GFP_NOFS);
2574 offset = max(new->file_pos, key.offset);
2575 end = min(new->file_pos + new->len, key.offset + num_bytes);
2577 old->bytenr = disk_bytenr;
2578 old->extent_offset = extent_offset;
2579 old->offset = offset - key.offset;
2580 old->len = end - offset;
2583 list_add_tail(&old->list, &new->head);
2589 btrfs_free_path(path);
2590 atomic_inc(&root->fs_info->defrag_running);
2595 btrfs_free_path(path);
2597 free_sa_defrag_extent(new);
2602 * helper function for btrfs_finish_ordered_io, this
2603 * just reads in some of the csum leaves to prime them into ram
2604 * before we start the transaction. It limits the amount of btree
2605 * reads required while inside the transaction.
2607 /* as ordered data IO finishes, this gets called so we can finish
2608 * an ordered extent if the range of bytes in the file it covers are
2611 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2613 struct inode *inode = ordered_extent->inode;
2614 struct btrfs_root *root = BTRFS_I(inode)->root;
2615 struct btrfs_trans_handle *trans = NULL;
2616 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2617 struct extent_state *cached_state = NULL;
2618 struct new_sa_defrag_extent *new = NULL;
2619 int compress_type = 0;
2623 nolock = btrfs_is_free_space_inode(inode);
2625 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2630 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2631 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2632 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2634 trans = btrfs_join_transaction_nolock(root);
2636 trans = btrfs_join_transaction(root);
2637 if (IS_ERR(trans)) {
2638 ret = PTR_ERR(trans);
2642 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2643 ret = btrfs_update_inode_fallback(trans, root, inode);
2644 if (ret) /* -ENOMEM or corruption */
2645 btrfs_abort_transaction(trans, root, ret);
2649 lock_extent_bits(io_tree, ordered_extent->file_offset,
2650 ordered_extent->file_offset + ordered_extent->len - 1,
2653 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2654 ordered_extent->file_offset + ordered_extent->len - 1,
2655 EXTENT_DEFRAG, 1, cached_state);
2657 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2658 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2659 /* the inode is shared */
2660 new = record_old_file_extents(inode, ordered_extent);
2662 clear_extent_bit(io_tree, ordered_extent->file_offset,
2663 ordered_extent->file_offset + ordered_extent->len - 1,
2664 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2668 trans = btrfs_join_transaction_nolock(root);
2670 trans = btrfs_join_transaction(root);
2671 if (IS_ERR(trans)) {
2672 ret = PTR_ERR(trans);
2676 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2678 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2679 compress_type = ordered_extent->compress_type;
2680 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2681 BUG_ON(compress_type);
2682 ret = btrfs_mark_extent_written(trans, inode,
2683 ordered_extent->file_offset,
2684 ordered_extent->file_offset +
2685 ordered_extent->len);
2687 BUG_ON(root == root->fs_info->tree_root);
2688 ret = insert_reserved_file_extent(trans, inode,
2689 ordered_extent->file_offset,
2690 ordered_extent->start,
2691 ordered_extent->disk_len,
2692 ordered_extent->len,
2693 ordered_extent->len,
2694 compress_type, 0, 0,
2695 BTRFS_FILE_EXTENT_REG);
2697 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2698 ordered_extent->file_offset, ordered_extent->len,
2701 btrfs_abort_transaction(trans, root, ret);
2705 add_pending_csums(trans, inode, ordered_extent->file_offset,
2706 &ordered_extent->list);
2708 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2709 ret = btrfs_update_inode_fallback(trans, root, inode);
2710 if (ret) { /* -ENOMEM or corruption */
2711 btrfs_abort_transaction(trans, root, ret);
2716 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2717 ordered_extent->file_offset +
2718 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2720 if (root != root->fs_info->tree_root)
2721 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2723 btrfs_end_transaction(trans, root);
2726 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
2727 ordered_extent->file_offset +
2728 ordered_extent->len - 1, NULL, GFP_NOFS);
2731 * If the ordered extent had an IOERR or something else went
2732 * wrong we need to return the space for this ordered extent
2733 * back to the allocator.
2735 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2736 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2737 btrfs_free_reserved_extent(root, ordered_extent->start,
2738 ordered_extent->disk_len);
2743 * This needs to be done to make sure anybody waiting knows we are done
2744 * updating everything for this ordered extent.
2746 btrfs_remove_ordered_extent(inode, ordered_extent);
2748 /* for snapshot-aware defrag */
2751 free_sa_defrag_extent(new);
2752 atomic_dec(&root->fs_info->defrag_running);
2754 relink_file_extents(new);
2759 btrfs_put_ordered_extent(ordered_extent);
2760 /* once for the tree */
2761 btrfs_put_ordered_extent(ordered_extent);
2766 static void finish_ordered_fn(struct btrfs_work *work)
2768 struct btrfs_ordered_extent *ordered_extent;
2769 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2770 btrfs_finish_ordered_io(ordered_extent);
2773 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2774 struct extent_state *state, int uptodate)
2776 struct inode *inode = page->mapping->host;
2777 struct btrfs_root *root = BTRFS_I(inode)->root;
2778 struct btrfs_ordered_extent *ordered_extent = NULL;
2779 struct btrfs_workers *workers;
2781 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2783 ClearPagePrivate2(page);
2784 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2785 end - start + 1, uptodate))
2788 ordered_extent->work.func = finish_ordered_fn;
2789 ordered_extent->work.flags = 0;
2791 if (btrfs_is_free_space_inode(inode))
2792 workers = &root->fs_info->endio_freespace_worker;
2794 workers = &root->fs_info->endio_write_workers;
2795 btrfs_queue_worker(workers, &ordered_extent->work);
2801 * when reads are done, we need to check csums to verify the data is correct
2802 * if there's a match, we allow the bio to finish. If not, the code in
2803 * extent_io.c will try to find good copies for us.
2805 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
2806 struct extent_state *state, int mirror)
2808 size_t offset = start - page_offset(page);
2809 struct inode *inode = page->mapping->host;
2810 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2812 u64 private = ~(u32)0;
2814 struct btrfs_root *root = BTRFS_I(inode)->root;
2816 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2817 DEFAULT_RATELIMIT_BURST);
2819 if (PageChecked(page)) {
2820 ClearPageChecked(page);
2824 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2827 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2828 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2829 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2834 if (state && state->start == start) {
2835 private = state->private;
2838 ret = get_state_private(io_tree, start, &private);
2840 kaddr = kmap_atomic(page);
2844 csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
2845 btrfs_csum_final(csum, (char *)&csum);
2846 if (csum != private)
2849 kunmap_atomic(kaddr);
2854 if (__ratelimit(&_rs))
2855 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u private %llu",
2856 (unsigned long long)btrfs_ino(page->mapping->host),
2857 (unsigned long long)start, csum,
2858 (unsigned long long)private);
2859 memset(kaddr + offset, 1, end - start + 1);
2860 flush_dcache_page(page);
2861 kunmap_atomic(kaddr);
2867 struct delayed_iput {
2868 struct list_head list;
2869 struct inode *inode;
2872 /* JDM: If this is fs-wide, why can't we add a pointer to
2873 * btrfs_inode instead and avoid the allocation? */
2874 void btrfs_add_delayed_iput(struct inode *inode)
2876 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2877 struct delayed_iput *delayed;
2879 if (atomic_add_unless(&inode->i_count, -1, 1))
2882 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2883 delayed->inode = inode;
2885 spin_lock(&fs_info->delayed_iput_lock);
2886 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2887 spin_unlock(&fs_info->delayed_iput_lock);
2890 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2893 struct btrfs_fs_info *fs_info = root->fs_info;
2894 struct delayed_iput *delayed;
2897 spin_lock(&fs_info->delayed_iput_lock);
2898 empty = list_empty(&fs_info->delayed_iputs);
2899 spin_unlock(&fs_info->delayed_iput_lock);
2903 spin_lock(&fs_info->delayed_iput_lock);
2904 list_splice_init(&fs_info->delayed_iputs, &list);
2905 spin_unlock(&fs_info->delayed_iput_lock);
2907 while (!list_empty(&list)) {
2908 delayed = list_entry(list.next, struct delayed_iput, list);
2909 list_del(&delayed->list);
2910 iput(delayed->inode);
2916 * This is called in transaction commit time. If there are no orphan
2917 * files in the subvolume, it removes orphan item and frees block_rsv
2920 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2921 struct btrfs_root *root)
2923 struct btrfs_block_rsv *block_rsv;
2926 if (atomic_read(&root->orphan_inodes) ||
2927 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2930 spin_lock(&root->orphan_lock);
2931 if (atomic_read(&root->orphan_inodes)) {
2932 spin_unlock(&root->orphan_lock);
2936 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2937 spin_unlock(&root->orphan_lock);
2941 block_rsv = root->orphan_block_rsv;
2942 root->orphan_block_rsv = NULL;
2943 spin_unlock(&root->orphan_lock);
2945 if (root->orphan_item_inserted &&
2946 btrfs_root_refs(&root->root_item) > 0) {
2947 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2948 root->root_key.objectid);
2950 root->orphan_item_inserted = 0;
2954 WARN_ON(block_rsv->size > 0);
2955 btrfs_free_block_rsv(root, block_rsv);
2960 * This creates an orphan entry for the given inode in case something goes
2961 * wrong in the middle of an unlink/truncate.
2963 * NOTE: caller of this function should reserve 5 units of metadata for
2966 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2968 struct btrfs_root *root = BTRFS_I(inode)->root;
2969 struct btrfs_block_rsv *block_rsv = NULL;
2974 if (!root->orphan_block_rsv) {
2975 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2980 spin_lock(&root->orphan_lock);
2981 if (!root->orphan_block_rsv) {
2982 root->orphan_block_rsv = block_rsv;
2983 } else if (block_rsv) {
2984 btrfs_free_block_rsv(root, block_rsv);
2988 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2989 &BTRFS_I(inode)->runtime_flags)) {
2992 * For proper ENOSPC handling, we should do orphan
2993 * cleanup when mounting. But this introduces backward
2994 * compatibility issue.
2996 if (!xchg(&root->orphan_item_inserted, 1))
3002 atomic_inc(&root->orphan_inodes);
3005 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3006 &BTRFS_I(inode)->runtime_flags))
3008 spin_unlock(&root->orphan_lock);
3010 /* grab metadata reservation from transaction handle */
3012 ret = btrfs_orphan_reserve_metadata(trans, inode);
3013 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3016 /* insert an orphan item to track this unlinked/truncated file */
3018 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3019 if (ret && ret != -EEXIST) {
3020 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3021 &BTRFS_I(inode)->runtime_flags);
3022 btrfs_abort_transaction(trans, root, ret);
3028 /* insert an orphan item to track subvolume contains orphan files */
3030 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3031 root->root_key.objectid);
3032 if (ret && ret != -EEXIST) {
3033 btrfs_abort_transaction(trans, root, ret);
3041 * We have done the truncate/delete so we can go ahead and remove the orphan
3042 * item for this particular inode.
3044 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3045 struct inode *inode)
3047 struct btrfs_root *root = BTRFS_I(inode)->root;
3048 int delete_item = 0;
3049 int release_rsv = 0;
3052 spin_lock(&root->orphan_lock);
3053 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3054 &BTRFS_I(inode)->runtime_flags))
3057 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3058 &BTRFS_I(inode)->runtime_flags))
3060 spin_unlock(&root->orphan_lock);
3062 if (trans && delete_item) {
3063 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3064 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3068 btrfs_orphan_release_metadata(inode);
3069 atomic_dec(&root->orphan_inodes);
3076 * this cleans up any orphans that may be left on the list from the last use
3079 int btrfs_orphan_cleanup(struct btrfs_root *root)
3081 struct btrfs_path *path;
3082 struct extent_buffer *leaf;
3083 struct btrfs_key key, found_key;
3084 struct btrfs_trans_handle *trans;
3085 struct inode *inode;
3086 u64 last_objectid = 0;
3087 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3089 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3092 path = btrfs_alloc_path();
3099 key.objectid = BTRFS_ORPHAN_OBJECTID;
3100 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3101 key.offset = (u64)-1;
3104 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3109 * if ret == 0 means we found what we were searching for, which
3110 * is weird, but possible, so only screw with path if we didn't
3111 * find the key and see if we have stuff that matches
3115 if (path->slots[0] == 0)
3120 /* pull out the item */
3121 leaf = path->nodes[0];
3122 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3124 /* make sure the item matches what we want */
3125 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3127 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3130 /* release the path since we're done with it */
3131 btrfs_release_path(path);
3134 * this is where we are basically btrfs_lookup, without the
3135 * crossing root thing. we store the inode number in the
3136 * offset of the orphan item.
3139 if (found_key.offset == last_objectid) {
3140 btrfs_err(root->fs_info,
3141 "Error removing orphan entry, stopping orphan cleanup");
3146 last_objectid = found_key.offset;
3148 found_key.objectid = found_key.offset;
3149 found_key.type = BTRFS_INODE_ITEM_KEY;
3150 found_key.offset = 0;
3151 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3152 ret = PTR_RET(inode);
3153 if (ret && ret != -ESTALE)
3156 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3157 struct btrfs_root *dead_root;
3158 struct btrfs_fs_info *fs_info = root->fs_info;
3159 int is_dead_root = 0;
3162 * this is an orphan in the tree root. Currently these
3163 * could come from 2 sources:
3164 * a) a snapshot deletion in progress
3165 * b) a free space cache inode
3166 * We need to distinguish those two, as the snapshot
3167 * orphan must not get deleted.
3168 * find_dead_roots already ran before us, so if this
3169 * is a snapshot deletion, we should find the root
3170 * in the dead_roots list
3172 spin_lock(&fs_info->trans_lock);
3173 list_for_each_entry(dead_root, &fs_info->dead_roots,
3175 if (dead_root->root_key.objectid ==
3176 found_key.objectid) {
3181 spin_unlock(&fs_info->trans_lock);
3183 /* prevent this orphan from being found again */
3184 key.offset = found_key.objectid - 1;
3189 * Inode is already gone but the orphan item is still there,
3190 * kill the orphan item.
3192 if (ret == -ESTALE) {
3193 trans = btrfs_start_transaction(root, 1);
3194 if (IS_ERR(trans)) {
3195 ret = PTR_ERR(trans);
3198 btrfs_debug(root->fs_info, "auto deleting %Lu",
3199 found_key.objectid);
3200 ret = btrfs_del_orphan_item(trans, root,
3201 found_key.objectid);
3202 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3203 btrfs_end_transaction(trans, root);
3208 * add this inode to the orphan list so btrfs_orphan_del does
3209 * the proper thing when we hit it
3211 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3212 &BTRFS_I(inode)->runtime_flags);
3213 atomic_inc(&root->orphan_inodes);
3215 /* if we have links, this was a truncate, lets do that */
3216 if (inode->i_nlink) {
3217 if (!S_ISREG(inode->i_mode)) {
3224 /* 1 for the orphan item deletion. */
3225 trans = btrfs_start_transaction(root, 1);
3226 if (IS_ERR(trans)) {
3227 ret = PTR_ERR(trans);
3230 ret = btrfs_orphan_add(trans, inode);
3231 btrfs_end_transaction(trans, root);
3235 ret = btrfs_truncate(inode);
3237 btrfs_orphan_del(NULL, inode);
3242 /* this will do delete_inode and everything for us */
3247 /* release the path since we're done with it */
3248 btrfs_release_path(path);
3250 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3252 if (root->orphan_block_rsv)
3253 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3256 if (root->orphan_block_rsv || root->orphan_item_inserted) {
3257 trans = btrfs_join_transaction(root);
3259 btrfs_end_transaction(trans, root);
3263 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3265 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3269 btrfs_crit(root->fs_info,
3270 "could not do orphan cleanup %d", ret);
3271 btrfs_free_path(path);
3276 * very simple check to peek ahead in the leaf looking for xattrs. If we
3277 * don't find any xattrs, we know there can't be any acls.
3279 * slot is the slot the inode is in, objectid is the objectid of the inode
3281 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3282 int slot, u64 objectid)
3284 u32 nritems = btrfs_header_nritems(leaf);
3285 struct btrfs_key found_key;
3289 while (slot < nritems) {
3290 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3292 /* we found a different objectid, there must not be acls */
3293 if (found_key.objectid != objectid)
3296 /* we found an xattr, assume we've got an acl */
3297 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
3301 * we found a key greater than an xattr key, there can't
3302 * be any acls later on
3304 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3311 * it goes inode, inode backrefs, xattrs, extents,
3312 * so if there are a ton of hard links to an inode there can
3313 * be a lot of backrefs. Don't waste time searching too hard,
3314 * this is just an optimization
3319 /* we hit the end of the leaf before we found an xattr or
3320 * something larger than an xattr. We have to assume the inode
3327 * read an inode from the btree into the in-memory inode
3329 static void btrfs_read_locked_inode(struct inode *inode)
3331 struct btrfs_path *path;
3332 struct extent_buffer *leaf;
3333 struct btrfs_inode_item *inode_item;
3334 struct btrfs_timespec *tspec;
3335 struct btrfs_root *root = BTRFS_I(inode)->root;
3336 struct btrfs_key location;
3340 bool filled = false;
3342 ret = btrfs_fill_inode(inode, &rdev);
3346 path = btrfs_alloc_path();
3350 path->leave_spinning = 1;
3351 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3353 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3357 leaf = path->nodes[0];
3362 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3363 struct btrfs_inode_item);
3364 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3365 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3366 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3367 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3368 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3370 tspec = btrfs_inode_atime(inode_item);
3371 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3372 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3374 tspec = btrfs_inode_mtime(inode_item);
3375 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3376 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3378 tspec = btrfs_inode_ctime(inode_item);
3379 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3380 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3382 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3383 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3384 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3387 * If we were modified in the current generation and evicted from memory
3388 * and then re-read we need to do a full sync since we don't have any
3389 * idea about which extents were modified before we were evicted from
3392 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3393 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3394 &BTRFS_I(inode)->runtime_flags);
3396 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3397 inode->i_generation = BTRFS_I(inode)->generation;
3399 rdev = btrfs_inode_rdev(leaf, inode_item);
3401 BTRFS_I(inode)->index_cnt = (u64)-1;
3402 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3405 * try to precache a NULL acl entry for files that don't have
3406 * any xattrs or acls
3408 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3411 cache_no_acl(inode);
3413 btrfs_free_path(path);
3415 switch (inode->i_mode & S_IFMT) {
3417 inode->i_mapping->a_ops = &btrfs_aops;
3418 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3419 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3420 inode->i_fop = &btrfs_file_operations;
3421 inode->i_op = &btrfs_file_inode_operations;
3424 inode->i_fop = &btrfs_dir_file_operations;
3425 if (root == root->fs_info->tree_root)
3426 inode->i_op = &btrfs_dir_ro_inode_operations;
3428 inode->i_op = &btrfs_dir_inode_operations;
3431 inode->i_op = &btrfs_symlink_inode_operations;
3432 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3433 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3436 inode->i_op = &btrfs_special_inode_operations;
3437 init_special_inode(inode, inode->i_mode, rdev);
3441 btrfs_update_iflags(inode);
3445 btrfs_free_path(path);
3446 make_bad_inode(inode);
3450 * given a leaf and an inode, copy the inode fields into the leaf
3452 static void fill_inode_item(struct btrfs_trans_handle *trans,
3453 struct extent_buffer *leaf,
3454 struct btrfs_inode_item *item,
3455 struct inode *inode)
3457 struct btrfs_map_token token;
3459 btrfs_init_map_token(&token);
3461 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3462 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3463 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3465 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3466 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3468 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3469 inode->i_atime.tv_sec, &token);
3470 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3471 inode->i_atime.tv_nsec, &token);
3473 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3474 inode->i_mtime.tv_sec, &token);
3475 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3476 inode->i_mtime.tv_nsec, &token);
3478 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3479 inode->i_ctime.tv_sec, &token);
3480 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3481 inode->i_ctime.tv_nsec, &token);
3483 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3485 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3487 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3488 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3489 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3490 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3491 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3495 * copy everything in the in-memory inode into the btree.
3497 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3498 struct btrfs_root *root, struct inode *inode)
3500 struct btrfs_inode_item *inode_item;
3501 struct btrfs_path *path;
3502 struct extent_buffer *leaf;
3505 path = btrfs_alloc_path();
3509 path->leave_spinning = 1;
3510 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3518 btrfs_unlock_up_safe(path, 1);
3519 leaf = path->nodes[0];
3520 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3521 struct btrfs_inode_item);
3523 fill_inode_item(trans, leaf, inode_item, inode);
3524 btrfs_mark_buffer_dirty(leaf);
3525 btrfs_set_inode_last_trans(trans, inode);
3528 btrfs_free_path(path);
3533 * copy everything in the in-memory inode into the btree.
3535 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3536 struct btrfs_root *root, struct inode *inode)
3541 * If the inode is a free space inode, we can deadlock during commit
3542 * if we put it into the delayed code.
3544 * The data relocation inode should also be directly updated
3547 if (!btrfs_is_free_space_inode(inode)
3548 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3549 && !root->fs_info->log_root_recovering) {
3550 btrfs_update_root_times(trans, root);
3552 ret = btrfs_delayed_update_inode(trans, root, inode);
3554 btrfs_set_inode_last_trans(trans, inode);
3558 return btrfs_update_inode_item(trans, root, inode);
3561 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3562 struct btrfs_root *root,
3563 struct inode *inode)
3567 ret = btrfs_update_inode(trans, root, inode);
3569 return btrfs_update_inode_item(trans, root, inode);
3574 * unlink helper that gets used here in inode.c and in the tree logging
3575 * recovery code. It remove a link in a directory with a given name, and
3576 * also drops the back refs in the inode to the directory
3578 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3579 struct btrfs_root *root,
3580 struct inode *dir, struct inode *inode,
3581 const char *name, int name_len)
3583 struct btrfs_path *path;
3585 struct extent_buffer *leaf;
3586 struct btrfs_dir_item *di;
3587 struct btrfs_key key;
3589 u64 ino = btrfs_ino(inode);
3590 u64 dir_ino = btrfs_ino(dir);
3592 path = btrfs_alloc_path();
3598 path->leave_spinning = 1;
3599 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3600 name, name_len, -1);
3609 leaf = path->nodes[0];
3610 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3611 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3614 btrfs_release_path(path);
3616 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3619 btrfs_info(root->fs_info,
3620 "failed to delete reference to %.*s, inode %llu parent %llu",
3622 (unsigned long long)ino, (unsigned long long)dir_ino);
3623 btrfs_abort_transaction(trans, root, ret);
3627 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3629 btrfs_abort_transaction(trans, root, ret);
3633 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3635 if (ret != 0 && ret != -ENOENT) {
3636 btrfs_abort_transaction(trans, root, ret);
3640 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3645 btrfs_abort_transaction(trans, root, ret);
3647 btrfs_free_path(path);
3651 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3652 inode_inc_iversion(inode);
3653 inode_inc_iversion(dir);
3654 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3655 ret = btrfs_update_inode(trans, root, dir);
3660 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3661 struct btrfs_root *root,
3662 struct inode *dir, struct inode *inode,
3663 const char *name, int name_len)
3666 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3668 btrfs_drop_nlink(inode);
3669 ret = btrfs_update_inode(trans, root, inode);
3675 /* helper to check if there is any shared block in the path */
3676 static int check_path_shared(struct btrfs_root *root,
3677 struct btrfs_path *path)
3679 struct extent_buffer *eb;
3683 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
3686 if (!path->nodes[level])
3688 eb = path->nodes[level];
3689 if (!btrfs_block_can_be_shared(root, eb))
3691 ret = btrfs_lookup_extent_info(NULL, root, eb->start, level, 1,
3700 * helper to start transaction for unlink and rmdir.
3702 * unlink and rmdir are special in btrfs, they do not always free space.
3703 * so in enospc case, we should make sure they will free space before
3704 * allowing them to use the global metadata reservation.
3706 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
3707 struct dentry *dentry)
3709 struct btrfs_trans_handle *trans;
3710 struct btrfs_root *root = BTRFS_I(dir)->root;
3711 struct btrfs_path *path;
3712 struct btrfs_dir_item *di;
3713 struct inode *inode = dentry->d_inode;
3718 u64 ino = btrfs_ino(inode);
3719 u64 dir_ino = btrfs_ino(dir);
3722 * 1 for the possible orphan item
3723 * 1 for the dir item
3724 * 1 for the dir index
3725 * 1 for the inode ref
3728 trans = btrfs_start_transaction(root, 5);
3729 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3732 if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
3733 return ERR_PTR(-ENOSPC);
3735 /* check if there is someone else holds reference */
3736 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
3737 return ERR_PTR(-ENOSPC);
3739 if (atomic_read(&inode->i_count) > 2)
3740 return ERR_PTR(-ENOSPC);
3742 if (xchg(&root->fs_info->enospc_unlink, 1))
3743 return ERR_PTR(-ENOSPC);
3745 path = btrfs_alloc_path();
3747 root->fs_info->enospc_unlink = 0;
3748 return ERR_PTR(-ENOMEM);
3751 /* 1 for the orphan item */
3752 trans = btrfs_start_transaction(root, 1);
3753 if (IS_ERR(trans)) {
3754 btrfs_free_path(path);
3755 root->fs_info->enospc_unlink = 0;
3759 path->skip_locking = 1;
3760 path->search_commit_root = 1;
3762 ret = btrfs_lookup_inode(trans, root, path,
3763 &BTRFS_I(dir)->location, 0);
3769 if (check_path_shared(root, path))
3774 btrfs_release_path(path);
3776 ret = btrfs_lookup_inode(trans, root, path,
3777 &BTRFS_I(inode)->location, 0);
3783 if (check_path_shared(root, path))
3788 btrfs_release_path(path);
3790 if (ret == 0 && S_ISREG(inode->i_mode)) {
3791 ret = btrfs_lookup_file_extent(trans, root, path,
3797 BUG_ON(ret == 0); /* Corruption */
3798 if (check_path_shared(root, path))
3800 btrfs_release_path(path);
3808 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3809 dentry->d_name.name, dentry->d_name.len, 0);
3815 if (check_path_shared(root, path))
3821 btrfs_release_path(path);
3823 ret = btrfs_get_inode_ref_index(trans, root, path, dentry->d_name.name,
3824 dentry->d_name.len, ino, dir_ino, 0,
3831 if (check_path_shared(root, path))
3834 btrfs_release_path(path);
3837 * This is a commit root search, if we can lookup inode item and other
3838 * relative items in the commit root, it means the transaction of
3839 * dir/file creation has been committed, and the dir index item that we
3840 * delay to insert has also been inserted into the commit root. So
3841 * we needn't worry about the delayed insertion of the dir index item
3844 di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
3845 dentry->d_name.name, dentry->d_name.len, 0);
3850 BUG_ON(ret == -ENOENT);
3851 if (check_path_shared(root, path))
3856 btrfs_free_path(path);
3857 /* Migrate the orphan reservation over */
3859 err = btrfs_block_rsv_migrate(trans->block_rsv,
3860 &root->fs_info->global_block_rsv,
3861 trans->bytes_reserved);
3864 btrfs_end_transaction(trans, root);
3865 root->fs_info->enospc_unlink = 0;
3866 return ERR_PTR(err);
3869 trans->block_rsv = &root->fs_info->global_block_rsv;
3873 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
3874 struct btrfs_root *root)
3876 if (trans->block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL) {
3877 btrfs_block_rsv_release(root, trans->block_rsv,
3878 trans->bytes_reserved);
3879 trans->block_rsv = &root->fs_info->trans_block_rsv;
3880 BUG_ON(!root->fs_info->enospc_unlink);
3881 root->fs_info->enospc_unlink = 0;
3883 btrfs_end_transaction(trans, root);
3886 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3888 struct btrfs_root *root = BTRFS_I(dir)->root;
3889 struct btrfs_trans_handle *trans;
3890 struct inode *inode = dentry->d_inode;
3893 trans = __unlink_start_trans(dir, dentry);
3895 return PTR_ERR(trans);
3897 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3899 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3900 dentry->d_name.name, dentry->d_name.len);
3904 if (inode->i_nlink == 0) {
3905 ret = btrfs_orphan_add(trans, inode);
3911 __unlink_end_trans(trans, root);
3912 btrfs_btree_balance_dirty(root);
3916 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3917 struct btrfs_root *root,
3918 struct inode *dir, u64 objectid,
3919 const char *name, int name_len)
3921 struct btrfs_path *path;
3922 struct extent_buffer *leaf;
3923 struct btrfs_dir_item *di;
3924 struct btrfs_key key;
3927 u64 dir_ino = btrfs_ino(dir);
3929 path = btrfs_alloc_path();
3933 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3934 name, name_len, -1);
3935 if (IS_ERR_OR_NULL(di)) {
3943 leaf = path->nodes[0];
3944 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3945 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3946 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3948 btrfs_abort_transaction(trans, root, ret);
3951 btrfs_release_path(path);
3953 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3954 objectid, root->root_key.objectid,
3955 dir_ino, &index, name, name_len);
3957 if (ret != -ENOENT) {
3958 btrfs_abort_transaction(trans, root, ret);
3961 di = btrfs_search_dir_index_item(root, path, dir_ino,
3963 if (IS_ERR_OR_NULL(di)) {
3968 btrfs_abort_transaction(trans, root, ret);
3972 leaf = path->nodes[0];
3973 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3974 btrfs_release_path(path);
3977 btrfs_release_path(path);
3979 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3981 btrfs_abort_transaction(trans, root, ret);
3985 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3986 inode_inc_iversion(dir);
3987 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3988 ret = btrfs_update_inode_fallback(trans, root, dir);
3990 btrfs_abort_transaction(trans, root, ret);
3992 btrfs_free_path(path);
3996 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3998 struct inode *inode = dentry->d_inode;
4000 struct btrfs_root *root = BTRFS_I(dir)->root;
4001 struct btrfs_trans_handle *trans;
4003 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4005 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
4008 trans = __unlink_start_trans(dir, dentry);
4010 return PTR_ERR(trans);
4012 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4013 err = btrfs_unlink_subvol(trans, root, dir,
4014 BTRFS_I(inode)->location.objectid,
4015 dentry->d_name.name,
4016 dentry->d_name.len);
4020 err = btrfs_orphan_add(trans, inode);
4024 /* now the directory is empty */
4025 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
4026 dentry->d_name.name, dentry->d_name.len);
4028 btrfs_i_size_write(inode, 0);
4030 __unlink_end_trans(trans, root);
4031 btrfs_btree_balance_dirty(root);
4037 * this can truncate away extent items, csum items and directory items.
4038 * It starts at a high offset and removes keys until it can't find
4039 * any higher than new_size
4041 * csum items that cross the new i_size are truncated to the new size
4044 * min_type is the minimum key type to truncate down to. If set to 0, this
4045 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4047 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4048 struct btrfs_root *root,
4049 struct inode *inode,
4050 u64 new_size, u32 min_type)
4052 struct btrfs_path *path;
4053 struct extent_buffer *leaf;
4054 struct btrfs_file_extent_item *fi;
4055 struct btrfs_key key;
4056 struct btrfs_key found_key;
4057 u64 extent_start = 0;
4058 u64 extent_num_bytes = 0;
4059 u64 extent_offset = 0;
4061 u32 found_type = (u8)-1;
4064 int pending_del_nr = 0;
4065 int pending_del_slot = 0;
4066 int extent_type = -1;
4069 u64 ino = btrfs_ino(inode);
4071 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4073 path = btrfs_alloc_path();
4079 * We want to drop from the next block forward in case this new size is
4080 * not block aligned since we will be keeping the last block of the
4081 * extent just the way it is.
4083 if (root->ref_cows || root == root->fs_info->tree_root)
4084 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4085 root->sectorsize), (u64)-1, 0);
4088 * This function is also used to drop the items in the log tree before
4089 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4090 * it is used to drop the loged items. So we shouldn't kill the delayed
4093 if (min_type == 0 && root == BTRFS_I(inode)->root)
4094 btrfs_kill_delayed_inode_items(inode);
4097 key.offset = (u64)-1;
4101 path->leave_spinning = 1;
4102 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4109 /* there are no items in the tree for us to truncate, we're
4112 if (path->slots[0] == 0)
4119 leaf = path->nodes[0];
4120 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4121 found_type = btrfs_key_type(&found_key);
4123 if (found_key.objectid != ino)
4126 if (found_type < min_type)
4129 item_end = found_key.offset;
4130 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4131 fi = btrfs_item_ptr(leaf, path->slots[0],
4132 struct btrfs_file_extent_item);
4133 extent_type = btrfs_file_extent_type(leaf, fi);
4134 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4136 btrfs_file_extent_num_bytes(leaf, fi);
4137 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4138 item_end += btrfs_file_extent_inline_len(leaf,
4143 if (found_type > min_type) {
4146 if (item_end < new_size)
4148 if (found_key.offset >= new_size)
4154 /* FIXME, shrink the extent if the ref count is only 1 */
4155 if (found_type != BTRFS_EXTENT_DATA_KEY)
4158 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4160 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4162 u64 orig_num_bytes =
4163 btrfs_file_extent_num_bytes(leaf, fi);
4164 extent_num_bytes = ALIGN(new_size -
4167 btrfs_set_file_extent_num_bytes(leaf, fi,
4169 num_dec = (orig_num_bytes -
4171 if (root->ref_cows && extent_start != 0)
4172 inode_sub_bytes(inode, num_dec);
4173 btrfs_mark_buffer_dirty(leaf);
4176 btrfs_file_extent_disk_num_bytes(leaf,
4178 extent_offset = found_key.offset -
4179 btrfs_file_extent_offset(leaf, fi);
4181 /* FIXME blocksize != 4096 */
4182 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4183 if (extent_start != 0) {
4186 inode_sub_bytes(inode, num_dec);
4189 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4191 * we can't truncate inline items that have had
4195 btrfs_file_extent_compression(leaf, fi) == 0 &&
4196 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4197 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4198 u32 size = new_size - found_key.offset;
4200 if (root->ref_cows) {
4201 inode_sub_bytes(inode, item_end + 1 -
4205 btrfs_file_extent_calc_inline_size(size);
4206 btrfs_truncate_item(root, path, size, 1);
4207 } else if (root->ref_cows) {
4208 inode_sub_bytes(inode, item_end + 1 -
4214 if (!pending_del_nr) {
4215 /* no pending yet, add ourselves */
4216 pending_del_slot = path->slots[0];
4218 } else if (pending_del_nr &&
4219 path->slots[0] + 1 == pending_del_slot) {
4220 /* hop on the pending chunk */
4222 pending_del_slot = path->slots[0];
4229 if (found_extent && (root->ref_cows ||
4230 root == root->fs_info->tree_root)) {
4231 btrfs_set_path_blocking(path);
4232 ret = btrfs_free_extent(trans, root, extent_start,
4233 extent_num_bytes, 0,
4234 btrfs_header_owner(leaf),
4235 ino, extent_offset, 0);
4239 if (found_type == BTRFS_INODE_ITEM_KEY)
4242 if (path->slots[0] == 0 ||
4243 path->slots[0] != pending_del_slot) {
4244 if (pending_del_nr) {
4245 ret = btrfs_del_items(trans, root, path,
4249 btrfs_abort_transaction(trans,
4255 btrfs_release_path(path);
4262 if (pending_del_nr) {
4263 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4266 btrfs_abort_transaction(trans, root, ret);
4269 btrfs_free_path(path);
4274 * btrfs_truncate_page - read, zero a chunk and write a page
4275 * @inode - inode that we're zeroing
4276 * @from - the offset to start zeroing
4277 * @len - the length to zero, 0 to zero the entire range respective to the
4279 * @front - zero up to the offset instead of from the offset on
4281 * This will find the page for the "from" offset and cow the page and zero the
4282 * part we want to zero. This is used with truncate and hole punching.
4284 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4287 struct address_space *mapping = inode->i_mapping;
4288 struct btrfs_root *root = BTRFS_I(inode)->root;
4289 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4290 struct btrfs_ordered_extent *ordered;
4291 struct extent_state *cached_state = NULL;
4293 u32 blocksize = root->sectorsize;
4294 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4295 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4297 gfp_t mask = btrfs_alloc_write_mask(mapping);
4302 if ((offset & (blocksize - 1)) == 0 &&
4303 (!len || ((len & (blocksize - 1)) == 0)))
4305 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4310 page = find_or_create_page(mapping, index, mask);
4312 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4317 page_start = page_offset(page);
4318 page_end = page_start + PAGE_CACHE_SIZE - 1;
4320 if (!PageUptodate(page)) {
4321 ret = btrfs_readpage(NULL, page);
4323 if (page->mapping != mapping) {
4325 page_cache_release(page);
4328 if (!PageUptodate(page)) {
4333 wait_on_page_writeback(page);
4335 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4336 set_page_extent_mapped(page);
4338 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4340 unlock_extent_cached(io_tree, page_start, page_end,
4341 &cached_state, GFP_NOFS);
4343 page_cache_release(page);
4344 btrfs_start_ordered_extent(inode, ordered, 1);
4345 btrfs_put_ordered_extent(ordered);
4349 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4350 EXTENT_DIRTY | EXTENT_DELALLOC |
4351 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4352 0, 0, &cached_state, GFP_NOFS);
4354 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4357 unlock_extent_cached(io_tree, page_start, page_end,
4358 &cached_state, GFP_NOFS);
4362 if (offset != PAGE_CACHE_SIZE) {
4364 len = PAGE_CACHE_SIZE - offset;
4367 memset(kaddr, 0, offset);
4369 memset(kaddr + offset, 0, len);
4370 flush_dcache_page(page);
4373 ClearPageChecked(page);
4374 set_page_dirty(page);
4375 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4380 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4382 page_cache_release(page);
4388 * This function puts in dummy file extents for the area we're creating a hole
4389 * for. So if we are truncating this file to a larger size we need to insert
4390 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4391 * the range between oldsize and size
4393 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4395 struct btrfs_trans_handle *trans;
4396 struct btrfs_root *root = BTRFS_I(inode)->root;
4397 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4398 struct extent_map *em = NULL;
4399 struct extent_state *cached_state = NULL;
4400 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4401 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4402 u64 block_end = ALIGN(size, root->sectorsize);
4408 if (size <= hole_start)
4412 struct btrfs_ordered_extent *ordered;
4413 btrfs_wait_ordered_range(inode, hole_start,
4414 block_end - hole_start);
4415 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4417 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
4420 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4421 &cached_state, GFP_NOFS);
4422 btrfs_put_ordered_extent(ordered);
4425 cur_offset = hole_start;
4427 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4428 block_end - cur_offset, 0);
4434 last_byte = min(extent_map_end(em), block_end);
4435 last_byte = ALIGN(last_byte , root->sectorsize);
4436 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4437 struct extent_map *hole_em;
4438 hole_size = last_byte - cur_offset;
4440 trans = btrfs_start_transaction(root, 3);
4441 if (IS_ERR(trans)) {
4442 err = PTR_ERR(trans);
4446 err = btrfs_drop_extents(trans, root, inode,
4448 cur_offset + hole_size, 1);
4450 btrfs_abort_transaction(trans, root, err);
4451 btrfs_end_transaction(trans, root);
4455 err = btrfs_insert_file_extent(trans, root,
4456 btrfs_ino(inode), cur_offset, 0,
4457 0, hole_size, 0, hole_size,
4460 btrfs_abort_transaction(trans, root, err);
4461 btrfs_end_transaction(trans, root);
4465 btrfs_drop_extent_cache(inode, cur_offset,
4466 cur_offset + hole_size - 1, 0);
4467 hole_em = alloc_extent_map();
4469 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4470 &BTRFS_I(inode)->runtime_flags);
4473 hole_em->start = cur_offset;
4474 hole_em->len = hole_size;
4475 hole_em->orig_start = cur_offset;
4477 hole_em->block_start = EXTENT_MAP_HOLE;
4478 hole_em->block_len = 0;
4479 hole_em->orig_block_len = 0;
4480 hole_em->ram_bytes = hole_size;
4481 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4482 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4483 hole_em->generation = trans->transid;
4486 write_lock(&em_tree->lock);
4487 err = add_extent_mapping(em_tree, hole_em, 1);
4488 write_unlock(&em_tree->lock);
4491 btrfs_drop_extent_cache(inode, cur_offset,
4495 free_extent_map(hole_em);
4497 btrfs_update_inode(trans, root, inode);
4498 btrfs_end_transaction(trans, root);
4500 free_extent_map(em);
4502 cur_offset = last_byte;
4503 if (cur_offset >= block_end)
4507 free_extent_map(em);
4508 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4513 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4515 struct btrfs_root *root = BTRFS_I(inode)->root;
4516 struct btrfs_trans_handle *trans;
4517 loff_t oldsize = i_size_read(inode);
4518 loff_t newsize = attr->ia_size;
4519 int mask = attr->ia_valid;
4522 if (newsize == oldsize)
4526 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4527 * special case where we need to update the times despite not having
4528 * these flags set. For all other operations the VFS set these flags
4529 * explicitly if it wants a timestamp update.
4531 if (newsize != oldsize) {
4532 inode_inc_iversion(inode);
4533 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4534 inode->i_ctime = inode->i_mtime =
4535 current_fs_time(inode->i_sb);
4538 if (newsize > oldsize) {
4539 truncate_pagecache(inode, oldsize, newsize);
4540 ret = btrfs_cont_expand(inode, oldsize, newsize);
4544 trans = btrfs_start_transaction(root, 1);
4546 return PTR_ERR(trans);
4548 i_size_write(inode, newsize);
4549 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4550 ret = btrfs_update_inode(trans, root, inode);
4551 btrfs_end_transaction(trans, root);
4555 * We're truncating a file that used to have good data down to
4556 * zero. Make sure it gets into the ordered flush list so that
4557 * any new writes get down to disk quickly.
4560 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4561 &BTRFS_I(inode)->runtime_flags);
4564 * 1 for the orphan item we're going to add
4565 * 1 for the orphan item deletion.
4567 trans = btrfs_start_transaction(root, 2);
4569 return PTR_ERR(trans);
4572 * We need to do this in case we fail at _any_ point during the
4573 * actual truncate. Once we do the truncate_setsize we could
4574 * invalidate pages which forces any outstanding ordered io to
4575 * be instantly completed which will give us extents that need
4576 * to be truncated. If we fail to get an orphan inode down we
4577 * could have left over extents that were never meant to live,
4578 * so we need to garuntee from this point on that everything
4579 * will be consistent.
4581 ret = btrfs_orphan_add(trans, inode);
4582 btrfs_end_transaction(trans, root);
4586 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4587 truncate_setsize(inode, newsize);
4589 /* Disable nonlocked read DIO to avoid the end less truncate */
4590 btrfs_inode_block_unlocked_dio(inode);
4591 inode_dio_wait(inode);
4592 btrfs_inode_resume_unlocked_dio(inode);
4594 ret = btrfs_truncate(inode);
4595 if (ret && inode->i_nlink)
4596 btrfs_orphan_del(NULL, inode);
4602 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4604 struct inode *inode = dentry->d_inode;
4605 struct btrfs_root *root = BTRFS_I(inode)->root;
4608 if (btrfs_root_readonly(root))
4611 err = inode_change_ok(inode, attr);
4615 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4616 err = btrfs_setsize(inode, attr);
4621 if (attr->ia_valid) {
4622 setattr_copy(inode, attr);
4623 inode_inc_iversion(inode);
4624 err = btrfs_dirty_inode(inode);
4626 if (!err && attr->ia_valid & ATTR_MODE)
4627 err = btrfs_acl_chmod(inode);
4633 void btrfs_evict_inode(struct inode *inode)
4635 struct btrfs_trans_handle *trans;
4636 struct btrfs_root *root = BTRFS_I(inode)->root;
4637 struct btrfs_block_rsv *rsv, *global_rsv;
4638 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4641 trace_btrfs_inode_evict(inode);
4643 truncate_inode_pages(&inode->i_data, 0);
4644 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
4645 btrfs_is_free_space_inode(inode)))
4648 if (is_bad_inode(inode)) {
4649 btrfs_orphan_del(NULL, inode);
4652 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4653 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4655 if (root->fs_info->log_root_recovering) {
4656 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4657 &BTRFS_I(inode)->runtime_flags));
4661 if (inode->i_nlink > 0) {
4662 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
4666 ret = btrfs_commit_inode_delayed_inode(inode);
4668 btrfs_orphan_del(NULL, inode);
4672 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4674 btrfs_orphan_del(NULL, inode);
4677 rsv->size = min_size;
4679 global_rsv = &root->fs_info->global_block_rsv;
4681 btrfs_i_size_write(inode, 0);
4684 * This is a bit simpler than btrfs_truncate since we've already
4685 * reserved our space for our orphan item in the unlink, so we just
4686 * need to reserve some slack space in case we add bytes and update
4687 * inode item when doing the truncate.
4690 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4691 BTRFS_RESERVE_FLUSH_LIMIT);
4694 * Try and steal from the global reserve since we will
4695 * likely not use this space anyway, we want to try as
4696 * hard as possible to get this to work.
4699 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4702 btrfs_warn(root->fs_info,
4703 "Could not get space for a delete, will truncate on mount %d",
4705 btrfs_orphan_del(NULL, inode);
4706 btrfs_free_block_rsv(root, rsv);
4710 trans = btrfs_join_transaction(root);
4711 if (IS_ERR(trans)) {
4712 btrfs_orphan_del(NULL, inode);
4713 btrfs_free_block_rsv(root, rsv);
4717 trans->block_rsv = rsv;
4719 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4723 trans->block_rsv = &root->fs_info->trans_block_rsv;
4724 btrfs_end_transaction(trans, root);
4726 btrfs_btree_balance_dirty(root);
4729 btrfs_free_block_rsv(root, rsv);
4732 trans->block_rsv = root->orphan_block_rsv;
4733 ret = btrfs_orphan_del(trans, inode);
4737 trans->block_rsv = &root->fs_info->trans_block_rsv;
4738 if (!(root == root->fs_info->tree_root ||
4739 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4740 btrfs_return_ino(root, btrfs_ino(inode));
4742 btrfs_end_transaction(trans, root);
4743 btrfs_btree_balance_dirty(root);
4745 btrfs_remove_delayed_node(inode);
4751 * this returns the key found in the dir entry in the location pointer.
4752 * If no dir entries were found, location->objectid is 0.
4754 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4755 struct btrfs_key *location)
4757 const char *name = dentry->d_name.name;
4758 int namelen = dentry->d_name.len;
4759 struct btrfs_dir_item *di;
4760 struct btrfs_path *path;
4761 struct btrfs_root *root = BTRFS_I(dir)->root;
4764 path = btrfs_alloc_path();
4768 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4773 if (IS_ERR_OR_NULL(di))
4776 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4778 btrfs_free_path(path);
4781 location->objectid = 0;
4786 * when we hit a tree root in a directory, the btrfs part of the inode
4787 * needs to be changed to reflect the root directory of the tree root. This
4788 * is kind of like crossing a mount point.
4790 static int fixup_tree_root_location(struct btrfs_root *root,
4792 struct dentry *dentry,
4793 struct btrfs_key *location,
4794 struct btrfs_root **sub_root)
4796 struct btrfs_path *path;
4797 struct btrfs_root *new_root;
4798 struct btrfs_root_ref *ref;
4799 struct extent_buffer *leaf;
4803 path = btrfs_alloc_path();
4810 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
4811 BTRFS_I(dir)->root->root_key.objectid,
4812 location->objectid);
4819 leaf = path->nodes[0];
4820 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4821 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4822 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4825 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4826 (unsigned long)(ref + 1),
4827 dentry->d_name.len);
4831 btrfs_release_path(path);
4833 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4834 if (IS_ERR(new_root)) {
4835 err = PTR_ERR(new_root);
4839 if (btrfs_root_refs(&new_root->root_item) == 0) {
4844 *sub_root = new_root;
4845 location->objectid = btrfs_root_dirid(&new_root->root_item);
4846 location->type = BTRFS_INODE_ITEM_KEY;
4847 location->offset = 0;
4850 btrfs_free_path(path);
4854 static void inode_tree_add(struct inode *inode)
4856 struct btrfs_root *root = BTRFS_I(inode)->root;
4857 struct btrfs_inode *entry;
4859 struct rb_node *parent;
4860 u64 ino = btrfs_ino(inode);
4862 if (inode_unhashed(inode))
4866 spin_lock(&root->inode_lock);
4867 p = &root->inode_tree.rb_node;
4870 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4872 if (ino < btrfs_ino(&entry->vfs_inode))
4873 p = &parent->rb_left;
4874 else if (ino > btrfs_ino(&entry->vfs_inode))
4875 p = &parent->rb_right;
4877 WARN_ON(!(entry->vfs_inode.i_state &
4878 (I_WILL_FREE | I_FREEING)));
4879 rb_erase(parent, &root->inode_tree);
4880 RB_CLEAR_NODE(parent);
4881 spin_unlock(&root->inode_lock);
4885 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
4886 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4887 spin_unlock(&root->inode_lock);
4890 static void inode_tree_del(struct inode *inode)
4892 struct btrfs_root *root = BTRFS_I(inode)->root;
4895 spin_lock(&root->inode_lock);
4896 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4897 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4898 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4899 empty = RB_EMPTY_ROOT(&root->inode_tree);
4901 spin_unlock(&root->inode_lock);
4904 * Free space cache has inodes in the tree root, but the tree root has a
4905 * root_refs of 0, so this could end up dropping the tree root as a
4906 * snapshot, so we need the extra !root->fs_info->tree_root check to
4907 * make sure we don't drop it.
4909 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4910 root != root->fs_info->tree_root) {
4911 synchronize_srcu(&root->fs_info->subvol_srcu);
4912 spin_lock(&root->inode_lock);
4913 empty = RB_EMPTY_ROOT(&root->inode_tree);
4914 spin_unlock(&root->inode_lock);
4916 btrfs_add_dead_root(root);
4920 void btrfs_invalidate_inodes(struct btrfs_root *root)
4922 struct rb_node *node;
4923 struct rb_node *prev;
4924 struct btrfs_inode *entry;
4925 struct inode *inode;
4928 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4930 spin_lock(&root->inode_lock);
4932 node = root->inode_tree.rb_node;
4936 entry = rb_entry(node, struct btrfs_inode, rb_node);
4938 if (objectid < btrfs_ino(&entry->vfs_inode))
4939 node = node->rb_left;
4940 else if (objectid > btrfs_ino(&entry->vfs_inode))
4941 node = node->rb_right;
4947 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4948 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4952 prev = rb_next(prev);
4956 entry = rb_entry(node, struct btrfs_inode, rb_node);
4957 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4958 inode = igrab(&entry->vfs_inode);
4960 spin_unlock(&root->inode_lock);
4961 if (atomic_read(&inode->i_count) > 1)
4962 d_prune_aliases(inode);
4964 * btrfs_drop_inode will have it removed from
4965 * the inode cache when its usage count
4970 spin_lock(&root->inode_lock);
4974 if (cond_resched_lock(&root->inode_lock))
4977 node = rb_next(node);
4979 spin_unlock(&root->inode_lock);
4982 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4984 struct btrfs_iget_args *args = p;
4985 inode->i_ino = args->ino;
4986 BTRFS_I(inode)->root = args->root;
4990 static int btrfs_find_actor(struct inode *inode, void *opaque)
4992 struct btrfs_iget_args *args = opaque;
4993 return args->ino == btrfs_ino(inode) &&
4994 args->root == BTRFS_I(inode)->root;
4997 static struct inode *btrfs_iget_locked(struct super_block *s,
4999 struct btrfs_root *root)
5001 struct inode *inode;
5002 struct btrfs_iget_args args;
5003 args.ino = objectid;
5006 inode = iget5_locked(s, objectid, btrfs_find_actor,
5007 btrfs_init_locked_inode,
5012 /* Get an inode object given its location and corresponding root.
5013 * Returns in *is_new if the inode was read from disk
5015 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5016 struct btrfs_root *root, int *new)
5018 struct inode *inode;
5020 inode = btrfs_iget_locked(s, location->objectid, root);
5022 return ERR_PTR(-ENOMEM);
5024 if (inode->i_state & I_NEW) {
5025 BTRFS_I(inode)->root = root;
5026 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
5027 btrfs_read_locked_inode(inode);
5028 if (!is_bad_inode(inode)) {
5029 inode_tree_add(inode);
5030 unlock_new_inode(inode);
5034 unlock_new_inode(inode);
5036 inode = ERR_PTR(-ESTALE);
5043 static struct inode *new_simple_dir(struct super_block *s,
5044 struct btrfs_key *key,
5045 struct btrfs_root *root)
5047 struct inode *inode = new_inode(s);
5050 return ERR_PTR(-ENOMEM);
5052 BTRFS_I(inode)->root = root;
5053 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5054 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5056 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5057 inode->i_op = &btrfs_dir_ro_inode_operations;
5058 inode->i_fop = &simple_dir_operations;
5059 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5060 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5065 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5067 struct inode *inode;
5068 struct btrfs_root *root = BTRFS_I(dir)->root;
5069 struct btrfs_root *sub_root = root;
5070 struct btrfs_key location;
5074 if (dentry->d_name.len > BTRFS_NAME_LEN)
5075 return ERR_PTR(-ENAMETOOLONG);
5077 ret = btrfs_inode_by_name(dir, dentry, &location);
5079 return ERR_PTR(ret);
5081 if (location.objectid == 0)
5084 if (location.type == BTRFS_INODE_ITEM_KEY) {
5085 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5089 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5091 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5092 ret = fixup_tree_root_location(root, dir, dentry,
5093 &location, &sub_root);
5096 inode = ERR_PTR(ret);
5098 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5100 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5102 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5104 if (!IS_ERR(inode) && root != sub_root) {
5105 down_read(&root->fs_info->cleanup_work_sem);
5106 if (!(inode->i_sb->s_flags & MS_RDONLY))
5107 ret = btrfs_orphan_cleanup(sub_root);
5108 up_read(&root->fs_info->cleanup_work_sem);
5110 inode = ERR_PTR(ret);
5116 static int btrfs_dentry_delete(const struct dentry *dentry)
5118 struct btrfs_root *root;
5119 struct inode *inode = dentry->d_inode;
5121 if (!inode && !IS_ROOT(dentry))
5122 inode = dentry->d_parent->d_inode;
5125 root = BTRFS_I(inode)->root;
5126 if (btrfs_root_refs(&root->root_item) == 0)
5129 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5135 static void btrfs_dentry_release(struct dentry *dentry)
5137 if (dentry->d_fsdata)
5138 kfree(dentry->d_fsdata);
5141 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5146 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
5150 unsigned char btrfs_filetype_table[] = {
5151 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5154 static int btrfs_real_readdir(struct file *filp, void *dirent,
5157 struct inode *inode = file_inode(filp);
5158 struct btrfs_root *root = BTRFS_I(inode)->root;
5159 struct btrfs_item *item;
5160 struct btrfs_dir_item *di;
5161 struct btrfs_key key;
5162 struct btrfs_key found_key;
5163 struct btrfs_path *path;
5164 struct list_head ins_list;
5165 struct list_head del_list;
5167 struct extent_buffer *leaf;
5169 unsigned char d_type;
5174 int key_type = BTRFS_DIR_INDEX_KEY;
5178 int is_curr = 0; /* filp->f_pos points to the current index? */
5180 /* FIXME, use a real flag for deciding about the key type */
5181 if (root->fs_info->tree_root == root)
5182 key_type = BTRFS_DIR_ITEM_KEY;
5184 /* special case for "." */
5185 if (filp->f_pos == 0) {
5186 over = filldir(dirent, ".", 1,
5187 filp->f_pos, btrfs_ino(inode), DT_DIR);
5192 /* special case for .., just use the back ref */
5193 if (filp->f_pos == 1) {
5194 u64 pino = parent_ino(filp->f_path.dentry);
5195 over = filldir(dirent, "..", 2,
5196 filp->f_pos, pino, DT_DIR);
5201 path = btrfs_alloc_path();
5207 if (key_type == BTRFS_DIR_INDEX_KEY) {
5208 INIT_LIST_HEAD(&ins_list);
5209 INIT_LIST_HEAD(&del_list);
5210 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5213 btrfs_set_key_type(&key, key_type);
5214 key.offset = filp->f_pos;
5215 key.objectid = btrfs_ino(inode);
5217 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5222 leaf = path->nodes[0];
5223 slot = path->slots[0];
5224 if (slot >= btrfs_header_nritems(leaf)) {
5225 ret = btrfs_next_leaf(root, path);
5233 item = btrfs_item_nr(leaf, slot);
5234 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5236 if (found_key.objectid != key.objectid)
5238 if (btrfs_key_type(&found_key) != key_type)
5240 if (found_key.offset < filp->f_pos)
5242 if (key_type == BTRFS_DIR_INDEX_KEY &&
5243 btrfs_should_delete_dir_index(&del_list,
5247 filp->f_pos = found_key.offset;
5250 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5252 di_total = btrfs_item_size(leaf, item);
5254 while (di_cur < di_total) {
5255 struct btrfs_key location;
5257 if (verify_dir_item(root, leaf, di))
5260 name_len = btrfs_dir_name_len(leaf, di);
5261 if (name_len <= sizeof(tmp_name)) {
5262 name_ptr = tmp_name;
5264 name_ptr = kmalloc(name_len, GFP_NOFS);
5270 read_extent_buffer(leaf, name_ptr,
5271 (unsigned long)(di + 1), name_len);
5273 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5274 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5277 /* is this a reference to our own snapshot? If so
5280 * In contrast to old kernels, we insert the snapshot's
5281 * dir item and dir index after it has been created, so
5282 * we won't find a reference to our own snapshot. We
5283 * still keep the following code for backward
5286 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5287 location.objectid == root->root_key.objectid) {
5291 over = filldir(dirent, name_ptr, name_len,
5292 found_key.offset, location.objectid,
5296 if (name_ptr != tmp_name)
5301 di_len = btrfs_dir_name_len(leaf, di) +
5302 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5304 di = (struct btrfs_dir_item *)((char *)di + di_len);
5310 if (key_type == BTRFS_DIR_INDEX_KEY) {
5313 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
5319 /* Reached end of directory/root. Bump pos past the last item. */
5320 if (key_type == BTRFS_DIR_INDEX_KEY)
5322 * 32-bit glibc will use getdents64, but then strtol -
5323 * so the last number we can serve is this.
5325 filp->f_pos = 0x7fffffff;
5331 if (key_type == BTRFS_DIR_INDEX_KEY)
5332 btrfs_put_delayed_items(&ins_list, &del_list);
5333 btrfs_free_path(path);
5337 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5339 struct btrfs_root *root = BTRFS_I(inode)->root;
5340 struct btrfs_trans_handle *trans;
5342 bool nolock = false;
5344 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5347 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5350 if (wbc->sync_mode == WB_SYNC_ALL) {
5352 trans = btrfs_join_transaction_nolock(root);
5354 trans = btrfs_join_transaction(root);
5356 return PTR_ERR(trans);
5357 ret = btrfs_commit_transaction(trans, root);
5363 * This is somewhat expensive, updating the tree every time the
5364 * inode changes. But, it is most likely to find the inode in cache.
5365 * FIXME, needs more benchmarking...there are no reasons other than performance
5366 * to keep or drop this code.
5368 static int btrfs_dirty_inode(struct inode *inode)
5370 struct btrfs_root *root = BTRFS_I(inode)->root;
5371 struct btrfs_trans_handle *trans;
5374 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5377 trans = btrfs_join_transaction(root);
5379 return PTR_ERR(trans);
5381 ret = btrfs_update_inode(trans, root, inode);
5382 if (ret && ret == -ENOSPC) {
5383 /* whoops, lets try again with the full transaction */
5384 btrfs_end_transaction(trans, root);
5385 trans = btrfs_start_transaction(root, 1);
5387 return PTR_ERR(trans);
5389 ret = btrfs_update_inode(trans, root, inode);
5391 btrfs_end_transaction(trans, root);
5392 if (BTRFS_I(inode)->delayed_node)
5393 btrfs_balance_delayed_items(root);
5399 * This is a copy of file_update_time. We need this so we can return error on
5400 * ENOSPC for updating the inode in the case of file write and mmap writes.
5402 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5405 struct btrfs_root *root = BTRFS_I(inode)->root;
5407 if (btrfs_root_readonly(root))
5410 if (flags & S_VERSION)
5411 inode_inc_iversion(inode);
5412 if (flags & S_CTIME)
5413 inode->i_ctime = *now;
5414 if (flags & S_MTIME)
5415 inode->i_mtime = *now;
5416 if (flags & S_ATIME)
5417 inode->i_atime = *now;
5418 return btrfs_dirty_inode(inode);
5422 * find the highest existing sequence number in a directory
5423 * and then set the in-memory index_cnt variable to reflect
5424 * free sequence numbers
5426 static int btrfs_set_inode_index_count(struct inode *inode)
5428 struct btrfs_root *root = BTRFS_I(inode)->root;
5429 struct btrfs_key key, found_key;
5430 struct btrfs_path *path;
5431 struct extent_buffer *leaf;
5434 key.objectid = btrfs_ino(inode);
5435 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5436 key.offset = (u64)-1;
5438 path = btrfs_alloc_path();
5442 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5445 /* FIXME: we should be able to handle this */
5451 * MAGIC NUMBER EXPLANATION:
5452 * since we search a directory based on f_pos we have to start at 2
5453 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5454 * else has to start at 2
5456 if (path->slots[0] == 0) {
5457 BTRFS_I(inode)->index_cnt = 2;
5463 leaf = path->nodes[0];
5464 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5466 if (found_key.objectid != btrfs_ino(inode) ||
5467 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5468 BTRFS_I(inode)->index_cnt = 2;
5472 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5474 btrfs_free_path(path);
5479 * helper to find a free sequence number in a given directory. This current
5480 * code is very simple, later versions will do smarter things in the btree
5482 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5486 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5487 ret = btrfs_inode_delayed_dir_index_count(dir);
5489 ret = btrfs_set_inode_index_count(dir);
5495 *index = BTRFS_I(dir)->index_cnt;
5496 BTRFS_I(dir)->index_cnt++;
5501 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5502 struct btrfs_root *root,
5504 const char *name, int name_len,
5505 u64 ref_objectid, u64 objectid,
5506 umode_t mode, u64 *index)
5508 struct inode *inode;
5509 struct btrfs_inode_item *inode_item;
5510 struct btrfs_key *location;
5511 struct btrfs_path *path;
5512 struct btrfs_inode_ref *ref;
5513 struct btrfs_key key[2];
5519 path = btrfs_alloc_path();
5521 return ERR_PTR(-ENOMEM);
5523 inode = new_inode(root->fs_info->sb);
5525 btrfs_free_path(path);
5526 return ERR_PTR(-ENOMEM);
5530 * we have to initialize this early, so we can reclaim the inode
5531 * number if we fail afterwards in this function.
5533 inode->i_ino = objectid;
5536 trace_btrfs_inode_request(dir);
5538 ret = btrfs_set_inode_index(dir, index);
5540 btrfs_free_path(path);
5542 return ERR_PTR(ret);
5546 * index_cnt is ignored for everything but a dir,
5547 * btrfs_get_inode_index_count has an explanation for the magic
5550 BTRFS_I(inode)->index_cnt = 2;
5551 BTRFS_I(inode)->root = root;
5552 BTRFS_I(inode)->generation = trans->transid;
5553 inode->i_generation = BTRFS_I(inode)->generation;
5556 * We could have gotten an inode number from somebody who was fsynced
5557 * and then removed in this same transaction, so let's just set full
5558 * sync since it will be a full sync anyway and this will blow away the
5559 * old info in the log.
5561 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5568 key[0].objectid = objectid;
5569 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5573 * Start new inodes with an inode_ref. This is slightly more
5574 * efficient for small numbers of hard links since they will
5575 * be packed into one item. Extended refs will kick in if we
5576 * add more hard links than can fit in the ref item.
5578 key[1].objectid = objectid;
5579 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5580 key[1].offset = ref_objectid;
5582 sizes[0] = sizeof(struct btrfs_inode_item);
5583 sizes[1] = name_len + sizeof(*ref);
5585 path->leave_spinning = 1;
5586 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
5590 inode_init_owner(inode, dir, mode);
5591 inode_set_bytes(inode, 0);
5592 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5593 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5594 struct btrfs_inode_item);
5595 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5596 sizeof(*inode_item));
5597 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5599 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5600 struct btrfs_inode_ref);
5601 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5602 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5603 ptr = (unsigned long)(ref + 1);
5604 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5606 btrfs_mark_buffer_dirty(path->nodes[0]);
5607 btrfs_free_path(path);
5609 location = &BTRFS_I(inode)->location;
5610 location->objectid = objectid;
5611 location->offset = 0;
5612 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5614 btrfs_inherit_iflags(inode, dir);
5616 if (S_ISREG(mode)) {
5617 if (btrfs_test_opt(root, NODATASUM))
5618 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5619 if (btrfs_test_opt(root, NODATACOW))
5620 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5621 BTRFS_INODE_NODATASUM;
5624 insert_inode_hash(inode);
5625 inode_tree_add(inode);
5627 trace_btrfs_inode_new(inode);
5628 btrfs_set_inode_last_trans(trans, inode);
5630 btrfs_update_root_times(trans, root);
5635 BTRFS_I(dir)->index_cnt--;
5636 btrfs_free_path(path);
5638 return ERR_PTR(ret);
5641 static inline u8 btrfs_inode_type(struct inode *inode)
5643 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5647 * utility function to add 'inode' into 'parent_inode' with
5648 * a give name and a given sequence number.
5649 * if 'add_backref' is true, also insert a backref from the
5650 * inode to the parent directory.
5652 int btrfs_add_link(struct btrfs_trans_handle *trans,
5653 struct inode *parent_inode, struct inode *inode,
5654 const char *name, int name_len, int add_backref, u64 index)
5657 struct btrfs_key key;
5658 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5659 u64 ino = btrfs_ino(inode);
5660 u64 parent_ino = btrfs_ino(parent_inode);
5662 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5663 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5666 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5670 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5671 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5672 key.objectid, root->root_key.objectid,
5673 parent_ino, index, name, name_len);
5674 } else if (add_backref) {
5675 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5679 /* Nothing to clean up yet */
5683 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5685 btrfs_inode_type(inode), index);
5686 if (ret == -EEXIST || ret == -EOVERFLOW)
5689 btrfs_abort_transaction(trans, root, ret);
5693 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5695 inode_inc_iversion(parent_inode);
5696 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5697 ret = btrfs_update_inode(trans, root, parent_inode);
5699 btrfs_abort_transaction(trans, root, ret);
5703 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5706 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5707 key.objectid, root->root_key.objectid,
5708 parent_ino, &local_index, name, name_len);
5710 } else if (add_backref) {
5714 err = btrfs_del_inode_ref(trans, root, name, name_len,
5715 ino, parent_ino, &local_index);
5720 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5721 struct inode *dir, struct dentry *dentry,
5722 struct inode *inode, int backref, u64 index)
5724 int err = btrfs_add_link(trans, dir, inode,
5725 dentry->d_name.name, dentry->d_name.len,
5732 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5733 umode_t mode, dev_t rdev)
5735 struct btrfs_trans_handle *trans;
5736 struct btrfs_root *root = BTRFS_I(dir)->root;
5737 struct inode *inode = NULL;
5743 if (!new_valid_dev(rdev))
5747 * 2 for inode item and ref
5749 * 1 for xattr if selinux is on
5751 trans = btrfs_start_transaction(root, 5);
5753 return PTR_ERR(trans);
5755 err = btrfs_find_free_ino(root, &objectid);
5759 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5760 dentry->d_name.len, btrfs_ino(dir), objectid,
5762 if (IS_ERR(inode)) {
5763 err = PTR_ERR(inode);
5767 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5774 * If the active LSM wants to access the inode during
5775 * d_instantiate it needs these. Smack checks to see
5776 * if the filesystem supports xattrs by looking at the
5780 inode->i_op = &btrfs_special_inode_operations;
5781 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5785 init_special_inode(inode, inode->i_mode, rdev);
5786 btrfs_update_inode(trans, root, inode);
5787 d_instantiate(dentry, inode);
5790 btrfs_end_transaction(trans, root);
5791 btrfs_btree_balance_dirty(root);
5793 inode_dec_link_count(inode);
5799 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5800 umode_t mode, bool excl)
5802 struct btrfs_trans_handle *trans;
5803 struct btrfs_root *root = BTRFS_I(dir)->root;
5804 struct inode *inode = NULL;
5805 int drop_inode_on_err = 0;
5811 * 2 for inode item and ref
5813 * 1 for xattr if selinux is on
5815 trans = btrfs_start_transaction(root, 5);
5817 return PTR_ERR(trans);
5819 err = btrfs_find_free_ino(root, &objectid);
5823 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5824 dentry->d_name.len, btrfs_ino(dir), objectid,
5826 if (IS_ERR(inode)) {
5827 err = PTR_ERR(inode);
5830 drop_inode_on_err = 1;
5832 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5836 err = btrfs_update_inode(trans, root, inode);
5841 * If the active LSM wants to access the inode during
5842 * d_instantiate it needs these. Smack checks to see
5843 * if the filesystem supports xattrs by looking at the
5846 inode->i_fop = &btrfs_file_operations;
5847 inode->i_op = &btrfs_file_inode_operations;
5849 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5853 inode->i_mapping->a_ops = &btrfs_aops;
5854 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5855 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5856 d_instantiate(dentry, inode);
5859 btrfs_end_transaction(trans, root);
5860 if (err && drop_inode_on_err) {
5861 inode_dec_link_count(inode);
5864 btrfs_btree_balance_dirty(root);
5868 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5869 struct dentry *dentry)
5871 struct btrfs_trans_handle *trans;
5872 struct btrfs_root *root = BTRFS_I(dir)->root;
5873 struct inode *inode = old_dentry->d_inode;
5878 /* do not allow sys_link's with other subvols of the same device */
5879 if (root->objectid != BTRFS_I(inode)->root->objectid)
5882 if (inode->i_nlink >= BTRFS_LINK_MAX)
5885 err = btrfs_set_inode_index(dir, &index);
5890 * 2 items for inode and inode ref
5891 * 2 items for dir items
5892 * 1 item for parent inode
5894 trans = btrfs_start_transaction(root, 5);
5895 if (IS_ERR(trans)) {
5896 err = PTR_ERR(trans);
5900 btrfs_inc_nlink(inode);
5901 inode_inc_iversion(inode);
5902 inode->i_ctime = CURRENT_TIME;
5904 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5906 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5911 struct dentry *parent = dentry->d_parent;
5912 err = btrfs_update_inode(trans, root, inode);
5915 d_instantiate(dentry, inode);
5916 btrfs_log_new_name(trans, inode, NULL, parent);
5919 btrfs_end_transaction(trans, root);
5922 inode_dec_link_count(inode);
5925 btrfs_btree_balance_dirty(root);
5929 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5931 struct inode *inode = NULL;
5932 struct btrfs_trans_handle *trans;
5933 struct btrfs_root *root = BTRFS_I(dir)->root;
5935 int drop_on_err = 0;
5940 * 2 items for inode and ref
5941 * 2 items for dir items
5942 * 1 for xattr if selinux is on
5944 trans = btrfs_start_transaction(root, 5);
5946 return PTR_ERR(trans);
5948 err = btrfs_find_free_ino(root, &objectid);
5952 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5953 dentry->d_name.len, btrfs_ino(dir), objectid,
5954 S_IFDIR | mode, &index);
5955 if (IS_ERR(inode)) {
5956 err = PTR_ERR(inode);
5962 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5966 inode->i_op = &btrfs_dir_inode_operations;
5967 inode->i_fop = &btrfs_dir_file_operations;
5969 btrfs_i_size_write(inode, 0);
5970 err = btrfs_update_inode(trans, root, inode);
5974 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5975 dentry->d_name.len, 0, index);
5979 d_instantiate(dentry, inode);
5983 btrfs_end_transaction(trans, root);
5986 btrfs_btree_balance_dirty(root);
5990 /* helper for btfs_get_extent. Given an existing extent in the tree,
5991 * and an extent that you want to insert, deal with overlap and insert
5992 * the new extent into the tree.
5994 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5995 struct extent_map *existing,
5996 struct extent_map *em,
5997 u64 map_start, u64 map_len)
6001 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6002 start_diff = map_start - em->start;
6003 em->start = map_start;
6005 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6006 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6007 em->block_start += start_diff;
6008 em->block_len -= start_diff;
6010 return add_extent_mapping(em_tree, em, 0);
6013 static noinline int uncompress_inline(struct btrfs_path *path,
6014 struct inode *inode, struct page *page,
6015 size_t pg_offset, u64 extent_offset,
6016 struct btrfs_file_extent_item *item)
6019 struct extent_buffer *leaf = path->nodes[0];
6022 unsigned long inline_size;
6026 WARN_ON(pg_offset != 0);
6027 compress_type = btrfs_file_extent_compression(leaf, item);
6028 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6029 inline_size = btrfs_file_extent_inline_item_len(leaf,
6030 btrfs_item_nr(leaf, path->slots[0]));
6031 tmp = kmalloc(inline_size, GFP_NOFS);
6034 ptr = btrfs_file_extent_inline_start(item);
6036 read_extent_buffer(leaf, tmp, ptr, inline_size);
6038 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6039 ret = btrfs_decompress(compress_type, tmp, page,
6040 extent_offset, inline_size, max_size);
6042 char *kaddr = kmap_atomic(page);
6043 unsigned long copy_size = min_t(u64,
6044 PAGE_CACHE_SIZE - pg_offset,
6045 max_size - extent_offset);
6046 memset(kaddr + pg_offset, 0, copy_size);
6047 kunmap_atomic(kaddr);
6054 * a bit scary, this does extent mapping from logical file offset to the disk.
6055 * the ugly parts come from merging extents from the disk with the in-ram
6056 * representation. This gets more complex because of the data=ordered code,
6057 * where the in-ram extents might be locked pending data=ordered completion.
6059 * This also copies inline extents directly into the page.
6062 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6063 size_t pg_offset, u64 start, u64 len,
6069 u64 extent_start = 0;
6071 u64 objectid = btrfs_ino(inode);
6073 struct btrfs_path *path = NULL;
6074 struct btrfs_root *root = BTRFS_I(inode)->root;
6075 struct btrfs_file_extent_item *item;
6076 struct extent_buffer *leaf;
6077 struct btrfs_key found_key;
6078 struct extent_map *em = NULL;
6079 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6080 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6081 struct btrfs_trans_handle *trans = NULL;
6085 read_lock(&em_tree->lock);
6086 em = lookup_extent_mapping(em_tree, start, len);
6088 em->bdev = root->fs_info->fs_devices->latest_bdev;
6089 read_unlock(&em_tree->lock);
6092 if (em->start > start || em->start + em->len <= start)
6093 free_extent_map(em);
6094 else if (em->block_start == EXTENT_MAP_INLINE && page)
6095 free_extent_map(em);
6099 em = alloc_extent_map();
6104 em->bdev = root->fs_info->fs_devices->latest_bdev;
6105 em->start = EXTENT_MAP_HOLE;
6106 em->orig_start = EXTENT_MAP_HOLE;
6108 em->block_len = (u64)-1;
6111 path = btrfs_alloc_path();
6117 * Chances are we'll be called again, so go ahead and do
6123 ret = btrfs_lookup_file_extent(trans, root, path,
6124 objectid, start, trans != NULL);
6131 if (path->slots[0] == 0)
6136 leaf = path->nodes[0];
6137 item = btrfs_item_ptr(leaf, path->slots[0],
6138 struct btrfs_file_extent_item);
6139 /* are we inside the extent that was found? */
6140 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6141 found_type = btrfs_key_type(&found_key);
6142 if (found_key.objectid != objectid ||
6143 found_type != BTRFS_EXTENT_DATA_KEY) {
6147 found_type = btrfs_file_extent_type(leaf, item);
6148 extent_start = found_key.offset;
6149 compress_type = btrfs_file_extent_compression(leaf, item);
6150 if (found_type == BTRFS_FILE_EXTENT_REG ||
6151 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6152 extent_end = extent_start +
6153 btrfs_file_extent_num_bytes(leaf, item);
6154 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6156 size = btrfs_file_extent_inline_len(leaf, item);
6157 extent_end = ALIGN(extent_start + size, root->sectorsize);
6160 if (start >= extent_end) {
6162 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6163 ret = btrfs_next_leaf(root, path);
6170 leaf = path->nodes[0];
6172 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6173 if (found_key.objectid != objectid ||
6174 found_key.type != BTRFS_EXTENT_DATA_KEY)
6176 if (start + len <= found_key.offset)
6179 em->orig_start = start;
6180 em->len = found_key.offset - start;
6184 em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
6185 if (found_type == BTRFS_FILE_EXTENT_REG ||
6186 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6187 em->start = extent_start;
6188 em->len = extent_end - extent_start;
6189 em->orig_start = extent_start -
6190 btrfs_file_extent_offset(leaf, item);
6191 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6193 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6195 em->block_start = EXTENT_MAP_HOLE;
6198 if (compress_type != BTRFS_COMPRESS_NONE) {
6199 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6200 em->compress_type = compress_type;
6201 em->block_start = bytenr;
6202 em->block_len = em->orig_block_len;
6204 bytenr += btrfs_file_extent_offset(leaf, item);
6205 em->block_start = bytenr;
6206 em->block_len = em->len;
6207 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6208 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6211 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6215 size_t extent_offset;
6218 em->block_start = EXTENT_MAP_INLINE;
6219 if (!page || create) {
6220 em->start = extent_start;
6221 em->len = extent_end - extent_start;
6225 size = btrfs_file_extent_inline_len(leaf, item);
6226 extent_offset = page_offset(page) + pg_offset - extent_start;
6227 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6228 size - extent_offset);
6229 em->start = extent_start + extent_offset;
6230 em->len = ALIGN(copy_size, root->sectorsize);
6231 em->orig_block_len = em->len;
6232 em->orig_start = em->start;
6233 if (compress_type) {
6234 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6235 em->compress_type = compress_type;
6237 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6238 if (create == 0 && !PageUptodate(page)) {
6239 if (btrfs_file_extent_compression(leaf, item) !=
6240 BTRFS_COMPRESS_NONE) {
6241 ret = uncompress_inline(path, inode, page,
6243 extent_offset, item);
6244 BUG_ON(ret); /* -ENOMEM */
6247 read_extent_buffer(leaf, map + pg_offset, ptr,
6249 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6250 memset(map + pg_offset + copy_size, 0,
6251 PAGE_CACHE_SIZE - pg_offset -
6256 flush_dcache_page(page);
6257 } else if (create && PageUptodate(page)) {
6261 free_extent_map(em);
6264 btrfs_release_path(path);
6265 trans = btrfs_join_transaction(root);
6268 return ERR_CAST(trans);
6272 write_extent_buffer(leaf, map + pg_offset, ptr,
6275 btrfs_mark_buffer_dirty(leaf);
6277 set_extent_uptodate(io_tree, em->start,
6278 extent_map_end(em) - 1, NULL, GFP_NOFS);
6281 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6285 em->orig_start = start;
6288 em->block_start = EXTENT_MAP_HOLE;
6289 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6291 btrfs_release_path(path);
6292 if (em->start > start || extent_map_end(em) <= start) {
6293 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6294 (unsigned long long)em->start,
6295 (unsigned long long)em->len,
6296 (unsigned long long)start,
6297 (unsigned long long)len);
6303 write_lock(&em_tree->lock);
6304 ret = add_extent_mapping(em_tree, em, 0);
6305 /* it is possible that someone inserted the extent into the tree
6306 * while we had the lock dropped. It is also possible that
6307 * an overlapping map exists in the tree
6309 if (ret == -EEXIST) {
6310 struct extent_map *existing;
6314 existing = lookup_extent_mapping(em_tree, start, len);
6315 if (existing && (existing->start > start ||
6316 existing->start + existing->len <= start)) {
6317 free_extent_map(existing);
6321 existing = lookup_extent_mapping(em_tree, em->start,
6324 err = merge_extent_mapping(em_tree, existing,
6327 free_extent_map(existing);
6329 free_extent_map(em);
6334 free_extent_map(em);
6338 free_extent_map(em);
6343 write_unlock(&em_tree->lock);
6347 trace_btrfs_get_extent(root, em);
6350 btrfs_free_path(path);
6352 ret = btrfs_end_transaction(trans, root);
6357 free_extent_map(em);
6358 return ERR_PTR(err);
6360 BUG_ON(!em); /* Error is always set */
6364 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6365 size_t pg_offset, u64 start, u64 len,
6368 struct extent_map *em;
6369 struct extent_map *hole_em = NULL;
6370 u64 range_start = start;
6376 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6383 * - a pre-alloc extent,
6384 * there might actually be delalloc bytes behind it.
6386 if (em->block_start != EXTENT_MAP_HOLE &&
6387 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6393 /* check to see if we've wrapped (len == -1 or similar) */
6402 /* ok, we didn't find anything, lets look for delalloc */
6403 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6404 end, len, EXTENT_DELALLOC, 1);
6405 found_end = range_start + found;
6406 if (found_end < range_start)
6407 found_end = (u64)-1;
6410 * we didn't find anything useful, return
6411 * the original results from get_extent()
6413 if (range_start > end || found_end <= start) {
6419 /* adjust the range_start to make sure it doesn't
6420 * go backwards from the start they passed in
6422 range_start = max(start,range_start);
6423 found = found_end - range_start;
6426 u64 hole_start = start;
6429 em = alloc_extent_map();
6435 * when btrfs_get_extent can't find anything it
6436 * returns one huge hole
6438 * make sure what it found really fits our range, and
6439 * adjust to make sure it is based on the start from
6443 u64 calc_end = extent_map_end(hole_em);
6445 if (calc_end <= start || (hole_em->start > end)) {
6446 free_extent_map(hole_em);
6449 hole_start = max(hole_em->start, start);
6450 hole_len = calc_end - hole_start;
6454 if (hole_em && range_start > hole_start) {
6455 /* our hole starts before our delalloc, so we
6456 * have to return just the parts of the hole
6457 * that go until the delalloc starts
6459 em->len = min(hole_len,
6460 range_start - hole_start);
6461 em->start = hole_start;
6462 em->orig_start = hole_start;
6464 * don't adjust block start at all,
6465 * it is fixed at EXTENT_MAP_HOLE
6467 em->block_start = hole_em->block_start;
6468 em->block_len = hole_len;
6469 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6470 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6472 em->start = range_start;
6474 em->orig_start = range_start;
6475 em->block_start = EXTENT_MAP_DELALLOC;
6476 em->block_len = found;
6478 } else if (hole_em) {
6483 free_extent_map(hole_em);
6485 free_extent_map(em);
6486 return ERR_PTR(err);
6491 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6494 struct btrfs_root *root = BTRFS_I(inode)->root;
6495 struct btrfs_trans_handle *trans;
6496 struct extent_map *em;
6497 struct btrfs_key ins;
6501 trans = btrfs_join_transaction(root);
6503 return ERR_CAST(trans);
6505 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
6507 alloc_hint = get_extent_allocation_hint(inode, start, len);
6508 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
6509 alloc_hint, &ins, 1);
6515 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6516 ins.offset, ins.offset, ins.offset, 0);
6520 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6521 ins.offset, ins.offset, 0);
6523 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6527 btrfs_end_transaction(trans, root);
6532 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6533 * block must be cow'd
6535 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
6536 struct inode *inode, u64 offset, u64 *len,
6537 u64 *orig_start, u64 *orig_block_len,
6540 struct btrfs_path *path;
6542 struct extent_buffer *leaf;
6543 struct btrfs_root *root = BTRFS_I(inode)->root;
6544 struct btrfs_file_extent_item *fi;
6545 struct btrfs_key key;
6553 path = btrfs_alloc_path();
6557 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
6562 slot = path->slots[0];
6565 /* can't find the item, must cow */
6572 leaf = path->nodes[0];
6573 btrfs_item_key_to_cpu(leaf, &key, slot);
6574 if (key.objectid != btrfs_ino(inode) ||
6575 key.type != BTRFS_EXTENT_DATA_KEY) {
6576 /* not our file or wrong item type, must cow */
6580 if (key.offset > offset) {
6581 /* Wrong offset, must cow */
6585 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6586 found_type = btrfs_file_extent_type(leaf, fi);
6587 if (found_type != BTRFS_FILE_EXTENT_REG &&
6588 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6589 /* not a regular extent, must cow */
6592 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6593 backref_offset = btrfs_file_extent_offset(leaf, fi);
6595 *orig_start = key.offset - backref_offset;
6596 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6597 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6599 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6600 if (extent_end < offset + *len) {
6601 /* extent doesn't include our full range, must cow */
6605 if (btrfs_extent_readonly(root, disk_bytenr))
6609 * look for other files referencing this extent, if we
6610 * find any we must cow
6612 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6613 key.offset - backref_offset, disk_bytenr))
6617 * adjust disk_bytenr and num_bytes to cover just the bytes
6618 * in this extent we are about to write. If there
6619 * are any csums in that range we have to cow in order
6620 * to keep the csums correct
6622 disk_bytenr += backref_offset;
6623 disk_bytenr += offset - key.offset;
6624 num_bytes = min(offset + *len, extent_end) - offset;
6625 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6628 * all of the above have passed, it is safe to overwrite this extent
6634 btrfs_free_path(path);
6638 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6639 struct extent_state **cached_state, int writing)
6641 struct btrfs_ordered_extent *ordered;
6645 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6648 * We're concerned with the entire range that we're going to be
6649 * doing DIO to, so we need to make sure theres no ordered
6650 * extents in this range.
6652 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6653 lockend - lockstart + 1);
6656 * We need to make sure there are no buffered pages in this
6657 * range either, we could have raced between the invalidate in
6658 * generic_file_direct_write and locking the extent. The
6659 * invalidate needs to happen so that reads after a write do not
6662 if (!ordered && (!writing ||
6663 !test_range_bit(&BTRFS_I(inode)->io_tree,
6664 lockstart, lockend, EXTENT_UPTODATE, 0,
6668 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6669 cached_state, GFP_NOFS);
6672 btrfs_start_ordered_extent(inode, ordered, 1);
6673 btrfs_put_ordered_extent(ordered);
6675 /* Screw you mmap */
6676 ret = filemap_write_and_wait_range(inode->i_mapping,
6683 * If we found a page that couldn't be invalidated just
6684 * fall back to buffered.
6686 ret = invalidate_inode_pages2_range(inode->i_mapping,
6687 lockstart >> PAGE_CACHE_SHIFT,
6688 lockend >> PAGE_CACHE_SHIFT);
6699 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6700 u64 len, u64 orig_start,
6701 u64 block_start, u64 block_len,
6702 u64 orig_block_len, u64 ram_bytes,
6705 struct extent_map_tree *em_tree;
6706 struct extent_map *em;
6707 struct btrfs_root *root = BTRFS_I(inode)->root;
6710 em_tree = &BTRFS_I(inode)->extent_tree;
6711 em = alloc_extent_map();
6713 return ERR_PTR(-ENOMEM);
6716 em->orig_start = orig_start;
6717 em->mod_start = start;
6720 em->block_len = block_len;
6721 em->block_start = block_start;
6722 em->bdev = root->fs_info->fs_devices->latest_bdev;
6723 em->orig_block_len = orig_block_len;
6724 em->ram_bytes = ram_bytes;
6725 em->generation = -1;
6726 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6727 if (type == BTRFS_ORDERED_PREALLOC)
6728 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6731 btrfs_drop_extent_cache(inode, em->start,
6732 em->start + em->len - 1, 0);
6733 write_lock(&em_tree->lock);
6734 ret = add_extent_mapping(em_tree, em, 1);
6735 write_unlock(&em_tree->lock);
6736 } while (ret == -EEXIST);
6739 free_extent_map(em);
6740 return ERR_PTR(ret);
6747 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6748 struct buffer_head *bh_result, int create)
6750 struct extent_map *em;
6751 struct btrfs_root *root = BTRFS_I(inode)->root;
6752 struct extent_state *cached_state = NULL;
6753 u64 start = iblock << inode->i_blkbits;
6754 u64 lockstart, lockend;
6755 u64 len = bh_result->b_size;
6756 struct btrfs_trans_handle *trans;
6757 int unlock_bits = EXTENT_LOCKED;
6761 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6763 len = min_t(u64, len, root->sectorsize);
6766 lockend = start + len - 1;
6769 * If this errors out it's because we couldn't invalidate pagecache for
6770 * this range and we need to fallback to buffered.
6772 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6775 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6782 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6783 * io. INLINE is special, and we could probably kludge it in here, but
6784 * it's still buffered so for safety lets just fall back to the generic
6787 * For COMPRESSED we _have_ to read the entire extent in so we can
6788 * decompress it, so there will be buffering required no matter what we
6789 * do, so go ahead and fallback to buffered.
6791 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6792 * to buffered IO. Don't blame me, this is the price we pay for using
6795 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6796 em->block_start == EXTENT_MAP_INLINE) {
6797 free_extent_map(em);
6802 /* Just a good old fashioned hole, return */
6803 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6804 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6805 free_extent_map(em);
6810 * We don't allocate a new extent in the following cases
6812 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6814 * 2) The extent is marked as PREALLOC. We're good to go here and can
6815 * just use the extent.
6819 len = min(len, em->len - (start - em->start));
6820 lockstart = start + len;
6824 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6825 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6826 em->block_start != EXTENT_MAP_HOLE)) {
6829 u64 block_start, orig_start, orig_block_len, ram_bytes;
6831 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6832 type = BTRFS_ORDERED_PREALLOC;
6834 type = BTRFS_ORDERED_NOCOW;
6835 len = min(len, em->len - (start - em->start));
6836 block_start = em->block_start + (start - em->start);
6839 * we're not going to log anything, but we do need
6840 * to make sure the current transaction stays open
6841 * while we look for nocow cross refs
6843 trans = btrfs_join_transaction(root);
6847 if (can_nocow_odirect(trans, inode, start, &len, &orig_start,
6848 &orig_block_len, &ram_bytes) == 1) {
6849 if (type == BTRFS_ORDERED_PREALLOC) {
6850 free_extent_map(em);
6851 em = create_pinned_em(inode, start, len,
6857 btrfs_end_transaction(trans, root);
6862 ret = btrfs_add_ordered_extent_dio(inode, start,
6863 block_start, len, len, type);
6864 btrfs_end_transaction(trans, root);
6866 free_extent_map(em);
6871 btrfs_end_transaction(trans, root);
6875 * this will cow the extent, reset the len in case we changed
6878 len = bh_result->b_size;
6879 free_extent_map(em);
6880 em = btrfs_new_extent_direct(inode, start, len);
6885 len = min(len, em->len - (start - em->start));
6887 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6889 bh_result->b_size = len;
6890 bh_result->b_bdev = em->bdev;
6891 set_buffer_mapped(bh_result);
6893 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6894 set_buffer_new(bh_result);
6897 * Need to update the i_size under the extent lock so buffered
6898 * readers will get the updated i_size when we unlock.
6900 if (start + len > i_size_read(inode))
6901 i_size_write(inode, start + len);
6903 spin_lock(&BTRFS_I(inode)->lock);
6904 BTRFS_I(inode)->outstanding_extents++;
6905 spin_unlock(&BTRFS_I(inode)->lock);
6907 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6908 lockstart + len - 1, EXTENT_DELALLOC, NULL,
6909 &cached_state, GFP_NOFS);
6914 * In the case of write we need to clear and unlock the entire range,
6915 * in the case of read we need to unlock only the end area that we
6916 * aren't using if there is any left over space.
6918 if (lockstart < lockend) {
6919 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6920 lockend, unlock_bits, 1, 0,
6921 &cached_state, GFP_NOFS);
6923 free_extent_state(cached_state);
6926 free_extent_map(em);
6931 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6932 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6936 struct btrfs_dio_private {
6937 struct inode *inode;
6943 /* number of bios pending for this dio */
6944 atomic_t pending_bios;
6949 /* orig_bio is our btrfs_io_bio */
6950 struct bio *orig_bio;
6952 /* dio_bio came from fs/direct-io.c */
6953 struct bio *dio_bio;
6956 static void btrfs_endio_direct_read(struct bio *bio, int err)
6958 struct btrfs_dio_private *dip = bio->bi_private;
6959 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6960 struct bio_vec *bvec = bio->bi_io_vec;
6961 struct inode *inode = dip->inode;
6962 struct btrfs_root *root = BTRFS_I(inode)->root;
6963 struct bio *dio_bio;
6966 start = dip->logical_offset;
6968 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6969 struct page *page = bvec->bv_page;
6972 u64 private = ~(u32)0;
6973 unsigned long flags;
6975 if (get_state_private(&BTRFS_I(inode)->io_tree,
6978 local_irq_save(flags);
6979 kaddr = kmap_atomic(page);
6980 csum = btrfs_csum_data(kaddr + bvec->bv_offset,
6981 csum, bvec->bv_len);
6982 btrfs_csum_final(csum, (char *)&csum);
6983 kunmap_atomic(kaddr);
6984 local_irq_restore(flags);
6986 flush_dcache_page(bvec->bv_page);
6987 if (csum != private) {
6989 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u private %u",
6990 (unsigned long long)btrfs_ino(inode),
6991 (unsigned long long)start,
6992 csum, (unsigned)private);
6997 start += bvec->bv_len;
6999 } while (bvec <= bvec_end);
7001 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
7002 dip->logical_offset + dip->bytes - 1);
7003 dio_bio = dip->dio_bio;
7007 /* If we had a csum failure make sure to clear the uptodate flag */
7009 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7010 dio_end_io(dio_bio, err);
7014 static void btrfs_endio_direct_write(struct bio *bio, int err)
7016 struct btrfs_dio_private *dip = bio->bi_private;
7017 struct inode *inode = dip->inode;
7018 struct btrfs_root *root = BTRFS_I(inode)->root;
7019 struct btrfs_ordered_extent *ordered = NULL;
7020 u64 ordered_offset = dip->logical_offset;
7021 u64 ordered_bytes = dip->bytes;
7022 struct bio *dio_bio;
7028 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7030 ordered_bytes, !err);
7034 ordered->work.func = finish_ordered_fn;
7035 ordered->work.flags = 0;
7036 btrfs_queue_worker(&root->fs_info->endio_write_workers,
7040 * our bio might span multiple ordered extents. If we haven't
7041 * completed the accounting for the whole dio, go back and try again
7043 if (ordered_offset < dip->logical_offset + dip->bytes) {
7044 ordered_bytes = dip->logical_offset + dip->bytes -
7050 dio_bio = dip->dio_bio;
7054 /* If we had an error make sure to clear the uptodate flag */
7056 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7057 dio_end_io(dio_bio, err);
7061 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7062 struct bio *bio, int mirror_num,
7063 unsigned long bio_flags, u64 offset)
7066 struct btrfs_root *root = BTRFS_I(inode)->root;
7067 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7068 BUG_ON(ret); /* -ENOMEM */
7072 static void btrfs_end_dio_bio(struct bio *bio, int err)
7074 struct btrfs_dio_private *dip = bio->bi_private;
7077 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
7078 "sector %#Lx len %u err no %d\n",
7079 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
7080 (unsigned long long)bio->bi_sector, bio->bi_size, err);
7084 * before atomic variable goto zero, we must make sure
7085 * dip->errors is perceived to be set.
7087 smp_mb__before_atomic_dec();
7090 /* if there are more bios still pending for this dio, just exit */
7091 if (!atomic_dec_and_test(&dip->pending_bios))
7095 bio_io_error(dip->orig_bio);
7097 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
7098 bio_endio(dip->orig_bio, 0);
7104 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7105 u64 first_sector, gfp_t gfp_flags)
7107 int nr_vecs = bio_get_nr_vecs(bdev);
7108 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7111 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7112 int rw, u64 file_offset, int skip_sum,
7115 int write = rw & REQ_WRITE;
7116 struct btrfs_root *root = BTRFS_I(inode)->root;
7120 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7125 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
7133 if (write && async_submit) {
7134 ret = btrfs_wq_submit_bio(root->fs_info,
7135 inode, rw, bio, 0, 0,
7137 __btrfs_submit_bio_start_direct_io,
7138 __btrfs_submit_bio_done);
7142 * If we aren't doing async submit, calculate the csum of the
7145 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7148 } else if (!skip_sum) {
7149 ret = btrfs_lookup_bio_sums_dio(root, inode, bio, file_offset);
7155 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7161 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7164 struct inode *inode = dip->inode;
7165 struct btrfs_root *root = BTRFS_I(inode)->root;
7167 struct bio *orig_bio = dip->orig_bio;
7168 struct bio_vec *bvec = orig_bio->bi_io_vec;
7169 u64 start_sector = orig_bio->bi_sector;
7170 u64 file_offset = dip->logical_offset;
7175 int async_submit = 0;
7177 map_length = orig_bio->bi_size;
7178 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7179 &map_length, NULL, 0);
7184 if (map_length >= orig_bio->bi_size) {
7189 /* async crcs make it difficult to collect full stripe writes. */
7190 if (btrfs_get_alloc_profile(root, 1) &
7191 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7196 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7199 bio->bi_private = dip;
7200 bio->bi_end_io = btrfs_end_dio_bio;
7201 atomic_inc(&dip->pending_bios);
7203 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7204 if (unlikely(map_length < submit_len + bvec->bv_len ||
7205 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7206 bvec->bv_offset) < bvec->bv_len)) {
7208 * inc the count before we submit the bio so
7209 * we know the end IO handler won't happen before
7210 * we inc the count. Otherwise, the dip might get freed
7211 * before we're done setting it up
7213 atomic_inc(&dip->pending_bios);
7214 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7215 file_offset, skip_sum,
7219 atomic_dec(&dip->pending_bios);
7223 start_sector += submit_len >> 9;
7224 file_offset += submit_len;
7229 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7230 start_sector, GFP_NOFS);
7233 bio->bi_private = dip;
7234 bio->bi_end_io = btrfs_end_dio_bio;
7236 map_length = orig_bio->bi_size;
7237 ret = btrfs_map_block(root->fs_info, rw,
7239 &map_length, NULL, 0);
7245 submit_len += bvec->bv_len;
7252 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7261 * before atomic variable goto zero, we must
7262 * make sure dip->errors is perceived to be set.
7264 smp_mb__before_atomic_dec();
7265 if (atomic_dec_and_test(&dip->pending_bios))
7266 bio_io_error(dip->orig_bio);
7268 /* bio_end_io() will handle error, so we needn't return it */
7272 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7273 struct inode *inode, loff_t file_offset)
7275 struct btrfs_root *root = BTRFS_I(inode)->root;
7276 struct btrfs_dio_private *dip;
7277 struct bio_vec *bvec = dio_bio->bi_io_vec;
7280 int write = rw & REQ_WRITE;
7283 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7285 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7292 dip = kmalloc(sizeof(*dip), GFP_NOFS);
7298 dip->private = dio_bio->bi_private;
7299 io_bio->bi_private = dio_bio->bi_private;
7301 dip->logical_offset = file_offset;
7305 dip->bytes += bvec->bv_len;
7307 } while (bvec <= (dio_bio->bi_io_vec + dio_bio->bi_vcnt - 1));
7309 dip->disk_bytenr = (u64)dio_bio->bi_sector << 9;
7310 io_bio->bi_private = dip;
7312 dip->orig_bio = io_bio;
7313 dip->dio_bio = dio_bio;
7314 atomic_set(&dip->pending_bios, 0);
7317 io_bio->bi_end_io = btrfs_endio_direct_write;
7319 io_bio->bi_end_io = btrfs_endio_direct_read;
7321 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7330 * If this is a write, we need to clean up the reserved space and kill
7331 * the ordered extent.
7334 struct btrfs_ordered_extent *ordered;
7335 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7336 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7337 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7338 btrfs_free_reserved_extent(root, ordered->start,
7340 btrfs_put_ordered_extent(ordered);
7341 btrfs_put_ordered_extent(ordered);
7343 bio_endio(dio_bio, ret);
7346 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7347 const struct iovec *iov, loff_t offset,
7348 unsigned long nr_segs)
7354 unsigned blocksize_mask = root->sectorsize - 1;
7355 ssize_t retval = -EINVAL;
7356 loff_t end = offset;
7358 if (offset & blocksize_mask)
7361 /* Check the memory alignment. Blocks cannot straddle pages */
7362 for (seg = 0; seg < nr_segs; seg++) {
7363 addr = (unsigned long)iov[seg].iov_base;
7364 size = iov[seg].iov_len;
7366 if ((addr & blocksize_mask) || (size & blocksize_mask))
7369 /* If this is a write we don't need to check anymore */
7374 * Check to make sure we don't have duplicate iov_base's in this
7375 * iovec, if so return EINVAL, otherwise we'll get csum errors
7376 * when reading back.
7378 for (i = seg + 1; i < nr_segs; i++) {
7379 if (iov[seg].iov_base == iov[i].iov_base)
7388 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7389 const struct iovec *iov, loff_t offset,
7390 unsigned long nr_segs)
7392 struct file *file = iocb->ki_filp;
7393 struct inode *inode = file->f_mapping->host;
7397 bool relock = false;
7400 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7404 atomic_inc(&inode->i_dio_count);
7405 smp_mb__after_atomic_inc();
7408 count = iov_length(iov, nr_segs);
7410 * If the write DIO is beyond the EOF, we need update
7411 * the isize, but it is protected by i_mutex. So we can
7412 * not unlock the i_mutex at this case.
7414 if (offset + count <= inode->i_size) {
7415 mutex_unlock(&inode->i_mutex);
7418 ret = btrfs_delalloc_reserve_space(inode, count);
7421 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7422 &BTRFS_I(inode)->runtime_flags))) {
7423 inode_dio_done(inode);
7424 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7428 ret = __blockdev_direct_IO(rw, iocb, inode,
7429 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7430 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7431 btrfs_submit_direct, flags);
7433 if (ret < 0 && ret != -EIOCBQUEUED)
7434 btrfs_delalloc_release_space(inode, count);
7435 else if (ret >= 0 && (size_t)ret < count)
7436 btrfs_delalloc_release_space(inode,
7437 count - (size_t)ret);
7439 btrfs_delalloc_release_metadata(inode, 0);
7443 inode_dio_done(inode);
7445 mutex_lock(&inode->i_mutex);
7450 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7452 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7453 __u64 start, __u64 len)
7457 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7461 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7464 int btrfs_readpage(struct file *file, struct page *page)
7466 struct extent_io_tree *tree;
7467 tree = &BTRFS_I(page->mapping->host)->io_tree;
7468 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7471 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7473 struct extent_io_tree *tree;
7476 if (current->flags & PF_MEMALLOC) {
7477 redirty_page_for_writepage(wbc, page);
7481 tree = &BTRFS_I(page->mapping->host)->io_tree;
7482 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7485 static int btrfs_writepages(struct address_space *mapping,
7486 struct writeback_control *wbc)
7488 struct extent_io_tree *tree;
7490 tree = &BTRFS_I(mapping->host)->io_tree;
7491 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7495 btrfs_readpages(struct file *file, struct address_space *mapping,
7496 struct list_head *pages, unsigned nr_pages)
7498 struct extent_io_tree *tree;
7499 tree = &BTRFS_I(mapping->host)->io_tree;
7500 return extent_readpages(tree, mapping, pages, nr_pages,
7503 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7505 struct extent_io_tree *tree;
7506 struct extent_map_tree *map;
7509 tree = &BTRFS_I(page->mapping->host)->io_tree;
7510 map = &BTRFS_I(page->mapping->host)->extent_tree;
7511 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7513 ClearPagePrivate(page);
7514 set_page_private(page, 0);
7515 page_cache_release(page);
7520 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7522 if (PageWriteback(page) || PageDirty(page))
7524 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7527 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
7529 struct inode *inode = page->mapping->host;
7530 struct extent_io_tree *tree;
7531 struct btrfs_ordered_extent *ordered;
7532 struct extent_state *cached_state = NULL;
7533 u64 page_start = page_offset(page);
7534 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7537 * we have the page locked, so new writeback can't start,
7538 * and the dirty bit won't be cleared while we are here.
7540 * Wait for IO on this page so that we can safely clear
7541 * the PagePrivate2 bit and do ordered accounting
7543 wait_on_page_writeback(page);
7545 tree = &BTRFS_I(inode)->io_tree;
7547 btrfs_releasepage(page, GFP_NOFS);
7550 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7551 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
7554 * IO on this page will never be started, so we need
7555 * to account for any ordered extents now
7557 clear_extent_bit(tree, page_start, page_end,
7558 EXTENT_DIRTY | EXTENT_DELALLOC |
7559 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7560 EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS);
7562 * whoever cleared the private bit is responsible
7563 * for the finish_ordered_io
7565 if (TestClearPagePrivate2(page) &&
7566 btrfs_dec_test_ordered_pending(inode, &ordered, page_start,
7567 PAGE_CACHE_SIZE, 1)) {
7568 btrfs_finish_ordered_io(ordered);
7570 btrfs_put_ordered_extent(ordered);
7571 cached_state = NULL;
7572 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7574 clear_extent_bit(tree, page_start, page_end,
7575 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
7576 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
7577 &cached_state, GFP_NOFS);
7578 __btrfs_releasepage(page, GFP_NOFS);
7580 ClearPageChecked(page);
7581 if (PagePrivate(page)) {
7582 ClearPagePrivate(page);
7583 set_page_private(page, 0);
7584 page_cache_release(page);
7589 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7590 * called from a page fault handler when a page is first dirtied. Hence we must
7591 * be careful to check for EOF conditions here. We set the page up correctly
7592 * for a written page which means we get ENOSPC checking when writing into
7593 * holes and correct delalloc and unwritten extent mapping on filesystems that
7594 * support these features.
7596 * We are not allowed to take the i_mutex here so we have to play games to
7597 * protect against truncate races as the page could now be beyond EOF. Because
7598 * vmtruncate() writes the inode size before removing pages, once we have the
7599 * page lock we can determine safely if the page is beyond EOF. If it is not
7600 * beyond EOF, then the page is guaranteed safe against truncation until we
7603 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7605 struct page *page = vmf->page;
7606 struct inode *inode = file_inode(vma->vm_file);
7607 struct btrfs_root *root = BTRFS_I(inode)->root;
7608 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7609 struct btrfs_ordered_extent *ordered;
7610 struct extent_state *cached_state = NULL;
7612 unsigned long zero_start;
7619 sb_start_pagefault(inode->i_sb);
7620 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7622 ret = file_update_time(vma->vm_file);
7628 else /* -ENOSPC, -EIO, etc */
7629 ret = VM_FAULT_SIGBUS;
7635 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7638 size = i_size_read(inode);
7639 page_start = page_offset(page);
7640 page_end = page_start + PAGE_CACHE_SIZE - 1;
7642 if ((page->mapping != inode->i_mapping) ||
7643 (page_start >= size)) {
7644 /* page got truncated out from underneath us */
7647 wait_on_page_writeback(page);
7649 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7650 set_page_extent_mapped(page);
7653 * we can't set the delalloc bits if there are pending ordered
7654 * extents. Drop our locks and wait for them to finish
7656 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7658 unlock_extent_cached(io_tree, page_start, page_end,
7659 &cached_state, GFP_NOFS);
7661 btrfs_start_ordered_extent(inode, ordered, 1);
7662 btrfs_put_ordered_extent(ordered);
7667 * XXX - page_mkwrite gets called every time the page is dirtied, even
7668 * if it was already dirty, so for space accounting reasons we need to
7669 * clear any delalloc bits for the range we are fixing to save. There
7670 * is probably a better way to do this, but for now keep consistent with
7671 * prepare_pages in the normal write path.
7673 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7674 EXTENT_DIRTY | EXTENT_DELALLOC |
7675 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7676 0, 0, &cached_state, GFP_NOFS);
7678 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7681 unlock_extent_cached(io_tree, page_start, page_end,
7682 &cached_state, GFP_NOFS);
7683 ret = VM_FAULT_SIGBUS;
7688 /* page is wholly or partially inside EOF */
7689 if (page_start + PAGE_CACHE_SIZE > size)
7690 zero_start = size & ~PAGE_CACHE_MASK;
7692 zero_start = PAGE_CACHE_SIZE;
7694 if (zero_start != PAGE_CACHE_SIZE) {
7696 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7697 flush_dcache_page(page);
7700 ClearPageChecked(page);
7701 set_page_dirty(page);
7702 SetPageUptodate(page);
7704 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7705 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7706 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7708 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7712 sb_end_pagefault(inode->i_sb);
7713 return VM_FAULT_LOCKED;
7717 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7719 sb_end_pagefault(inode->i_sb);
7723 static int btrfs_truncate(struct inode *inode)
7725 struct btrfs_root *root = BTRFS_I(inode)->root;
7726 struct btrfs_block_rsv *rsv;
7729 struct btrfs_trans_handle *trans;
7730 u64 mask = root->sectorsize - 1;
7731 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7733 ret = btrfs_truncate_page(inode, inode->i_size, 0, 0);
7737 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
7738 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
7741 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7742 * 3 things going on here
7744 * 1) We need to reserve space for our orphan item and the space to
7745 * delete our orphan item. Lord knows we don't want to have a dangling
7746 * orphan item because we didn't reserve space to remove it.
7748 * 2) We need to reserve space to update our inode.
7750 * 3) We need to have something to cache all the space that is going to
7751 * be free'd up by the truncate operation, but also have some slack
7752 * space reserved in case it uses space during the truncate (thank you
7753 * very much snapshotting).
7755 * And we need these to all be seperate. The fact is we can use alot of
7756 * space doing the truncate, and we have no earthly idea how much space
7757 * we will use, so we need the truncate reservation to be seperate so it
7758 * doesn't end up using space reserved for updating the inode or
7759 * removing the orphan item. We also need to be able to stop the
7760 * transaction and start a new one, which means we need to be able to
7761 * update the inode several times, and we have no idea of knowing how
7762 * many times that will be, so we can't just reserve 1 item for the
7763 * entirety of the opration, so that has to be done seperately as well.
7764 * Then there is the orphan item, which does indeed need to be held on
7765 * to for the whole operation, and we need nobody to touch this reserved
7766 * space except the orphan code.
7768 * So that leaves us with
7770 * 1) root->orphan_block_rsv - for the orphan deletion.
7771 * 2) rsv - for the truncate reservation, which we will steal from the
7772 * transaction reservation.
7773 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7774 * updating the inode.
7776 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7779 rsv->size = min_size;
7783 * 1 for the truncate slack space
7784 * 1 for updating the inode.
7786 trans = btrfs_start_transaction(root, 2);
7787 if (IS_ERR(trans)) {
7788 err = PTR_ERR(trans);
7792 /* Migrate the slack space for the truncate to our reserve */
7793 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7798 * setattr is responsible for setting the ordered_data_close flag,
7799 * but that is only tested during the last file release. That
7800 * could happen well after the next commit, leaving a great big
7801 * window where new writes may get lost if someone chooses to write
7802 * to this file after truncating to zero
7804 * The inode doesn't have any dirty data here, and so if we commit
7805 * this is a noop. If someone immediately starts writing to the inode
7806 * it is very likely we'll catch some of their writes in this
7807 * transaction, and the commit will find this file on the ordered
7808 * data list with good things to send down.
7810 * This is a best effort solution, there is still a window where
7811 * using truncate to replace the contents of the file will
7812 * end up with a zero length file after a crash.
7814 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7815 &BTRFS_I(inode)->runtime_flags))
7816 btrfs_add_ordered_operation(trans, root, inode);
7819 * So if we truncate and then write and fsync we normally would just
7820 * write the extents that changed, which is a problem if we need to
7821 * first truncate that entire inode. So set this flag so we write out
7822 * all of the extents in the inode to the sync log so we're completely
7825 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7826 trans->block_rsv = rsv;
7829 ret = btrfs_truncate_inode_items(trans, root, inode,
7831 BTRFS_EXTENT_DATA_KEY);
7832 if (ret != -ENOSPC) {
7837 trans->block_rsv = &root->fs_info->trans_block_rsv;
7838 ret = btrfs_update_inode(trans, root, inode);
7844 btrfs_end_transaction(trans, root);
7845 btrfs_btree_balance_dirty(root);
7847 trans = btrfs_start_transaction(root, 2);
7848 if (IS_ERR(trans)) {
7849 ret = err = PTR_ERR(trans);
7854 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7856 BUG_ON(ret); /* shouldn't happen */
7857 trans->block_rsv = rsv;
7860 if (ret == 0 && inode->i_nlink > 0) {
7861 trans->block_rsv = root->orphan_block_rsv;
7862 ret = btrfs_orphan_del(trans, inode);
7868 trans->block_rsv = &root->fs_info->trans_block_rsv;
7869 ret = btrfs_update_inode(trans, root, inode);
7873 ret = btrfs_end_transaction(trans, root);
7874 btrfs_btree_balance_dirty(root);
7878 btrfs_free_block_rsv(root, rsv);
7887 * create a new subvolume directory/inode (helper for the ioctl).
7889 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7890 struct btrfs_root *new_root, u64 new_dirid)
7892 struct inode *inode;
7896 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7897 new_dirid, new_dirid,
7898 S_IFDIR | (~current_umask() & S_IRWXUGO),
7901 return PTR_ERR(inode);
7902 inode->i_op = &btrfs_dir_inode_operations;
7903 inode->i_fop = &btrfs_dir_file_operations;
7905 set_nlink(inode, 1);
7906 btrfs_i_size_write(inode, 0);
7908 err = btrfs_update_inode(trans, new_root, inode);
7914 struct inode *btrfs_alloc_inode(struct super_block *sb)
7916 struct btrfs_inode *ei;
7917 struct inode *inode;
7919 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7926 ei->last_sub_trans = 0;
7927 ei->logged_trans = 0;
7928 ei->delalloc_bytes = 0;
7929 ei->disk_i_size = 0;
7932 ei->index_cnt = (u64)-1;
7933 ei->last_unlink_trans = 0;
7934 ei->last_log_commit = 0;
7936 spin_lock_init(&ei->lock);
7937 ei->outstanding_extents = 0;
7938 ei->reserved_extents = 0;
7940 ei->runtime_flags = 0;
7941 ei->force_compress = BTRFS_COMPRESS_NONE;
7943 ei->delayed_node = NULL;
7945 inode = &ei->vfs_inode;
7946 extent_map_tree_init(&ei->extent_tree);
7947 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7948 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7949 ei->io_tree.track_uptodate = 1;
7950 ei->io_failure_tree.track_uptodate = 1;
7951 atomic_set(&ei->sync_writers, 0);
7952 mutex_init(&ei->log_mutex);
7953 mutex_init(&ei->delalloc_mutex);
7954 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7955 INIT_LIST_HEAD(&ei->delalloc_inodes);
7956 INIT_LIST_HEAD(&ei->ordered_operations);
7957 RB_CLEAR_NODE(&ei->rb_node);
7962 static void btrfs_i_callback(struct rcu_head *head)
7964 struct inode *inode = container_of(head, struct inode, i_rcu);
7965 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7968 void btrfs_destroy_inode(struct inode *inode)
7970 struct btrfs_ordered_extent *ordered;
7971 struct btrfs_root *root = BTRFS_I(inode)->root;
7973 WARN_ON(!hlist_empty(&inode->i_dentry));
7974 WARN_ON(inode->i_data.nrpages);
7975 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7976 WARN_ON(BTRFS_I(inode)->reserved_extents);
7977 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7978 WARN_ON(BTRFS_I(inode)->csum_bytes);
7981 * This can happen where we create an inode, but somebody else also
7982 * created the same inode and we need to destroy the one we already
7989 * Make sure we're properly removed from the ordered operation
7993 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7994 spin_lock(&root->fs_info->ordered_extent_lock);
7995 list_del_init(&BTRFS_I(inode)->ordered_operations);
7996 spin_unlock(&root->fs_info->ordered_extent_lock);
7999 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8000 &BTRFS_I(inode)->runtime_flags)) {
8001 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
8002 (unsigned long long)btrfs_ino(inode));
8003 atomic_dec(&root->orphan_inodes);
8007 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8011 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
8012 (unsigned long long)ordered->file_offset,
8013 (unsigned long long)ordered->len);
8014 btrfs_remove_ordered_extent(inode, ordered);
8015 btrfs_put_ordered_extent(ordered);
8016 btrfs_put_ordered_extent(ordered);
8019 inode_tree_del(inode);
8020 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8022 call_rcu(&inode->i_rcu, btrfs_i_callback);
8025 int btrfs_drop_inode(struct inode *inode)
8027 struct btrfs_root *root = BTRFS_I(inode)->root;
8032 /* the snap/subvol tree is on deleting */
8033 if (btrfs_root_refs(&root->root_item) == 0 &&
8034 root != root->fs_info->tree_root)
8037 return generic_drop_inode(inode);
8040 static void init_once(void *foo)
8042 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8044 inode_init_once(&ei->vfs_inode);
8047 void btrfs_destroy_cachep(void)
8050 * Make sure all delayed rcu free inodes are flushed before we
8054 if (btrfs_inode_cachep)
8055 kmem_cache_destroy(btrfs_inode_cachep);
8056 if (btrfs_trans_handle_cachep)
8057 kmem_cache_destroy(btrfs_trans_handle_cachep);
8058 if (btrfs_transaction_cachep)
8059 kmem_cache_destroy(btrfs_transaction_cachep);
8060 if (btrfs_path_cachep)
8061 kmem_cache_destroy(btrfs_path_cachep);
8062 if (btrfs_free_space_cachep)
8063 kmem_cache_destroy(btrfs_free_space_cachep);
8064 if (btrfs_delalloc_work_cachep)
8065 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8068 int btrfs_init_cachep(void)
8070 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8071 sizeof(struct btrfs_inode), 0,
8072 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8073 if (!btrfs_inode_cachep)
8076 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8077 sizeof(struct btrfs_trans_handle), 0,
8078 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8079 if (!btrfs_trans_handle_cachep)
8082 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8083 sizeof(struct btrfs_transaction), 0,
8084 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8085 if (!btrfs_transaction_cachep)
8088 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8089 sizeof(struct btrfs_path), 0,
8090 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8091 if (!btrfs_path_cachep)
8094 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8095 sizeof(struct btrfs_free_space), 0,
8096 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8097 if (!btrfs_free_space_cachep)
8100 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8101 sizeof(struct btrfs_delalloc_work), 0,
8102 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8104 if (!btrfs_delalloc_work_cachep)
8109 btrfs_destroy_cachep();
8113 static int btrfs_getattr(struct vfsmount *mnt,
8114 struct dentry *dentry, struct kstat *stat)
8117 struct inode *inode = dentry->d_inode;
8118 u32 blocksize = inode->i_sb->s_blocksize;
8120 generic_fillattr(inode, stat);
8121 stat->dev = BTRFS_I(inode)->root->anon_dev;
8122 stat->blksize = PAGE_CACHE_SIZE;
8124 spin_lock(&BTRFS_I(inode)->lock);
8125 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8126 spin_unlock(&BTRFS_I(inode)->lock);
8127 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8128 ALIGN(delalloc_bytes, blocksize)) >> 9;
8132 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8133 struct inode *new_dir, struct dentry *new_dentry)
8135 struct btrfs_trans_handle *trans;
8136 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8137 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8138 struct inode *new_inode = new_dentry->d_inode;
8139 struct inode *old_inode = old_dentry->d_inode;
8140 struct timespec ctime = CURRENT_TIME;
8144 u64 old_ino = btrfs_ino(old_inode);
8146 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8149 /* we only allow rename subvolume link between subvolumes */
8150 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8153 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8154 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8157 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8158 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8162 /* check for collisions, even if the name isn't there */
8163 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8164 new_dentry->d_name.name,
8165 new_dentry->d_name.len);
8168 if (ret == -EEXIST) {
8170 * eexist without a new_inode */
8176 /* maybe -EOVERFLOW */
8183 * we're using rename to replace one file with another.
8184 * and the replacement file is large. Start IO on it now so
8185 * we don't add too much work to the end of the transaction
8187 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8188 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8189 filemap_flush(old_inode->i_mapping);
8191 /* close the racy window with snapshot create/destroy ioctl */
8192 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8193 down_read(&root->fs_info->subvol_sem);
8195 * We want to reserve the absolute worst case amount of items. So if
8196 * both inodes are subvols and we need to unlink them then that would
8197 * require 4 item modifications, but if they are both normal inodes it
8198 * would require 5 item modifications, so we'll assume their normal
8199 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8200 * should cover the worst case number of items we'll modify.
8202 trans = btrfs_start_transaction(root, 11);
8203 if (IS_ERR(trans)) {
8204 ret = PTR_ERR(trans);
8209 btrfs_record_root_in_trans(trans, dest);
8211 ret = btrfs_set_inode_index(new_dir, &index);
8215 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8216 /* force full log commit if subvolume involved. */
8217 root->fs_info->last_trans_log_full_commit = trans->transid;
8219 ret = btrfs_insert_inode_ref(trans, dest,
8220 new_dentry->d_name.name,
8221 new_dentry->d_name.len,
8223 btrfs_ino(new_dir), index);
8227 * this is an ugly little race, but the rename is required
8228 * to make sure that if we crash, the inode is either at the
8229 * old name or the new one. pinning the log transaction lets
8230 * us make sure we don't allow a log commit to come in after
8231 * we unlink the name but before we add the new name back in.
8233 btrfs_pin_log_trans(root);
8236 * make sure the inode gets flushed if it is replacing
8239 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8240 btrfs_add_ordered_operation(trans, root, old_inode);
8242 inode_inc_iversion(old_dir);
8243 inode_inc_iversion(new_dir);
8244 inode_inc_iversion(old_inode);
8245 old_dir->i_ctime = old_dir->i_mtime = ctime;
8246 new_dir->i_ctime = new_dir->i_mtime = ctime;
8247 old_inode->i_ctime = ctime;
8249 if (old_dentry->d_parent != new_dentry->d_parent)
8250 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8252 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8253 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8254 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8255 old_dentry->d_name.name,
8256 old_dentry->d_name.len);
8258 ret = __btrfs_unlink_inode(trans, root, old_dir,
8259 old_dentry->d_inode,
8260 old_dentry->d_name.name,
8261 old_dentry->d_name.len);
8263 ret = btrfs_update_inode(trans, root, old_inode);
8266 btrfs_abort_transaction(trans, root, ret);
8271 inode_inc_iversion(new_inode);
8272 new_inode->i_ctime = CURRENT_TIME;
8273 if (unlikely(btrfs_ino(new_inode) ==
8274 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8275 root_objectid = BTRFS_I(new_inode)->location.objectid;
8276 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8278 new_dentry->d_name.name,
8279 new_dentry->d_name.len);
8280 BUG_ON(new_inode->i_nlink == 0);
8282 ret = btrfs_unlink_inode(trans, dest, new_dir,
8283 new_dentry->d_inode,
8284 new_dentry->d_name.name,
8285 new_dentry->d_name.len);
8287 if (!ret && new_inode->i_nlink == 0) {
8288 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8292 btrfs_abort_transaction(trans, root, ret);
8297 ret = btrfs_add_link(trans, new_dir, old_inode,
8298 new_dentry->d_name.name,
8299 new_dentry->d_name.len, 0, index);
8301 btrfs_abort_transaction(trans, root, ret);
8305 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8306 struct dentry *parent = new_dentry->d_parent;
8307 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8308 btrfs_end_log_trans(root);
8311 btrfs_end_transaction(trans, root);
8313 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8314 up_read(&root->fs_info->subvol_sem);
8319 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8321 struct btrfs_delalloc_work *delalloc_work;
8323 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8325 if (delalloc_work->wait)
8326 btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1);
8328 filemap_flush(delalloc_work->inode->i_mapping);
8330 if (delalloc_work->delay_iput)
8331 btrfs_add_delayed_iput(delalloc_work->inode);
8333 iput(delalloc_work->inode);
8334 complete(&delalloc_work->completion);
8337 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8338 int wait, int delay_iput)
8340 struct btrfs_delalloc_work *work;
8342 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8346 init_completion(&work->completion);
8347 INIT_LIST_HEAD(&work->list);
8348 work->inode = inode;
8350 work->delay_iput = delay_iput;
8351 work->work.func = btrfs_run_delalloc_work;
8356 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8358 wait_for_completion(&work->completion);
8359 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8363 * some fairly slow code that needs optimization. This walks the list
8364 * of all the inodes with pending delalloc and forces them to disk.
8366 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8368 struct btrfs_inode *binode;
8369 struct inode *inode;
8370 struct btrfs_delalloc_work *work, *next;
8371 struct list_head works;
8372 struct list_head splice;
8375 if (root->fs_info->sb->s_flags & MS_RDONLY)
8378 INIT_LIST_HEAD(&works);
8379 INIT_LIST_HEAD(&splice);
8381 spin_lock(&root->fs_info->delalloc_lock);
8382 list_splice_init(&root->fs_info->delalloc_inodes, &splice);
8383 while (!list_empty(&splice)) {
8384 binode = list_entry(splice.next, struct btrfs_inode,
8387 list_del_init(&binode->delalloc_inodes);
8389 inode = igrab(&binode->vfs_inode);
8391 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
8392 &binode->runtime_flags);
8396 list_add_tail(&binode->delalloc_inodes,
8397 &root->fs_info->delalloc_inodes);
8398 spin_unlock(&root->fs_info->delalloc_lock);
8400 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8401 if (unlikely(!work)) {
8405 list_add_tail(&work->list, &works);
8406 btrfs_queue_worker(&root->fs_info->flush_workers,
8410 spin_lock(&root->fs_info->delalloc_lock);
8412 spin_unlock(&root->fs_info->delalloc_lock);
8414 list_for_each_entry_safe(work, next, &works, list) {
8415 list_del_init(&work->list);
8416 btrfs_wait_and_free_delalloc_work(work);
8419 /* the filemap_flush will queue IO into the worker threads, but
8420 * we have to make sure the IO is actually started and that
8421 * ordered extents get created before we return
8423 atomic_inc(&root->fs_info->async_submit_draining);
8424 while (atomic_read(&root->fs_info->nr_async_submits) ||
8425 atomic_read(&root->fs_info->async_delalloc_pages)) {
8426 wait_event(root->fs_info->async_submit_wait,
8427 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8428 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8430 atomic_dec(&root->fs_info->async_submit_draining);
8433 list_for_each_entry_safe(work, next, &works, list) {
8434 list_del_init(&work->list);
8435 btrfs_wait_and_free_delalloc_work(work);
8438 if (!list_empty_careful(&splice)) {
8439 spin_lock(&root->fs_info->delalloc_lock);
8440 list_splice_tail(&splice, &root->fs_info->delalloc_inodes);
8441 spin_unlock(&root->fs_info->delalloc_lock);
8446 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8447 const char *symname)
8449 struct btrfs_trans_handle *trans;
8450 struct btrfs_root *root = BTRFS_I(dir)->root;
8451 struct btrfs_path *path;
8452 struct btrfs_key key;
8453 struct inode *inode = NULL;
8461 struct btrfs_file_extent_item *ei;
8462 struct extent_buffer *leaf;
8464 name_len = strlen(symname) + 1;
8465 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8466 return -ENAMETOOLONG;
8469 * 2 items for inode item and ref
8470 * 2 items for dir items
8471 * 1 item for xattr if selinux is on
8473 trans = btrfs_start_transaction(root, 5);
8475 return PTR_ERR(trans);
8477 err = btrfs_find_free_ino(root, &objectid);
8481 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8482 dentry->d_name.len, btrfs_ino(dir), objectid,
8483 S_IFLNK|S_IRWXUGO, &index);
8484 if (IS_ERR(inode)) {
8485 err = PTR_ERR(inode);
8489 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8496 * If the active LSM wants to access the inode during
8497 * d_instantiate it needs these. Smack checks to see
8498 * if the filesystem supports xattrs by looking at the
8501 inode->i_fop = &btrfs_file_operations;
8502 inode->i_op = &btrfs_file_inode_operations;
8504 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8508 inode->i_mapping->a_ops = &btrfs_aops;
8509 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8510 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8515 path = btrfs_alloc_path();
8521 key.objectid = btrfs_ino(inode);
8523 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8524 datasize = btrfs_file_extent_calc_inline_size(name_len);
8525 err = btrfs_insert_empty_item(trans, root, path, &key,
8529 btrfs_free_path(path);
8532 leaf = path->nodes[0];
8533 ei = btrfs_item_ptr(leaf, path->slots[0],
8534 struct btrfs_file_extent_item);
8535 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8536 btrfs_set_file_extent_type(leaf, ei,
8537 BTRFS_FILE_EXTENT_INLINE);
8538 btrfs_set_file_extent_encryption(leaf, ei, 0);
8539 btrfs_set_file_extent_compression(leaf, ei, 0);
8540 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8541 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8543 ptr = btrfs_file_extent_inline_start(ei);
8544 write_extent_buffer(leaf, symname, ptr, name_len);
8545 btrfs_mark_buffer_dirty(leaf);
8546 btrfs_free_path(path);
8548 inode->i_op = &btrfs_symlink_inode_operations;
8549 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8550 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8551 inode_set_bytes(inode, name_len);
8552 btrfs_i_size_write(inode, name_len - 1);
8553 err = btrfs_update_inode(trans, root, inode);
8559 d_instantiate(dentry, inode);
8560 btrfs_end_transaction(trans, root);
8562 inode_dec_link_count(inode);
8565 btrfs_btree_balance_dirty(root);
8569 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8570 u64 start, u64 num_bytes, u64 min_size,
8571 loff_t actual_len, u64 *alloc_hint,
8572 struct btrfs_trans_handle *trans)
8574 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8575 struct extent_map *em;
8576 struct btrfs_root *root = BTRFS_I(inode)->root;
8577 struct btrfs_key ins;
8578 u64 cur_offset = start;
8582 bool own_trans = true;
8586 while (num_bytes > 0) {
8588 trans = btrfs_start_transaction(root, 3);
8589 if (IS_ERR(trans)) {
8590 ret = PTR_ERR(trans);
8595 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8596 cur_bytes = max(cur_bytes, min_size);
8597 ret = btrfs_reserve_extent(trans, root, cur_bytes,
8598 min_size, 0, *alloc_hint, &ins, 1);
8601 btrfs_end_transaction(trans, root);
8605 ret = insert_reserved_file_extent(trans, inode,
8606 cur_offset, ins.objectid,
8607 ins.offset, ins.offset,
8608 ins.offset, 0, 0, 0,
8609 BTRFS_FILE_EXTENT_PREALLOC);
8611 btrfs_abort_transaction(trans, root, ret);
8613 btrfs_end_transaction(trans, root);
8616 btrfs_drop_extent_cache(inode, cur_offset,
8617 cur_offset + ins.offset -1, 0);
8619 em = alloc_extent_map();
8621 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8622 &BTRFS_I(inode)->runtime_flags);
8626 em->start = cur_offset;
8627 em->orig_start = cur_offset;
8628 em->len = ins.offset;
8629 em->block_start = ins.objectid;
8630 em->block_len = ins.offset;
8631 em->orig_block_len = ins.offset;
8632 em->ram_bytes = ins.offset;
8633 em->bdev = root->fs_info->fs_devices->latest_bdev;
8634 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8635 em->generation = trans->transid;
8638 write_lock(&em_tree->lock);
8639 ret = add_extent_mapping(em_tree, em, 1);
8640 write_unlock(&em_tree->lock);
8643 btrfs_drop_extent_cache(inode, cur_offset,
8644 cur_offset + ins.offset - 1,
8647 free_extent_map(em);
8649 num_bytes -= ins.offset;
8650 cur_offset += ins.offset;
8651 *alloc_hint = ins.objectid + ins.offset;
8653 inode_inc_iversion(inode);
8654 inode->i_ctime = CURRENT_TIME;
8655 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8656 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8657 (actual_len > inode->i_size) &&
8658 (cur_offset > inode->i_size)) {
8659 if (cur_offset > actual_len)
8660 i_size = actual_len;
8662 i_size = cur_offset;
8663 i_size_write(inode, i_size);
8664 btrfs_ordered_update_i_size(inode, i_size, NULL);
8667 ret = btrfs_update_inode(trans, root, inode);
8670 btrfs_abort_transaction(trans, root, ret);
8672 btrfs_end_transaction(trans, root);
8677 btrfs_end_transaction(trans, root);
8682 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8683 u64 start, u64 num_bytes, u64 min_size,
8684 loff_t actual_len, u64 *alloc_hint)
8686 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8687 min_size, actual_len, alloc_hint,
8691 int btrfs_prealloc_file_range_trans(struct inode *inode,
8692 struct btrfs_trans_handle *trans, int mode,
8693 u64 start, u64 num_bytes, u64 min_size,
8694 loff_t actual_len, u64 *alloc_hint)
8696 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8697 min_size, actual_len, alloc_hint, trans);
8700 static int btrfs_set_page_dirty(struct page *page)
8702 return __set_page_dirty_nobuffers(page);
8705 static int btrfs_permission(struct inode *inode, int mask)
8707 struct btrfs_root *root = BTRFS_I(inode)->root;
8708 umode_t mode = inode->i_mode;
8710 if (mask & MAY_WRITE &&
8711 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8712 if (btrfs_root_readonly(root))
8714 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8717 return generic_permission(inode, mask);
8720 static const struct inode_operations btrfs_dir_inode_operations = {
8721 .getattr = btrfs_getattr,
8722 .lookup = btrfs_lookup,
8723 .create = btrfs_create,
8724 .unlink = btrfs_unlink,
8726 .mkdir = btrfs_mkdir,
8727 .rmdir = btrfs_rmdir,
8728 .rename = btrfs_rename,
8729 .symlink = btrfs_symlink,
8730 .setattr = btrfs_setattr,
8731 .mknod = btrfs_mknod,
8732 .setxattr = btrfs_setxattr,
8733 .getxattr = btrfs_getxattr,
8734 .listxattr = btrfs_listxattr,
8735 .removexattr = btrfs_removexattr,
8736 .permission = btrfs_permission,
8737 .get_acl = btrfs_get_acl,
8739 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8740 .lookup = btrfs_lookup,
8741 .permission = btrfs_permission,
8742 .get_acl = btrfs_get_acl,
8745 static const struct file_operations btrfs_dir_file_operations = {
8746 .llseek = generic_file_llseek,
8747 .read = generic_read_dir,
8748 .readdir = btrfs_real_readdir,
8749 .unlocked_ioctl = btrfs_ioctl,
8750 #ifdef CONFIG_COMPAT
8751 .compat_ioctl = btrfs_ioctl,
8753 .release = btrfs_release_file,
8754 .fsync = btrfs_sync_file,
8757 static struct extent_io_ops btrfs_extent_io_ops = {
8758 .fill_delalloc = run_delalloc_range,
8759 .submit_bio_hook = btrfs_submit_bio_hook,
8760 .merge_bio_hook = btrfs_merge_bio_hook,
8761 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8762 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8763 .writepage_start_hook = btrfs_writepage_start_hook,
8764 .set_bit_hook = btrfs_set_bit_hook,
8765 .clear_bit_hook = btrfs_clear_bit_hook,
8766 .merge_extent_hook = btrfs_merge_extent_hook,
8767 .split_extent_hook = btrfs_split_extent_hook,
8771 * btrfs doesn't support the bmap operation because swapfiles
8772 * use bmap to make a mapping of extents in the file. They assume
8773 * these extents won't change over the life of the file and they
8774 * use the bmap result to do IO directly to the drive.
8776 * the btrfs bmap call would return logical addresses that aren't
8777 * suitable for IO and they also will change frequently as COW
8778 * operations happen. So, swapfile + btrfs == corruption.
8780 * For now we're avoiding this by dropping bmap.
8782 static const struct address_space_operations btrfs_aops = {
8783 .readpage = btrfs_readpage,
8784 .writepage = btrfs_writepage,
8785 .writepages = btrfs_writepages,
8786 .readpages = btrfs_readpages,
8787 .direct_IO = btrfs_direct_IO,
8788 .invalidatepage = btrfs_invalidatepage,
8789 .releasepage = btrfs_releasepage,
8790 .set_page_dirty = btrfs_set_page_dirty,
8791 .error_remove_page = generic_error_remove_page,
8794 static const struct address_space_operations btrfs_symlink_aops = {
8795 .readpage = btrfs_readpage,
8796 .writepage = btrfs_writepage,
8797 .invalidatepage = btrfs_invalidatepage,
8798 .releasepage = btrfs_releasepage,
8801 static const struct inode_operations btrfs_file_inode_operations = {
8802 .getattr = btrfs_getattr,
8803 .setattr = btrfs_setattr,
8804 .setxattr = btrfs_setxattr,
8805 .getxattr = btrfs_getxattr,
8806 .listxattr = btrfs_listxattr,
8807 .removexattr = btrfs_removexattr,
8808 .permission = btrfs_permission,
8809 .fiemap = btrfs_fiemap,
8810 .get_acl = btrfs_get_acl,
8811 .update_time = btrfs_update_time,
8813 static const struct inode_operations btrfs_special_inode_operations = {
8814 .getattr = btrfs_getattr,
8815 .setattr = btrfs_setattr,
8816 .permission = btrfs_permission,
8817 .setxattr = btrfs_setxattr,
8818 .getxattr = btrfs_getxattr,
8819 .listxattr = btrfs_listxattr,
8820 .removexattr = btrfs_removexattr,
8821 .get_acl = btrfs_get_acl,
8822 .update_time = btrfs_update_time,
8824 static const struct inode_operations btrfs_symlink_inode_operations = {
8825 .readlink = generic_readlink,
8826 .follow_link = page_follow_link_light,
8827 .put_link = page_put_link,
8828 .getattr = btrfs_getattr,
8829 .setattr = btrfs_setattr,
8830 .permission = btrfs_permission,
8831 .setxattr = btrfs_setxattr,
8832 .getxattr = btrfs_getxattr,
8833 .listxattr = btrfs_listxattr,
8834 .removexattr = btrfs_removexattr,
8835 .get_acl = btrfs_get_acl,
8836 .update_time = btrfs_update_time,
8839 const struct dentry_operations btrfs_dentry_operations = {
8840 .d_delete = btrfs_dentry_delete,
8841 .d_release = btrfs_dentry_release,