2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
43 #include "transaction.h"
44 #include "btrfs_inode.h"
46 #include "print-tree.h"
48 #include "ordered-data.h"
51 #include "compression.h"
53 #include "free-space-cache.h"
55 struct btrfs_iget_args {
57 struct btrfs_root *root;
60 static const struct inode_operations btrfs_dir_inode_operations;
61 static const struct inode_operations btrfs_symlink_inode_operations;
62 static const struct inode_operations btrfs_dir_ro_inode_operations;
63 static const struct inode_operations btrfs_special_inode_operations;
64 static const struct inode_operations btrfs_file_inode_operations;
65 static const struct address_space_operations btrfs_aops;
66 static const struct address_space_operations btrfs_symlink_aops;
67 static const struct file_operations btrfs_dir_file_operations;
68 static struct extent_io_ops btrfs_extent_io_ops;
70 static struct kmem_cache *btrfs_inode_cachep;
71 struct kmem_cache *btrfs_trans_handle_cachep;
72 struct kmem_cache *btrfs_transaction_cachep;
73 struct kmem_cache *btrfs_path_cachep;
74 struct kmem_cache *btrfs_free_space_cachep;
77 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
78 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
79 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
80 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
81 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
82 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
83 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
84 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
87 static int btrfs_setsize(struct inode *inode, loff_t newsize);
88 static int btrfs_truncate(struct inode *inode);
89 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
90 static noinline int cow_file_range(struct inode *inode,
91 struct page *locked_page,
92 u64 start, u64 end, int *page_started,
93 unsigned long *nr_written, int unlock);
95 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
96 struct inode *inode, struct inode *dir)
100 err = btrfs_init_acl(trans, inode, dir);
102 err = btrfs_xattr_security_init(trans, inode, dir);
107 * this does all the hard work for inserting an inline extent into
108 * the btree. The caller should have done a btrfs_drop_extents so that
109 * no overlapping inline items exist in the btree
111 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
112 struct btrfs_root *root, struct inode *inode,
113 u64 start, size_t size, size_t compressed_size,
114 struct page **compressed_pages)
116 struct btrfs_key key;
117 struct btrfs_path *path;
118 struct extent_buffer *leaf;
119 struct page *page = NULL;
122 struct btrfs_file_extent_item *ei;
125 size_t cur_size = size;
127 unsigned long offset;
128 int compress_type = BTRFS_COMPRESS_NONE;
130 if (compressed_size && compressed_pages) {
131 compress_type = root->fs_info->compress_type;
132 cur_size = compressed_size;
135 path = btrfs_alloc_path();
139 path->leave_spinning = 1;
140 btrfs_set_trans_block_group(trans, inode);
142 key.objectid = inode->i_ino;
144 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
145 datasize = btrfs_file_extent_calc_inline_size(cur_size);
147 inode_add_bytes(inode, size);
148 ret = btrfs_insert_empty_item(trans, root, path, &key,
155 leaf = path->nodes[0];
156 ei = btrfs_item_ptr(leaf, path->slots[0],
157 struct btrfs_file_extent_item);
158 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
159 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
160 btrfs_set_file_extent_encryption(leaf, ei, 0);
161 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
162 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
163 ptr = btrfs_file_extent_inline_start(ei);
165 if (compress_type != BTRFS_COMPRESS_NONE) {
168 while (compressed_size > 0) {
169 cpage = compressed_pages[i];
170 cur_size = min_t(unsigned long, compressed_size,
173 kaddr = kmap_atomic(cpage, KM_USER0);
174 write_extent_buffer(leaf, kaddr, ptr, cur_size);
175 kunmap_atomic(kaddr, KM_USER0);
179 compressed_size -= cur_size;
181 btrfs_set_file_extent_compression(leaf, ei,
184 page = find_get_page(inode->i_mapping,
185 start >> PAGE_CACHE_SHIFT);
186 btrfs_set_file_extent_compression(leaf, ei, 0);
187 kaddr = kmap_atomic(page, KM_USER0);
188 offset = start & (PAGE_CACHE_SIZE - 1);
189 write_extent_buffer(leaf, kaddr + offset, ptr, size);
190 kunmap_atomic(kaddr, KM_USER0);
191 page_cache_release(page);
193 btrfs_mark_buffer_dirty(leaf);
194 btrfs_free_path(path);
197 * we're an inline extent, so nobody can
198 * extend the file past i_size without locking
199 * a page we already have locked.
201 * We must do any isize and inode updates
202 * before we unlock the pages. Otherwise we
203 * could end up racing with unlink.
205 BTRFS_I(inode)->disk_i_size = inode->i_size;
206 btrfs_update_inode(trans, root, inode);
210 btrfs_free_path(path);
216 * conditionally insert an inline extent into the file. This
217 * does the checks required to make sure the data is small enough
218 * to fit as an inline extent.
220 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
221 struct btrfs_root *root,
222 struct inode *inode, u64 start, u64 end,
223 size_t compressed_size,
224 struct page **compressed_pages)
226 u64 isize = i_size_read(inode);
227 u64 actual_end = min(end + 1, isize);
228 u64 inline_len = actual_end - start;
229 u64 aligned_end = (end + root->sectorsize - 1) &
230 ~((u64)root->sectorsize - 1);
232 u64 data_len = inline_len;
236 data_len = compressed_size;
239 actual_end >= PAGE_CACHE_SIZE ||
240 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
242 (actual_end & (root->sectorsize - 1)) == 0) ||
244 data_len > root->fs_info->max_inline) {
248 ret = btrfs_drop_extents(trans, inode, start, aligned_end,
252 if (isize > actual_end)
253 inline_len = min_t(u64, isize, actual_end);
254 ret = insert_inline_extent(trans, root, inode, start,
255 inline_len, compressed_size,
258 btrfs_delalloc_release_metadata(inode, end + 1 - start);
259 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
263 struct async_extent {
268 unsigned long nr_pages;
270 struct list_head list;
275 struct btrfs_root *root;
276 struct page *locked_page;
279 struct list_head extents;
280 struct btrfs_work work;
283 static noinline int add_async_extent(struct async_cow *cow,
284 u64 start, u64 ram_size,
287 unsigned long nr_pages,
290 struct async_extent *async_extent;
292 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
293 async_extent->start = start;
294 async_extent->ram_size = ram_size;
295 async_extent->compressed_size = compressed_size;
296 async_extent->pages = pages;
297 async_extent->nr_pages = nr_pages;
298 async_extent->compress_type = compress_type;
299 list_add_tail(&async_extent->list, &cow->extents);
304 * we create compressed extents in two phases. The first
305 * phase compresses a range of pages that have already been
306 * locked (both pages and state bits are locked).
308 * This is done inside an ordered work queue, and the compression
309 * is spread across many cpus. The actual IO submission is step
310 * two, and the ordered work queue takes care of making sure that
311 * happens in the same order things were put onto the queue by
312 * writepages and friends.
314 * If this code finds it can't get good compression, it puts an
315 * entry onto the work queue to write the uncompressed bytes. This
316 * makes sure that both compressed inodes and uncompressed inodes
317 * are written in the same order that pdflush sent them down.
319 static noinline int compress_file_range(struct inode *inode,
320 struct page *locked_page,
322 struct async_cow *async_cow,
325 struct btrfs_root *root = BTRFS_I(inode)->root;
326 struct btrfs_trans_handle *trans;
328 u64 blocksize = root->sectorsize;
330 u64 isize = i_size_read(inode);
332 struct page **pages = NULL;
333 unsigned long nr_pages;
334 unsigned long nr_pages_ret = 0;
335 unsigned long total_compressed = 0;
336 unsigned long total_in = 0;
337 unsigned long max_compressed = 128 * 1024;
338 unsigned long max_uncompressed = 128 * 1024;
341 int compress_type = root->fs_info->compress_type;
343 actual_end = min_t(u64, isize, end + 1);
346 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
347 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
350 * we don't want to send crud past the end of i_size through
351 * compression, that's just a waste of CPU time. So, if the
352 * end of the file is before the start of our current
353 * requested range of bytes, we bail out to the uncompressed
354 * cleanup code that can deal with all of this.
356 * It isn't really the fastest way to fix things, but this is a
357 * very uncommon corner.
359 if (actual_end <= start)
360 goto cleanup_and_bail_uncompressed;
362 total_compressed = actual_end - start;
364 /* we want to make sure that amount of ram required to uncompress
365 * an extent is reasonable, so we limit the total size in ram
366 * of a compressed extent to 128k. This is a crucial number
367 * because it also controls how easily we can spread reads across
368 * cpus for decompression.
370 * We also want to make sure the amount of IO required to do
371 * a random read is reasonably small, so we limit the size of
372 * a compressed extent to 128k.
374 total_compressed = min(total_compressed, max_uncompressed);
375 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
376 num_bytes = max(blocksize, num_bytes);
381 * we do compression for mount -o compress and when the
382 * inode has not been flagged as nocompress. This flag can
383 * change at any time if we discover bad compression ratios.
385 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
386 (btrfs_test_opt(root, COMPRESS) ||
387 (BTRFS_I(inode)->force_compress))) {
389 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
391 if (BTRFS_I(inode)->force_compress)
392 compress_type = BTRFS_I(inode)->force_compress;
394 ret = btrfs_compress_pages(compress_type,
395 inode->i_mapping, start,
396 total_compressed, pages,
397 nr_pages, &nr_pages_ret,
403 unsigned long offset = total_compressed &
404 (PAGE_CACHE_SIZE - 1);
405 struct page *page = pages[nr_pages_ret - 1];
408 /* zero the tail end of the last page, we might be
409 * sending it down to disk
412 kaddr = kmap_atomic(page, KM_USER0);
413 memset(kaddr + offset, 0,
414 PAGE_CACHE_SIZE - offset);
415 kunmap_atomic(kaddr, KM_USER0);
421 trans = btrfs_join_transaction(root, 1);
422 BUG_ON(IS_ERR(trans));
423 btrfs_set_trans_block_group(trans, inode);
424 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
426 /* lets try to make an inline extent */
427 if (ret || total_in < (actual_end - start)) {
428 /* we didn't compress the entire range, try
429 * to make an uncompressed inline extent.
431 ret = cow_file_range_inline(trans, root, inode,
432 start, end, 0, NULL);
434 /* try making a compressed inline extent */
435 ret = cow_file_range_inline(trans, root, inode,
437 total_compressed, pages);
441 * inline extent creation worked, we don't need
442 * to create any more async work items. Unlock
443 * and free up our temp pages.
445 extent_clear_unlock_delalloc(inode,
446 &BTRFS_I(inode)->io_tree,
448 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
449 EXTENT_CLEAR_DELALLOC |
450 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
452 btrfs_end_transaction(trans, root);
455 btrfs_end_transaction(trans, root);
460 * we aren't doing an inline extent round the compressed size
461 * up to a block size boundary so the allocator does sane
464 total_compressed = (total_compressed + blocksize - 1) &
468 * one last check to make sure the compression is really a
469 * win, compare the page count read with the blocks on disk
471 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
472 ~(PAGE_CACHE_SIZE - 1);
473 if (total_compressed >= total_in) {
476 num_bytes = total_in;
479 if (!will_compress && pages) {
481 * the compression code ran but failed to make things smaller,
482 * free any pages it allocated and our page pointer array
484 for (i = 0; i < nr_pages_ret; i++) {
485 WARN_ON(pages[i]->mapping);
486 page_cache_release(pages[i]);
490 total_compressed = 0;
493 /* flag the file so we don't compress in the future */
494 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
495 !(BTRFS_I(inode)->force_compress)) {
496 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
502 /* the async work queues will take care of doing actual
503 * allocation on disk for these compressed pages,
504 * and will submit them to the elevator.
506 add_async_extent(async_cow, start, num_bytes,
507 total_compressed, pages, nr_pages_ret,
510 if (start + num_bytes < end) {
517 cleanup_and_bail_uncompressed:
519 * No compression, but we still need to write the pages in
520 * the file we've been given so far. redirty the locked
521 * page if it corresponds to our extent and set things up
522 * for the async work queue to run cow_file_range to do
523 * the normal delalloc dance
525 if (page_offset(locked_page) >= start &&
526 page_offset(locked_page) <= end) {
527 __set_page_dirty_nobuffers(locked_page);
528 /* unlocked later on in the async handlers */
530 add_async_extent(async_cow, start, end - start + 1,
531 0, NULL, 0, BTRFS_COMPRESS_NONE);
539 for (i = 0; i < nr_pages_ret; i++) {
540 WARN_ON(pages[i]->mapping);
541 page_cache_release(pages[i]);
549 * phase two of compressed writeback. This is the ordered portion
550 * of the code, which only gets called in the order the work was
551 * queued. We walk all the async extents created by compress_file_range
552 * and send them down to the disk.
554 static noinline int submit_compressed_extents(struct inode *inode,
555 struct async_cow *async_cow)
557 struct async_extent *async_extent;
559 struct btrfs_trans_handle *trans;
560 struct btrfs_key ins;
561 struct extent_map *em;
562 struct btrfs_root *root = BTRFS_I(inode)->root;
563 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
564 struct extent_io_tree *io_tree;
567 if (list_empty(&async_cow->extents))
571 while (!list_empty(&async_cow->extents)) {
572 async_extent = list_entry(async_cow->extents.next,
573 struct async_extent, list);
574 list_del(&async_extent->list);
576 io_tree = &BTRFS_I(inode)->io_tree;
579 /* did the compression code fall back to uncompressed IO? */
580 if (!async_extent->pages) {
581 int page_started = 0;
582 unsigned long nr_written = 0;
584 lock_extent(io_tree, async_extent->start,
585 async_extent->start +
586 async_extent->ram_size - 1, GFP_NOFS);
588 /* allocate blocks */
589 ret = cow_file_range(inode, async_cow->locked_page,
591 async_extent->start +
592 async_extent->ram_size - 1,
593 &page_started, &nr_written, 0);
596 * if page_started, cow_file_range inserted an
597 * inline extent and took care of all the unlocking
598 * and IO for us. Otherwise, we need to submit
599 * all those pages down to the drive.
601 if (!page_started && !ret)
602 extent_write_locked_range(io_tree,
603 inode, async_extent->start,
604 async_extent->start +
605 async_extent->ram_size - 1,
613 lock_extent(io_tree, async_extent->start,
614 async_extent->start + async_extent->ram_size - 1,
617 trans = btrfs_join_transaction(root, 1);
618 BUG_ON(IS_ERR(trans));
619 ret = btrfs_reserve_extent(trans, root,
620 async_extent->compressed_size,
621 async_extent->compressed_size,
624 btrfs_end_transaction(trans, root);
628 for (i = 0; i < async_extent->nr_pages; i++) {
629 WARN_ON(async_extent->pages[i]->mapping);
630 page_cache_release(async_extent->pages[i]);
632 kfree(async_extent->pages);
633 async_extent->nr_pages = 0;
634 async_extent->pages = NULL;
635 unlock_extent(io_tree, async_extent->start,
636 async_extent->start +
637 async_extent->ram_size - 1, GFP_NOFS);
642 * here we're doing allocation and writeback of the
645 btrfs_drop_extent_cache(inode, async_extent->start,
646 async_extent->start +
647 async_extent->ram_size - 1, 0);
649 em = alloc_extent_map(GFP_NOFS);
651 em->start = async_extent->start;
652 em->len = async_extent->ram_size;
653 em->orig_start = em->start;
655 em->block_start = ins.objectid;
656 em->block_len = ins.offset;
657 em->bdev = root->fs_info->fs_devices->latest_bdev;
658 em->compress_type = async_extent->compress_type;
659 set_bit(EXTENT_FLAG_PINNED, &em->flags);
660 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
663 write_lock(&em_tree->lock);
664 ret = add_extent_mapping(em_tree, em);
665 write_unlock(&em_tree->lock);
666 if (ret != -EEXIST) {
670 btrfs_drop_extent_cache(inode, async_extent->start,
671 async_extent->start +
672 async_extent->ram_size - 1, 0);
675 ret = btrfs_add_ordered_extent_compress(inode,
678 async_extent->ram_size,
680 BTRFS_ORDERED_COMPRESSED,
681 async_extent->compress_type);
685 * clear dirty, set writeback and unlock the pages.
687 extent_clear_unlock_delalloc(inode,
688 &BTRFS_I(inode)->io_tree,
690 async_extent->start +
691 async_extent->ram_size - 1,
692 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
693 EXTENT_CLEAR_UNLOCK |
694 EXTENT_CLEAR_DELALLOC |
695 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
697 ret = btrfs_submit_compressed_write(inode,
699 async_extent->ram_size,
701 ins.offset, async_extent->pages,
702 async_extent->nr_pages);
705 alloc_hint = ins.objectid + ins.offset;
713 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
716 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
717 struct extent_map *em;
720 read_lock(&em_tree->lock);
721 em = search_extent_mapping(em_tree, start, num_bytes);
724 * if block start isn't an actual block number then find the
725 * first block in this inode and use that as a hint. If that
726 * block is also bogus then just don't worry about it.
728 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
730 em = search_extent_mapping(em_tree, 0, 0);
731 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
732 alloc_hint = em->block_start;
736 alloc_hint = em->block_start;
740 read_unlock(&em_tree->lock);
746 * when extent_io.c finds a delayed allocation range in the file,
747 * the call backs end up in this code. The basic idea is to
748 * allocate extents on disk for the range, and create ordered data structs
749 * in ram to track those extents.
751 * locked_page is the page that writepage had locked already. We use
752 * it to make sure we don't do extra locks or unlocks.
754 * *page_started is set to one if we unlock locked_page and do everything
755 * required to start IO on it. It may be clean and already done with
758 static noinline int cow_file_range(struct inode *inode,
759 struct page *locked_page,
760 u64 start, u64 end, int *page_started,
761 unsigned long *nr_written,
764 struct btrfs_root *root = BTRFS_I(inode)->root;
765 struct btrfs_trans_handle *trans;
768 unsigned long ram_size;
771 u64 blocksize = root->sectorsize;
772 struct btrfs_key ins;
773 struct extent_map *em;
774 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
777 BUG_ON(root == root->fs_info->tree_root);
778 trans = btrfs_join_transaction(root, 1);
779 BUG_ON(IS_ERR(trans));
780 btrfs_set_trans_block_group(trans, inode);
781 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
783 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
784 num_bytes = max(blocksize, num_bytes);
785 disk_num_bytes = num_bytes;
789 /* lets try to make an inline extent */
790 ret = cow_file_range_inline(trans, root, inode,
791 start, end, 0, NULL);
793 extent_clear_unlock_delalloc(inode,
794 &BTRFS_I(inode)->io_tree,
796 EXTENT_CLEAR_UNLOCK_PAGE |
797 EXTENT_CLEAR_UNLOCK |
798 EXTENT_CLEAR_DELALLOC |
800 EXTENT_SET_WRITEBACK |
801 EXTENT_END_WRITEBACK);
803 *nr_written = *nr_written +
804 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
811 BUG_ON(disk_num_bytes >
812 btrfs_super_total_bytes(&root->fs_info->super_copy));
814 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
815 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
817 while (disk_num_bytes > 0) {
820 cur_alloc_size = disk_num_bytes;
821 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
822 root->sectorsize, 0, alloc_hint,
826 em = alloc_extent_map(GFP_NOFS);
829 em->orig_start = em->start;
830 ram_size = ins.offset;
831 em->len = ins.offset;
833 em->block_start = ins.objectid;
834 em->block_len = ins.offset;
835 em->bdev = root->fs_info->fs_devices->latest_bdev;
836 set_bit(EXTENT_FLAG_PINNED, &em->flags);
839 write_lock(&em_tree->lock);
840 ret = add_extent_mapping(em_tree, em);
841 write_unlock(&em_tree->lock);
842 if (ret != -EEXIST) {
846 btrfs_drop_extent_cache(inode, start,
847 start + ram_size - 1, 0);
850 cur_alloc_size = ins.offset;
851 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
852 ram_size, cur_alloc_size, 0);
855 if (root->root_key.objectid ==
856 BTRFS_DATA_RELOC_TREE_OBJECTID) {
857 ret = btrfs_reloc_clone_csums(inode, start,
862 if (disk_num_bytes < cur_alloc_size)
865 /* we're not doing compressed IO, don't unlock the first
866 * page (which the caller expects to stay locked), don't
867 * clear any dirty bits and don't set any writeback bits
869 * Do set the Private2 bit so we know this page was properly
870 * setup for writepage
872 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
873 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
876 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
877 start, start + ram_size - 1,
879 disk_num_bytes -= cur_alloc_size;
880 num_bytes -= cur_alloc_size;
881 alloc_hint = ins.objectid + ins.offset;
882 start += cur_alloc_size;
886 btrfs_end_transaction(trans, root);
892 * work queue call back to started compression on a file and pages
894 static noinline void async_cow_start(struct btrfs_work *work)
896 struct async_cow *async_cow;
898 async_cow = container_of(work, struct async_cow, work);
900 compress_file_range(async_cow->inode, async_cow->locked_page,
901 async_cow->start, async_cow->end, async_cow,
904 async_cow->inode = NULL;
908 * work queue call back to submit previously compressed pages
910 static noinline void async_cow_submit(struct btrfs_work *work)
912 struct async_cow *async_cow;
913 struct btrfs_root *root;
914 unsigned long nr_pages;
916 async_cow = container_of(work, struct async_cow, work);
918 root = async_cow->root;
919 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
922 atomic_sub(nr_pages, &root->fs_info->async_delalloc_pages);
924 if (atomic_read(&root->fs_info->async_delalloc_pages) <
926 waitqueue_active(&root->fs_info->async_submit_wait))
927 wake_up(&root->fs_info->async_submit_wait);
929 if (async_cow->inode)
930 submit_compressed_extents(async_cow->inode, async_cow);
933 static noinline void async_cow_free(struct btrfs_work *work)
935 struct async_cow *async_cow;
936 async_cow = container_of(work, struct async_cow, work);
940 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
941 u64 start, u64 end, int *page_started,
942 unsigned long *nr_written)
944 struct async_cow *async_cow;
945 struct btrfs_root *root = BTRFS_I(inode)->root;
946 unsigned long nr_pages;
948 int limit = 10 * 1024 * 1042;
950 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
951 1, 0, NULL, GFP_NOFS);
952 while (start < end) {
953 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
954 async_cow->inode = inode;
955 async_cow->root = root;
956 async_cow->locked_page = locked_page;
957 async_cow->start = start;
959 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
962 cur_end = min(end, start + 512 * 1024 - 1);
964 async_cow->end = cur_end;
965 INIT_LIST_HEAD(&async_cow->extents);
967 async_cow->work.func = async_cow_start;
968 async_cow->work.ordered_func = async_cow_submit;
969 async_cow->work.ordered_free = async_cow_free;
970 async_cow->work.flags = 0;
972 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
974 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
976 btrfs_queue_worker(&root->fs_info->delalloc_workers,
979 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
980 wait_event(root->fs_info->async_submit_wait,
981 (atomic_read(&root->fs_info->async_delalloc_pages) <
985 while (atomic_read(&root->fs_info->async_submit_draining) &&
986 atomic_read(&root->fs_info->async_delalloc_pages)) {
987 wait_event(root->fs_info->async_submit_wait,
988 (atomic_read(&root->fs_info->async_delalloc_pages) ==
992 *nr_written += nr_pages;
999 static noinline int csum_exist_in_range(struct btrfs_root *root,
1000 u64 bytenr, u64 num_bytes)
1003 struct btrfs_ordered_sum *sums;
1006 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1007 bytenr + num_bytes - 1, &list);
1008 if (ret == 0 && list_empty(&list))
1011 while (!list_empty(&list)) {
1012 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1013 list_del(&sums->list);
1020 * when nowcow writeback call back. This checks for snapshots or COW copies
1021 * of the extents that exist in the file, and COWs the file as required.
1023 * If no cow copies or snapshots exist, we write directly to the existing
1026 static noinline int run_delalloc_nocow(struct inode *inode,
1027 struct page *locked_page,
1028 u64 start, u64 end, int *page_started, int force,
1029 unsigned long *nr_written)
1031 struct btrfs_root *root = BTRFS_I(inode)->root;
1032 struct btrfs_trans_handle *trans;
1033 struct extent_buffer *leaf;
1034 struct btrfs_path *path;
1035 struct btrfs_file_extent_item *fi;
1036 struct btrfs_key found_key;
1048 bool nolock = false;
1050 path = btrfs_alloc_path();
1052 if (root == root->fs_info->tree_root) {
1054 trans = btrfs_join_transaction_nolock(root, 1);
1056 trans = btrfs_join_transaction(root, 1);
1058 BUG_ON(IS_ERR(trans));
1060 cow_start = (u64)-1;
1063 ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
1066 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1067 leaf = path->nodes[0];
1068 btrfs_item_key_to_cpu(leaf, &found_key,
1069 path->slots[0] - 1);
1070 if (found_key.objectid == inode->i_ino &&
1071 found_key.type == BTRFS_EXTENT_DATA_KEY)
1076 leaf = path->nodes[0];
1077 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1078 ret = btrfs_next_leaf(root, path);
1083 leaf = path->nodes[0];
1089 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1091 if (found_key.objectid > inode->i_ino ||
1092 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1093 found_key.offset > end)
1096 if (found_key.offset > cur_offset) {
1097 extent_end = found_key.offset;
1102 fi = btrfs_item_ptr(leaf, path->slots[0],
1103 struct btrfs_file_extent_item);
1104 extent_type = btrfs_file_extent_type(leaf, fi);
1106 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1107 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1108 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1109 extent_offset = btrfs_file_extent_offset(leaf, fi);
1110 extent_end = found_key.offset +
1111 btrfs_file_extent_num_bytes(leaf, fi);
1112 if (extent_end <= start) {
1116 if (disk_bytenr == 0)
1118 if (btrfs_file_extent_compression(leaf, fi) ||
1119 btrfs_file_extent_encryption(leaf, fi) ||
1120 btrfs_file_extent_other_encoding(leaf, fi))
1122 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1124 if (btrfs_extent_readonly(root, disk_bytenr))
1126 if (btrfs_cross_ref_exist(trans, root, inode->i_ino,
1128 extent_offset, disk_bytenr))
1130 disk_bytenr += extent_offset;
1131 disk_bytenr += cur_offset - found_key.offset;
1132 num_bytes = min(end + 1, extent_end) - cur_offset;
1134 * force cow if csum exists in the range.
1135 * this ensure that csum for a given extent are
1136 * either valid or do not exist.
1138 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1141 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1142 extent_end = found_key.offset +
1143 btrfs_file_extent_inline_len(leaf, fi);
1144 extent_end = ALIGN(extent_end, root->sectorsize);
1149 if (extent_end <= start) {
1154 if (cow_start == (u64)-1)
1155 cow_start = cur_offset;
1156 cur_offset = extent_end;
1157 if (cur_offset > end)
1163 btrfs_release_path(root, path);
1164 if (cow_start != (u64)-1) {
1165 ret = cow_file_range(inode, locked_page, cow_start,
1166 found_key.offset - 1, page_started,
1169 cow_start = (u64)-1;
1172 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1173 struct extent_map *em;
1174 struct extent_map_tree *em_tree;
1175 em_tree = &BTRFS_I(inode)->extent_tree;
1176 em = alloc_extent_map(GFP_NOFS);
1178 em->start = cur_offset;
1179 em->orig_start = em->start;
1180 em->len = num_bytes;
1181 em->block_len = num_bytes;
1182 em->block_start = disk_bytenr;
1183 em->bdev = root->fs_info->fs_devices->latest_bdev;
1184 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1186 write_lock(&em_tree->lock);
1187 ret = add_extent_mapping(em_tree, em);
1188 write_unlock(&em_tree->lock);
1189 if (ret != -EEXIST) {
1190 free_extent_map(em);
1193 btrfs_drop_extent_cache(inode, em->start,
1194 em->start + em->len - 1, 0);
1196 type = BTRFS_ORDERED_PREALLOC;
1198 type = BTRFS_ORDERED_NOCOW;
1201 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1202 num_bytes, num_bytes, type);
1205 if (root->root_key.objectid ==
1206 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1207 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1212 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1213 cur_offset, cur_offset + num_bytes - 1,
1214 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1215 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1216 EXTENT_SET_PRIVATE2);
1217 cur_offset = extent_end;
1218 if (cur_offset > end)
1221 btrfs_release_path(root, path);
1223 if (cur_offset <= end && cow_start == (u64)-1)
1224 cow_start = cur_offset;
1225 if (cow_start != (u64)-1) {
1226 ret = cow_file_range(inode, locked_page, cow_start, end,
1227 page_started, nr_written, 1);
1232 ret = btrfs_end_transaction_nolock(trans, root);
1235 ret = btrfs_end_transaction(trans, root);
1238 btrfs_free_path(path);
1243 * extent_io.c call back to do delayed allocation processing
1245 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1246 u64 start, u64 end, int *page_started,
1247 unsigned long *nr_written)
1250 struct btrfs_root *root = BTRFS_I(inode)->root;
1252 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)
1253 ret = run_delalloc_nocow(inode, locked_page, start, end,
1254 page_started, 1, nr_written);
1255 else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)
1256 ret = run_delalloc_nocow(inode, locked_page, start, end,
1257 page_started, 0, nr_written);
1258 else if (!btrfs_test_opt(root, COMPRESS) &&
1259 !(BTRFS_I(inode)->force_compress))
1260 ret = cow_file_range(inode, locked_page, start, end,
1261 page_started, nr_written, 1);
1263 ret = cow_file_range_async(inode, locked_page, start, end,
1264 page_started, nr_written);
1268 static int btrfs_split_extent_hook(struct inode *inode,
1269 struct extent_state *orig, u64 split)
1271 /* not delalloc, ignore it */
1272 if (!(orig->state & EXTENT_DELALLOC))
1275 atomic_inc(&BTRFS_I(inode)->outstanding_extents);
1280 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1281 * extents so we can keep track of new extents that are just merged onto old
1282 * extents, such as when we are doing sequential writes, so we can properly
1283 * account for the metadata space we'll need.
1285 static int btrfs_merge_extent_hook(struct inode *inode,
1286 struct extent_state *new,
1287 struct extent_state *other)
1289 /* not delalloc, ignore it */
1290 if (!(other->state & EXTENT_DELALLOC))
1293 atomic_dec(&BTRFS_I(inode)->outstanding_extents);
1298 * extent_io.c set_bit_hook, used to track delayed allocation
1299 * bytes in this file, and to maintain the list of inodes that
1300 * have pending delalloc work to be done.
1302 static int btrfs_set_bit_hook(struct inode *inode,
1303 struct extent_state *state, int *bits)
1307 * set_bit and clear bit hooks normally require _irqsave/restore
1308 * but in this case, we are only testeing for the DELALLOC
1309 * bit, which is only set or cleared with irqs on
1311 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1312 struct btrfs_root *root = BTRFS_I(inode)->root;
1313 u64 len = state->end + 1 - state->start;
1314 int do_list = (root->root_key.objectid !=
1315 BTRFS_ROOT_TREE_OBJECTID);
1317 if (*bits & EXTENT_FIRST_DELALLOC)
1318 *bits &= ~EXTENT_FIRST_DELALLOC;
1320 atomic_inc(&BTRFS_I(inode)->outstanding_extents);
1322 spin_lock(&root->fs_info->delalloc_lock);
1323 BTRFS_I(inode)->delalloc_bytes += len;
1324 root->fs_info->delalloc_bytes += len;
1325 if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1326 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1327 &root->fs_info->delalloc_inodes);
1329 spin_unlock(&root->fs_info->delalloc_lock);
1335 * extent_io.c clear_bit_hook, see set_bit_hook for why
1337 static int btrfs_clear_bit_hook(struct inode *inode,
1338 struct extent_state *state, int *bits)
1341 * set_bit and clear bit hooks normally require _irqsave/restore
1342 * but in this case, we are only testeing for the DELALLOC
1343 * bit, which is only set or cleared with irqs on
1345 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1346 struct btrfs_root *root = BTRFS_I(inode)->root;
1347 u64 len = state->end + 1 - state->start;
1348 int do_list = (root->root_key.objectid !=
1349 BTRFS_ROOT_TREE_OBJECTID);
1351 if (*bits & EXTENT_FIRST_DELALLOC)
1352 *bits &= ~EXTENT_FIRST_DELALLOC;
1353 else if (!(*bits & EXTENT_DO_ACCOUNTING))
1354 atomic_dec(&BTRFS_I(inode)->outstanding_extents);
1356 if (*bits & EXTENT_DO_ACCOUNTING)
1357 btrfs_delalloc_release_metadata(inode, len);
1359 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1361 btrfs_free_reserved_data_space(inode, len);
1363 spin_lock(&root->fs_info->delalloc_lock);
1364 root->fs_info->delalloc_bytes -= len;
1365 BTRFS_I(inode)->delalloc_bytes -= len;
1367 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1368 !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1369 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1371 spin_unlock(&root->fs_info->delalloc_lock);
1377 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1378 * we don't create bios that span stripes or chunks
1380 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1381 size_t size, struct bio *bio,
1382 unsigned long bio_flags)
1384 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1385 struct btrfs_mapping_tree *map_tree;
1386 u64 logical = (u64)bio->bi_sector << 9;
1391 if (bio_flags & EXTENT_BIO_COMPRESSED)
1394 length = bio->bi_size;
1395 map_tree = &root->fs_info->mapping_tree;
1396 map_length = length;
1397 ret = btrfs_map_block(map_tree, READ, logical,
1398 &map_length, NULL, 0);
1400 if (map_length < length + size)
1406 * in order to insert checksums into the metadata in large chunks,
1407 * we wait until bio submission time. All the pages in the bio are
1408 * checksummed and sums are attached onto the ordered extent record.
1410 * At IO completion time the cums attached on the ordered extent record
1411 * are inserted into the btree
1413 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1414 struct bio *bio, int mirror_num,
1415 unsigned long bio_flags,
1418 struct btrfs_root *root = BTRFS_I(inode)->root;
1421 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1427 * in order to insert checksums into the metadata in large chunks,
1428 * we wait until bio submission time. All the pages in the bio are
1429 * checksummed and sums are attached onto the ordered extent record.
1431 * At IO completion time the cums attached on the ordered extent record
1432 * are inserted into the btree
1434 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1435 int mirror_num, unsigned long bio_flags,
1438 struct btrfs_root *root = BTRFS_I(inode)->root;
1439 return btrfs_map_bio(root, rw, bio, mirror_num, 1);
1443 * extent_io.c submission hook. This does the right thing for csum calculation
1444 * on write, or reading the csums from the tree before a read
1446 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1447 int mirror_num, unsigned long bio_flags,
1450 struct btrfs_root *root = BTRFS_I(inode)->root;
1454 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1456 if (root == root->fs_info->tree_root)
1457 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 2);
1459 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
1462 if (!(rw & REQ_WRITE)) {
1463 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1464 return btrfs_submit_compressed_read(inode, bio,
1465 mirror_num, bio_flags);
1466 } else if (!skip_sum)
1467 btrfs_lookup_bio_sums(root, inode, bio, NULL);
1469 } else if (!skip_sum) {
1470 /* csum items have already been cloned */
1471 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1473 /* we're doing a write, do the async checksumming */
1474 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1475 inode, rw, bio, mirror_num,
1476 bio_flags, bio_offset,
1477 __btrfs_submit_bio_start,
1478 __btrfs_submit_bio_done);
1482 return btrfs_map_bio(root, rw, bio, mirror_num, 0);
1486 * given a list of ordered sums record them in the inode. This happens
1487 * at IO completion time based on sums calculated at bio submission time.
1489 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1490 struct inode *inode, u64 file_offset,
1491 struct list_head *list)
1493 struct btrfs_ordered_sum *sum;
1495 btrfs_set_trans_block_group(trans, inode);
1497 list_for_each_entry(sum, list, list) {
1498 btrfs_csum_file_blocks(trans,
1499 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1504 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1505 struct extent_state **cached_state)
1507 if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
1509 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1510 cached_state, GFP_NOFS);
1513 /* see btrfs_writepage_start_hook for details on why this is required */
1514 struct btrfs_writepage_fixup {
1516 struct btrfs_work work;
1519 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1521 struct btrfs_writepage_fixup *fixup;
1522 struct btrfs_ordered_extent *ordered;
1523 struct extent_state *cached_state = NULL;
1525 struct inode *inode;
1529 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1533 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1534 ClearPageChecked(page);
1538 inode = page->mapping->host;
1539 page_start = page_offset(page);
1540 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1542 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1543 &cached_state, GFP_NOFS);
1545 /* already ordered? We're done */
1546 if (PagePrivate2(page))
1549 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1551 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1552 page_end, &cached_state, GFP_NOFS);
1554 btrfs_start_ordered_extent(inode, ordered, 1);
1559 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1560 ClearPageChecked(page);
1562 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1563 &cached_state, GFP_NOFS);
1566 page_cache_release(page);
1571 * There are a few paths in the higher layers of the kernel that directly
1572 * set the page dirty bit without asking the filesystem if it is a
1573 * good idea. This causes problems because we want to make sure COW
1574 * properly happens and the data=ordered rules are followed.
1576 * In our case any range that doesn't have the ORDERED bit set
1577 * hasn't been properly setup for IO. We kick off an async process
1578 * to fix it up. The async helper will wait for ordered extents, set
1579 * the delalloc bit and make it safe to write the page.
1581 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1583 struct inode *inode = page->mapping->host;
1584 struct btrfs_writepage_fixup *fixup;
1585 struct btrfs_root *root = BTRFS_I(inode)->root;
1587 /* this page is properly in the ordered list */
1588 if (TestClearPagePrivate2(page))
1591 if (PageChecked(page))
1594 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1598 SetPageChecked(page);
1599 page_cache_get(page);
1600 fixup->work.func = btrfs_writepage_fixup_worker;
1602 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1606 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1607 struct inode *inode, u64 file_pos,
1608 u64 disk_bytenr, u64 disk_num_bytes,
1609 u64 num_bytes, u64 ram_bytes,
1610 u8 compression, u8 encryption,
1611 u16 other_encoding, int extent_type)
1613 struct btrfs_root *root = BTRFS_I(inode)->root;
1614 struct btrfs_file_extent_item *fi;
1615 struct btrfs_path *path;
1616 struct extent_buffer *leaf;
1617 struct btrfs_key ins;
1621 path = btrfs_alloc_path();
1624 path->leave_spinning = 1;
1627 * we may be replacing one extent in the tree with another.
1628 * The new extent is pinned in the extent map, and we don't want
1629 * to drop it from the cache until it is completely in the btree.
1631 * So, tell btrfs_drop_extents to leave this extent in the cache.
1632 * the caller is expected to unpin it and allow it to be merged
1635 ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
1639 ins.objectid = inode->i_ino;
1640 ins.offset = file_pos;
1641 ins.type = BTRFS_EXTENT_DATA_KEY;
1642 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1644 leaf = path->nodes[0];
1645 fi = btrfs_item_ptr(leaf, path->slots[0],
1646 struct btrfs_file_extent_item);
1647 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1648 btrfs_set_file_extent_type(leaf, fi, extent_type);
1649 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1650 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1651 btrfs_set_file_extent_offset(leaf, fi, 0);
1652 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1653 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1654 btrfs_set_file_extent_compression(leaf, fi, compression);
1655 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1656 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1658 btrfs_unlock_up_safe(path, 1);
1659 btrfs_set_lock_blocking(leaf);
1661 btrfs_mark_buffer_dirty(leaf);
1663 inode_add_bytes(inode, num_bytes);
1665 ins.objectid = disk_bytenr;
1666 ins.offset = disk_num_bytes;
1667 ins.type = BTRFS_EXTENT_ITEM_KEY;
1668 ret = btrfs_alloc_reserved_file_extent(trans, root,
1669 root->root_key.objectid,
1670 inode->i_ino, file_pos, &ins);
1672 btrfs_free_path(path);
1678 * helper function for btrfs_finish_ordered_io, this
1679 * just reads in some of the csum leaves to prime them into ram
1680 * before we start the transaction. It limits the amount of btree
1681 * reads required while inside the transaction.
1683 /* as ordered data IO finishes, this gets called so we can finish
1684 * an ordered extent if the range of bytes in the file it covers are
1687 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
1689 struct btrfs_root *root = BTRFS_I(inode)->root;
1690 struct btrfs_trans_handle *trans = NULL;
1691 struct btrfs_ordered_extent *ordered_extent = NULL;
1692 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1693 struct extent_state *cached_state = NULL;
1694 int compress_type = 0;
1696 bool nolock = false;
1698 ret = btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
1702 BUG_ON(!ordered_extent);
1704 nolock = (root == root->fs_info->tree_root);
1706 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1707 BUG_ON(!list_empty(&ordered_extent->list));
1708 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1711 trans = btrfs_join_transaction_nolock(root, 1);
1713 trans = btrfs_join_transaction(root, 1);
1714 BUG_ON(IS_ERR(trans));
1715 btrfs_set_trans_block_group(trans, inode);
1716 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1717 ret = btrfs_update_inode(trans, root, inode);
1723 lock_extent_bits(io_tree, ordered_extent->file_offset,
1724 ordered_extent->file_offset + ordered_extent->len - 1,
1725 0, &cached_state, GFP_NOFS);
1728 trans = btrfs_join_transaction_nolock(root, 1);
1730 trans = btrfs_join_transaction(root, 1);
1731 BUG_ON(IS_ERR(trans));
1732 btrfs_set_trans_block_group(trans, inode);
1733 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1735 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1736 compress_type = ordered_extent->compress_type;
1737 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1738 BUG_ON(compress_type);
1739 ret = btrfs_mark_extent_written(trans, inode,
1740 ordered_extent->file_offset,
1741 ordered_extent->file_offset +
1742 ordered_extent->len);
1745 BUG_ON(root == root->fs_info->tree_root);
1746 ret = insert_reserved_file_extent(trans, inode,
1747 ordered_extent->file_offset,
1748 ordered_extent->start,
1749 ordered_extent->disk_len,
1750 ordered_extent->len,
1751 ordered_extent->len,
1752 compress_type, 0, 0,
1753 BTRFS_FILE_EXTENT_REG);
1754 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1755 ordered_extent->file_offset,
1756 ordered_extent->len);
1759 unlock_extent_cached(io_tree, ordered_extent->file_offset,
1760 ordered_extent->file_offset +
1761 ordered_extent->len - 1, &cached_state, GFP_NOFS);
1763 add_pending_csums(trans, inode, ordered_extent->file_offset,
1764 &ordered_extent->list);
1766 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1767 ret = btrfs_update_inode(trans, root, inode);
1772 btrfs_end_transaction_nolock(trans, root);
1774 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
1776 btrfs_end_transaction(trans, root);
1780 btrfs_put_ordered_extent(ordered_extent);
1781 /* once for the tree */
1782 btrfs_put_ordered_extent(ordered_extent);
1787 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
1788 struct extent_state *state, int uptodate)
1790 ClearPagePrivate2(page);
1791 return btrfs_finish_ordered_io(page->mapping->host, start, end);
1795 * When IO fails, either with EIO or csum verification fails, we
1796 * try other mirrors that might have a good copy of the data. This
1797 * io_failure_record is used to record state as we go through all the
1798 * mirrors. If another mirror has good data, the page is set up to date
1799 * and things continue. If a good mirror can't be found, the original
1800 * bio end_io callback is called to indicate things have failed.
1802 struct io_failure_record {
1807 unsigned long bio_flags;
1811 static int btrfs_io_failed_hook(struct bio *failed_bio,
1812 struct page *page, u64 start, u64 end,
1813 struct extent_state *state)
1815 struct io_failure_record *failrec = NULL;
1817 struct extent_map *em;
1818 struct inode *inode = page->mapping->host;
1819 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
1820 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1827 ret = get_state_private(failure_tree, start, &private);
1829 failrec = kmalloc(sizeof(*failrec), GFP_NOFS);
1832 failrec->start = start;
1833 failrec->len = end - start + 1;
1834 failrec->last_mirror = 0;
1835 failrec->bio_flags = 0;
1837 read_lock(&em_tree->lock);
1838 em = lookup_extent_mapping(em_tree, start, failrec->len);
1839 if (em->start > start || em->start + em->len < start) {
1840 free_extent_map(em);
1843 read_unlock(&em_tree->lock);
1845 if (!em || IS_ERR(em)) {
1849 logical = start - em->start;
1850 logical = em->block_start + logical;
1851 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
1852 logical = em->block_start;
1853 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
1854 extent_set_compress_type(&failrec->bio_flags,
1857 failrec->logical = logical;
1858 free_extent_map(em);
1859 set_extent_bits(failure_tree, start, end, EXTENT_LOCKED |
1860 EXTENT_DIRTY, GFP_NOFS);
1861 set_state_private(failure_tree, start,
1862 (u64)(unsigned long)failrec);
1864 failrec = (struct io_failure_record *)(unsigned long)private;
1866 num_copies = btrfs_num_copies(
1867 &BTRFS_I(inode)->root->fs_info->mapping_tree,
1868 failrec->logical, failrec->len);
1869 failrec->last_mirror++;
1871 spin_lock(&BTRFS_I(inode)->io_tree.lock);
1872 state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
1875 if (state && state->start != failrec->start)
1877 spin_unlock(&BTRFS_I(inode)->io_tree.lock);
1879 if (!state || failrec->last_mirror > num_copies) {
1880 set_state_private(failure_tree, failrec->start, 0);
1881 clear_extent_bits(failure_tree, failrec->start,
1882 failrec->start + failrec->len - 1,
1883 EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
1887 bio = bio_alloc(GFP_NOFS, 1);
1888 bio->bi_private = state;
1889 bio->bi_end_io = failed_bio->bi_end_io;
1890 bio->bi_sector = failrec->logical >> 9;
1891 bio->bi_bdev = failed_bio->bi_bdev;
1894 bio_add_page(bio, page, failrec->len, start - page_offset(page));
1895 if (failed_bio->bi_rw & REQ_WRITE)
1900 BTRFS_I(inode)->io_tree.ops->submit_bio_hook(inode, rw, bio,
1901 failrec->last_mirror,
1902 failrec->bio_flags, 0);
1907 * each time an IO finishes, we do a fast check in the IO failure tree
1908 * to see if we need to process or clean up an io_failure_record
1910 static int btrfs_clean_io_failures(struct inode *inode, u64 start)
1913 u64 private_failure;
1914 struct io_failure_record *failure;
1918 if (count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
1919 (u64)-1, 1, EXTENT_DIRTY, 0)) {
1920 ret = get_state_private(&BTRFS_I(inode)->io_failure_tree,
1921 start, &private_failure);
1923 failure = (struct io_failure_record *)(unsigned long)
1925 set_state_private(&BTRFS_I(inode)->io_failure_tree,
1927 clear_extent_bits(&BTRFS_I(inode)->io_failure_tree,
1929 failure->start + failure->len - 1,
1930 EXTENT_DIRTY | EXTENT_LOCKED,
1939 * when reads are done, we need to check csums to verify the data is correct
1940 * if there's a match, we allow the bio to finish. If not, we go through
1941 * the io_failure_record routines to find good copies
1943 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
1944 struct extent_state *state)
1946 size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
1947 struct inode *inode = page->mapping->host;
1948 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1950 u64 private = ~(u32)0;
1952 struct btrfs_root *root = BTRFS_I(inode)->root;
1955 if (PageChecked(page)) {
1956 ClearPageChecked(page);
1960 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
1963 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
1964 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
1965 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
1970 if (state && state->start == start) {
1971 private = state->private;
1974 ret = get_state_private(io_tree, start, &private);
1976 kaddr = kmap_atomic(page, KM_USER0);
1980 csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
1981 btrfs_csum_final(csum, (char *)&csum);
1982 if (csum != private)
1985 kunmap_atomic(kaddr, KM_USER0);
1987 /* if the io failure tree for this inode is non-empty,
1988 * check to see if we've recovered from a failed IO
1990 btrfs_clean_io_failures(inode, start);
1994 if (printk_ratelimit()) {
1995 printk(KERN_INFO "btrfs csum failed ino %lu off %llu csum %u "
1996 "private %llu\n", page->mapping->host->i_ino,
1997 (unsigned long long)start, csum,
1998 (unsigned long long)private);
2000 memset(kaddr + offset, 1, end - start + 1);
2001 flush_dcache_page(page);
2002 kunmap_atomic(kaddr, KM_USER0);
2008 struct delayed_iput {
2009 struct list_head list;
2010 struct inode *inode;
2013 void btrfs_add_delayed_iput(struct inode *inode)
2015 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2016 struct delayed_iput *delayed;
2018 if (atomic_add_unless(&inode->i_count, -1, 1))
2021 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2022 delayed->inode = inode;
2024 spin_lock(&fs_info->delayed_iput_lock);
2025 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2026 spin_unlock(&fs_info->delayed_iput_lock);
2029 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2032 struct btrfs_fs_info *fs_info = root->fs_info;
2033 struct delayed_iput *delayed;
2036 spin_lock(&fs_info->delayed_iput_lock);
2037 empty = list_empty(&fs_info->delayed_iputs);
2038 spin_unlock(&fs_info->delayed_iput_lock);
2042 down_read(&root->fs_info->cleanup_work_sem);
2043 spin_lock(&fs_info->delayed_iput_lock);
2044 list_splice_init(&fs_info->delayed_iputs, &list);
2045 spin_unlock(&fs_info->delayed_iput_lock);
2047 while (!list_empty(&list)) {
2048 delayed = list_entry(list.next, struct delayed_iput, list);
2049 list_del(&delayed->list);
2050 iput(delayed->inode);
2053 up_read(&root->fs_info->cleanup_work_sem);
2057 * calculate extra metadata reservation when snapshotting a subvolume
2058 * contains orphan files.
2060 void btrfs_orphan_pre_snapshot(struct btrfs_trans_handle *trans,
2061 struct btrfs_pending_snapshot *pending,
2062 u64 *bytes_to_reserve)
2064 struct btrfs_root *root;
2065 struct btrfs_block_rsv *block_rsv;
2069 root = pending->root;
2070 if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2073 block_rsv = root->orphan_block_rsv;
2075 /* orphan block reservation for the snapshot */
2076 num_bytes = block_rsv->size;
2079 * after the snapshot is created, COWing tree blocks may use more
2080 * space than it frees. So we should make sure there is enough
2083 index = trans->transid & 0x1;
2084 if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2085 num_bytes += block_rsv->size -
2086 (block_rsv->reserved + block_rsv->freed[index]);
2089 *bytes_to_reserve += num_bytes;
2092 void btrfs_orphan_post_snapshot(struct btrfs_trans_handle *trans,
2093 struct btrfs_pending_snapshot *pending)
2095 struct btrfs_root *root = pending->root;
2096 struct btrfs_root *snap = pending->snap;
2097 struct btrfs_block_rsv *block_rsv;
2102 if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2105 /* refill source subvolume's orphan block reservation */
2106 block_rsv = root->orphan_block_rsv;
2107 index = trans->transid & 0x1;
2108 if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2109 num_bytes = block_rsv->size -
2110 (block_rsv->reserved + block_rsv->freed[index]);
2111 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2112 root->orphan_block_rsv,
2117 /* setup orphan block reservation for the snapshot */
2118 block_rsv = btrfs_alloc_block_rsv(snap);
2121 btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2122 snap->orphan_block_rsv = block_rsv;
2124 num_bytes = root->orphan_block_rsv->size;
2125 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2126 block_rsv, num_bytes);
2130 /* insert orphan item for the snapshot */
2131 WARN_ON(!root->orphan_item_inserted);
2132 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2133 snap->root_key.objectid);
2135 snap->orphan_item_inserted = 1;
2139 enum btrfs_orphan_cleanup_state {
2140 ORPHAN_CLEANUP_STARTED = 1,
2141 ORPHAN_CLEANUP_DONE = 2,
2145 * This is called in transaction commmit time. If there are no orphan
2146 * files in the subvolume, it removes orphan item and frees block_rsv
2149 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2150 struct btrfs_root *root)
2154 if (!list_empty(&root->orphan_list) ||
2155 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2158 if (root->orphan_item_inserted &&
2159 btrfs_root_refs(&root->root_item) > 0) {
2160 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2161 root->root_key.objectid);
2163 root->orphan_item_inserted = 0;
2166 if (root->orphan_block_rsv) {
2167 WARN_ON(root->orphan_block_rsv->size > 0);
2168 btrfs_free_block_rsv(root, root->orphan_block_rsv);
2169 root->orphan_block_rsv = NULL;
2174 * This creates an orphan entry for the given inode in case something goes
2175 * wrong in the middle of an unlink/truncate.
2177 * NOTE: caller of this function should reserve 5 units of metadata for
2180 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2182 struct btrfs_root *root = BTRFS_I(inode)->root;
2183 struct btrfs_block_rsv *block_rsv = NULL;
2188 if (!root->orphan_block_rsv) {
2189 block_rsv = btrfs_alloc_block_rsv(root);
2193 spin_lock(&root->orphan_lock);
2194 if (!root->orphan_block_rsv) {
2195 root->orphan_block_rsv = block_rsv;
2196 } else if (block_rsv) {
2197 btrfs_free_block_rsv(root, block_rsv);
2201 if (list_empty(&BTRFS_I(inode)->i_orphan)) {
2202 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2205 * For proper ENOSPC handling, we should do orphan
2206 * cleanup when mounting. But this introduces backward
2207 * compatibility issue.
2209 if (!xchg(&root->orphan_item_inserted, 1))
2216 WARN_ON(!BTRFS_I(inode)->orphan_meta_reserved);
2219 if (!BTRFS_I(inode)->orphan_meta_reserved) {
2220 BTRFS_I(inode)->orphan_meta_reserved = 1;
2223 spin_unlock(&root->orphan_lock);
2226 btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2228 /* grab metadata reservation from transaction handle */
2230 ret = btrfs_orphan_reserve_metadata(trans, inode);
2234 /* insert an orphan item to track this unlinked/truncated file */
2236 ret = btrfs_insert_orphan_item(trans, root, inode->i_ino);
2240 /* insert an orphan item to track subvolume contains orphan files */
2242 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2243 root->root_key.objectid);
2250 * We have done the truncate/delete so we can go ahead and remove the orphan
2251 * item for this particular inode.
2253 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2255 struct btrfs_root *root = BTRFS_I(inode)->root;
2256 int delete_item = 0;
2257 int release_rsv = 0;
2260 spin_lock(&root->orphan_lock);
2261 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
2262 list_del_init(&BTRFS_I(inode)->i_orphan);
2266 if (BTRFS_I(inode)->orphan_meta_reserved) {
2267 BTRFS_I(inode)->orphan_meta_reserved = 0;
2270 spin_unlock(&root->orphan_lock);
2272 if (trans && delete_item) {
2273 ret = btrfs_del_orphan_item(trans, root, inode->i_ino);
2278 btrfs_orphan_release_metadata(inode);
2284 * this cleans up any orphans that may be left on the list from the last use
2287 int btrfs_orphan_cleanup(struct btrfs_root *root)
2289 struct btrfs_path *path;
2290 struct extent_buffer *leaf;
2291 struct btrfs_key key, found_key;
2292 struct btrfs_trans_handle *trans;
2293 struct inode *inode;
2294 int ret = 0, nr_unlink = 0, nr_truncate = 0;
2296 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2299 path = btrfs_alloc_path();
2306 key.objectid = BTRFS_ORPHAN_OBJECTID;
2307 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2308 key.offset = (u64)-1;
2311 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2316 * if ret == 0 means we found what we were searching for, which
2317 * is weird, but possible, so only screw with path if we didnt
2318 * find the key and see if we have stuff that matches
2322 if (path->slots[0] == 0)
2327 /* pull out the item */
2328 leaf = path->nodes[0];
2329 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2331 /* make sure the item matches what we want */
2332 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2334 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2337 /* release the path since we're done with it */
2338 btrfs_release_path(root, path);
2341 * this is where we are basically btrfs_lookup, without the
2342 * crossing root thing. we store the inode number in the
2343 * offset of the orphan item.
2345 found_key.objectid = found_key.offset;
2346 found_key.type = BTRFS_INODE_ITEM_KEY;
2347 found_key.offset = 0;
2348 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2349 if (IS_ERR(inode)) {
2350 ret = PTR_ERR(inode);
2355 * add this inode to the orphan list so btrfs_orphan_del does
2356 * the proper thing when we hit it
2358 spin_lock(&root->orphan_lock);
2359 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2360 spin_unlock(&root->orphan_lock);
2363 * if this is a bad inode, means we actually succeeded in
2364 * removing the inode, but not the orphan record, which means
2365 * we need to manually delete the orphan since iput will just
2366 * do a destroy_inode
2368 if (is_bad_inode(inode)) {
2369 trans = btrfs_start_transaction(root, 0);
2370 if (IS_ERR(trans)) {
2371 ret = PTR_ERR(trans);
2374 btrfs_orphan_del(trans, inode);
2375 btrfs_end_transaction(trans, root);
2380 /* if we have links, this was a truncate, lets do that */
2381 if (inode->i_nlink) {
2382 if (!S_ISREG(inode->i_mode)) {
2388 ret = btrfs_truncate(inode);
2393 /* this will do delete_inode and everything for us */
2398 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2400 if (root->orphan_block_rsv)
2401 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2404 if (root->orphan_block_rsv || root->orphan_item_inserted) {
2405 trans = btrfs_join_transaction(root, 1);
2407 btrfs_end_transaction(trans, root);
2411 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2413 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2417 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
2418 btrfs_free_path(path);
2423 * very simple check to peek ahead in the leaf looking for xattrs. If we
2424 * don't find any xattrs, we know there can't be any acls.
2426 * slot is the slot the inode is in, objectid is the objectid of the inode
2428 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2429 int slot, u64 objectid)
2431 u32 nritems = btrfs_header_nritems(leaf);
2432 struct btrfs_key found_key;
2436 while (slot < nritems) {
2437 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2439 /* we found a different objectid, there must not be acls */
2440 if (found_key.objectid != objectid)
2443 /* we found an xattr, assume we've got an acl */
2444 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2448 * we found a key greater than an xattr key, there can't
2449 * be any acls later on
2451 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2458 * it goes inode, inode backrefs, xattrs, extents,
2459 * so if there are a ton of hard links to an inode there can
2460 * be a lot of backrefs. Don't waste time searching too hard,
2461 * this is just an optimization
2466 /* we hit the end of the leaf before we found an xattr or
2467 * something larger than an xattr. We have to assume the inode
2474 * read an inode from the btree into the in-memory inode
2476 static void btrfs_read_locked_inode(struct inode *inode)
2478 struct btrfs_path *path;
2479 struct extent_buffer *leaf;
2480 struct btrfs_inode_item *inode_item;
2481 struct btrfs_timespec *tspec;
2482 struct btrfs_root *root = BTRFS_I(inode)->root;
2483 struct btrfs_key location;
2485 u64 alloc_group_block;
2489 path = btrfs_alloc_path();
2491 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2493 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2497 leaf = path->nodes[0];
2498 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2499 struct btrfs_inode_item);
2501 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2502 inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
2503 inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2504 inode->i_gid = btrfs_inode_gid(leaf, inode_item);
2505 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2507 tspec = btrfs_inode_atime(inode_item);
2508 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2509 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2511 tspec = btrfs_inode_mtime(inode_item);
2512 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2513 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2515 tspec = btrfs_inode_ctime(inode_item);
2516 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2517 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2519 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2520 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2521 BTRFS_I(inode)->sequence = btrfs_inode_sequence(leaf, inode_item);
2522 inode->i_generation = BTRFS_I(inode)->generation;
2524 rdev = btrfs_inode_rdev(leaf, inode_item);
2526 BTRFS_I(inode)->index_cnt = (u64)-1;
2527 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2529 alloc_group_block = btrfs_inode_block_group(leaf, inode_item);
2532 * try to precache a NULL acl entry for files that don't have
2533 * any xattrs or acls
2535 maybe_acls = acls_after_inode_item(leaf, path->slots[0], inode->i_ino);
2537 cache_no_acl(inode);
2539 BTRFS_I(inode)->block_group = btrfs_find_block_group(root, 0,
2540 alloc_group_block, 0);
2541 btrfs_free_path(path);
2544 switch (inode->i_mode & S_IFMT) {
2546 inode->i_mapping->a_ops = &btrfs_aops;
2547 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2548 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2549 inode->i_fop = &btrfs_file_operations;
2550 inode->i_op = &btrfs_file_inode_operations;
2553 inode->i_fop = &btrfs_dir_file_operations;
2554 if (root == root->fs_info->tree_root)
2555 inode->i_op = &btrfs_dir_ro_inode_operations;
2557 inode->i_op = &btrfs_dir_inode_operations;
2560 inode->i_op = &btrfs_symlink_inode_operations;
2561 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2562 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2565 inode->i_op = &btrfs_special_inode_operations;
2566 init_special_inode(inode, inode->i_mode, rdev);
2570 btrfs_update_iflags(inode);
2574 btrfs_free_path(path);
2575 make_bad_inode(inode);
2579 * given a leaf and an inode, copy the inode fields into the leaf
2581 static void fill_inode_item(struct btrfs_trans_handle *trans,
2582 struct extent_buffer *leaf,
2583 struct btrfs_inode_item *item,
2584 struct inode *inode)
2586 btrfs_set_inode_uid(leaf, item, inode->i_uid);
2587 btrfs_set_inode_gid(leaf, item, inode->i_gid);
2588 btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
2589 btrfs_set_inode_mode(leaf, item, inode->i_mode);
2590 btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2592 btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2593 inode->i_atime.tv_sec);
2594 btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2595 inode->i_atime.tv_nsec);
2597 btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2598 inode->i_mtime.tv_sec);
2599 btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2600 inode->i_mtime.tv_nsec);
2602 btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2603 inode->i_ctime.tv_sec);
2604 btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2605 inode->i_ctime.tv_nsec);
2607 btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
2608 btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
2609 btrfs_set_inode_sequence(leaf, item, BTRFS_I(inode)->sequence);
2610 btrfs_set_inode_transid(leaf, item, trans->transid);
2611 btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
2612 btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
2613 btrfs_set_inode_block_group(leaf, item, BTRFS_I(inode)->block_group);
2617 * copy everything in the in-memory inode into the btree.
2619 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2620 struct btrfs_root *root, struct inode *inode)
2622 struct btrfs_inode_item *inode_item;
2623 struct btrfs_path *path;
2624 struct extent_buffer *leaf;
2627 path = btrfs_alloc_path();
2629 path->leave_spinning = 1;
2630 ret = btrfs_lookup_inode(trans, root, path,
2631 &BTRFS_I(inode)->location, 1);
2638 btrfs_unlock_up_safe(path, 1);
2639 leaf = path->nodes[0];
2640 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2641 struct btrfs_inode_item);
2643 fill_inode_item(trans, leaf, inode_item, inode);
2644 btrfs_mark_buffer_dirty(leaf);
2645 btrfs_set_inode_last_trans(trans, inode);
2648 btrfs_free_path(path);
2654 * unlink helper that gets used here in inode.c and in the tree logging
2655 * recovery code. It remove a link in a directory with a given name, and
2656 * also drops the back refs in the inode to the directory
2658 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2659 struct btrfs_root *root,
2660 struct inode *dir, struct inode *inode,
2661 const char *name, int name_len)
2663 struct btrfs_path *path;
2665 struct extent_buffer *leaf;
2666 struct btrfs_dir_item *di;
2667 struct btrfs_key key;
2670 path = btrfs_alloc_path();
2676 path->leave_spinning = 1;
2677 di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2678 name, name_len, -1);
2687 leaf = path->nodes[0];
2688 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2689 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2692 btrfs_release_path(root, path);
2694 ret = btrfs_del_inode_ref(trans, root, name, name_len,
2696 dir->i_ino, &index);
2698 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2699 "inode %lu parent %lu\n", name_len, name,
2700 inode->i_ino, dir->i_ino);
2704 di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
2705 index, name, name_len, -1);
2714 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2715 btrfs_release_path(root, path);
2717 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2719 BUG_ON(ret != 0 && ret != -ENOENT);
2721 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2726 btrfs_free_path(path);
2730 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2731 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2732 btrfs_update_inode(trans, root, dir);
2733 btrfs_drop_nlink(inode);
2734 ret = btrfs_update_inode(trans, root, inode);
2739 /* helper to check if there is any shared block in the path */
2740 static int check_path_shared(struct btrfs_root *root,
2741 struct btrfs_path *path)
2743 struct extent_buffer *eb;
2747 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2750 if (!path->nodes[level])
2752 eb = path->nodes[level];
2753 if (!btrfs_block_can_be_shared(root, eb))
2755 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2764 * helper to start transaction for unlink and rmdir.
2766 * unlink and rmdir are special in btrfs, they do not always free space.
2767 * so in enospc case, we should make sure they will free space before
2768 * allowing them to use the global metadata reservation.
2770 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2771 struct dentry *dentry)
2773 struct btrfs_trans_handle *trans;
2774 struct btrfs_root *root = BTRFS_I(dir)->root;
2775 struct btrfs_path *path;
2776 struct btrfs_inode_ref *ref;
2777 struct btrfs_dir_item *di;
2778 struct inode *inode = dentry->d_inode;
2784 trans = btrfs_start_transaction(root, 10);
2785 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2788 if (inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2789 return ERR_PTR(-ENOSPC);
2791 /* check if there is someone else holds reference */
2792 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2793 return ERR_PTR(-ENOSPC);
2795 if (atomic_read(&inode->i_count) > 2)
2796 return ERR_PTR(-ENOSPC);
2798 if (xchg(&root->fs_info->enospc_unlink, 1))
2799 return ERR_PTR(-ENOSPC);
2801 path = btrfs_alloc_path();
2803 root->fs_info->enospc_unlink = 0;
2804 return ERR_PTR(-ENOMEM);
2807 trans = btrfs_start_transaction(root, 0);
2808 if (IS_ERR(trans)) {
2809 btrfs_free_path(path);
2810 root->fs_info->enospc_unlink = 0;
2814 path->skip_locking = 1;
2815 path->search_commit_root = 1;
2817 ret = btrfs_lookup_inode(trans, root, path,
2818 &BTRFS_I(dir)->location, 0);
2824 if (check_path_shared(root, path))
2829 btrfs_release_path(root, path);
2831 ret = btrfs_lookup_inode(trans, root, path,
2832 &BTRFS_I(inode)->location, 0);
2838 if (check_path_shared(root, path))
2843 btrfs_release_path(root, path);
2845 if (ret == 0 && S_ISREG(inode->i_mode)) {
2846 ret = btrfs_lookup_file_extent(trans, root, path,
2847 inode->i_ino, (u64)-1, 0);
2853 if (check_path_shared(root, path))
2855 btrfs_release_path(root, path);
2863 di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2864 dentry->d_name.name, dentry->d_name.len, 0);
2870 if (check_path_shared(root, path))
2876 btrfs_release_path(root, path);
2878 ref = btrfs_lookup_inode_ref(trans, root, path,
2879 dentry->d_name.name, dentry->d_name.len,
2880 inode->i_ino, dir->i_ino, 0);
2886 if (check_path_shared(root, path))
2888 index = btrfs_inode_ref_index(path->nodes[0], ref);
2889 btrfs_release_path(root, path);
2891 di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino, index,
2892 dentry->d_name.name, dentry->d_name.len, 0);
2897 BUG_ON(ret == -ENOENT);
2898 if (check_path_shared(root, path))
2903 btrfs_free_path(path);
2905 btrfs_end_transaction(trans, root);
2906 root->fs_info->enospc_unlink = 0;
2907 return ERR_PTR(err);
2910 trans->block_rsv = &root->fs_info->global_block_rsv;
2914 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
2915 struct btrfs_root *root)
2917 if (trans->block_rsv == &root->fs_info->global_block_rsv) {
2918 BUG_ON(!root->fs_info->enospc_unlink);
2919 root->fs_info->enospc_unlink = 0;
2921 btrfs_end_transaction_throttle(trans, root);
2924 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
2926 struct btrfs_root *root = BTRFS_I(dir)->root;
2927 struct btrfs_trans_handle *trans;
2928 struct inode *inode = dentry->d_inode;
2930 unsigned long nr = 0;
2932 trans = __unlink_start_trans(dir, dentry);
2934 return PTR_ERR(trans);
2936 btrfs_set_trans_block_group(trans, dir);
2938 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
2940 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2941 dentry->d_name.name, dentry->d_name.len);
2944 if (inode->i_nlink == 0) {
2945 ret = btrfs_orphan_add(trans, inode);
2949 nr = trans->blocks_used;
2950 __unlink_end_trans(trans, root);
2951 btrfs_btree_balance_dirty(root, nr);
2955 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
2956 struct btrfs_root *root,
2957 struct inode *dir, u64 objectid,
2958 const char *name, int name_len)
2960 struct btrfs_path *path;
2961 struct extent_buffer *leaf;
2962 struct btrfs_dir_item *di;
2963 struct btrfs_key key;
2967 path = btrfs_alloc_path();
2971 di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2972 name, name_len, -1);
2973 BUG_ON(!di || IS_ERR(di));
2975 leaf = path->nodes[0];
2976 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2977 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2978 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2980 btrfs_release_path(root, path);
2982 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
2983 objectid, root->root_key.objectid,
2984 dir->i_ino, &index, name, name_len);
2986 BUG_ON(ret != -ENOENT);
2987 di = btrfs_search_dir_index_item(root, path, dir->i_ino,
2989 BUG_ON(!di || IS_ERR(di));
2991 leaf = path->nodes[0];
2992 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2993 btrfs_release_path(root, path);
2997 di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
2998 index, name, name_len, -1);
2999 BUG_ON(!di || IS_ERR(di));
3001 leaf = path->nodes[0];
3002 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3003 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3004 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3006 btrfs_release_path(root, path);
3008 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3009 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3010 ret = btrfs_update_inode(trans, root, dir);
3013 btrfs_free_path(path);
3017 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3019 struct inode *inode = dentry->d_inode;
3021 struct btrfs_root *root = BTRFS_I(dir)->root;
3022 struct btrfs_trans_handle *trans;
3023 unsigned long nr = 0;
3025 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
3026 inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
3029 trans = __unlink_start_trans(dir, dentry);
3031 return PTR_ERR(trans);
3033 btrfs_set_trans_block_group(trans, dir);
3035 if (unlikely(inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3036 err = btrfs_unlink_subvol(trans, root, dir,
3037 BTRFS_I(inode)->location.objectid,
3038 dentry->d_name.name,
3039 dentry->d_name.len);
3043 err = btrfs_orphan_add(trans, inode);
3047 /* now the directory is empty */
3048 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3049 dentry->d_name.name, dentry->d_name.len);
3051 btrfs_i_size_write(inode, 0);
3053 nr = trans->blocks_used;
3054 __unlink_end_trans(trans, root);
3055 btrfs_btree_balance_dirty(root, nr);
3062 * when truncating bytes in a file, it is possible to avoid reading
3063 * the leaves that contain only checksum items. This can be the
3064 * majority of the IO required to delete a large file, but it must
3065 * be done carefully.
3067 * The keys in the level just above the leaves are checked to make sure
3068 * the lowest key in a given leaf is a csum key, and starts at an offset
3069 * after the new size.
3071 * Then the key for the next leaf is checked to make sure it also has
3072 * a checksum item for the same file. If it does, we know our target leaf
3073 * contains only checksum items, and it can be safely freed without reading
3076 * This is just an optimization targeted at large files. It may do
3077 * nothing. It will return 0 unless things went badly.
3079 static noinline int drop_csum_leaves(struct btrfs_trans_handle *trans,
3080 struct btrfs_root *root,
3081 struct btrfs_path *path,
3082 struct inode *inode, u64 new_size)
3084 struct btrfs_key key;
3087 struct btrfs_key found_key;
3088 struct btrfs_key other_key;
3089 struct btrfs_leaf_ref *ref;
3093 path->lowest_level = 1;
3094 key.objectid = inode->i_ino;
3095 key.type = BTRFS_CSUM_ITEM_KEY;
3096 key.offset = new_size;
3098 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3102 if (path->nodes[1] == NULL) {
3107 btrfs_node_key_to_cpu(path->nodes[1], &found_key, path->slots[1]);
3108 nritems = btrfs_header_nritems(path->nodes[1]);
3113 if (path->slots[1] >= nritems)
3116 /* did we find a key greater than anything we want to delete? */
3117 if (found_key.objectid > inode->i_ino ||
3118 (found_key.objectid == inode->i_ino && found_key.type > key.type))
3121 /* we check the next key in the node to make sure the leave contains
3122 * only checksum items. This comparison doesn't work if our
3123 * leaf is the last one in the node
3125 if (path->slots[1] + 1 >= nritems) {
3127 /* search forward from the last key in the node, this
3128 * will bring us into the next node in the tree
3130 btrfs_node_key_to_cpu(path->nodes[1], &found_key, nritems - 1);
3132 /* unlikely, but we inc below, so check to be safe */
3133 if (found_key.offset == (u64)-1)
3136 /* search_forward needs a path with locks held, do the
3137 * search again for the original key. It is possible
3138 * this will race with a balance and return a path that
3139 * we could modify, but this drop is just an optimization
3140 * and is allowed to miss some leaves.
3142 btrfs_release_path(root, path);
3145 /* setup a max key for search_forward */
3146 other_key.offset = (u64)-1;
3147 other_key.type = key.type;
3148 other_key.objectid = key.objectid;
3150 path->keep_locks = 1;
3151 ret = btrfs_search_forward(root, &found_key, &other_key,
3153 path->keep_locks = 0;
3154 if (ret || found_key.objectid != key.objectid ||
3155 found_key.type != key.type) {
3160 key.offset = found_key.offset;
3161 btrfs_release_path(root, path);
3166 /* we know there's one more slot after us in the tree,
3167 * read that key so we can verify it is also a checksum item
3169 btrfs_node_key_to_cpu(path->nodes[1], &other_key, path->slots[1] + 1);
3171 if (found_key.objectid < inode->i_ino)
3174 if (found_key.type != key.type || found_key.offset < new_size)
3178 * if the key for the next leaf isn't a csum key from this objectid,
3179 * we can't be sure there aren't good items inside this leaf.
3182 if (other_key.objectid != inode->i_ino || other_key.type != key.type)
3185 leaf_start = btrfs_node_blockptr(path->nodes[1], path->slots[1]);
3186 leaf_gen = btrfs_node_ptr_generation(path->nodes[1], path->slots[1]);
3188 * it is safe to delete this leaf, it contains only
3189 * csum items from this inode at an offset >= new_size
3191 ret = btrfs_del_leaf(trans, root, path, leaf_start);
3194 if (root->ref_cows && leaf_gen < trans->transid) {
3195 ref = btrfs_alloc_leaf_ref(root, 0);
3197 ref->root_gen = root->root_key.offset;
3198 ref->bytenr = leaf_start;
3200 ref->generation = leaf_gen;
3203 btrfs_sort_leaf_ref(ref);
3205 ret = btrfs_add_leaf_ref(root, ref, 0);
3207 btrfs_free_leaf_ref(root, ref);
3213 btrfs_release_path(root, path);
3215 if (other_key.objectid == inode->i_ino &&
3216 other_key.type == key.type && other_key.offset > key.offset) {
3217 key.offset = other_key.offset;
3223 /* fixup any changes we've made to the path */
3224 path->lowest_level = 0;
3225 path->keep_locks = 0;
3226 btrfs_release_path(root, path);
3233 * this can truncate away extent items, csum items and directory items.
3234 * It starts at a high offset and removes keys until it can't find
3235 * any higher than new_size
3237 * csum items that cross the new i_size are truncated to the new size
3240 * min_type is the minimum key type to truncate down to. If set to 0, this
3241 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3243 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3244 struct btrfs_root *root,
3245 struct inode *inode,
3246 u64 new_size, u32 min_type)
3248 struct btrfs_path *path;
3249 struct extent_buffer *leaf;
3250 struct btrfs_file_extent_item *fi;
3251 struct btrfs_key key;
3252 struct btrfs_key found_key;
3253 u64 extent_start = 0;
3254 u64 extent_num_bytes = 0;
3255 u64 extent_offset = 0;
3257 u64 mask = root->sectorsize - 1;
3258 u32 found_type = (u8)-1;
3261 int pending_del_nr = 0;
3262 int pending_del_slot = 0;
3263 int extent_type = -1;
3268 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3270 if (root->ref_cows || root == root->fs_info->tree_root)
3271 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
3273 path = btrfs_alloc_path();
3277 key.objectid = inode->i_ino;
3278 key.offset = (u64)-1;
3282 path->leave_spinning = 1;
3283 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3290 /* there are no items in the tree for us to truncate, we're
3293 if (path->slots[0] == 0)
3300 leaf = path->nodes[0];
3301 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3302 found_type = btrfs_key_type(&found_key);
3305 if (found_key.objectid != inode->i_ino)
3308 if (found_type < min_type)
3311 item_end = found_key.offset;
3312 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3313 fi = btrfs_item_ptr(leaf, path->slots[0],
3314 struct btrfs_file_extent_item);
3315 extent_type = btrfs_file_extent_type(leaf, fi);
3316 encoding = btrfs_file_extent_compression(leaf, fi);
3317 encoding |= btrfs_file_extent_encryption(leaf, fi);
3318 encoding |= btrfs_file_extent_other_encoding(leaf, fi);
3320 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3322 btrfs_file_extent_num_bytes(leaf, fi);
3323 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3324 item_end += btrfs_file_extent_inline_len(leaf,
3329 if (found_type > min_type) {
3332 if (item_end < new_size)
3334 if (found_key.offset >= new_size)
3340 /* FIXME, shrink the extent if the ref count is only 1 */
3341 if (found_type != BTRFS_EXTENT_DATA_KEY)
3344 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3346 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3347 if (!del_item && !encoding) {
3348 u64 orig_num_bytes =
3349 btrfs_file_extent_num_bytes(leaf, fi);
3350 extent_num_bytes = new_size -
3351 found_key.offset + root->sectorsize - 1;
3352 extent_num_bytes = extent_num_bytes &
3353 ~((u64)root->sectorsize - 1);
3354 btrfs_set_file_extent_num_bytes(leaf, fi,
3356 num_dec = (orig_num_bytes -
3358 if (root->ref_cows && extent_start != 0)
3359 inode_sub_bytes(inode, num_dec);
3360 btrfs_mark_buffer_dirty(leaf);
3363 btrfs_file_extent_disk_num_bytes(leaf,
3365 extent_offset = found_key.offset -
3366 btrfs_file_extent_offset(leaf, fi);
3368 /* FIXME blocksize != 4096 */
3369 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3370 if (extent_start != 0) {
3373 inode_sub_bytes(inode, num_dec);
3376 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3378 * we can't truncate inline items that have had
3382 btrfs_file_extent_compression(leaf, fi) == 0 &&
3383 btrfs_file_extent_encryption(leaf, fi) == 0 &&
3384 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3385 u32 size = new_size - found_key.offset;
3387 if (root->ref_cows) {
3388 inode_sub_bytes(inode, item_end + 1 -
3392 btrfs_file_extent_calc_inline_size(size);
3393 ret = btrfs_truncate_item(trans, root, path,
3396 } else if (root->ref_cows) {
3397 inode_sub_bytes(inode, item_end + 1 -
3403 if (!pending_del_nr) {
3404 /* no pending yet, add ourselves */
3405 pending_del_slot = path->slots[0];
3407 } else if (pending_del_nr &&
3408 path->slots[0] + 1 == pending_del_slot) {
3409 /* hop on the pending chunk */
3411 pending_del_slot = path->slots[0];
3418 if (found_extent && (root->ref_cows ||
3419 root == root->fs_info->tree_root)) {
3420 btrfs_set_path_blocking(path);
3421 ret = btrfs_free_extent(trans, root, extent_start,
3422 extent_num_bytes, 0,
3423 btrfs_header_owner(leaf),
3424 inode->i_ino, extent_offset);
3428 if (found_type == BTRFS_INODE_ITEM_KEY)
3431 if (path->slots[0] == 0 ||
3432 path->slots[0] != pending_del_slot) {
3433 if (root->ref_cows) {
3437 if (pending_del_nr) {
3438 ret = btrfs_del_items(trans, root, path,
3444 btrfs_release_path(root, path);
3451 if (pending_del_nr) {
3452 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3456 btrfs_free_path(path);
3461 * taken from block_truncate_page, but does cow as it zeros out
3462 * any bytes left in the last page in the file.
3464 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
3466 struct inode *inode = mapping->host;
3467 struct btrfs_root *root = BTRFS_I(inode)->root;
3468 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3469 struct btrfs_ordered_extent *ordered;
3470 struct extent_state *cached_state = NULL;
3472 u32 blocksize = root->sectorsize;
3473 pgoff_t index = from >> PAGE_CACHE_SHIFT;
3474 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3480 if ((offset & (blocksize - 1)) == 0)
3482 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3488 page = grab_cache_page(mapping, index);
3490 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3494 page_start = page_offset(page);
3495 page_end = page_start + PAGE_CACHE_SIZE - 1;
3497 if (!PageUptodate(page)) {
3498 ret = btrfs_readpage(NULL, page);
3500 if (page->mapping != mapping) {
3502 page_cache_release(page);
3505 if (!PageUptodate(page)) {
3510 wait_on_page_writeback(page);
3512 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
3514 set_page_extent_mapped(page);
3516 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3518 unlock_extent_cached(io_tree, page_start, page_end,
3519 &cached_state, GFP_NOFS);
3521 page_cache_release(page);
3522 btrfs_start_ordered_extent(inode, ordered, 1);
3523 btrfs_put_ordered_extent(ordered);
3527 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3528 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
3529 0, 0, &cached_state, GFP_NOFS);
3531 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3534 unlock_extent_cached(io_tree, page_start, page_end,
3535 &cached_state, GFP_NOFS);
3540 if (offset != PAGE_CACHE_SIZE) {
3542 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
3543 flush_dcache_page(page);
3546 ClearPageChecked(page);
3547 set_page_dirty(page);
3548 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3553 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3555 page_cache_release(page);
3561 * This function puts in dummy file extents for the area we're creating a hole
3562 * for. So if we are truncating this file to a larger size we need to insert
3563 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
3564 * the range between oldsize and size
3566 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
3568 struct btrfs_trans_handle *trans;
3569 struct btrfs_root *root = BTRFS_I(inode)->root;
3570 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3571 struct extent_map *em = NULL;
3572 struct extent_state *cached_state = NULL;
3573 u64 mask = root->sectorsize - 1;
3574 u64 hole_start = (oldsize + mask) & ~mask;
3575 u64 block_end = (size + mask) & ~mask;
3581 if (size <= hole_start)
3585 struct btrfs_ordered_extent *ordered;
3586 btrfs_wait_ordered_range(inode, hole_start,
3587 block_end - hole_start);
3588 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3589 &cached_state, GFP_NOFS);
3590 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3593 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3594 &cached_state, GFP_NOFS);
3595 btrfs_put_ordered_extent(ordered);
3598 cur_offset = hole_start;
3600 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3601 block_end - cur_offset, 0);
3602 BUG_ON(IS_ERR(em) || !em);
3603 last_byte = min(extent_map_end(em), block_end);
3604 last_byte = (last_byte + mask) & ~mask;
3605 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3607 hole_size = last_byte - cur_offset;
3609 trans = btrfs_start_transaction(root, 2);
3610 if (IS_ERR(trans)) {
3611 err = PTR_ERR(trans);
3614 btrfs_set_trans_block_group(trans, inode);
3616 err = btrfs_drop_extents(trans, inode, cur_offset,
3617 cur_offset + hole_size,
3622 err = btrfs_insert_file_extent(trans, root,
3623 inode->i_ino, cur_offset, 0,
3624 0, hole_size, 0, hole_size,
3629 btrfs_drop_extent_cache(inode, hole_start,
3632 btrfs_end_transaction(trans, root);
3634 free_extent_map(em);
3636 cur_offset = last_byte;
3637 if (cur_offset >= block_end)
3641 free_extent_map(em);
3642 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3647 static int btrfs_setsize(struct inode *inode, loff_t newsize)
3649 loff_t oldsize = i_size_read(inode);
3652 if (newsize == oldsize)
3655 if (newsize > oldsize) {
3656 i_size_write(inode, newsize);
3657 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
3658 truncate_pagecache(inode, oldsize, newsize);
3659 ret = btrfs_cont_expand(inode, oldsize, newsize);
3661 btrfs_setsize(inode, oldsize);
3665 mark_inode_dirty(inode);
3669 * We're truncating a file that used to have good data down to
3670 * zero. Make sure it gets into the ordered flush list so that
3671 * any new writes get down to disk quickly.
3674 BTRFS_I(inode)->ordered_data_close = 1;
3676 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3677 truncate_setsize(inode, newsize);
3678 ret = btrfs_truncate(inode);
3684 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3686 struct inode *inode = dentry->d_inode;
3687 struct btrfs_root *root = BTRFS_I(inode)->root;
3690 if (btrfs_root_readonly(root))
3693 err = inode_change_ok(inode, attr);
3697 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3698 err = btrfs_setsize(inode, attr->ia_size);
3703 if (attr->ia_valid) {
3704 setattr_copy(inode, attr);
3705 mark_inode_dirty(inode);
3707 if (attr->ia_valid & ATTR_MODE)
3708 err = btrfs_acl_chmod(inode);
3714 void btrfs_evict_inode(struct inode *inode)
3716 struct btrfs_trans_handle *trans;
3717 struct btrfs_root *root = BTRFS_I(inode)->root;
3721 truncate_inode_pages(&inode->i_data, 0);
3722 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
3723 root == root->fs_info->tree_root))
3726 if (is_bad_inode(inode)) {
3727 btrfs_orphan_del(NULL, inode);
3730 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
3731 btrfs_wait_ordered_range(inode, 0, (u64)-1);
3733 if (root->fs_info->log_root_recovering) {
3734 BUG_ON(!list_empty(&BTRFS_I(inode)->i_orphan));
3738 if (inode->i_nlink > 0) {
3739 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3743 btrfs_i_size_write(inode, 0);
3746 trans = btrfs_start_transaction(root, 0);
3747 BUG_ON(IS_ERR(trans));
3748 btrfs_set_trans_block_group(trans, inode);
3749 trans->block_rsv = root->orphan_block_rsv;
3751 ret = btrfs_block_rsv_check(trans, root,
3752 root->orphan_block_rsv, 0, 5);
3754 BUG_ON(ret != -EAGAIN);
3755 ret = btrfs_commit_transaction(trans, root);
3760 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3764 nr = trans->blocks_used;
3765 btrfs_end_transaction(trans, root);
3767 btrfs_btree_balance_dirty(root, nr);
3772 ret = btrfs_orphan_del(trans, inode);
3776 nr = trans->blocks_used;
3777 btrfs_end_transaction(trans, root);
3778 btrfs_btree_balance_dirty(root, nr);
3780 end_writeback(inode);
3785 * this returns the key found in the dir entry in the location pointer.
3786 * If no dir entries were found, location->objectid is 0.
3788 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3789 struct btrfs_key *location)
3791 const char *name = dentry->d_name.name;
3792 int namelen = dentry->d_name.len;
3793 struct btrfs_dir_item *di;
3794 struct btrfs_path *path;
3795 struct btrfs_root *root = BTRFS_I(dir)->root;
3798 path = btrfs_alloc_path();
3801 di = btrfs_lookup_dir_item(NULL, root, path, dir->i_ino, name,
3806 if (!di || IS_ERR(di))
3809 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
3811 btrfs_free_path(path);
3814 location->objectid = 0;
3819 * when we hit a tree root in a directory, the btrfs part of the inode
3820 * needs to be changed to reflect the root directory of the tree root. This
3821 * is kind of like crossing a mount point.
3823 static int fixup_tree_root_location(struct btrfs_root *root,
3825 struct dentry *dentry,
3826 struct btrfs_key *location,
3827 struct btrfs_root **sub_root)
3829 struct btrfs_path *path;
3830 struct btrfs_root *new_root;
3831 struct btrfs_root_ref *ref;
3832 struct extent_buffer *leaf;
3836 path = btrfs_alloc_path();
3843 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
3844 BTRFS_I(dir)->root->root_key.objectid,
3845 location->objectid);
3852 leaf = path->nodes[0];
3853 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
3854 if (btrfs_root_ref_dirid(leaf, ref) != dir->i_ino ||
3855 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
3858 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
3859 (unsigned long)(ref + 1),
3860 dentry->d_name.len);
3864 btrfs_release_path(root->fs_info->tree_root, path);
3866 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
3867 if (IS_ERR(new_root)) {
3868 err = PTR_ERR(new_root);
3872 if (btrfs_root_refs(&new_root->root_item) == 0) {
3877 *sub_root = new_root;
3878 location->objectid = btrfs_root_dirid(&new_root->root_item);
3879 location->type = BTRFS_INODE_ITEM_KEY;
3880 location->offset = 0;
3883 btrfs_free_path(path);
3887 static void inode_tree_add(struct inode *inode)
3889 struct btrfs_root *root = BTRFS_I(inode)->root;
3890 struct btrfs_inode *entry;
3892 struct rb_node *parent;
3894 p = &root->inode_tree.rb_node;
3897 if (inode_unhashed(inode))
3900 spin_lock(&root->inode_lock);
3903 entry = rb_entry(parent, struct btrfs_inode, rb_node);
3905 if (inode->i_ino < entry->vfs_inode.i_ino)
3906 p = &parent->rb_left;
3907 else if (inode->i_ino > entry->vfs_inode.i_ino)
3908 p = &parent->rb_right;
3910 WARN_ON(!(entry->vfs_inode.i_state &
3911 (I_WILL_FREE | I_FREEING)));
3912 rb_erase(parent, &root->inode_tree);
3913 RB_CLEAR_NODE(parent);
3914 spin_unlock(&root->inode_lock);
3918 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
3919 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3920 spin_unlock(&root->inode_lock);
3923 static void inode_tree_del(struct inode *inode)
3925 struct btrfs_root *root = BTRFS_I(inode)->root;
3928 spin_lock(&root->inode_lock);
3929 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
3930 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3931 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
3932 empty = RB_EMPTY_ROOT(&root->inode_tree);
3934 spin_unlock(&root->inode_lock);
3937 * Free space cache has inodes in the tree root, but the tree root has a
3938 * root_refs of 0, so this could end up dropping the tree root as a
3939 * snapshot, so we need the extra !root->fs_info->tree_root check to
3940 * make sure we don't drop it.
3942 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
3943 root != root->fs_info->tree_root) {
3944 synchronize_srcu(&root->fs_info->subvol_srcu);
3945 spin_lock(&root->inode_lock);
3946 empty = RB_EMPTY_ROOT(&root->inode_tree);
3947 spin_unlock(&root->inode_lock);
3949 btrfs_add_dead_root(root);
3953 int btrfs_invalidate_inodes(struct btrfs_root *root)
3955 struct rb_node *node;
3956 struct rb_node *prev;
3957 struct btrfs_inode *entry;
3958 struct inode *inode;
3961 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3963 spin_lock(&root->inode_lock);
3965 node = root->inode_tree.rb_node;
3969 entry = rb_entry(node, struct btrfs_inode, rb_node);
3971 if (objectid < entry->vfs_inode.i_ino)
3972 node = node->rb_left;
3973 else if (objectid > entry->vfs_inode.i_ino)
3974 node = node->rb_right;
3980 entry = rb_entry(prev, struct btrfs_inode, rb_node);
3981 if (objectid <= entry->vfs_inode.i_ino) {
3985 prev = rb_next(prev);
3989 entry = rb_entry(node, struct btrfs_inode, rb_node);
3990 objectid = entry->vfs_inode.i_ino + 1;
3991 inode = igrab(&entry->vfs_inode);
3993 spin_unlock(&root->inode_lock);
3994 if (atomic_read(&inode->i_count) > 1)
3995 d_prune_aliases(inode);
3997 * btrfs_drop_inode will have it removed from
3998 * the inode cache when its usage count
4003 spin_lock(&root->inode_lock);
4007 if (cond_resched_lock(&root->inode_lock))
4010 node = rb_next(node);
4012 spin_unlock(&root->inode_lock);
4016 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4018 struct btrfs_iget_args *args = p;
4019 inode->i_ino = args->ino;
4020 BTRFS_I(inode)->root = args->root;
4021 btrfs_set_inode_space_info(args->root, inode);
4025 static int btrfs_find_actor(struct inode *inode, void *opaque)
4027 struct btrfs_iget_args *args = opaque;
4028 return args->ino == inode->i_ino &&
4029 args->root == BTRFS_I(inode)->root;
4032 static struct inode *btrfs_iget_locked(struct super_block *s,
4034 struct btrfs_root *root)
4036 struct inode *inode;
4037 struct btrfs_iget_args args;
4038 args.ino = objectid;
4041 inode = iget5_locked(s, objectid, btrfs_find_actor,
4042 btrfs_init_locked_inode,
4047 /* Get an inode object given its location and corresponding root.
4048 * Returns in *is_new if the inode was read from disk
4050 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4051 struct btrfs_root *root, int *new)
4053 struct inode *inode;
4055 inode = btrfs_iget_locked(s, location->objectid, root);
4057 return ERR_PTR(-ENOMEM);
4059 if (inode->i_state & I_NEW) {
4060 BTRFS_I(inode)->root = root;
4061 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4062 btrfs_read_locked_inode(inode);
4064 inode_tree_add(inode);
4065 unlock_new_inode(inode);
4073 static struct inode *new_simple_dir(struct super_block *s,
4074 struct btrfs_key *key,
4075 struct btrfs_root *root)
4077 struct inode *inode = new_inode(s);
4080 return ERR_PTR(-ENOMEM);
4082 BTRFS_I(inode)->root = root;
4083 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4084 BTRFS_I(inode)->dummy_inode = 1;
4086 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4087 inode->i_op = &simple_dir_inode_operations;
4088 inode->i_fop = &simple_dir_operations;
4089 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4090 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4095 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4097 struct inode *inode;
4098 struct btrfs_root *root = BTRFS_I(dir)->root;
4099 struct btrfs_root *sub_root = root;
4100 struct btrfs_key location;
4104 if (dentry->d_name.len > BTRFS_NAME_LEN)
4105 return ERR_PTR(-ENAMETOOLONG);
4107 ret = btrfs_inode_by_name(dir, dentry, &location);
4110 return ERR_PTR(ret);
4112 if (location.objectid == 0)
4115 if (location.type == BTRFS_INODE_ITEM_KEY) {
4116 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4120 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4122 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4123 ret = fixup_tree_root_location(root, dir, dentry,
4124 &location, &sub_root);
4127 inode = ERR_PTR(ret);
4129 inode = new_simple_dir(dir->i_sb, &location, sub_root);
4131 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4133 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4135 if (!IS_ERR(inode) && root != sub_root) {
4136 down_read(&root->fs_info->cleanup_work_sem);
4137 if (!(inode->i_sb->s_flags & MS_RDONLY))
4138 ret = btrfs_orphan_cleanup(sub_root);
4139 up_read(&root->fs_info->cleanup_work_sem);
4141 inode = ERR_PTR(ret);
4147 static int btrfs_dentry_delete(const struct dentry *dentry)
4149 struct btrfs_root *root;
4151 if (!dentry->d_inode && !IS_ROOT(dentry))
4152 dentry = dentry->d_parent;
4154 if (dentry->d_inode) {
4155 root = BTRFS_I(dentry->d_inode)->root;
4156 if (btrfs_root_refs(&root->root_item) == 0)
4162 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4163 struct nameidata *nd)
4165 struct inode *inode;
4167 inode = btrfs_lookup_dentry(dir, dentry);
4169 return ERR_CAST(inode);
4171 return d_splice_alias(inode, dentry);
4174 static unsigned char btrfs_filetype_table[] = {
4175 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4178 static int btrfs_real_readdir(struct file *filp, void *dirent,
4181 struct inode *inode = filp->f_dentry->d_inode;
4182 struct btrfs_root *root = BTRFS_I(inode)->root;
4183 struct btrfs_item *item;
4184 struct btrfs_dir_item *di;
4185 struct btrfs_key key;
4186 struct btrfs_key found_key;
4187 struct btrfs_path *path;
4190 struct extent_buffer *leaf;
4193 unsigned char d_type;
4198 int key_type = BTRFS_DIR_INDEX_KEY;
4203 /* FIXME, use a real flag for deciding about the key type */
4204 if (root->fs_info->tree_root == root)
4205 key_type = BTRFS_DIR_ITEM_KEY;
4207 /* special case for "." */
4208 if (filp->f_pos == 0) {
4209 over = filldir(dirent, ".", 1,
4216 /* special case for .., just use the back ref */
4217 if (filp->f_pos == 1) {
4218 u64 pino = parent_ino(filp->f_path.dentry);
4219 over = filldir(dirent, "..", 2,
4225 path = btrfs_alloc_path();
4228 btrfs_set_key_type(&key, key_type);
4229 key.offset = filp->f_pos;
4230 key.objectid = inode->i_ino;
4232 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4238 leaf = path->nodes[0];
4239 nritems = btrfs_header_nritems(leaf);
4240 slot = path->slots[0];
4241 if (advance || slot >= nritems) {
4242 if (slot >= nritems - 1) {
4243 ret = btrfs_next_leaf(root, path);
4246 leaf = path->nodes[0];
4247 nritems = btrfs_header_nritems(leaf);
4248 slot = path->slots[0];
4256 item = btrfs_item_nr(leaf, slot);
4257 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4259 if (found_key.objectid != key.objectid)
4261 if (btrfs_key_type(&found_key) != key_type)
4263 if (found_key.offset < filp->f_pos)
4266 filp->f_pos = found_key.offset;
4268 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4270 di_total = btrfs_item_size(leaf, item);
4272 while (di_cur < di_total) {
4273 struct btrfs_key location;
4275 if (verify_dir_item(root, leaf, di))
4278 name_len = btrfs_dir_name_len(leaf, di);
4279 if (name_len <= sizeof(tmp_name)) {
4280 name_ptr = tmp_name;
4282 name_ptr = kmalloc(name_len, GFP_NOFS);
4288 read_extent_buffer(leaf, name_ptr,
4289 (unsigned long)(di + 1), name_len);
4291 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4292 btrfs_dir_item_key_to_cpu(leaf, di, &location);
4294 /* is this a reference to our own snapshot? If so
4297 if (location.type == BTRFS_ROOT_ITEM_KEY &&
4298 location.objectid == root->root_key.objectid) {
4302 over = filldir(dirent, name_ptr, name_len,
4303 found_key.offset, location.objectid,
4307 if (name_ptr != tmp_name)
4312 di_len = btrfs_dir_name_len(leaf, di) +
4313 btrfs_dir_data_len(leaf, di) + sizeof(*di);
4315 di = (struct btrfs_dir_item *)((char *)di + di_len);
4319 /* Reached end of directory/root. Bump pos past the last item. */
4320 if (key_type == BTRFS_DIR_INDEX_KEY)
4322 * 32-bit glibc will use getdents64, but then strtol -
4323 * so the last number we can serve is this.
4325 filp->f_pos = 0x7fffffff;
4331 btrfs_free_path(path);
4335 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4337 struct btrfs_root *root = BTRFS_I(inode)->root;
4338 struct btrfs_trans_handle *trans;
4340 bool nolock = false;
4342 if (BTRFS_I(inode)->dummy_inode)
4346 nolock = (root->fs_info->closing && root == root->fs_info->tree_root);
4348 if (wbc->sync_mode == WB_SYNC_ALL) {
4350 trans = btrfs_join_transaction_nolock(root, 1);
4352 trans = btrfs_join_transaction(root, 1);
4354 return PTR_ERR(trans);
4355 btrfs_set_trans_block_group(trans, inode);
4357 ret = btrfs_end_transaction_nolock(trans, root);
4359 ret = btrfs_commit_transaction(trans, root);
4365 * This is somewhat expensive, updating the tree every time the
4366 * inode changes. But, it is most likely to find the inode in cache.
4367 * FIXME, needs more benchmarking...there are no reasons other than performance
4368 * to keep or drop this code.
4370 void btrfs_dirty_inode(struct inode *inode)
4372 struct btrfs_root *root = BTRFS_I(inode)->root;
4373 struct btrfs_trans_handle *trans;
4376 if (BTRFS_I(inode)->dummy_inode)
4379 trans = btrfs_join_transaction(root, 1);
4380 BUG_ON(IS_ERR(trans));
4381 btrfs_set_trans_block_group(trans, inode);
4383 ret = btrfs_update_inode(trans, root, inode);
4384 if (ret && ret == -ENOSPC) {
4385 /* whoops, lets try again with the full transaction */
4386 btrfs_end_transaction(trans, root);
4387 trans = btrfs_start_transaction(root, 1);
4388 if (IS_ERR(trans)) {
4389 if (printk_ratelimit()) {
4390 printk(KERN_ERR "btrfs: fail to "
4391 "dirty inode %lu error %ld\n",
4392 inode->i_ino, PTR_ERR(trans));
4396 btrfs_set_trans_block_group(trans, inode);
4398 ret = btrfs_update_inode(trans, root, inode);
4400 if (printk_ratelimit()) {
4401 printk(KERN_ERR "btrfs: fail to "
4402 "dirty inode %lu error %d\n",
4407 btrfs_end_transaction(trans, root);
4411 * find the highest existing sequence number in a directory
4412 * and then set the in-memory index_cnt variable to reflect
4413 * free sequence numbers
4415 static int btrfs_set_inode_index_count(struct inode *inode)
4417 struct btrfs_root *root = BTRFS_I(inode)->root;
4418 struct btrfs_key key, found_key;
4419 struct btrfs_path *path;
4420 struct extent_buffer *leaf;
4423 key.objectid = inode->i_ino;
4424 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4425 key.offset = (u64)-1;
4427 path = btrfs_alloc_path();
4431 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4434 /* FIXME: we should be able to handle this */
4440 * MAGIC NUMBER EXPLANATION:
4441 * since we search a directory based on f_pos we have to start at 2
4442 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4443 * else has to start at 2
4445 if (path->slots[0] == 0) {
4446 BTRFS_I(inode)->index_cnt = 2;
4452 leaf = path->nodes[0];
4453 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4455 if (found_key.objectid != inode->i_ino ||
4456 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4457 BTRFS_I(inode)->index_cnt = 2;
4461 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4463 btrfs_free_path(path);
4468 * helper to find a free sequence number in a given directory. This current
4469 * code is very simple, later versions will do smarter things in the btree
4471 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4475 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4476 ret = btrfs_set_inode_index_count(dir);
4481 *index = BTRFS_I(dir)->index_cnt;
4482 BTRFS_I(dir)->index_cnt++;
4487 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4488 struct btrfs_root *root,
4490 const char *name, int name_len,
4491 u64 ref_objectid, u64 objectid,
4492 u64 alloc_hint, int mode, u64 *index)
4494 struct inode *inode;
4495 struct btrfs_inode_item *inode_item;
4496 struct btrfs_key *location;
4497 struct btrfs_path *path;
4498 struct btrfs_inode_ref *ref;
4499 struct btrfs_key key[2];
4505 path = btrfs_alloc_path();
4508 inode = new_inode(root->fs_info->sb);
4510 return ERR_PTR(-ENOMEM);
4513 ret = btrfs_set_inode_index(dir, index);
4516 return ERR_PTR(ret);
4520 * index_cnt is ignored for everything but a dir,
4521 * btrfs_get_inode_index_count has an explanation for the magic
4524 BTRFS_I(inode)->index_cnt = 2;
4525 BTRFS_I(inode)->root = root;
4526 BTRFS_I(inode)->generation = trans->transid;
4527 inode->i_generation = BTRFS_I(inode)->generation;
4528 btrfs_set_inode_space_info(root, inode);
4534 BTRFS_I(inode)->block_group =
4535 btrfs_find_block_group(root, 0, alloc_hint, owner);
4537 key[0].objectid = objectid;
4538 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4541 key[1].objectid = objectid;
4542 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4543 key[1].offset = ref_objectid;
4545 sizes[0] = sizeof(struct btrfs_inode_item);
4546 sizes[1] = name_len + sizeof(*ref);
4548 path->leave_spinning = 1;
4549 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4553 inode_init_owner(inode, dir, mode);
4554 inode->i_ino = objectid;
4555 inode_set_bytes(inode, 0);
4556 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4557 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4558 struct btrfs_inode_item);
4559 fill_inode_item(trans, path->nodes[0], inode_item, inode);
4561 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4562 struct btrfs_inode_ref);
4563 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4564 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4565 ptr = (unsigned long)(ref + 1);
4566 write_extent_buffer(path->nodes[0], name, ptr, name_len);
4568 btrfs_mark_buffer_dirty(path->nodes[0]);
4569 btrfs_free_path(path);
4571 location = &BTRFS_I(inode)->location;
4572 location->objectid = objectid;
4573 location->offset = 0;
4574 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4576 btrfs_inherit_iflags(inode, dir);
4578 if ((mode & S_IFREG)) {
4579 if (btrfs_test_opt(root, NODATASUM))
4580 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4581 if (btrfs_test_opt(root, NODATACOW))
4582 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4585 insert_inode_hash(inode);
4586 inode_tree_add(inode);
4590 BTRFS_I(dir)->index_cnt--;
4591 btrfs_free_path(path);
4593 return ERR_PTR(ret);
4596 static inline u8 btrfs_inode_type(struct inode *inode)
4598 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4602 * utility function to add 'inode' into 'parent_inode' with
4603 * a give name and a given sequence number.
4604 * if 'add_backref' is true, also insert a backref from the
4605 * inode to the parent directory.
4607 int btrfs_add_link(struct btrfs_trans_handle *trans,
4608 struct inode *parent_inode, struct inode *inode,
4609 const char *name, int name_len, int add_backref, u64 index)
4612 struct btrfs_key key;
4613 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4615 if (unlikely(inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4616 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4618 key.objectid = inode->i_ino;
4619 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4623 if (unlikely(inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4624 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4625 key.objectid, root->root_key.objectid,
4626 parent_inode->i_ino,
4627 index, name, name_len);
4628 } else if (add_backref) {
4629 ret = btrfs_insert_inode_ref(trans, root,
4630 name, name_len, inode->i_ino,
4631 parent_inode->i_ino, index);
4635 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4636 parent_inode->i_ino, &key,
4637 btrfs_inode_type(inode), index);
4640 btrfs_i_size_write(parent_inode, parent_inode->i_size +
4642 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4643 ret = btrfs_update_inode(trans, root, parent_inode);
4648 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4649 struct inode *dir, struct dentry *dentry,
4650 struct inode *inode, int backref, u64 index)
4652 int err = btrfs_add_link(trans, dir, inode,
4653 dentry->d_name.name, dentry->d_name.len,
4656 d_instantiate(dentry, inode);
4664 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4665 int mode, dev_t rdev)
4667 struct btrfs_trans_handle *trans;
4668 struct btrfs_root *root = BTRFS_I(dir)->root;
4669 struct inode *inode = NULL;
4673 unsigned long nr = 0;
4676 if (!new_valid_dev(rdev))
4679 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4684 * 2 for inode item and ref
4686 * 1 for xattr if selinux is on
4688 trans = btrfs_start_transaction(root, 5);
4690 return PTR_ERR(trans);
4692 btrfs_set_trans_block_group(trans, dir);
4694 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4695 dentry->d_name.len, dir->i_ino, objectid,
4696 BTRFS_I(dir)->block_group, mode, &index);
4697 err = PTR_ERR(inode);
4701 err = btrfs_init_inode_security(trans, inode, dir);
4707 btrfs_set_trans_block_group(trans, inode);
4708 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4712 inode->i_op = &btrfs_special_inode_operations;
4713 init_special_inode(inode, inode->i_mode, rdev);
4714 btrfs_update_inode(trans, root, inode);
4716 btrfs_update_inode_block_group(trans, inode);
4717 btrfs_update_inode_block_group(trans, dir);
4719 nr = trans->blocks_used;
4720 btrfs_end_transaction_throttle(trans, root);
4721 btrfs_btree_balance_dirty(root, nr);
4723 inode_dec_link_count(inode);
4729 static int btrfs_create(struct inode *dir, struct dentry *dentry,
4730 int mode, struct nameidata *nd)
4732 struct btrfs_trans_handle *trans;
4733 struct btrfs_root *root = BTRFS_I(dir)->root;
4734 struct inode *inode = NULL;
4737 unsigned long nr = 0;
4741 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4745 * 2 for inode item and ref
4747 * 1 for xattr if selinux is on
4749 trans = btrfs_start_transaction(root, 5);
4751 return PTR_ERR(trans);
4753 btrfs_set_trans_block_group(trans, dir);
4755 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4756 dentry->d_name.len, dir->i_ino, objectid,
4757 BTRFS_I(dir)->block_group, mode, &index);
4758 err = PTR_ERR(inode);
4762 err = btrfs_init_inode_security(trans, inode, dir);
4768 btrfs_set_trans_block_group(trans, inode);
4769 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4773 inode->i_mapping->a_ops = &btrfs_aops;
4774 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4775 inode->i_fop = &btrfs_file_operations;
4776 inode->i_op = &btrfs_file_inode_operations;
4777 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
4779 btrfs_update_inode_block_group(trans, inode);
4780 btrfs_update_inode_block_group(trans, dir);
4782 nr = trans->blocks_used;
4783 btrfs_end_transaction_throttle(trans, root);
4785 inode_dec_link_count(inode);
4788 btrfs_btree_balance_dirty(root, nr);
4792 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
4793 struct dentry *dentry)
4795 struct btrfs_trans_handle *trans;
4796 struct btrfs_root *root = BTRFS_I(dir)->root;
4797 struct inode *inode = old_dentry->d_inode;
4799 unsigned long nr = 0;
4803 if (inode->i_nlink == 0)
4806 /* do not allow sys_link's with other subvols of the same device */
4807 if (root->objectid != BTRFS_I(inode)->root->objectid)
4810 btrfs_inc_nlink(inode);
4811 inode->i_ctime = CURRENT_TIME;
4813 err = btrfs_set_inode_index(dir, &index);
4818 * 2 items for inode and inode ref
4819 * 2 items for dir items
4820 * 1 item for parent inode
4822 trans = btrfs_start_transaction(root, 5);
4823 if (IS_ERR(trans)) {
4824 err = PTR_ERR(trans);
4828 btrfs_set_trans_block_group(trans, dir);
4831 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
4836 struct dentry *parent = dget_parent(dentry);
4837 btrfs_update_inode_block_group(trans, dir);
4838 err = btrfs_update_inode(trans, root, inode);
4840 btrfs_log_new_name(trans, inode, NULL, parent);
4844 nr = trans->blocks_used;
4845 btrfs_end_transaction_throttle(trans, root);
4848 inode_dec_link_count(inode);
4851 btrfs_btree_balance_dirty(root, nr);
4855 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
4857 struct inode *inode = NULL;
4858 struct btrfs_trans_handle *trans;
4859 struct btrfs_root *root = BTRFS_I(dir)->root;
4861 int drop_on_err = 0;
4864 unsigned long nr = 1;
4866 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4871 * 2 items for inode and ref
4872 * 2 items for dir items
4873 * 1 for xattr if selinux is on
4875 trans = btrfs_start_transaction(root, 5);
4877 return PTR_ERR(trans);
4878 btrfs_set_trans_block_group(trans, dir);
4880 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4881 dentry->d_name.len, dir->i_ino, objectid,
4882 BTRFS_I(dir)->block_group, S_IFDIR | mode,
4884 if (IS_ERR(inode)) {
4885 err = PTR_ERR(inode);
4891 err = btrfs_init_inode_security(trans, inode, dir);
4895 inode->i_op = &btrfs_dir_inode_operations;
4896 inode->i_fop = &btrfs_dir_file_operations;
4897 btrfs_set_trans_block_group(trans, inode);
4899 btrfs_i_size_write(inode, 0);
4900 err = btrfs_update_inode(trans, root, inode);
4904 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
4905 dentry->d_name.len, 0, index);
4909 d_instantiate(dentry, inode);
4911 btrfs_update_inode_block_group(trans, inode);
4912 btrfs_update_inode_block_group(trans, dir);
4915 nr = trans->blocks_used;
4916 btrfs_end_transaction_throttle(trans, root);
4919 btrfs_btree_balance_dirty(root, nr);
4923 /* helper for btfs_get_extent. Given an existing extent in the tree,
4924 * and an extent that you want to insert, deal with overlap and insert
4925 * the new extent into the tree.
4927 static int merge_extent_mapping(struct extent_map_tree *em_tree,
4928 struct extent_map *existing,
4929 struct extent_map *em,
4930 u64 map_start, u64 map_len)
4934 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
4935 start_diff = map_start - em->start;
4936 em->start = map_start;
4938 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
4939 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
4940 em->block_start += start_diff;
4941 em->block_len -= start_diff;
4943 return add_extent_mapping(em_tree, em);
4946 static noinline int uncompress_inline(struct btrfs_path *path,
4947 struct inode *inode, struct page *page,
4948 size_t pg_offset, u64 extent_offset,
4949 struct btrfs_file_extent_item *item)
4952 struct extent_buffer *leaf = path->nodes[0];
4955 unsigned long inline_size;
4959 WARN_ON(pg_offset != 0);
4960 compress_type = btrfs_file_extent_compression(leaf, item);
4961 max_size = btrfs_file_extent_ram_bytes(leaf, item);
4962 inline_size = btrfs_file_extent_inline_item_len(leaf,
4963 btrfs_item_nr(leaf, path->slots[0]));
4964 tmp = kmalloc(inline_size, GFP_NOFS);
4965 ptr = btrfs_file_extent_inline_start(item);
4967 read_extent_buffer(leaf, tmp, ptr, inline_size);
4969 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
4970 ret = btrfs_decompress(compress_type, tmp, page,
4971 extent_offset, inline_size, max_size);
4973 char *kaddr = kmap_atomic(page, KM_USER0);
4974 unsigned long copy_size = min_t(u64,
4975 PAGE_CACHE_SIZE - pg_offset,
4976 max_size - extent_offset);
4977 memset(kaddr + pg_offset, 0, copy_size);
4978 kunmap_atomic(kaddr, KM_USER0);
4985 * a bit scary, this does extent mapping from logical file offset to the disk.
4986 * the ugly parts come from merging extents from the disk with the in-ram
4987 * representation. This gets more complex because of the data=ordered code,
4988 * where the in-ram extents might be locked pending data=ordered completion.
4990 * This also copies inline extents directly into the page.
4993 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
4994 size_t pg_offset, u64 start, u64 len,
5000 u64 extent_start = 0;
5002 u64 objectid = inode->i_ino;
5004 struct btrfs_path *path = NULL;
5005 struct btrfs_root *root = BTRFS_I(inode)->root;
5006 struct btrfs_file_extent_item *item;
5007 struct extent_buffer *leaf;
5008 struct btrfs_key found_key;
5009 struct extent_map *em = NULL;
5010 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5011 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5012 struct btrfs_trans_handle *trans = NULL;
5016 read_lock(&em_tree->lock);
5017 em = lookup_extent_mapping(em_tree, start, len);
5019 em->bdev = root->fs_info->fs_devices->latest_bdev;
5020 read_unlock(&em_tree->lock);
5023 if (em->start > start || em->start + em->len <= start)
5024 free_extent_map(em);
5025 else if (em->block_start == EXTENT_MAP_INLINE && page)
5026 free_extent_map(em);
5030 em = alloc_extent_map(GFP_NOFS);
5035 em->bdev = root->fs_info->fs_devices->latest_bdev;
5036 em->start = EXTENT_MAP_HOLE;
5037 em->orig_start = EXTENT_MAP_HOLE;
5039 em->block_len = (u64)-1;
5042 path = btrfs_alloc_path();
5046 ret = btrfs_lookup_file_extent(trans, root, path,
5047 objectid, start, trans != NULL);
5054 if (path->slots[0] == 0)
5059 leaf = path->nodes[0];
5060 item = btrfs_item_ptr(leaf, path->slots[0],
5061 struct btrfs_file_extent_item);
5062 /* are we inside the extent that was found? */
5063 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5064 found_type = btrfs_key_type(&found_key);
5065 if (found_key.objectid != objectid ||
5066 found_type != BTRFS_EXTENT_DATA_KEY) {
5070 found_type = btrfs_file_extent_type(leaf, item);
5071 extent_start = found_key.offset;
5072 compress_type = btrfs_file_extent_compression(leaf, item);
5073 if (found_type == BTRFS_FILE_EXTENT_REG ||
5074 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5075 extent_end = extent_start +
5076 btrfs_file_extent_num_bytes(leaf, item);
5077 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5079 size = btrfs_file_extent_inline_len(leaf, item);
5080 extent_end = (extent_start + size + root->sectorsize - 1) &
5081 ~((u64)root->sectorsize - 1);
5084 if (start >= extent_end) {
5086 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
5087 ret = btrfs_next_leaf(root, path);
5094 leaf = path->nodes[0];
5096 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5097 if (found_key.objectid != objectid ||
5098 found_key.type != BTRFS_EXTENT_DATA_KEY)
5100 if (start + len <= found_key.offset)
5103 em->len = found_key.offset - start;
5107 if (found_type == BTRFS_FILE_EXTENT_REG ||
5108 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5109 em->start = extent_start;
5110 em->len = extent_end - extent_start;
5111 em->orig_start = extent_start -
5112 btrfs_file_extent_offset(leaf, item);
5113 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5115 em->block_start = EXTENT_MAP_HOLE;
5118 if (compress_type != BTRFS_COMPRESS_NONE) {
5119 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5120 em->compress_type = compress_type;
5121 em->block_start = bytenr;
5122 em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
5125 bytenr += btrfs_file_extent_offset(leaf, item);
5126 em->block_start = bytenr;
5127 em->block_len = em->len;
5128 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5129 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5132 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5136 size_t extent_offset;
5139 em->block_start = EXTENT_MAP_INLINE;
5140 if (!page || create) {
5141 em->start = extent_start;
5142 em->len = extent_end - extent_start;
5146 size = btrfs_file_extent_inline_len(leaf, item);
5147 extent_offset = page_offset(page) + pg_offset - extent_start;
5148 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
5149 size - extent_offset);
5150 em->start = extent_start + extent_offset;
5151 em->len = (copy_size + root->sectorsize - 1) &
5152 ~((u64)root->sectorsize - 1);
5153 em->orig_start = EXTENT_MAP_INLINE;
5154 if (compress_type) {
5155 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5156 em->compress_type = compress_type;
5158 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5159 if (create == 0 && !PageUptodate(page)) {
5160 if (btrfs_file_extent_compression(leaf, item) !=
5161 BTRFS_COMPRESS_NONE) {
5162 ret = uncompress_inline(path, inode, page,
5164 extent_offset, item);
5168 read_extent_buffer(leaf, map + pg_offset, ptr,
5170 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5171 memset(map + pg_offset + copy_size, 0,
5172 PAGE_CACHE_SIZE - pg_offset -
5177 flush_dcache_page(page);
5178 } else if (create && PageUptodate(page)) {
5182 free_extent_map(em);
5184 btrfs_release_path(root, path);
5185 trans = btrfs_join_transaction(root, 1);
5187 return ERR_CAST(trans);
5191 write_extent_buffer(leaf, map + pg_offset, ptr,
5194 btrfs_mark_buffer_dirty(leaf);
5196 set_extent_uptodate(io_tree, em->start,
5197 extent_map_end(em) - 1, GFP_NOFS);
5200 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
5207 em->block_start = EXTENT_MAP_HOLE;
5208 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5210 btrfs_release_path(root, path);
5211 if (em->start > start || extent_map_end(em) <= start) {
5212 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5213 "[%llu %llu]\n", (unsigned long long)em->start,
5214 (unsigned long long)em->len,
5215 (unsigned long long)start,
5216 (unsigned long long)len);
5222 write_lock(&em_tree->lock);
5223 ret = add_extent_mapping(em_tree, em);
5224 /* it is possible that someone inserted the extent into the tree
5225 * while we had the lock dropped. It is also possible that
5226 * an overlapping map exists in the tree
5228 if (ret == -EEXIST) {
5229 struct extent_map *existing;
5233 existing = lookup_extent_mapping(em_tree, start, len);
5234 if (existing && (existing->start > start ||
5235 existing->start + existing->len <= start)) {
5236 free_extent_map(existing);
5240 existing = lookup_extent_mapping(em_tree, em->start,
5243 err = merge_extent_mapping(em_tree, existing,
5246 free_extent_map(existing);
5248 free_extent_map(em);
5253 free_extent_map(em);
5257 free_extent_map(em);
5262 write_unlock(&em_tree->lock);
5265 btrfs_free_path(path);
5267 ret = btrfs_end_transaction(trans, root);
5272 free_extent_map(em);
5273 return ERR_PTR(err);
5278 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
5279 size_t pg_offset, u64 start, u64 len,
5282 struct extent_map *em;
5283 struct extent_map *hole_em = NULL;
5284 u64 range_start = start;
5290 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
5295 * if our em maps to a hole, there might
5296 * actually be delalloc bytes behind it
5298 if (em->block_start != EXTENT_MAP_HOLE)
5304 /* check to see if we've wrapped (len == -1 or similar) */
5313 /* ok, we didn't find anything, lets look for delalloc */
5314 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
5315 end, len, EXTENT_DELALLOC, 1);
5316 found_end = range_start + found;
5317 if (found_end < range_start)
5318 found_end = (u64)-1;
5321 * we didn't find anything useful, return
5322 * the original results from get_extent()
5324 if (range_start > end || found_end <= start) {
5330 /* adjust the range_start to make sure it doesn't
5331 * go backwards from the start they passed in
5333 range_start = max(start,range_start);
5334 found = found_end - range_start;
5337 u64 hole_start = start;
5340 em = alloc_extent_map(GFP_NOFS);
5346 * when btrfs_get_extent can't find anything it
5347 * returns one huge hole
5349 * make sure what it found really fits our range, and
5350 * adjust to make sure it is based on the start from
5354 u64 calc_end = extent_map_end(hole_em);
5356 if (calc_end <= start || (hole_em->start > end)) {
5357 free_extent_map(hole_em);
5360 hole_start = max(hole_em->start, start);
5361 hole_len = calc_end - hole_start;
5365 if (hole_em && range_start > hole_start) {
5366 /* our hole starts before our delalloc, so we
5367 * have to return just the parts of the hole
5368 * that go until the delalloc starts
5370 em->len = min(hole_len,
5371 range_start - hole_start);
5372 em->start = hole_start;
5373 em->orig_start = hole_start;
5375 * don't adjust block start at all,
5376 * it is fixed at EXTENT_MAP_HOLE
5378 em->block_start = hole_em->block_start;
5379 em->block_len = hole_len;
5381 em->start = range_start;
5383 em->orig_start = range_start;
5384 em->block_start = EXTENT_MAP_DELALLOC;
5385 em->block_len = found;
5387 } else if (hole_em) {
5392 free_extent_map(hole_em);
5394 free_extent_map(em);
5395 return ERR_PTR(err);
5400 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5403 struct btrfs_root *root = BTRFS_I(inode)->root;
5404 struct btrfs_trans_handle *trans;
5405 struct extent_map *em;
5406 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5407 struct btrfs_key ins;
5411 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
5413 trans = btrfs_join_transaction(root, 0);
5415 return ERR_CAST(trans);
5417 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5419 alloc_hint = get_extent_allocation_hint(inode, start, len);
5420 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5421 alloc_hint, (u64)-1, &ins, 1);
5427 em = alloc_extent_map(GFP_NOFS);
5429 em = ERR_PTR(-ENOMEM);
5434 em->orig_start = em->start;
5435 em->len = ins.offset;
5437 em->block_start = ins.objectid;
5438 em->block_len = ins.offset;
5439 em->bdev = root->fs_info->fs_devices->latest_bdev;
5440 set_bit(EXTENT_FLAG_PINNED, &em->flags);
5443 write_lock(&em_tree->lock);
5444 ret = add_extent_mapping(em_tree, em);
5445 write_unlock(&em_tree->lock);
5448 btrfs_drop_extent_cache(inode, start, start + em->len - 1, 0);
5451 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5452 ins.offset, ins.offset, 0);
5454 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5458 btrfs_end_transaction(trans, root);
5463 * returns 1 when the nocow is safe, < 1 on error, 0 if the
5464 * block must be cow'd
5466 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5467 struct inode *inode, u64 offset, u64 len)
5469 struct btrfs_path *path;
5471 struct extent_buffer *leaf;
5472 struct btrfs_root *root = BTRFS_I(inode)->root;
5473 struct btrfs_file_extent_item *fi;
5474 struct btrfs_key key;
5482 path = btrfs_alloc_path();
5486 ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
5491 slot = path->slots[0];
5494 /* can't find the item, must cow */
5501 leaf = path->nodes[0];
5502 btrfs_item_key_to_cpu(leaf, &key, slot);
5503 if (key.objectid != inode->i_ino ||
5504 key.type != BTRFS_EXTENT_DATA_KEY) {
5505 /* not our file or wrong item type, must cow */
5509 if (key.offset > offset) {
5510 /* Wrong offset, must cow */
5514 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5515 found_type = btrfs_file_extent_type(leaf, fi);
5516 if (found_type != BTRFS_FILE_EXTENT_REG &&
5517 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5518 /* not a regular extent, must cow */
5521 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5522 backref_offset = btrfs_file_extent_offset(leaf, fi);
5524 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5525 if (extent_end < offset + len) {
5526 /* extent doesn't include our full range, must cow */
5530 if (btrfs_extent_readonly(root, disk_bytenr))
5534 * look for other files referencing this extent, if we
5535 * find any we must cow
5537 if (btrfs_cross_ref_exist(trans, root, inode->i_ino,
5538 key.offset - backref_offset, disk_bytenr))
5542 * adjust disk_bytenr and num_bytes to cover just the bytes
5543 * in this extent we are about to write. If there
5544 * are any csums in that range we have to cow in order
5545 * to keep the csums correct
5547 disk_bytenr += backref_offset;
5548 disk_bytenr += offset - key.offset;
5549 num_bytes = min(offset + len, extent_end) - offset;
5550 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5553 * all of the above have passed, it is safe to overwrite this extent
5558 btrfs_free_path(path);
5562 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
5563 struct buffer_head *bh_result, int create)
5565 struct extent_map *em;
5566 struct btrfs_root *root = BTRFS_I(inode)->root;
5567 u64 start = iblock << inode->i_blkbits;
5568 u64 len = bh_result->b_size;
5569 struct btrfs_trans_handle *trans;
5571 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
5576 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
5577 * io. INLINE is special, and we could probably kludge it in here, but
5578 * it's still buffered so for safety lets just fall back to the generic
5581 * For COMPRESSED we _have_ to read the entire extent in so we can
5582 * decompress it, so there will be buffering required no matter what we
5583 * do, so go ahead and fallback to buffered.
5585 * We return -ENOTBLK because thats what makes DIO go ahead and go back
5586 * to buffered IO. Don't blame me, this is the price we pay for using
5589 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
5590 em->block_start == EXTENT_MAP_INLINE) {
5591 free_extent_map(em);
5595 /* Just a good old fashioned hole, return */
5596 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
5597 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
5598 free_extent_map(em);
5599 /* DIO will do one hole at a time, so just unlock a sector */
5600 unlock_extent(&BTRFS_I(inode)->io_tree, start,
5601 start + root->sectorsize - 1, GFP_NOFS);
5606 * We don't allocate a new extent in the following cases
5608 * 1) The inode is marked as NODATACOW. In this case we'll just use the
5610 * 2) The extent is marked as PREALLOC. We're good to go here and can
5611 * just use the extent.
5615 len = em->len - (start - em->start);
5619 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
5620 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
5621 em->block_start != EXTENT_MAP_HOLE)) {
5626 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5627 type = BTRFS_ORDERED_PREALLOC;
5629 type = BTRFS_ORDERED_NOCOW;
5630 len = min(len, em->len - (start - em->start));
5631 block_start = em->block_start + (start - em->start);
5634 * we're not going to log anything, but we do need
5635 * to make sure the current transaction stays open
5636 * while we look for nocow cross refs
5638 trans = btrfs_join_transaction(root, 0);
5642 if (can_nocow_odirect(trans, inode, start, len) == 1) {
5643 ret = btrfs_add_ordered_extent_dio(inode, start,
5644 block_start, len, len, type);
5645 btrfs_end_transaction(trans, root);
5647 free_extent_map(em);
5652 btrfs_end_transaction(trans, root);
5656 * this will cow the extent, reset the len in case we changed
5659 len = bh_result->b_size;
5660 free_extent_map(em);
5661 em = btrfs_new_extent_direct(inode, start, len);
5664 len = min(len, em->len - (start - em->start));
5666 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, start + len - 1,
5667 EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DIRTY, 1,
5670 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
5672 bh_result->b_size = len;
5673 bh_result->b_bdev = em->bdev;
5674 set_buffer_mapped(bh_result);
5675 if (create && !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5676 set_buffer_new(bh_result);
5678 free_extent_map(em);
5683 struct btrfs_dio_private {
5684 struct inode *inode;
5691 /* number of bios pending for this dio */
5692 atomic_t pending_bios;
5697 struct bio *orig_bio;
5700 static void btrfs_endio_direct_read(struct bio *bio, int err)
5702 struct btrfs_dio_private *dip = bio->bi_private;
5703 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
5704 struct bio_vec *bvec = bio->bi_io_vec;
5705 struct inode *inode = dip->inode;
5706 struct btrfs_root *root = BTRFS_I(inode)->root;
5708 u32 *private = dip->csums;
5710 start = dip->logical_offset;
5712 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
5713 struct page *page = bvec->bv_page;
5716 unsigned long flags;
5718 local_irq_save(flags);
5719 kaddr = kmap_atomic(page, KM_IRQ0);
5720 csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
5721 csum, bvec->bv_len);
5722 btrfs_csum_final(csum, (char *)&csum);
5723 kunmap_atomic(kaddr, KM_IRQ0);
5724 local_irq_restore(flags);
5726 flush_dcache_page(bvec->bv_page);
5727 if (csum != *private) {
5728 printk(KERN_ERR "btrfs csum failed ino %lu off"
5729 " %llu csum %u private %u\n",
5730 inode->i_ino, (unsigned long long)start,
5736 start += bvec->bv_len;
5739 } while (bvec <= bvec_end);
5741 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
5742 dip->logical_offset + dip->bytes - 1, GFP_NOFS);
5743 bio->bi_private = dip->private;
5747 dio_end_io(bio, err);
5750 static void btrfs_endio_direct_write(struct bio *bio, int err)
5752 struct btrfs_dio_private *dip = bio->bi_private;
5753 struct inode *inode = dip->inode;
5754 struct btrfs_root *root = BTRFS_I(inode)->root;
5755 struct btrfs_trans_handle *trans;
5756 struct btrfs_ordered_extent *ordered = NULL;
5757 struct extent_state *cached_state = NULL;
5758 u64 ordered_offset = dip->logical_offset;
5759 u64 ordered_bytes = dip->bytes;
5765 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
5773 trans = btrfs_join_transaction(root, 1);
5774 if (IS_ERR(trans)) {
5778 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5780 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) {
5781 ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5783 ret = btrfs_update_inode(trans, root, inode);
5788 lock_extent_bits(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5789 ordered->file_offset + ordered->len - 1, 0,
5790 &cached_state, GFP_NOFS);
5792 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags)) {
5793 ret = btrfs_mark_extent_written(trans, inode,
5794 ordered->file_offset,
5795 ordered->file_offset +
5802 ret = insert_reserved_file_extent(trans, inode,
5803 ordered->file_offset,
5809 BTRFS_FILE_EXTENT_REG);
5810 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
5811 ordered->file_offset, ordered->len);
5819 add_pending_csums(trans, inode, ordered->file_offset, &ordered->list);
5820 btrfs_ordered_update_i_size(inode, 0, ordered);
5821 btrfs_update_inode(trans, root, inode);
5823 unlock_extent_cached(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5824 ordered->file_offset + ordered->len - 1,
5825 &cached_state, GFP_NOFS);
5827 btrfs_delalloc_release_metadata(inode, ordered->len);
5828 btrfs_end_transaction(trans, root);
5829 ordered_offset = ordered->file_offset + ordered->len;
5830 btrfs_put_ordered_extent(ordered);
5831 btrfs_put_ordered_extent(ordered);
5835 * our bio might span multiple ordered extents. If we haven't
5836 * completed the accounting for the whole dio, go back and try again
5838 if (ordered_offset < dip->logical_offset + dip->bytes) {
5839 ordered_bytes = dip->logical_offset + dip->bytes -
5844 bio->bi_private = dip->private;
5848 dio_end_io(bio, err);
5851 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
5852 struct bio *bio, int mirror_num,
5853 unsigned long bio_flags, u64 offset)
5856 struct btrfs_root *root = BTRFS_I(inode)->root;
5857 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
5862 static void btrfs_end_dio_bio(struct bio *bio, int err)
5864 struct btrfs_dio_private *dip = bio->bi_private;
5867 printk(KERN_ERR "btrfs direct IO failed ino %lu rw %lu "
5868 "sector %#Lx len %u err no %d\n",
5869 dip->inode->i_ino, bio->bi_rw,
5870 (unsigned long long)bio->bi_sector, bio->bi_size, err);
5874 * before atomic variable goto zero, we must make sure
5875 * dip->errors is perceived to be set.
5877 smp_mb__before_atomic_dec();
5880 /* if there are more bios still pending for this dio, just exit */
5881 if (!atomic_dec_and_test(&dip->pending_bios))
5885 bio_io_error(dip->orig_bio);
5887 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
5888 bio_endio(dip->orig_bio, 0);
5894 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
5895 u64 first_sector, gfp_t gfp_flags)
5897 int nr_vecs = bio_get_nr_vecs(bdev);
5898 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
5901 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
5902 int rw, u64 file_offset, int skip_sum,
5905 int write = rw & REQ_WRITE;
5906 struct btrfs_root *root = BTRFS_I(inode)->root;
5910 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
5914 if (write && !skip_sum) {
5915 ret = btrfs_wq_submit_bio(root->fs_info,
5916 inode, rw, bio, 0, 0,
5918 __btrfs_submit_bio_start_direct_io,
5919 __btrfs_submit_bio_done);
5921 } else if (!skip_sum)
5922 btrfs_lookup_bio_sums_dio(root, inode, bio,
5923 file_offset, csums);
5925 ret = btrfs_map_bio(root, rw, bio, 0, 1);
5931 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
5934 struct inode *inode = dip->inode;
5935 struct btrfs_root *root = BTRFS_I(inode)->root;
5936 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
5938 struct bio *orig_bio = dip->orig_bio;
5939 struct bio_vec *bvec = orig_bio->bi_io_vec;
5940 u64 start_sector = orig_bio->bi_sector;
5941 u64 file_offset = dip->logical_offset;
5945 u32 *csums = dip->csums;
5948 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
5951 bio->bi_private = dip;
5952 bio->bi_end_io = btrfs_end_dio_bio;
5953 atomic_inc(&dip->pending_bios);
5955 map_length = orig_bio->bi_size;
5956 ret = btrfs_map_block(map_tree, READ, start_sector << 9,
5957 &map_length, NULL, 0);
5963 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
5964 if (unlikely(map_length < submit_len + bvec->bv_len ||
5965 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
5966 bvec->bv_offset) < bvec->bv_len)) {
5968 * inc the count before we submit the bio so
5969 * we know the end IO handler won't happen before
5970 * we inc the count. Otherwise, the dip might get freed
5971 * before we're done setting it up
5973 atomic_inc(&dip->pending_bios);
5974 ret = __btrfs_submit_dio_bio(bio, inode, rw,
5975 file_offset, skip_sum,
5979 atomic_dec(&dip->pending_bios);
5984 csums = csums + nr_pages;
5985 start_sector += submit_len >> 9;
5986 file_offset += submit_len;
5991 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
5992 start_sector, GFP_NOFS);
5995 bio->bi_private = dip;
5996 bio->bi_end_io = btrfs_end_dio_bio;
5998 map_length = orig_bio->bi_size;
5999 ret = btrfs_map_block(map_tree, READ, start_sector << 9,
6000 &map_length, NULL, 0);
6006 submit_len += bvec->bv_len;
6012 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
6021 * before atomic variable goto zero, we must
6022 * make sure dip->errors is perceived to be set.
6024 smp_mb__before_atomic_dec();
6025 if (atomic_dec_and_test(&dip->pending_bios))
6026 bio_io_error(dip->orig_bio);
6028 /* bio_end_io() will handle error, so we needn't return it */
6032 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
6035 struct btrfs_root *root = BTRFS_I(inode)->root;
6036 struct btrfs_dio_private *dip;
6037 struct bio_vec *bvec = bio->bi_io_vec;
6039 int write = rw & REQ_WRITE;
6042 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
6044 dip = kmalloc(sizeof(*dip), GFP_NOFS);
6052 dip->csums = kmalloc(sizeof(u32) * bio->bi_vcnt, GFP_NOFS);
6060 dip->private = bio->bi_private;
6062 dip->logical_offset = file_offset;
6066 dip->bytes += bvec->bv_len;
6068 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
6070 dip->disk_bytenr = (u64)bio->bi_sector << 9;
6071 bio->bi_private = dip;
6073 dip->orig_bio = bio;
6074 atomic_set(&dip->pending_bios, 0);
6077 bio->bi_end_io = btrfs_endio_direct_write;
6079 bio->bi_end_io = btrfs_endio_direct_read;
6081 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
6086 * If this is a write, we need to clean up the reserved space and kill
6087 * the ordered extent.
6090 struct btrfs_ordered_extent *ordered;
6091 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
6092 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
6093 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
6094 btrfs_free_reserved_extent(root, ordered->start,
6096 btrfs_put_ordered_extent(ordered);
6097 btrfs_put_ordered_extent(ordered);
6099 bio_endio(bio, ret);
6102 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
6103 const struct iovec *iov, loff_t offset,
6104 unsigned long nr_segs)
6109 unsigned blocksize_mask = root->sectorsize - 1;
6110 ssize_t retval = -EINVAL;
6111 loff_t end = offset;
6113 if (offset & blocksize_mask)
6116 /* Check the memory alignment. Blocks cannot straddle pages */
6117 for (seg = 0; seg < nr_segs; seg++) {
6118 addr = (unsigned long)iov[seg].iov_base;
6119 size = iov[seg].iov_len;
6121 if ((addr & blocksize_mask) || (size & blocksize_mask))
6128 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
6129 const struct iovec *iov, loff_t offset,
6130 unsigned long nr_segs)
6132 struct file *file = iocb->ki_filp;
6133 struct inode *inode = file->f_mapping->host;
6134 struct btrfs_ordered_extent *ordered;
6135 struct extent_state *cached_state = NULL;
6136 u64 lockstart, lockend;
6138 int writing = rw & WRITE;
6140 size_t count = iov_length(iov, nr_segs);
6142 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
6148 lockend = offset + count - 1;
6151 ret = btrfs_delalloc_reserve_space(inode, count);
6157 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6158 0, &cached_state, GFP_NOFS);
6160 * We're concerned with the entire range that we're going to be
6161 * doing DIO to, so we need to make sure theres no ordered
6162 * extents in this range.
6164 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6165 lockend - lockstart + 1);
6168 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6169 &cached_state, GFP_NOFS);
6170 btrfs_start_ordered_extent(inode, ordered, 1);
6171 btrfs_put_ordered_extent(ordered);
6176 * we don't use btrfs_set_extent_delalloc because we don't want
6177 * the dirty or uptodate bits
6180 write_bits = EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING;
6181 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6182 EXTENT_DELALLOC, 0, NULL, &cached_state,
6185 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6186 lockend, EXTENT_LOCKED | write_bits,
6187 1, 0, &cached_state, GFP_NOFS);
6192 free_extent_state(cached_state);
6193 cached_state = NULL;
6195 ret = __blockdev_direct_IO(rw, iocb, inode,
6196 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
6197 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
6198 btrfs_submit_direct, 0);
6200 if (ret < 0 && ret != -EIOCBQUEUED) {
6201 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset,
6202 offset + iov_length(iov, nr_segs) - 1,
6203 EXTENT_LOCKED | write_bits, 1, 0,
6204 &cached_state, GFP_NOFS);
6205 } else if (ret >= 0 && ret < iov_length(iov, nr_segs)) {
6207 * We're falling back to buffered, unlock the section we didn't
6210 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset + ret,
6211 offset + iov_length(iov, nr_segs) - 1,
6212 EXTENT_LOCKED | write_bits, 1, 0,
6213 &cached_state, GFP_NOFS);
6216 free_extent_state(cached_state);
6220 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
6221 __u64 start, __u64 len)
6223 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
6226 int btrfs_readpage(struct file *file, struct page *page)
6228 struct extent_io_tree *tree;
6229 tree = &BTRFS_I(page->mapping->host)->io_tree;
6230 return extent_read_full_page(tree, page, btrfs_get_extent);
6233 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
6235 struct extent_io_tree *tree;
6238 if (current->flags & PF_MEMALLOC) {
6239 redirty_page_for_writepage(wbc, page);
6243 tree = &BTRFS_I(page->mapping->host)->io_tree;
6244 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
6247 int btrfs_writepages(struct address_space *mapping,
6248 struct writeback_control *wbc)
6250 struct extent_io_tree *tree;
6252 tree = &BTRFS_I(mapping->host)->io_tree;
6253 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
6257 btrfs_readpages(struct file *file, struct address_space *mapping,
6258 struct list_head *pages, unsigned nr_pages)
6260 struct extent_io_tree *tree;
6261 tree = &BTRFS_I(mapping->host)->io_tree;
6262 return extent_readpages(tree, mapping, pages, nr_pages,
6265 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6267 struct extent_io_tree *tree;
6268 struct extent_map_tree *map;
6271 tree = &BTRFS_I(page->mapping->host)->io_tree;
6272 map = &BTRFS_I(page->mapping->host)->extent_tree;
6273 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
6275 ClearPagePrivate(page);
6276 set_page_private(page, 0);
6277 page_cache_release(page);
6282 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6284 if (PageWriteback(page) || PageDirty(page))
6286 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
6289 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
6291 struct extent_io_tree *tree;
6292 struct btrfs_ordered_extent *ordered;
6293 struct extent_state *cached_state = NULL;
6294 u64 page_start = page_offset(page);
6295 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
6299 * we have the page locked, so new writeback can't start,
6300 * and the dirty bit won't be cleared while we are here.
6302 * Wait for IO on this page so that we can safely clear
6303 * the PagePrivate2 bit and do ordered accounting
6305 wait_on_page_writeback(page);
6307 tree = &BTRFS_I(page->mapping->host)->io_tree;
6309 btrfs_releasepage(page, GFP_NOFS);
6312 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6314 ordered = btrfs_lookup_ordered_extent(page->mapping->host,
6318 * IO on this page will never be started, so we need
6319 * to account for any ordered extents now
6321 clear_extent_bit(tree, page_start, page_end,
6322 EXTENT_DIRTY | EXTENT_DELALLOC |
6323 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
6324 &cached_state, GFP_NOFS);
6326 * whoever cleared the private bit is responsible
6327 * for the finish_ordered_io
6329 if (TestClearPagePrivate2(page)) {
6330 btrfs_finish_ordered_io(page->mapping->host,
6331 page_start, page_end);
6333 btrfs_put_ordered_extent(ordered);
6334 cached_state = NULL;
6335 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6338 clear_extent_bit(tree, page_start, page_end,
6339 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
6340 EXTENT_DO_ACCOUNTING, 1, 1, &cached_state, GFP_NOFS);
6341 __btrfs_releasepage(page, GFP_NOFS);
6343 ClearPageChecked(page);
6344 if (PagePrivate(page)) {
6345 ClearPagePrivate(page);
6346 set_page_private(page, 0);
6347 page_cache_release(page);
6352 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6353 * called from a page fault handler when a page is first dirtied. Hence we must
6354 * be careful to check for EOF conditions here. We set the page up correctly
6355 * for a written page which means we get ENOSPC checking when writing into
6356 * holes and correct delalloc and unwritten extent mapping on filesystems that
6357 * support these features.
6359 * We are not allowed to take the i_mutex here so we have to play games to
6360 * protect against truncate races as the page could now be beyond EOF. Because
6361 * vmtruncate() writes the inode size before removing pages, once we have the
6362 * page lock we can determine safely if the page is beyond EOF. If it is not
6363 * beyond EOF, then the page is guaranteed safe against truncation until we
6366 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
6368 struct page *page = vmf->page;
6369 struct inode *inode = fdentry(vma->vm_file)->d_inode;
6370 struct btrfs_root *root = BTRFS_I(inode)->root;
6371 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6372 struct btrfs_ordered_extent *ordered;
6373 struct extent_state *cached_state = NULL;
6375 unsigned long zero_start;
6381 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
6385 else /* -ENOSPC, -EIO, etc */
6386 ret = VM_FAULT_SIGBUS;
6390 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
6393 size = i_size_read(inode);
6394 page_start = page_offset(page);
6395 page_end = page_start + PAGE_CACHE_SIZE - 1;
6397 if ((page->mapping != inode->i_mapping) ||
6398 (page_start >= size)) {
6399 /* page got truncated out from underneath us */
6402 wait_on_page_writeback(page);
6404 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
6406 set_page_extent_mapped(page);
6409 * we can't set the delalloc bits if there are pending ordered
6410 * extents. Drop our locks and wait for them to finish
6412 ordered = btrfs_lookup_ordered_extent(inode, page_start);
6414 unlock_extent_cached(io_tree, page_start, page_end,
6415 &cached_state, GFP_NOFS);
6417 btrfs_start_ordered_extent(inode, ordered, 1);
6418 btrfs_put_ordered_extent(ordered);
6423 * XXX - page_mkwrite gets called every time the page is dirtied, even
6424 * if it was already dirty, so for space accounting reasons we need to
6425 * clear any delalloc bits for the range we are fixing to save. There
6426 * is probably a better way to do this, but for now keep consistent with
6427 * prepare_pages in the normal write path.
6429 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
6430 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
6431 0, 0, &cached_state, GFP_NOFS);
6433 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6436 unlock_extent_cached(io_tree, page_start, page_end,
6437 &cached_state, GFP_NOFS);
6438 ret = VM_FAULT_SIGBUS;
6443 /* page is wholly or partially inside EOF */
6444 if (page_start + PAGE_CACHE_SIZE > size)
6445 zero_start = size & ~PAGE_CACHE_MASK;
6447 zero_start = PAGE_CACHE_SIZE;
6449 if (zero_start != PAGE_CACHE_SIZE) {
6451 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6452 flush_dcache_page(page);
6455 ClearPageChecked(page);
6456 set_page_dirty(page);
6457 SetPageUptodate(page);
6459 BTRFS_I(inode)->last_trans = root->fs_info->generation;
6460 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6462 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
6466 return VM_FAULT_LOCKED;
6468 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
6473 static int btrfs_truncate(struct inode *inode)
6475 struct btrfs_root *root = BTRFS_I(inode)->root;
6478 struct btrfs_trans_handle *trans;
6480 u64 mask = root->sectorsize - 1;
6482 ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
6486 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
6487 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
6489 trans = btrfs_start_transaction(root, 5);
6491 return PTR_ERR(trans);
6493 btrfs_set_trans_block_group(trans, inode);
6495 ret = btrfs_orphan_add(trans, inode);
6497 btrfs_end_transaction(trans, root);
6501 nr = trans->blocks_used;
6502 btrfs_end_transaction(trans, root);
6503 btrfs_btree_balance_dirty(root, nr);
6505 /* Now start a transaction for the truncate */
6506 trans = btrfs_start_transaction(root, 0);
6508 return PTR_ERR(trans);
6509 btrfs_set_trans_block_group(trans, inode);
6510 trans->block_rsv = root->orphan_block_rsv;
6513 * setattr is responsible for setting the ordered_data_close flag,
6514 * but that is only tested during the last file release. That
6515 * could happen well after the next commit, leaving a great big
6516 * window where new writes may get lost if someone chooses to write
6517 * to this file after truncating to zero
6519 * The inode doesn't have any dirty data here, and so if we commit
6520 * this is a noop. If someone immediately starts writing to the inode
6521 * it is very likely we'll catch some of their writes in this
6522 * transaction, and the commit will find this file on the ordered
6523 * data list with good things to send down.
6525 * This is a best effort solution, there is still a window where
6526 * using truncate to replace the contents of the file will
6527 * end up with a zero length file after a crash.
6529 if (inode->i_size == 0 && BTRFS_I(inode)->ordered_data_close)
6530 btrfs_add_ordered_operation(trans, root, inode);
6534 trans = btrfs_start_transaction(root, 0);
6536 return PTR_ERR(trans);
6537 btrfs_set_trans_block_group(trans, inode);
6538 trans->block_rsv = root->orphan_block_rsv;
6541 ret = btrfs_block_rsv_check(trans, root,
6542 root->orphan_block_rsv, 0, 5);
6543 if (ret == -EAGAIN) {
6544 ret = btrfs_commit_transaction(trans, root);
6554 ret = btrfs_truncate_inode_items(trans, root, inode,
6556 BTRFS_EXTENT_DATA_KEY);
6557 if (ret != -EAGAIN) {
6562 ret = btrfs_update_inode(trans, root, inode);
6568 nr = trans->blocks_used;
6569 btrfs_end_transaction(trans, root);
6571 btrfs_btree_balance_dirty(root, nr);
6574 if (ret == 0 && inode->i_nlink > 0) {
6575 ret = btrfs_orphan_del(trans, inode);
6578 } else if (ret && inode->i_nlink > 0) {
6580 * Failed to do the truncate, remove us from the in memory
6583 ret = btrfs_orphan_del(NULL, inode);
6586 ret = btrfs_update_inode(trans, root, inode);
6590 nr = trans->blocks_used;
6591 ret = btrfs_end_transaction_throttle(trans, root);
6594 btrfs_btree_balance_dirty(root, nr);
6600 * create a new subvolume directory/inode (helper for the ioctl).
6602 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
6603 struct btrfs_root *new_root,
6604 u64 new_dirid, u64 alloc_hint)
6606 struct inode *inode;
6610 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
6611 new_dirid, alloc_hint, S_IFDIR | 0700, &index);
6613 return PTR_ERR(inode);
6614 inode->i_op = &btrfs_dir_inode_operations;
6615 inode->i_fop = &btrfs_dir_file_operations;
6618 btrfs_i_size_write(inode, 0);
6620 err = btrfs_update_inode(trans, new_root, inode);
6627 /* helper function for file defrag and space balancing. This
6628 * forces readahead on a given range of bytes in an inode
6630 unsigned long btrfs_force_ra(struct address_space *mapping,
6631 struct file_ra_state *ra, struct file *file,
6632 pgoff_t offset, pgoff_t last_index)
6634 pgoff_t req_size = last_index - offset + 1;
6636 page_cache_sync_readahead(mapping, ra, file, offset, req_size);
6637 return offset + req_size;
6640 struct inode *btrfs_alloc_inode(struct super_block *sb)
6642 struct btrfs_inode *ei;
6643 struct inode *inode;
6645 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
6650 ei->space_info = NULL;
6654 ei->last_sub_trans = 0;
6655 ei->logged_trans = 0;
6656 ei->delalloc_bytes = 0;
6657 ei->reserved_bytes = 0;
6658 ei->disk_i_size = 0;
6660 ei->index_cnt = (u64)-1;
6661 ei->last_unlink_trans = 0;
6663 atomic_set(&ei->outstanding_extents, 0);
6664 atomic_set(&ei->reserved_extents, 0);
6666 ei->ordered_data_close = 0;
6667 ei->orphan_meta_reserved = 0;
6668 ei->dummy_inode = 0;
6669 ei->force_compress = BTRFS_COMPRESS_NONE;
6671 inode = &ei->vfs_inode;
6672 extent_map_tree_init(&ei->extent_tree, GFP_NOFS);
6673 extent_io_tree_init(&ei->io_tree, &inode->i_data, GFP_NOFS);
6674 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data, GFP_NOFS);
6675 mutex_init(&ei->log_mutex);
6676 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
6677 INIT_LIST_HEAD(&ei->i_orphan);
6678 INIT_LIST_HEAD(&ei->delalloc_inodes);
6679 INIT_LIST_HEAD(&ei->ordered_operations);
6680 RB_CLEAR_NODE(&ei->rb_node);
6685 static void btrfs_i_callback(struct rcu_head *head)
6687 struct inode *inode = container_of(head, struct inode, i_rcu);
6688 INIT_LIST_HEAD(&inode->i_dentry);
6689 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
6692 void btrfs_destroy_inode(struct inode *inode)
6694 struct btrfs_ordered_extent *ordered;
6695 struct btrfs_root *root = BTRFS_I(inode)->root;
6697 WARN_ON(!list_empty(&inode->i_dentry));
6698 WARN_ON(inode->i_data.nrpages);
6699 WARN_ON(atomic_read(&BTRFS_I(inode)->outstanding_extents));
6700 WARN_ON(atomic_read(&BTRFS_I(inode)->reserved_extents));
6703 * This can happen where we create an inode, but somebody else also
6704 * created the same inode and we need to destroy the one we already
6711 * Make sure we're properly removed from the ordered operation
6715 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
6716 spin_lock(&root->fs_info->ordered_extent_lock);
6717 list_del_init(&BTRFS_I(inode)->ordered_operations);
6718 spin_unlock(&root->fs_info->ordered_extent_lock);
6721 if (root == root->fs_info->tree_root) {
6722 struct btrfs_block_group_cache *block_group;
6724 block_group = btrfs_lookup_block_group(root->fs_info,
6725 BTRFS_I(inode)->block_group);
6726 if (block_group && block_group->inode == inode) {
6727 spin_lock(&block_group->lock);
6728 block_group->inode = NULL;
6729 spin_unlock(&block_group->lock);
6730 btrfs_put_block_group(block_group);
6731 } else if (block_group) {
6732 btrfs_put_block_group(block_group);
6736 spin_lock(&root->orphan_lock);
6737 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
6738 printk(KERN_INFO "BTRFS: inode %lu still on the orphan list\n",
6740 list_del_init(&BTRFS_I(inode)->i_orphan);
6742 spin_unlock(&root->orphan_lock);
6745 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
6749 printk(KERN_ERR "btrfs found ordered "
6750 "extent %llu %llu on inode cleanup\n",
6751 (unsigned long long)ordered->file_offset,
6752 (unsigned long long)ordered->len);
6753 btrfs_remove_ordered_extent(inode, ordered);
6754 btrfs_put_ordered_extent(ordered);
6755 btrfs_put_ordered_extent(ordered);
6758 inode_tree_del(inode);
6759 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
6761 call_rcu(&inode->i_rcu, btrfs_i_callback);
6764 int btrfs_drop_inode(struct inode *inode)
6766 struct btrfs_root *root = BTRFS_I(inode)->root;
6768 if (btrfs_root_refs(&root->root_item) == 0 &&
6769 root != root->fs_info->tree_root)
6772 return generic_drop_inode(inode);
6775 static void init_once(void *foo)
6777 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
6779 inode_init_once(&ei->vfs_inode);
6782 void btrfs_destroy_cachep(void)
6784 if (btrfs_inode_cachep)
6785 kmem_cache_destroy(btrfs_inode_cachep);
6786 if (btrfs_trans_handle_cachep)
6787 kmem_cache_destroy(btrfs_trans_handle_cachep);
6788 if (btrfs_transaction_cachep)
6789 kmem_cache_destroy(btrfs_transaction_cachep);
6790 if (btrfs_path_cachep)
6791 kmem_cache_destroy(btrfs_path_cachep);
6792 if (btrfs_free_space_cachep)
6793 kmem_cache_destroy(btrfs_free_space_cachep);
6796 int btrfs_init_cachep(void)
6798 btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
6799 sizeof(struct btrfs_inode), 0,
6800 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
6801 if (!btrfs_inode_cachep)
6804 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
6805 sizeof(struct btrfs_trans_handle), 0,
6806 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6807 if (!btrfs_trans_handle_cachep)
6810 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
6811 sizeof(struct btrfs_transaction), 0,
6812 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6813 if (!btrfs_transaction_cachep)
6816 btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
6817 sizeof(struct btrfs_path), 0,
6818 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6819 if (!btrfs_path_cachep)
6822 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space_cache",
6823 sizeof(struct btrfs_free_space), 0,
6824 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6825 if (!btrfs_free_space_cachep)
6830 btrfs_destroy_cachep();
6834 static int btrfs_getattr(struct vfsmount *mnt,
6835 struct dentry *dentry, struct kstat *stat)
6837 struct inode *inode = dentry->d_inode;
6838 generic_fillattr(inode, stat);
6839 stat->dev = BTRFS_I(inode)->root->anon_super.s_dev;
6840 stat->blksize = PAGE_CACHE_SIZE;
6841 stat->blocks = (inode_get_bytes(inode) +
6842 BTRFS_I(inode)->delalloc_bytes) >> 9;
6846 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
6847 struct inode *new_dir, struct dentry *new_dentry)
6849 struct btrfs_trans_handle *trans;
6850 struct btrfs_root *root = BTRFS_I(old_dir)->root;
6851 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
6852 struct inode *new_inode = new_dentry->d_inode;
6853 struct inode *old_inode = old_dentry->d_inode;
6854 struct timespec ctime = CURRENT_TIME;
6859 if (new_dir->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
6862 /* we only allow rename subvolume link between subvolumes */
6863 if (old_inode->i_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
6866 if (old_inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
6867 (new_inode && new_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID))
6870 if (S_ISDIR(old_inode->i_mode) && new_inode &&
6871 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
6874 * we're using rename to replace one file with another.
6875 * and the replacement file is large. Start IO on it now so
6876 * we don't add too much work to the end of the transaction
6878 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
6879 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
6880 filemap_flush(old_inode->i_mapping);
6882 /* close the racy window with snapshot create/destroy ioctl */
6883 if (old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
6884 down_read(&root->fs_info->subvol_sem);
6886 * We want to reserve the absolute worst case amount of items. So if
6887 * both inodes are subvols and we need to unlink them then that would
6888 * require 4 item modifications, but if they are both normal inodes it
6889 * would require 5 item modifications, so we'll assume their normal
6890 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
6891 * should cover the worst case number of items we'll modify.
6893 trans = btrfs_start_transaction(root, 20);
6895 return PTR_ERR(trans);
6897 btrfs_set_trans_block_group(trans, new_dir);
6900 btrfs_record_root_in_trans(trans, dest);
6902 ret = btrfs_set_inode_index(new_dir, &index);
6906 if (unlikely(old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6907 /* force full log commit if subvolume involved. */
6908 root->fs_info->last_trans_log_full_commit = trans->transid;
6910 ret = btrfs_insert_inode_ref(trans, dest,
6911 new_dentry->d_name.name,
6912 new_dentry->d_name.len,
6914 new_dir->i_ino, index);
6918 * this is an ugly little race, but the rename is required
6919 * to make sure that if we crash, the inode is either at the
6920 * old name or the new one. pinning the log transaction lets
6921 * us make sure we don't allow a log commit to come in after
6922 * we unlink the name but before we add the new name back in.
6924 btrfs_pin_log_trans(root);
6927 * make sure the inode gets flushed if it is replacing
6930 if (new_inode && new_inode->i_size &&
6931 old_inode && S_ISREG(old_inode->i_mode)) {
6932 btrfs_add_ordered_operation(trans, root, old_inode);
6935 old_dir->i_ctime = old_dir->i_mtime = ctime;
6936 new_dir->i_ctime = new_dir->i_mtime = ctime;
6937 old_inode->i_ctime = ctime;
6939 if (old_dentry->d_parent != new_dentry->d_parent)
6940 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
6942 if (unlikely(old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6943 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
6944 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
6945 old_dentry->d_name.name,
6946 old_dentry->d_name.len);
6948 btrfs_inc_nlink(old_dentry->d_inode);
6949 ret = btrfs_unlink_inode(trans, root, old_dir,
6950 old_dentry->d_inode,
6951 old_dentry->d_name.name,
6952 old_dentry->d_name.len);
6957 new_inode->i_ctime = CURRENT_TIME;
6958 if (unlikely(new_inode->i_ino ==
6959 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
6960 root_objectid = BTRFS_I(new_inode)->location.objectid;
6961 ret = btrfs_unlink_subvol(trans, dest, new_dir,
6963 new_dentry->d_name.name,
6964 new_dentry->d_name.len);
6965 BUG_ON(new_inode->i_nlink == 0);
6967 ret = btrfs_unlink_inode(trans, dest, new_dir,
6968 new_dentry->d_inode,
6969 new_dentry->d_name.name,
6970 new_dentry->d_name.len);
6973 if (new_inode->i_nlink == 0) {
6974 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
6979 ret = btrfs_add_link(trans, new_dir, old_inode,
6980 new_dentry->d_name.name,
6981 new_dentry->d_name.len, 0, index);
6984 if (old_inode->i_ino != BTRFS_FIRST_FREE_OBJECTID) {
6985 struct dentry *parent = dget_parent(new_dentry);
6986 btrfs_log_new_name(trans, old_inode, old_dir, parent);
6988 btrfs_end_log_trans(root);
6991 btrfs_end_transaction_throttle(trans, root);
6993 if (old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
6994 up_read(&root->fs_info->subvol_sem);
7000 * some fairly slow code that needs optimization. This walks the list
7001 * of all the inodes with pending delalloc and forces them to disk.
7003 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
7005 struct list_head *head = &root->fs_info->delalloc_inodes;
7006 struct btrfs_inode *binode;
7007 struct inode *inode;
7009 if (root->fs_info->sb->s_flags & MS_RDONLY)
7012 spin_lock(&root->fs_info->delalloc_lock);
7013 while (!list_empty(head)) {
7014 binode = list_entry(head->next, struct btrfs_inode,
7016 inode = igrab(&binode->vfs_inode);
7018 list_del_init(&binode->delalloc_inodes);
7019 spin_unlock(&root->fs_info->delalloc_lock);
7021 filemap_flush(inode->i_mapping);
7023 btrfs_add_delayed_iput(inode);
7028 spin_lock(&root->fs_info->delalloc_lock);
7030 spin_unlock(&root->fs_info->delalloc_lock);
7032 /* the filemap_flush will queue IO into the worker threads, but
7033 * we have to make sure the IO is actually started and that
7034 * ordered extents get created before we return
7036 atomic_inc(&root->fs_info->async_submit_draining);
7037 while (atomic_read(&root->fs_info->nr_async_submits) ||
7038 atomic_read(&root->fs_info->async_delalloc_pages)) {
7039 wait_event(root->fs_info->async_submit_wait,
7040 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
7041 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
7043 atomic_dec(&root->fs_info->async_submit_draining);
7047 int btrfs_start_one_delalloc_inode(struct btrfs_root *root, int delay_iput,
7050 struct btrfs_inode *binode;
7051 struct inode *inode = NULL;
7053 spin_lock(&root->fs_info->delalloc_lock);
7054 while (!list_empty(&root->fs_info->delalloc_inodes)) {
7055 binode = list_entry(root->fs_info->delalloc_inodes.next,
7056 struct btrfs_inode, delalloc_inodes);
7057 inode = igrab(&binode->vfs_inode);
7059 list_move_tail(&binode->delalloc_inodes,
7060 &root->fs_info->delalloc_inodes);
7064 list_del_init(&binode->delalloc_inodes);
7065 cond_resched_lock(&root->fs_info->delalloc_lock);
7067 spin_unlock(&root->fs_info->delalloc_lock);
7071 filemap_write_and_wait(inode->i_mapping);
7073 * We have to do this because compression doesn't
7074 * actually set PG_writeback until it submits the pages
7075 * for IO, which happens in an async thread, so we could
7076 * race and not actually wait for any writeback pages
7077 * because they've not been submitted yet. Technically
7078 * this could still be the case for the ordered stuff
7079 * since the async thread may not have started to do its
7080 * work yet. If this becomes the case then we need to
7081 * figure out a way to make sure that in writepage we
7082 * wait for any async pages to be submitted before
7083 * returning so that fdatawait does what its supposed to
7086 btrfs_wait_ordered_range(inode, 0, (u64)-1);
7088 filemap_flush(inode->i_mapping);
7091 btrfs_add_delayed_iput(inode);
7099 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
7100 const char *symname)
7102 struct btrfs_trans_handle *trans;
7103 struct btrfs_root *root = BTRFS_I(dir)->root;
7104 struct btrfs_path *path;
7105 struct btrfs_key key;
7106 struct inode *inode = NULL;
7114 struct btrfs_file_extent_item *ei;
7115 struct extent_buffer *leaf;
7116 unsigned long nr = 0;
7118 name_len = strlen(symname) + 1;
7119 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
7120 return -ENAMETOOLONG;
7122 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
7126 * 2 items for inode item and ref
7127 * 2 items for dir items
7128 * 1 item for xattr if selinux is on
7130 trans = btrfs_start_transaction(root, 5);
7132 return PTR_ERR(trans);
7134 btrfs_set_trans_block_group(trans, dir);
7136 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
7137 dentry->d_name.len, dir->i_ino, objectid,
7138 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO,
7140 err = PTR_ERR(inode);
7144 err = btrfs_init_inode_security(trans, inode, dir);
7150 btrfs_set_trans_block_group(trans, inode);
7151 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
7155 inode->i_mapping->a_ops = &btrfs_aops;
7156 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7157 inode->i_fop = &btrfs_file_operations;
7158 inode->i_op = &btrfs_file_inode_operations;
7159 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
7161 btrfs_update_inode_block_group(trans, inode);
7162 btrfs_update_inode_block_group(trans, dir);
7166 path = btrfs_alloc_path();
7168 key.objectid = inode->i_ino;
7170 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
7171 datasize = btrfs_file_extent_calc_inline_size(name_len);
7172 err = btrfs_insert_empty_item(trans, root, path, &key,
7178 leaf = path->nodes[0];
7179 ei = btrfs_item_ptr(leaf, path->slots[0],
7180 struct btrfs_file_extent_item);
7181 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
7182 btrfs_set_file_extent_type(leaf, ei,
7183 BTRFS_FILE_EXTENT_INLINE);
7184 btrfs_set_file_extent_encryption(leaf, ei, 0);
7185 btrfs_set_file_extent_compression(leaf, ei, 0);
7186 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
7187 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
7189 ptr = btrfs_file_extent_inline_start(ei);
7190 write_extent_buffer(leaf, symname, ptr, name_len);
7191 btrfs_mark_buffer_dirty(leaf);
7192 btrfs_free_path(path);
7194 inode->i_op = &btrfs_symlink_inode_operations;
7195 inode->i_mapping->a_ops = &btrfs_symlink_aops;
7196 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7197 inode_set_bytes(inode, name_len);
7198 btrfs_i_size_write(inode, name_len - 1);
7199 err = btrfs_update_inode(trans, root, inode);
7204 nr = trans->blocks_used;
7205 btrfs_end_transaction_throttle(trans, root);
7207 inode_dec_link_count(inode);
7210 btrfs_btree_balance_dirty(root, nr);
7214 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
7215 u64 start, u64 num_bytes, u64 min_size,
7216 loff_t actual_len, u64 *alloc_hint,
7217 struct btrfs_trans_handle *trans)
7219 struct btrfs_root *root = BTRFS_I(inode)->root;
7220 struct btrfs_key ins;
7221 u64 cur_offset = start;
7224 bool own_trans = true;
7228 while (num_bytes > 0) {
7230 trans = btrfs_start_transaction(root, 3);
7231 if (IS_ERR(trans)) {
7232 ret = PTR_ERR(trans);
7237 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
7238 0, *alloc_hint, (u64)-1, &ins, 1);
7241 btrfs_end_transaction(trans, root);
7245 ret = insert_reserved_file_extent(trans, inode,
7246 cur_offset, ins.objectid,
7247 ins.offset, ins.offset,
7248 ins.offset, 0, 0, 0,
7249 BTRFS_FILE_EXTENT_PREALLOC);
7251 btrfs_drop_extent_cache(inode, cur_offset,
7252 cur_offset + ins.offset -1, 0);
7254 num_bytes -= ins.offset;
7255 cur_offset += ins.offset;
7256 *alloc_hint = ins.objectid + ins.offset;
7258 inode->i_ctime = CURRENT_TIME;
7259 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
7260 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
7261 (actual_len > inode->i_size) &&
7262 (cur_offset > inode->i_size)) {
7263 if (cur_offset > actual_len)
7264 i_size = actual_len;
7266 i_size = cur_offset;
7267 i_size_write(inode, i_size);
7268 btrfs_ordered_update_i_size(inode, i_size, NULL);
7271 ret = btrfs_update_inode(trans, root, inode);
7275 btrfs_end_transaction(trans, root);
7280 int btrfs_prealloc_file_range(struct inode *inode, int mode,
7281 u64 start, u64 num_bytes, u64 min_size,
7282 loff_t actual_len, u64 *alloc_hint)
7284 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7285 min_size, actual_len, alloc_hint,
7289 int btrfs_prealloc_file_range_trans(struct inode *inode,
7290 struct btrfs_trans_handle *trans, int mode,
7291 u64 start, u64 num_bytes, u64 min_size,
7292 loff_t actual_len, u64 *alloc_hint)
7294 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7295 min_size, actual_len, alloc_hint, trans);
7298 static int btrfs_set_page_dirty(struct page *page)
7300 return __set_page_dirty_nobuffers(page);
7303 static int btrfs_permission(struct inode *inode, int mask, unsigned int flags)
7305 struct btrfs_root *root = BTRFS_I(inode)->root;
7307 if (btrfs_root_readonly(root) && (mask & MAY_WRITE))
7309 if ((BTRFS_I(inode)->flags & BTRFS_INODE_READONLY) && (mask & MAY_WRITE))
7311 return generic_permission(inode, mask, flags, btrfs_check_acl);
7314 static const struct inode_operations btrfs_dir_inode_operations = {
7315 .getattr = btrfs_getattr,
7316 .lookup = btrfs_lookup,
7317 .create = btrfs_create,
7318 .unlink = btrfs_unlink,
7320 .mkdir = btrfs_mkdir,
7321 .rmdir = btrfs_rmdir,
7322 .rename = btrfs_rename,
7323 .symlink = btrfs_symlink,
7324 .setattr = btrfs_setattr,
7325 .mknod = btrfs_mknod,
7326 .setxattr = btrfs_setxattr,
7327 .getxattr = btrfs_getxattr,
7328 .listxattr = btrfs_listxattr,
7329 .removexattr = btrfs_removexattr,
7330 .permission = btrfs_permission,
7332 static const struct inode_operations btrfs_dir_ro_inode_operations = {
7333 .lookup = btrfs_lookup,
7334 .permission = btrfs_permission,
7337 static const struct file_operations btrfs_dir_file_operations = {
7338 .llseek = generic_file_llseek,
7339 .read = generic_read_dir,
7340 .readdir = btrfs_real_readdir,
7341 .unlocked_ioctl = btrfs_ioctl,
7342 #ifdef CONFIG_COMPAT
7343 .compat_ioctl = btrfs_ioctl,
7345 .release = btrfs_release_file,
7346 .fsync = btrfs_sync_file,
7349 static struct extent_io_ops btrfs_extent_io_ops = {
7350 .fill_delalloc = run_delalloc_range,
7351 .submit_bio_hook = btrfs_submit_bio_hook,
7352 .merge_bio_hook = btrfs_merge_bio_hook,
7353 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
7354 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
7355 .writepage_start_hook = btrfs_writepage_start_hook,
7356 .readpage_io_failed_hook = btrfs_io_failed_hook,
7357 .set_bit_hook = btrfs_set_bit_hook,
7358 .clear_bit_hook = btrfs_clear_bit_hook,
7359 .merge_extent_hook = btrfs_merge_extent_hook,
7360 .split_extent_hook = btrfs_split_extent_hook,
7364 * btrfs doesn't support the bmap operation because swapfiles
7365 * use bmap to make a mapping of extents in the file. They assume
7366 * these extents won't change over the life of the file and they
7367 * use the bmap result to do IO directly to the drive.
7369 * the btrfs bmap call would return logical addresses that aren't
7370 * suitable for IO and they also will change frequently as COW
7371 * operations happen. So, swapfile + btrfs == corruption.
7373 * For now we're avoiding this by dropping bmap.
7375 static const struct address_space_operations btrfs_aops = {
7376 .readpage = btrfs_readpage,
7377 .writepage = btrfs_writepage,
7378 .writepages = btrfs_writepages,
7379 .readpages = btrfs_readpages,
7380 .sync_page = block_sync_page,
7381 .direct_IO = btrfs_direct_IO,
7382 .invalidatepage = btrfs_invalidatepage,
7383 .releasepage = btrfs_releasepage,
7384 .set_page_dirty = btrfs_set_page_dirty,
7385 .error_remove_page = generic_error_remove_page,
7388 static const struct address_space_operations btrfs_symlink_aops = {
7389 .readpage = btrfs_readpage,
7390 .writepage = btrfs_writepage,
7391 .invalidatepage = btrfs_invalidatepage,
7392 .releasepage = btrfs_releasepage,
7395 static const struct inode_operations btrfs_file_inode_operations = {
7396 .getattr = btrfs_getattr,
7397 .setattr = btrfs_setattr,
7398 .setxattr = btrfs_setxattr,
7399 .getxattr = btrfs_getxattr,
7400 .listxattr = btrfs_listxattr,
7401 .removexattr = btrfs_removexattr,
7402 .permission = btrfs_permission,
7403 .fiemap = btrfs_fiemap,
7405 static const struct inode_operations btrfs_special_inode_operations = {
7406 .getattr = btrfs_getattr,
7407 .setattr = btrfs_setattr,
7408 .permission = btrfs_permission,
7409 .setxattr = btrfs_setxattr,
7410 .getxattr = btrfs_getxattr,
7411 .listxattr = btrfs_listxattr,
7412 .removexattr = btrfs_removexattr,
7414 static const struct inode_operations btrfs_symlink_inode_operations = {
7415 .readlink = generic_readlink,
7416 .follow_link = page_follow_link_light,
7417 .put_link = page_put_link,
7418 .getattr = btrfs_getattr,
7419 .permission = btrfs_permission,
7420 .setxattr = btrfs_setxattr,
7421 .getxattr = btrfs_getxattr,
7422 .listxattr = btrfs_listxattr,
7423 .removexattr = btrfs_removexattr,
7426 const struct dentry_operations btrfs_dentry_operations = {
7427 .d_delete = btrfs_dentry_delete,