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"
54 struct btrfs_iget_args {
56 struct btrfs_root *root;
59 static const struct inode_operations btrfs_dir_inode_operations;
60 static const struct inode_operations btrfs_symlink_inode_operations;
61 static const struct inode_operations btrfs_dir_ro_inode_operations;
62 static const struct inode_operations btrfs_special_inode_operations;
63 static const struct inode_operations btrfs_file_inode_operations;
64 static const struct address_space_operations btrfs_aops;
65 static const struct address_space_operations btrfs_symlink_aops;
66 static const struct file_operations btrfs_dir_file_operations;
67 static struct extent_io_ops btrfs_extent_io_ops;
69 static struct kmem_cache *btrfs_inode_cachep;
70 struct kmem_cache *btrfs_trans_handle_cachep;
71 struct kmem_cache *btrfs_transaction_cachep;
72 struct kmem_cache *btrfs_path_cachep;
75 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
76 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
77 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
78 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
79 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
80 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
81 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
82 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
85 static void btrfs_truncate(struct inode *inode);
86 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
87 static noinline int cow_file_range(struct inode *inode,
88 struct page *locked_page,
89 u64 start, u64 end, int *page_started,
90 unsigned long *nr_written, int unlock);
92 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
93 struct inode *inode, struct inode *dir)
97 err = btrfs_init_acl(trans, inode, dir);
99 err = btrfs_xattr_security_init(trans, inode, dir);
104 * this does all the hard work for inserting an inline extent into
105 * the btree. The caller should have done a btrfs_drop_extents so that
106 * no overlapping inline items exist in the btree
108 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
109 struct btrfs_root *root, struct inode *inode,
110 u64 start, size_t size, size_t compressed_size,
111 struct page **compressed_pages)
113 struct btrfs_key key;
114 struct btrfs_path *path;
115 struct extent_buffer *leaf;
116 struct page *page = NULL;
119 struct btrfs_file_extent_item *ei;
122 size_t cur_size = size;
124 unsigned long offset;
125 int compress_type = BTRFS_COMPRESS_NONE;
127 if (compressed_size && compressed_pages) {
128 compress_type = root->fs_info->compress_type;
129 cur_size = compressed_size;
132 path = btrfs_alloc_path();
136 path->leave_spinning = 1;
137 btrfs_set_trans_block_group(trans, inode);
139 key.objectid = inode->i_ino;
141 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
142 datasize = btrfs_file_extent_calc_inline_size(cur_size);
144 inode_add_bytes(inode, size);
145 ret = btrfs_insert_empty_item(trans, root, path, &key,
152 leaf = path->nodes[0];
153 ei = btrfs_item_ptr(leaf, path->slots[0],
154 struct btrfs_file_extent_item);
155 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
156 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
157 btrfs_set_file_extent_encryption(leaf, ei, 0);
158 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
159 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
160 ptr = btrfs_file_extent_inline_start(ei);
162 if (compress_type != BTRFS_COMPRESS_NONE) {
165 while (compressed_size > 0) {
166 cpage = compressed_pages[i];
167 cur_size = min_t(unsigned long, compressed_size,
170 kaddr = kmap_atomic(cpage, KM_USER0);
171 write_extent_buffer(leaf, kaddr, ptr, cur_size);
172 kunmap_atomic(kaddr, KM_USER0);
176 compressed_size -= cur_size;
178 btrfs_set_file_extent_compression(leaf, ei,
181 page = find_get_page(inode->i_mapping,
182 start >> PAGE_CACHE_SHIFT);
183 btrfs_set_file_extent_compression(leaf, ei, 0);
184 kaddr = kmap_atomic(page, KM_USER0);
185 offset = start & (PAGE_CACHE_SIZE - 1);
186 write_extent_buffer(leaf, kaddr + offset, ptr, size);
187 kunmap_atomic(kaddr, KM_USER0);
188 page_cache_release(page);
190 btrfs_mark_buffer_dirty(leaf);
191 btrfs_free_path(path);
194 * we're an inline extent, so nobody can
195 * extend the file past i_size without locking
196 * a page we already have locked.
198 * We must do any isize and inode updates
199 * before we unlock the pages. Otherwise we
200 * could end up racing with unlink.
202 BTRFS_I(inode)->disk_i_size = inode->i_size;
203 btrfs_update_inode(trans, root, inode);
207 btrfs_free_path(path);
213 * conditionally insert an inline extent into the file. This
214 * does the checks required to make sure the data is small enough
215 * to fit as an inline extent.
217 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
218 struct btrfs_root *root,
219 struct inode *inode, u64 start, u64 end,
220 size_t compressed_size,
221 struct page **compressed_pages)
223 u64 isize = i_size_read(inode);
224 u64 actual_end = min(end + 1, isize);
225 u64 inline_len = actual_end - start;
226 u64 aligned_end = (end + root->sectorsize - 1) &
227 ~((u64)root->sectorsize - 1);
229 u64 data_len = inline_len;
233 data_len = compressed_size;
236 actual_end >= PAGE_CACHE_SIZE ||
237 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
239 (actual_end & (root->sectorsize - 1)) == 0) ||
241 data_len > root->fs_info->max_inline) {
245 ret = btrfs_drop_extents(trans, inode, start, aligned_end,
249 if (isize > actual_end)
250 inline_len = min_t(u64, isize, actual_end);
251 ret = insert_inline_extent(trans, root, inode, start,
252 inline_len, compressed_size,
255 btrfs_delalloc_release_metadata(inode, end + 1 - start);
256 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
260 struct async_extent {
265 unsigned long nr_pages;
267 struct list_head list;
272 struct btrfs_root *root;
273 struct page *locked_page;
276 struct list_head extents;
277 struct btrfs_work work;
280 static noinline int add_async_extent(struct async_cow *cow,
281 u64 start, u64 ram_size,
284 unsigned long nr_pages,
287 struct async_extent *async_extent;
289 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
290 async_extent->start = start;
291 async_extent->ram_size = ram_size;
292 async_extent->compressed_size = compressed_size;
293 async_extent->pages = pages;
294 async_extent->nr_pages = nr_pages;
295 async_extent->compress_type = compress_type;
296 list_add_tail(&async_extent->list, &cow->extents);
301 * we create compressed extents in two phases. The first
302 * phase compresses a range of pages that have already been
303 * locked (both pages and state bits are locked).
305 * This is done inside an ordered work queue, and the compression
306 * is spread across many cpus. The actual IO submission is step
307 * two, and the ordered work queue takes care of making sure that
308 * happens in the same order things were put onto the queue by
309 * writepages and friends.
311 * If this code finds it can't get good compression, it puts an
312 * entry onto the work queue to write the uncompressed bytes. This
313 * makes sure that both compressed inodes and uncompressed inodes
314 * are written in the same order that pdflush sent them down.
316 static noinline int compress_file_range(struct inode *inode,
317 struct page *locked_page,
319 struct async_cow *async_cow,
322 struct btrfs_root *root = BTRFS_I(inode)->root;
323 struct btrfs_trans_handle *trans;
325 u64 blocksize = root->sectorsize;
327 u64 isize = i_size_read(inode);
329 struct page **pages = NULL;
330 unsigned long nr_pages;
331 unsigned long nr_pages_ret = 0;
332 unsigned long total_compressed = 0;
333 unsigned long total_in = 0;
334 unsigned long max_compressed = 128 * 1024;
335 unsigned long max_uncompressed = 128 * 1024;
338 int compress_type = root->fs_info->compress_type;
340 actual_end = min_t(u64, isize, end + 1);
343 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
344 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
347 * we don't want to send crud past the end of i_size through
348 * compression, that's just a waste of CPU time. So, if the
349 * end of the file is before the start of our current
350 * requested range of bytes, we bail out to the uncompressed
351 * cleanup code that can deal with all of this.
353 * It isn't really the fastest way to fix things, but this is a
354 * very uncommon corner.
356 if (actual_end <= start)
357 goto cleanup_and_bail_uncompressed;
359 total_compressed = actual_end - start;
361 /* we want to make sure that amount of ram required to uncompress
362 * an extent is reasonable, so we limit the total size in ram
363 * of a compressed extent to 128k. This is a crucial number
364 * because it also controls how easily we can spread reads across
365 * cpus for decompression.
367 * We also want to make sure the amount of IO required to do
368 * a random read is reasonably small, so we limit the size of
369 * a compressed extent to 128k.
371 total_compressed = min(total_compressed, max_uncompressed);
372 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
373 num_bytes = max(blocksize, num_bytes);
378 * we do compression for mount -o compress and when the
379 * inode has not been flagged as nocompress. This flag can
380 * change at any time if we discover bad compression ratios.
382 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
383 (btrfs_test_opt(root, COMPRESS) ||
384 (BTRFS_I(inode)->force_compress))) {
386 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
388 if (BTRFS_I(inode)->force_compress)
389 compress_type = BTRFS_I(inode)->force_compress;
391 ret = btrfs_compress_pages(compress_type,
392 inode->i_mapping, start,
393 total_compressed, pages,
394 nr_pages, &nr_pages_ret,
400 unsigned long offset = total_compressed &
401 (PAGE_CACHE_SIZE - 1);
402 struct page *page = pages[nr_pages_ret - 1];
405 /* zero the tail end of the last page, we might be
406 * sending it down to disk
409 kaddr = kmap_atomic(page, KM_USER0);
410 memset(kaddr + offset, 0,
411 PAGE_CACHE_SIZE - offset);
412 kunmap_atomic(kaddr, KM_USER0);
418 trans = btrfs_join_transaction(root, 1);
420 btrfs_set_trans_block_group(trans, inode);
421 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
423 /* lets try to make an inline extent */
424 if (ret || total_in < (actual_end - start)) {
425 /* we didn't compress the entire range, try
426 * to make an uncompressed inline extent.
428 ret = cow_file_range_inline(trans, root, inode,
429 start, end, 0, NULL);
431 /* try making a compressed inline extent */
432 ret = cow_file_range_inline(trans, root, inode,
434 total_compressed, pages);
438 * inline extent creation worked, we don't need
439 * to create any more async work items. Unlock
440 * and free up our temp pages.
442 extent_clear_unlock_delalloc(inode,
443 &BTRFS_I(inode)->io_tree,
445 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
446 EXTENT_CLEAR_DELALLOC |
447 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
449 btrfs_end_transaction(trans, root);
452 btrfs_end_transaction(trans, root);
457 * we aren't doing an inline extent round the compressed size
458 * up to a block size boundary so the allocator does sane
461 total_compressed = (total_compressed + blocksize - 1) &
465 * one last check to make sure the compression is really a
466 * win, compare the page count read with the blocks on disk
468 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
469 ~(PAGE_CACHE_SIZE - 1);
470 if (total_compressed >= total_in) {
473 num_bytes = total_in;
476 if (!will_compress && pages) {
478 * the compression code ran but failed to make things smaller,
479 * free any pages it allocated and our page pointer array
481 for (i = 0; i < nr_pages_ret; i++) {
482 WARN_ON(pages[i]->mapping);
483 page_cache_release(pages[i]);
487 total_compressed = 0;
490 /* flag the file so we don't compress in the future */
491 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
492 !(BTRFS_I(inode)->force_compress)) {
493 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
499 /* the async work queues will take care of doing actual
500 * allocation on disk for these compressed pages,
501 * and will submit them to the elevator.
503 add_async_extent(async_cow, start, num_bytes,
504 total_compressed, pages, nr_pages_ret,
507 if (start + num_bytes < end) {
514 cleanup_and_bail_uncompressed:
516 * No compression, but we still need to write the pages in
517 * the file we've been given so far. redirty the locked
518 * page if it corresponds to our extent and set things up
519 * for the async work queue to run cow_file_range to do
520 * the normal delalloc dance
522 if (page_offset(locked_page) >= start &&
523 page_offset(locked_page) <= end) {
524 __set_page_dirty_nobuffers(locked_page);
525 /* unlocked later on in the async handlers */
527 add_async_extent(async_cow, start, end - start + 1,
528 0, NULL, 0, BTRFS_COMPRESS_NONE);
536 for (i = 0; i < nr_pages_ret; i++) {
537 WARN_ON(pages[i]->mapping);
538 page_cache_release(pages[i]);
546 * phase two of compressed writeback. This is the ordered portion
547 * of the code, which only gets called in the order the work was
548 * queued. We walk all the async extents created by compress_file_range
549 * and send them down to the disk.
551 static noinline int submit_compressed_extents(struct inode *inode,
552 struct async_cow *async_cow)
554 struct async_extent *async_extent;
556 struct btrfs_trans_handle *trans;
557 struct btrfs_key ins;
558 struct extent_map *em;
559 struct btrfs_root *root = BTRFS_I(inode)->root;
560 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
561 struct extent_io_tree *io_tree;
564 if (list_empty(&async_cow->extents))
568 while (!list_empty(&async_cow->extents)) {
569 async_extent = list_entry(async_cow->extents.next,
570 struct async_extent, list);
571 list_del(&async_extent->list);
573 io_tree = &BTRFS_I(inode)->io_tree;
576 /* did the compression code fall back to uncompressed IO? */
577 if (!async_extent->pages) {
578 int page_started = 0;
579 unsigned long nr_written = 0;
581 lock_extent(io_tree, async_extent->start,
582 async_extent->start +
583 async_extent->ram_size - 1, GFP_NOFS);
585 /* allocate blocks */
586 ret = cow_file_range(inode, async_cow->locked_page,
588 async_extent->start +
589 async_extent->ram_size - 1,
590 &page_started, &nr_written, 0);
593 * if page_started, cow_file_range inserted an
594 * inline extent and took care of all the unlocking
595 * and IO for us. Otherwise, we need to submit
596 * all those pages down to the drive.
598 if (!page_started && !ret)
599 extent_write_locked_range(io_tree,
600 inode, async_extent->start,
601 async_extent->start +
602 async_extent->ram_size - 1,
610 lock_extent(io_tree, async_extent->start,
611 async_extent->start + async_extent->ram_size - 1,
614 trans = btrfs_join_transaction(root, 1);
615 ret = btrfs_reserve_extent(trans, root,
616 async_extent->compressed_size,
617 async_extent->compressed_size,
620 btrfs_end_transaction(trans, root);
624 for (i = 0; i < async_extent->nr_pages; i++) {
625 WARN_ON(async_extent->pages[i]->mapping);
626 page_cache_release(async_extent->pages[i]);
628 kfree(async_extent->pages);
629 async_extent->nr_pages = 0;
630 async_extent->pages = NULL;
631 unlock_extent(io_tree, async_extent->start,
632 async_extent->start +
633 async_extent->ram_size - 1, GFP_NOFS);
638 * here we're doing allocation and writeback of the
641 btrfs_drop_extent_cache(inode, async_extent->start,
642 async_extent->start +
643 async_extent->ram_size - 1, 0);
645 em = alloc_extent_map(GFP_NOFS);
646 em->start = async_extent->start;
647 em->len = async_extent->ram_size;
648 em->orig_start = em->start;
650 em->block_start = ins.objectid;
651 em->block_len = ins.offset;
652 em->bdev = root->fs_info->fs_devices->latest_bdev;
653 em->compress_type = async_extent->compress_type;
654 set_bit(EXTENT_FLAG_PINNED, &em->flags);
655 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
658 write_lock(&em_tree->lock);
659 ret = add_extent_mapping(em_tree, em);
660 write_unlock(&em_tree->lock);
661 if (ret != -EEXIST) {
665 btrfs_drop_extent_cache(inode, async_extent->start,
666 async_extent->start +
667 async_extent->ram_size - 1, 0);
670 ret = btrfs_add_ordered_extent_compress(inode,
673 async_extent->ram_size,
675 BTRFS_ORDERED_COMPRESSED,
676 async_extent->compress_type);
680 * clear dirty, set writeback and unlock the pages.
682 extent_clear_unlock_delalloc(inode,
683 &BTRFS_I(inode)->io_tree,
685 async_extent->start +
686 async_extent->ram_size - 1,
687 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
688 EXTENT_CLEAR_UNLOCK |
689 EXTENT_CLEAR_DELALLOC |
690 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
692 ret = btrfs_submit_compressed_write(inode,
694 async_extent->ram_size,
696 ins.offset, async_extent->pages,
697 async_extent->nr_pages);
700 alloc_hint = ins.objectid + ins.offset;
708 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
711 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
712 struct extent_map *em;
715 read_lock(&em_tree->lock);
716 em = search_extent_mapping(em_tree, start, num_bytes);
719 * if block start isn't an actual block number then find the
720 * first block in this inode and use that as a hint. If that
721 * block is also bogus then just don't worry about it.
723 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
725 em = search_extent_mapping(em_tree, 0, 0);
726 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
727 alloc_hint = em->block_start;
731 alloc_hint = em->block_start;
735 read_unlock(&em_tree->lock);
741 * when extent_io.c finds a delayed allocation range in the file,
742 * the call backs end up in this code. The basic idea is to
743 * allocate extents on disk for the range, and create ordered data structs
744 * in ram to track those extents.
746 * locked_page is the page that writepage had locked already. We use
747 * it to make sure we don't do extra locks or unlocks.
749 * *page_started is set to one if we unlock locked_page and do everything
750 * required to start IO on it. It may be clean and already done with
753 static noinline int cow_file_range(struct inode *inode,
754 struct page *locked_page,
755 u64 start, u64 end, int *page_started,
756 unsigned long *nr_written,
759 struct btrfs_root *root = BTRFS_I(inode)->root;
760 struct btrfs_trans_handle *trans;
763 unsigned long ram_size;
766 u64 blocksize = root->sectorsize;
767 struct btrfs_key ins;
768 struct extent_map *em;
769 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
772 BUG_ON(root == root->fs_info->tree_root);
773 trans = btrfs_join_transaction(root, 1);
775 btrfs_set_trans_block_group(trans, inode);
776 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
778 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
779 num_bytes = max(blocksize, num_bytes);
780 disk_num_bytes = num_bytes;
784 /* lets try to make an inline extent */
785 ret = cow_file_range_inline(trans, root, inode,
786 start, end, 0, NULL);
788 extent_clear_unlock_delalloc(inode,
789 &BTRFS_I(inode)->io_tree,
791 EXTENT_CLEAR_UNLOCK_PAGE |
792 EXTENT_CLEAR_UNLOCK |
793 EXTENT_CLEAR_DELALLOC |
795 EXTENT_SET_WRITEBACK |
796 EXTENT_END_WRITEBACK);
798 *nr_written = *nr_written +
799 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
806 BUG_ON(disk_num_bytes >
807 btrfs_super_total_bytes(&root->fs_info->super_copy));
809 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
810 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
812 while (disk_num_bytes > 0) {
815 cur_alloc_size = disk_num_bytes;
816 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
817 root->sectorsize, 0, alloc_hint,
821 em = alloc_extent_map(GFP_NOFS);
823 em->orig_start = em->start;
824 ram_size = ins.offset;
825 em->len = ins.offset;
827 em->block_start = ins.objectid;
828 em->block_len = ins.offset;
829 em->bdev = root->fs_info->fs_devices->latest_bdev;
830 set_bit(EXTENT_FLAG_PINNED, &em->flags);
833 write_lock(&em_tree->lock);
834 ret = add_extent_mapping(em_tree, em);
835 write_unlock(&em_tree->lock);
836 if (ret != -EEXIST) {
840 btrfs_drop_extent_cache(inode, start,
841 start + ram_size - 1, 0);
844 cur_alloc_size = ins.offset;
845 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
846 ram_size, cur_alloc_size, 0);
849 if (root->root_key.objectid ==
850 BTRFS_DATA_RELOC_TREE_OBJECTID) {
851 ret = btrfs_reloc_clone_csums(inode, start,
856 if (disk_num_bytes < cur_alloc_size)
859 /* we're not doing compressed IO, don't unlock the first
860 * page (which the caller expects to stay locked), don't
861 * clear any dirty bits and don't set any writeback bits
863 * Do set the Private2 bit so we know this page was properly
864 * setup for writepage
866 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
867 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
870 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
871 start, start + ram_size - 1,
873 disk_num_bytes -= cur_alloc_size;
874 num_bytes -= cur_alloc_size;
875 alloc_hint = ins.objectid + ins.offset;
876 start += cur_alloc_size;
880 btrfs_end_transaction(trans, root);
886 * work queue call back to started compression on a file and pages
888 static noinline void async_cow_start(struct btrfs_work *work)
890 struct async_cow *async_cow;
892 async_cow = container_of(work, struct async_cow, work);
894 compress_file_range(async_cow->inode, async_cow->locked_page,
895 async_cow->start, async_cow->end, async_cow,
898 async_cow->inode = NULL;
902 * work queue call back to submit previously compressed pages
904 static noinline void async_cow_submit(struct btrfs_work *work)
906 struct async_cow *async_cow;
907 struct btrfs_root *root;
908 unsigned long nr_pages;
910 async_cow = container_of(work, struct async_cow, work);
912 root = async_cow->root;
913 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
916 atomic_sub(nr_pages, &root->fs_info->async_delalloc_pages);
918 if (atomic_read(&root->fs_info->async_delalloc_pages) <
920 waitqueue_active(&root->fs_info->async_submit_wait))
921 wake_up(&root->fs_info->async_submit_wait);
923 if (async_cow->inode)
924 submit_compressed_extents(async_cow->inode, async_cow);
927 static noinline void async_cow_free(struct btrfs_work *work)
929 struct async_cow *async_cow;
930 async_cow = container_of(work, struct async_cow, work);
934 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
935 u64 start, u64 end, int *page_started,
936 unsigned long *nr_written)
938 struct async_cow *async_cow;
939 struct btrfs_root *root = BTRFS_I(inode)->root;
940 unsigned long nr_pages;
942 int limit = 10 * 1024 * 1042;
944 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
945 1, 0, NULL, GFP_NOFS);
946 while (start < end) {
947 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
948 async_cow->inode = inode;
949 async_cow->root = root;
950 async_cow->locked_page = locked_page;
951 async_cow->start = start;
953 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
956 cur_end = min(end, start + 512 * 1024 - 1);
958 async_cow->end = cur_end;
959 INIT_LIST_HEAD(&async_cow->extents);
961 async_cow->work.func = async_cow_start;
962 async_cow->work.ordered_func = async_cow_submit;
963 async_cow->work.ordered_free = async_cow_free;
964 async_cow->work.flags = 0;
966 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
968 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
970 btrfs_queue_worker(&root->fs_info->delalloc_workers,
973 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
974 wait_event(root->fs_info->async_submit_wait,
975 (atomic_read(&root->fs_info->async_delalloc_pages) <
979 while (atomic_read(&root->fs_info->async_submit_draining) &&
980 atomic_read(&root->fs_info->async_delalloc_pages)) {
981 wait_event(root->fs_info->async_submit_wait,
982 (atomic_read(&root->fs_info->async_delalloc_pages) ==
986 *nr_written += nr_pages;
993 static noinline int csum_exist_in_range(struct btrfs_root *root,
994 u64 bytenr, u64 num_bytes)
997 struct btrfs_ordered_sum *sums;
1000 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1001 bytenr + num_bytes - 1, &list);
1002 if (ret == 0 && list_empty(&list))
1005 while (!list_empty(&list)) {
1006 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1007 list_del(&sums->list);
1014 * when nowcow writeback call back. This checks for snapshots or COW copies
1015 * of the extents that exist in the file, and COWs the file as required.
1017 * If no cow copies or snapshots exist, we write directly to the existing
1020 static noinline int run_delalloc_nocow(struct inode *inode,
1021 struct page *locked_page,
1022 u64 start, u64 end, int *page_started, int force,
1023 unsigned long *nr_written)
1025 struct btrfs_root *root = BTRFS_I(inode)->root;
1026 struct btrfs_trans_handle *trans;
1027 struct extent_buffer *leaf;
1028 struct btrfs_path *path;
1029 struct btrfs_file_extent_item *fi;
1030 struct btrfs_key found_key;
1042 bool nolock = false;
1044 path = btrfs_alloc_path();
1046 if (root == root->fs_info->tree_root) {
1048 trans = btrfs_join_transaction_nolock(root, 1);
1050 trans = btrfs_join_transaction(root, 1);
1054 cow_start = (u64)-1;
1057 ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
1060 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1061 leaf = path->nodes[0];
1062 btrfs_item_key_to_cpu(leaf, &found_key,
1063 path->slots[0] - 1);
1064 if (found_key.objectid == inode->i_ino &&
1065 found_key.type == BTRFS_EXTENT_DATA_KEY)
1070 leaf = path->nodes[0];
1071 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1072 ret = btrfs_next_leaf(root, path);
1077 leaf = path->nodes[0];
1083 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1085 if (found_key.objectid > inode->i_ino ||
1086 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1087 found_key.offset > end)
1090 if (found_key.offset > cur_offset) {
1091 extent_end = found_key.offset;
1096 fi = btrfs_item_ptr(leaf, path->slots[0],
1097 struct btrfs_file_extent_item);
1098 extent_type = btrfs_file_extent_type(leaf, fi);
1100 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1101 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1102 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1103 extent_offset = btrfs_file_extent_offset(leaf, fi);
1104 extent_end = found_key.offset +
1105 btrfs_file_extent_num_bytes(leaf, fi);
1106 if (extent_end <= start) {
1110 if (disk_bytenr == 0)
1112 if (btrfs_file_extent_compression(leaf, fi) ||
1113 btrfs_file_extent_encryption(leaf, fi) ||
1114 btrfs_file_extent_other_encoding(leaf, fi))
1116 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1118 if (btrfs_extent_readonly(root, disk_bytenr))
1120 if (btrfs_cross_ref_exist(trans, root, inode->i_ino,
1122 extent_offset, disk_bytenr))
1124 disk_bytenr += extent_offset;
1125 disk_bytenr += cur_offset - found_key.offset;
1126 num_bytes = min(end + 1, extent_end) - cur_offset;
1128 * force cow if csum exists in the range.
1129 * this ensure that csum for a given extent are
1130 * either valid or do not exist.
1132 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1135 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1136 extent_end = found_key.offset +
1137 btrfs_file_extent_inline_len(leaf, fi);
1138 extent_end = ALIGN(extent_end, root->sectorsize);
1143 if (extent_end <= start) {
1148 if (cow_start == (u64)-1)
1149 cow_start = cur_offset;
1150 cur_offset = extent_end;
1151 if (cur_offset > end)
1157 btrfs_release_path(root, path);
1158 if (cow_start != (u64)-1) {
1159 ret = cow_file_range(inode, locked_page, cow_start,
1160 found_key.offset - 1, page_started,
1163 cow_start = (u64)-1;
1166 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1167 struct extent_map *em;
1168 struct extent_map_tree *em_tree;
1169 em_tree = &BTRFS_I(inode)->extent_tree;
1170 em = alloc_extent_map(GFP_NOFS);
1171 em->start = cur_offset;
1172 em->orig_start = em->start;
1173 em->len = num_bytes;
1174 em->block_len = num_bytes;
1175 em->block_start = disk_bytenr;
1176 em->bdev = root->fs_info->fs_devices->latest_bdev;
1177 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1179 write_lock(&em_tree->lock);
1180 ret = add_extent_mapping(em_tree, em);
1181 write_unlock(&em_tree->lock);
1182 if (ret != -EEXIST) {
1183 free_extent_map(em);
1186 btrfs_drop_extent_cache(inode, em->start,
1187 em->start + em->len - 1, 0);
1189 type = BTRFS_ORDERED_PREALLOC;
1191 type = BTRFS_ORDERED_NOCOW;
1194 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1195 num_bytes, num_bytes, type);
1198 if (root->root_key.objectid ==
1199 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1200 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1205 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1206 cur_offset, cur_offset + num_bytes - 1,
1207 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1208 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1209 EXTENT_SET_PRIVATE2);
1210 cur_offset = extent_end;
1211 if (cur_offset > end)
1214 btrfs_release_path(root, path);
1216 if (cur_offset <= end && cow_start == (u64)-1)
1217 cow_start = cur_offset;
1218 if (cow_start != (u64)-1) {
1219 ret = cow_file_range(inode, locked_page, cow_start, end,
1220 page_started, nr_written, 1);
1225 ret = btrfs_end_transaction_nolock(trans, root);
1228 ret = btrfs_end_transaction(trans, root);
1231 btrfs_free_path(path);
1236 * extent_io.c call back to do delayed allocation processing
1238 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1239 u64 start, u64 end, int *page_started,
1240 unsigned long *nr_written)
1243 struct btrfs_root *root = BTRFS_I(inode)->root;
1245 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)
1246 ret = run_delalloc_nocow(inode, locked_page, start, end,
1247 page_started, 1, nr_written);
1248 else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)
1249 ret = run_delalloc_nocow(inode, locked_page, start, end,
1250 page_started, 0, nr_written);
1251 else if (!btrfs_test_opt(root, COMPRESS) &&
1252 !(BTRFS_I(inode)->force_compress))
1253 ret = cow_file_range(inode, locked_page, start, end,
1254 page_started, nr_written, 1);
1256 ret = cow_file_range_async(inode, locked_page, start, end,
1257 page_started, nr_written);
1261 static int btrfs_split_extent_hook(struct inode *inode,
1262 struct extent_state *orig, u64 split)
1264 /* not delalloc, ignore it */
1265 if (!(orig->state & EXTENT_DELALLOC))
1268 atomic_inc(&BTRFS_I(inode)->outstanding_extents);
1273 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1274 * extents so we can keep track of new extents that are just merged onto old
1275 * extents, such as when we are doing sequential writes, so we can properly
1276 * account for the metadata space we'll need.
1278 static int btrfs_merge_extent_hook(struct inode *inode,
1279 struct extent_state *new,
1280 struct extent_state *other)
1282 /* not delalloc, ignore it */
1283 if (!(other->state & EXTENT_DELALLOC))
1286 atomic_dec(&BTRFS_I(inode)->outstanding_extents);
1291 * extent_io.c set_bit_hook, used to track delayed allocation
1292 * bytes in this file, and to maintain the list of inodes that
1293 * have pending delalloc work to be done.
1295 static int btrfs_set_bit_hook(struct inode *inode,
1296 struct extent_state *state, int *bits)
1300 * set_bit and clear bit hooks normally require _irqsave/restore
1301 * but in this case, we are only testeing for the DELALLOC
1302 * bit, which is only set or cleared with irqs on
1304 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1305 struct btrfs_root *root = BTRFS_I(inode)->root;
1306 u64 len = state->end + 1 - state->start;
1307 int do_list = (root->root_key.objectid !=
1308 BTRFS_ROOT_TREE_OBJECTID);
1310 if (*bits & EXTENT_FIRST_DELALLOC)
1311 *bits &= ~EXTENT_FIRST_DELALLOC;
1313 atomic_inc(&BTRFS_I(inode)->outstanding_extents);
1315 spin_lock(&root->fs_info->delalloc_lock);
1316 BTRFS_I(inode)->delalloc_bytes += len;
1317 root->fs_info->delalloc_bytes += len;
1318 if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1319 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1320 &root->fs_info->delalloc_inodes);
1322 spin_unlock(&root->fs_info->delalloc_lock);
1328 * extent_io.c clear_bit_hook, see set_bit_hook for why
1330 static int btrfs_clear_bit_hook(struct inode *inode,
1331 struct extent_state *state, int *bits)
1334 * set_bit and clear bit hooks normally require _irqsave/restore
1335 * but in this case, we are only testeing for the DELALLOC
1336 * bit, which is only set or cleared with irqs on
1338 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1339 struct btrfs_root *root = BTRFS_I(inode)->root;
1340 u64 len = state->end + 1 - state->start;
1341 int do_list = (root->root_key.objectid !=
1342 BTRFS_ROOT_TREE_OBJECTID);
1344 if (*bits & EXTENT_FIRST_DELALLOC)
1345 *bits &= ~EXTENT_FIRST_DELALLOC;
1346 else if (!(*bits & EXTENT_DO_ACCOUNTING))
1347 atomic_dec(&BTRFS_I(inode)->outstanding_extents);
1349 if (*bits & EXTENT_DO_ACCOUNTING)
1350 btrfs_delalloc_release_metadata(inode, len);
1352 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1354 btrfs_free_reserved_data_space(inode, len);
1356 spin_lock(&root->fs_info->delalloc_lock);
1357 root->fs_info->delalloc_bytes -= len;
1358 BTRFS_I(inode)->delalloc_bytes -= len;
1360 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1361 !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1362 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1364 spin_unlock(&root->fs_info->delalloc_lock);
1370 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1371 * we don't create bios that span stripes or chunks
1373 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1374 size_t size, struct bio *bio,
1375 unsigned long bio_flags)
1377 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1378 struct btrfs_mapping_tree *map_tree;
1379 u64 logical = (u64)bio->bi_sector << 9;
1384 if (bio_flags & EXTENT_BIO_COMPRESSED)
1387 length = bio->bi_size;
1388 map_tree = &root->fs_info->mapping_tree;
1389 map_length = length;
1390 ret = btrfs_map_block(map_tree, READ, logical,
1391 &map_length, NULL, 0);
1393 if (map_length < length + size)
1399 * in order to insert checksums into the metadata in large chunks,
1400 * we wait until bio submission time. All the pages in the bio are
1401 * checksummed and sums are attached onto the ordered extent record.
1403 * At IO completion time the cums attached on the ordered extent record
1404 * are inserted into the btree
1406 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1407 struct bio *bio, int mirror_num,
1408 unsigned long bio_flags,
1411 struct btrfs_root *root = BTRFS_I(inode)->root;
1414 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1420 * in order to insert checksums into the metadata in large chunks,
1421 * we wait until bio submission time. All the pages in the bio are
1422 * checksummed and sums are attached onto the ordered extent record.
1424 * At IO completion time the cums attached on the ordered extent record
1425 * are inserted into the btree
1427 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1428 int mirror_num, unsigned long bio_flags,
1431 struct btrfs_root *root = BTRFS_I(inode)->root;
1432 return btrfs_map_bio(root, rw, bio, mirror_num, 1);
1436 * extent_io.c submission hook. This does the right thing for csum calculation
1437 * on write, or reading the csums from the tree before a read
1439 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1440 int mirror_num, unsigned long bio_flags,
1443 struct btrfs_root *root = BTRFS_I(inode)->root;
1447 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1449 if (root == root->fs_info->tree_root)
1450 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 2);
1452 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
1455 if (!(rw & REQ_WRITE)) {
1456 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1457 return btrfs_submit_compressed_read(inode, bio,
1458 mirror_num, bio_flags);
1459 } else if (!skip_sum)
1460 btrfs_lookup_bio_sums(root, inode, bio, NULL);
1462 } else if (!skip_sum) {
1463 /* csum items have already been cloned */
1464 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1466 /* we're doing a write, do the async checksumming */
1467 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1468 inode, rw, bio, mirror_num,
1469 bio_flags, bio_offset,
1470 __btrfs_submit_bio_start,
1471 __btrfs_submit_bio_done);
1475 return btrfs_map_bio(root, rw, bio, mirror_num, 0);
1479 * given a list of ordered sums record them in the inode. This happens
1480 * at IO completion time based on sums calculated at bio submission time.
1482 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1483 struct inode *inode, u64 file_offset,
1484 struct list_head *list)
1486 struct btrfs_ordered_sum *sum;
1488 btrfs_set_trans_block_group(trans, inode);
1490 list_for_each_entry(sum, list, list) {
1491 btrfs_csum_file_blocks(trans,
1492 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1497 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1498 struct extent_state **cached_state)
1500 if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
1502 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1503 cached_state, GFP_NOFS);
1506 /* see btrfs_writepage_start_hook for details on why this is required */
1507 struct btrfs_writepage_fixup {
1509 struct btrfs_work work;
1512 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1514 struct btrfs_writepage_fixup *fixup;
1515 struct btrfs_ordered_extent *ordered;
1516 struct extent_state *cached_state = NULL;
1518 struct inode *inode;
1522 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1526 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1527 ClearPageChecked(page);
1531 inode = page->mapping->host;
1532 page_start = page_offset(page);
1533 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1535 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1536 &cached_state, GFP_NOFS);
1538 /* already ordered? We're done */
1539 if (PagePrivate2(page))
1542 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1544 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1545 page_end, &cached_state, GFP_NOFS);
1547 btrfs_start_ordered_extent(inode, ordered, 1);
1552 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1553 ClearPageChecked(page);
1555 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1556 &cached_state, GFP_NOFS);
1559 page_cache_release(page);
1564 * There are a few paths in the higher layers of the kernel that directly
1565 * set the page dirty bit without asking the filesystem if it is a
1566 * good idea. This causes problems because we want to make sure COW
1567 * properly happens and the data=ordered rules are followed.
1569 * In our case any range that doesn't have the ORDERED bit set
1570 * hasn't been properly setup for IO. We kick off an async process
1571 * to fix it up. The async helper will wait for ordered extents, set
1572 * the delalloc bit and make it safe to write the page.
1574 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1576 struct inode *inode = page->mapping->host;
1577 struct btrfs_writepage_fixup *fixup;
1578 struct btrfs_root *root = BTRFS_I(inode)->root;
1580 /* this page is properly in the ordered list */
1581 if (TestClearPagePrivate2(page))
1584 if (PageChecked(page))
1587 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1591 SetPageChecked(page);
1592 page_cache_get(page);
1593 fixup->work.func = btrfs_writepage_fixup_worker;
1595 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1599 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1600 struct inode *inode, u64 file_pos,
1601 u64 disk_bytenr, u64 disk_num_bytes,
1602 u64 num_bytes, u64 ram_bytes,
1603 u8 compression, u8 encryption,
1604 u16 other_encoding, int extent_type)
1606 struct btrfs_root *root = BTRFS_I(inode)->root;
1607 struct btrfs_file_extent_item *fi;
1608 struct btrfs_path *path;
1609 struct extent_buffer *leaf;
1610 struct btrfs_key ins;
1614 path = btrfs_alloc_path();
1617 path->leave_spinning = 1;
1620 * we may be replacing one extent in the tree with another.
1621 * The new extent is pinned in the extent map, and we don't want
1622 * to drop it from the cache until it is completely in the btree.
1624 * So, tell btrfs_drop_extents to leave this extent in the cache.
1625 * the caller is expected to unpin it and allow it to be merged
1628 ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
1632 ins.objectid = inode->i_ino;
1633 ins.offset = file_pos;
1634 ins.type = BTRFS_EXTENT_DATA_KEY;
1635 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1637 leaf = path->nodes[0];
1638 fi = btrfs_item_ptr(leaf, path->slots[0],
1639 struct btrfs_file_extent_item);
1640 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1641 btrfs_set_file_extent_type(leaf, fi, extent_type);
1642 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1643 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1644 btrfs_set_file_extent_offset(leaf, fi, 0);
1645 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1646 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1647 btrfs_set_file_extent_compression(leaf, fi, compression);
1648 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1649 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1651 btrfs_unlock_up_safe(path, 1);
1652 btrfs_set_lock_blocking(leaf);
1654 btrfs_mark_buffer_dirty(leaf);
1656 inode_add_bytes(inode, num_bytes);
1658 ins.objectid = disk_bytenr;
1659 ins.offset = disk_num_bytes;
1660 ins.type = BTRFS_EXTENT_ITEM_KEY;
1661 ret = btrfs_alloc_reserved_file_extent(trans, root,
1662 root->root_key.objectid,
1663 inode->i_ino, file_pos, &ins);
1665 btrfs_free_path(path);
1671 * helper function for btrfs_finish_ordered_io, this
1672 * just reads in some of the csum leaves to prime them into ram
1673 * before we start the transaction. It limits the amount of btree
1674 * reads required while inside the transaction.
1676 /* as ordered data IO finishes, this gets called so we can finish
1677 * an ordered extent if the range of bytes in the file it covers are
1680 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
1682 struct btrfs_root *root = BTRFS_I(inode)->root;
1683 struct btrfs_trans_handle *trans = NULL;
1684 struct btrfs_ordered_extent *ordered_extent = NULL;
1685 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1686 struct extent_state *cached_state = NULL;
1687 int compress_type = 0;
1689 bool nolock = false;
1691 ret = btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
1695 BUG_ON(!ordered_extent);
1697 nolock = (root == root->fs_info->tree_root);
1699 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1700 BUG_ON(!list_empty(&ordered_extent->list));
1701 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1704 trans = btrfs_join_transaction_nolock(root, 1);
1706 trans = btrfs_join_transaction(root, 1);
1708 btrfs_set_trans_block_group(trans, inode);
1709 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1710 ret = btrfs_update_inode(trans, root, inode);
1716 lock_extent_bits(io_tree, ordered_extent->file_offset,
1717 ordered_extent->file_offset + ordered_extent->len - 1,
1718 0, &cached_state, GFP_NOFS);
1721 trans = btrfs_join_transaction_nolock(root, 1);
1723 trans = btrfs_join_transaction(root, 1);
1724 btrfs_set_trans_block_group(trans, inode);
1725 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1727 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1728 compress_type = ordered_extent->compress_type;
1729 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1730 BUG_ON(compress_type);
1731 ret = btrfs_mark_extent_written(trans, inode,
1732 ordered_extent->file_offset,
1733 ordered_extent->file_offset +
1734 ordered_extent->len);
1737 BUG_ON(root == root->fs_info->tree_root);
1738 ret = insert_reserved_file_extent(trans, inode,
1739 ordered_extent->file_offset,
1740 ordered_extent->start,
1741 ordered_extent->disk_len,
1742 ordered_extent->len,
1743 ordered_extent->len,
1744 compress_type, 0, 0,
1745 BTRFS_FILE_EXTENT_REG);
1746 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1747 ordered_extent->file_offset,
1748 ordered_extent->len);
1751 unlock_extent_cached(io_tree, ordered_extent->file_offset,
1752 ordered_extent->file_offset +
1753 ordered_extent->len - 1, &cached_state, GFP_NOFS);
1755 add_pending_csums(trans, inode, ordered_extent->file_offset,
1756 &ordered_extent->list);
1758 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1759 ret = btrfs_update_inode(trans, root, inode);
1764 btrfs_end_transaction_nolock(trans, root);
1766 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
1768 btrfs_end_transaction(trans, root);
1772 btrfs_put_ordered_extent(ordered_extent);
1773 /* once for the tree */
1774 btrfs_put_ordered_extent(ordered_extent);
1779 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
1780 struct extent_state *state, int uptodate)
1782 ClearPagePrivate2(page);
1783 return btrfs_finish_ordered_io(page->mapping->host, start, end);
1787 * When IO fails, either with EIO or csum verification fails, we
1788 * try other mirrors that might have a good copy of the data. This
1789 * io_failure_record is used to record state as we go through all the
1790 * mirrors. If another mirror has good data, the page is set up to date
1791 * and things continue. If a good mirror can't be found, the original
1792 * bio end_io callback is called to indicate things have failed.
1794 struct io_failure_record {
1799 unsigned long bio_flags;
1803 static int btrfs_io_failed_hook(struct bio *failed_bio,
1804 struct page *page, u64 start, u64 end,
1805 struct extent_state *state)
1807 struct io_failure_record *failrec = NULL;
1809 struct extent_map *em;
1810 struct inode *inode = page->mapping->host;
1811 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
1812 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1819 ret = get_state_private(failure_tree, start, &private);
1821 failrec = kmalloc(sizeof(*failrec), GFP_NOFS);
1824 failrec->start = start;
1825 failrec->len = end - start + 1;
1826 failrec->last_mirror = 0;
1827 failrec->bio_flags = 0;
1829 read_lock(&em_tree->lock);
1830 em = lookup_extent_mapping(em_tree, start, failrec->len);
1831 if (em->start > start || em->start + em->len < start) {
1832 free_extent_map(em);
1835 read_unlock(&em_tree->lock);
1837 if (!em || IS_ERR(em)) {
1841 logical = start - em->start;
1842 logical = em->block_start + logical;
1843 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
1844 logical = em->block_start;
1845 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
1846 extent_set_compress_type(&failrec->bio_flags,
1849 failrec->logical = logical;
1850 free_extent_map(em);
1851 set_extent_bits(failure_tree, start, end, EXTENT_LOCKED |
1852 EXTENT_DIRTY, GFP_NOFS);
1853 set_state_private(failure_tree, start,
1854 (u64)(unsigned long)failrec);
1856 failrec = (struct io_failure_record *)(unsigned long)private;
1858 num_copies = btrfs_num_copies(
1859 &BTRFS_I(inode)->root->fs_info->mapping_tree,
1860 failrec->logical, failrec->len);
1861 failrec->last_mirror++;
1863 spin_lock(&BTRFS_I(inode)->io_tree.lock);
1864 state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
1867 if (state && state->start != failrec->start)
1869 spin_unlock(&BTRFS_I(inode)->io_tree.lock);
1871 if (!state || failrec->last_mirror > num_copies) {
1872 set_state_private(failure_tree, failrec->start, 0);
1873 clear_extent_bits(failure_tree, failrec->start,
1874 failrec->start + failrec->len - 1,
1875 EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
1879 bio = bio_alloc(GFP_NOFS, 1);
1880 bio->bi_private = state;
1881 bio->bi_end_io = failed_bio->bi_end_io;
1882 bio->bi_sector = failrec->logical >> 9;
1883 bio->bi_bdev = failed_bio->bi_bdev;
1886 bio_add_page(bio, page, failrec->len, start - page_offset(page));
1887 if (failed_bio->bi_rw & REQ_WRITE)
1892 BTRFS_I(inode)->io_tree.ops->submit_bio_hook(inode, rw, bio,
1893 failrec->last_mirror,
1894 failrec->bio_flags, 0);
1899 * each time an IO finishes, we do a fast check in the IO failure tree
1900 * to see if we need to process or clean up an io_failure_record
1902 static int btrfs_clean_io_failures(struct inode *inode, u64 start)
1905 u64 private_failure;
1906 struct io_failure_record *failure;
1910 if (count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
1911 (u64)-1, 1, EXTENT_DIRTY)) {
1912 ret = get_state_private(&BTRFS_I(inode)->io_failure_tree,
1913 start, &private_failure);
1915 failure = (struct io_failure_record *)(unsigned long)
1917 set_state_private(&BTRFS_I(inode)->io_failure_tree,
1919 clear_extent_bits(&BTRFS_I(inode)->io_failure_tree,
1921 failure->start + failure->len - 1,
1922 EXTENT_DIRTY | EXTENT_LOCKED,
1931 * when reads are done, we need to check csums to verify the data is correct
1932 * if there's a match, we allow the bio to finish. If not, we go through
1933 * the io_failure_record routines to find good copies
1935 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
1936 struct extent_state *state)
1938 size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
1939 struct inode *inode = page->mapping->host;
1940 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1942 u64 private = ~(u32)0;
1944 struct btrfs_root *root = BTRFS_I(inode)->root;
1947 if (PageChecked(page)) {
1948 ClearPageChecked(page);
1952 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
1955 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
1956 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
1957 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
1962 if (state && state->start == start) {
1963 private = state->private;
1966 ret = get_state_private(io_tree, start, &private);
1968 kaddr = kmap_atomic(page, KM_USER0);
1972 csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
1973 btrfs_csum_final(csum, (char *)&csum);
1974 if (csum != private)
1977 kunmap_atomic(kaddr, KM_USER0);
1979 /* if the io failure tree for this inode is non-empty,
1980 * check to see if we've recovered from a failed IO
1982 btrfs_clean_io_failures(inode, start);
1986 if (printk_ratelimit()) {
1987 printk(KERN_INFO "btrfs csum failed ino %lu off %llu csum %u "
1988 "private %llu\n", page->mapping->host->i_ino,
1989 (unsigned long long)start, csum,
1990 (unsigned long long)private);
1992 memset(kaddr + offset, 1, end - start + 1);
1993 flush_dcache_page(page);
1994 kunmap_atomic(kaddr, KM_USER0);
2000 struct delayed_iput {
2001 struct list_head list;
2002 struct inode *inode;
2005 void btrfs_add_delayed_iput(struct inode *inode)
2007 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2008 struct delayed_iput *delayed;
2010 if (atomic_add_unless(&inode->i_count, -1, 1))
2013 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2014 delayed->inode = inode;
2016 spin_lock(&fs_info->delayed_iput_lock);
2017 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2018 spin_unlock(&fs_info->delayed_iput_lock);
2021 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2024 struct btrfs_fs_info *fs_info = root->fs_info;
2025 struct delayed_iput *delayed;
2028 spin_lock(&fs_info->delayed_iput_lock);
2029 empty = list_empty(&fs_info->delayed_iputs);
2030 spin_unlock(&fs_info->delayed_iput_lock);
2034 down_read(&root->fs_info->cleanup_work_sem);
2035 spin_lock(&fs_info->delayed_iput_lock);
2036 list_splice_init(&fs_info->delayed_iputs, &list);
2037 spin_unlock(&fs_info->delayed_iput_lock);
2039 while (!list_empty(&list)) {
2040 delayed = list_entry(list.next, struct delayed_iput, list);
2041 list_del(&delayed->list);
2042 iput(delayed->inode);
2045 up_read(&root->fs_info->cleanup_work_sem);
2049 * calculate extra metadata reservation when snapshotting a subvolume
2050 * contains orphan files.
2052 void btrfs_orphan_pre_snapshot(struct btrfs_trans_handle *trans,
2053 struct btrfs_pending_snapshot *pending,
2054 u64 *bytes_to_reserve)
2056 struct btrfs_root *root;
2057 struct btrfs_block_rsv *block_rsv;
2061 root = pending->root;
2062 if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2065 block_rsv = root->orphan_block_rsv;
2067 /* orphan block reservation for the snapshot */
2068 num_bytes = block_rsv->size;
2071 * after the snapshot is created, COWing tree blocks may use more
2072 * space than it frees. So we should make sure there is enough
2075 index = trans->transid & 0x1;
2076 if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2077 num_bytes += block_rsv->size -
2078 (block_rsv->reserved + block_rsv->freed[index]);
2081 *bytes_to_reserve += num_bytes;
2084 void btrfs_orphan_post_snapshot(struct btrfs_trans_handle *trans,
2085 struct btrfs_pending_snapshot *pending)
2087 struct btrfs_root *root = pending->root;
2088 struct btrfs_root *snap = pending->snap;
2089 struct btrfs_block_rsv *block_rsv;
2094 if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2097 /* refill source subvolume's orphan block reservation */
2098 block_rsv = root->orphan_block_rsv;
2099 index = trans->transid & 0x1;
2100 if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2101 num_bytes = block_rsv->size -
2102 (block_rsv->reserved + block_rsv->freed[index]);
2103 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2104 root->orphan_block_rsv,
2109 /* setup orphan block reservation for the snapshot */
2110 block_rsv = btrfs_alloc_block_rsv(snap);
2113 btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2114 snap->orphan_block_rsv = block_rsv;
2116 num_bytes = root->orphan_block_rsv->size;
2117 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2118 block_rsv, num_bytes);
2122 /* insert orphan item for the snapshot */
2123 WARN_ON(!root->orphan_item_inserted);
2124 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2125 snap->root_key.objectid);
2127 snap->orphan_item_inserted = 1;
2131 enum btrfs_orphan_cleanup_state {
2132 ORPHAN_CLEANUP_STARTED = 1,
2133 ORPHAN_CLEANUP_DONE = 2,
2137 * This is called in transaction commmit time. If there are no orphan
2138 * files in the subvolume, it removes orphan item and frees block_rsv
2141 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2142 struct btrfs_root *root)
2146 if (!list_empty(&root->orphan_list) ||
2147 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2150 if (root->orphan_item_inserted &&
2151 btrfs_root_refs(&root->root_item) > 0) {
2152 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2153 root->root_key.objectid);
2155 root->orphan_item_inserted = 0;
2158 if (root->orphan_block_rsv) {
2159 WARN_ON(root->orphan_block_rsv->size > 0);
2160 btrfs_free_block_rsv(root, root->orphan_block_rsv);
2161 root->orphan_block_rsv = NULL;
2166 * This creates an orphan entry for the given inode in case something goes
2167 * wrong in the middle of an unlink/truncate.
2169 * NOTE: caller of this function should reserve 5 units of metadata for
2172 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2174 struct btrfs_root *root = BTRFS_I(inode)->root;
2175 struct btrfs_block_rsv *block_rsv = NULL;
2180 if (!root->orphan_block_rsv) {
2181 block_rsv = btrfs_alloc_block_rsv(root);
2185 spin_lock(&root->orphan_lock);
2186 if (!root->orphan_block_rsv) {
2187 root->orphan_block_rsv = block_rsv;
2188 } else if (block_rsv) {
2189 btrfs_free_block_rsv(root, block_rsv);
2193 if (list_empty(&BTRFS_I(inode)->i_orphan)) {
2194 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2197 * For proper ENOSPC handling, we should do orphan
2198 * cleanup when mounting. But this introduces backward
2199 * compatibility issue.
2201 if (!xchg(&root->orphan_item_inserted, 1))
2208 WARN_ON(!BTRFS_I(inode)->orphan_meta_reserved);
2211 if (!BTRFS_I(inode)->orphan_meta_reserved) {
2212 BTRFS_I(inode)->orphan_meta_reserved = 1;
2215 spin_unlock(&root->orphan_lock);
2218 btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2220 /* grab metadata reservation from transaction handle */
2222 ret = btrfs_orphan_reserve_metadata(trans, inode);
2226 /* insert an orphan item to track this unlinked/truncated file */
2228 ret = btrfs_insert_orphan_item(trans, root, inode->i_ino);
2232 /* insert an orphan item to track subvolume contains orphan files */
2234 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2235 root->root_key.objectid);
2242 * We have done the truncate/delete so we can go ahead and remove the orphan
2243 * item for this particular inode.
2245 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2247 struct btrfs_root *root = BTRFS_I(inode)->root;
2248 int delete_item = 0;
2249 int release_rsv = 0;
2252 spin_lock(&root->orphan_lock);
2253 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
2254 list_del_init(&BTRFS_I(inode)->i_orphan);
2258 if (BTRFS_I(inode)->orphan_meta_reserved) {
2259 BTRFS_I(inode)->orphan_meta_reserved = 0;
2262 spin_unlock(&root->orphan_lock);
2264 if (trans && delete_item) {
2265 ret = btrfs_del_orphan_item(trans, root, inode->i_ino);
2270 btrfs_orphan_release_metadata(inode);
2276 * this cleans up any orphans that may be left on the list from the last use
2279 void btrfs_orphan_cleanup(struct btrfs_root *root)
2281 struct btrfs_path *path;
2282 struct extent_buffer *leaf;
2283 struct btrfs_key key, found_key;
2284 struct btrfs_trans_handle *trans;
2285 struct inode *inode;
2286 int ret = 0, nr_unlink = 0, nr_truncate = 0;
2288 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2291 path = btrfs_alloc_path();
2295 key.objectid = BTRFS_ORPHAN_OBJECTID;
2296 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2297 key.offset = (u64)-1;
2300 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2302 printk(KERN_ERR "Error searching slot for orphan: %d"
2308 * if ret == 0 means we found what we were searching for, which
2309 * is weird, but possible, so only screw with path if we didnt
2310 * find the key and see if we have stuff that matches
2313 if (path->slots[0] == 0)
2318 /* pull out the item */
2319 leaf = path->nodes[0];
2320 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2322 /* make sure the item matches what we want */
2323 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2325 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2328 /* release the path since we're done with it */
2329 btrfs_release_path(root, path);
2332 * this is where we are basically btrfs_lookup, without the
2333 * crossing root thing. we store the inode number in the
2334 * offset of the orphan item.
2336 found_key.objectid = found_key.offset;
2337 found_key.type = BTRFS_INODE_ITEM_KEY;
2338 found_key.offset = 0;
2339 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2340 BUG_ON(IS_ERR(inode));
2343 * add this inode to the orphan list so btrfs_orphan_del does
2344 * the proper thing when we hit it
2346 spin_lock(&root->orphan_lock);
2347 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2348 spin_unlock(&root->orphan_lock);
2351 * if this is a bad inode, means we actually succeeded in
2352 * removing the inode, but not the orphan record, which means
2353 * we need to manually delete the orphan since iput will just
2354 * do a destroy_inode
2356 if (is_bad_inode(inode)) {
2357 trans = btrfs_start_transaction(root, 0);
2358 btrfs_orphan_del(trans, inode);
2359 btrfs_end_transaction(trans, root);
2364 /* if we have links, this was a truncate, lets do that */
2365 if (inode->i_nlink) {
2367 btrfs_truncate(inode);
2372 /* this will do delete_inode and everything for us */
2375 btrfs_free_path(path);
2377 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2379 if (root->orphan_block_rsv)
2380 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2383 if (root->orphan_block_rsv || root->orphan_item_inserted) {
2384 trans = btrfs_join_transaction(root, 1);
2385 btrfs_end_transaction(trans, root);
2389 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2391 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2395 * very simple check to peek ahead in the leaf looking for xattrs. If we
2396 * don't find any xattrs, we know there can't be any acls.
2398 * slot is the slot the inode is in, objectid is the objectid of the inode
2400 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2401 int slot, u64 objectid)
2403 u32 nritems = btrfs_header_nritems(leaf);
2404 struct btrfs_key found_key;
2408 while (slot < nritems) {
2409 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2411 /* we found a different objectid, there must not be acls */
2412 if (found_key.objectid != objectid)
2415 /* we found an xattr, assume we've got an acl */
2416 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2420 * we found a key greater than an xattr key, there can't
2421 * be any acls later on
2423 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2430 * it goes inode, inode backrefs, xattrs, extents,
2431 * so if there are a ton of hard links to an inode there can
2432 * be a lot of backrefs. Don't waste time searching too hard,
2433 * this is just an optimization
2438 /* we hit the end of the leaf before we found an xattr or
2439 * something larger than an xattr. We have to assume the inode
2446 * read an inode from the btree into the in-memory inode
2448 static void btrfs_read_locked_inode(struct inode *inode)
2450 struct btrfs_path *path;
2451 struct extent_buffer *leaf;
2452 struct btrfs_inode_item *inode_item;
2453 struct btrfs_timespec *tspec;
2454 struct btrfs_root *root = BTRFS_I(inode)->root;
2455 struct btrfs_key location;
2457 u64 alloc_group_block;
2461 path = btrfs_alloc_path();
2463 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2465 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2469 leaf = path->nodes[0];
2470 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2471 struct btrfs_inode_item);
2473 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2474 inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
2475 inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2476 inode->i_gid = btrfs_inode_gid(leaf, inode_item);
2477 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2479 tspec = btrfs_inode_atime(inode_item);
2480 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2481 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2483 tspec = btrfs_inode_mtime(inode_item);
2484 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2485 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2487 tspec = btrfs_inode_ctime(inode_item);
2488 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2489 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2491 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2492 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2493 BTRFS_I(inode)->sequence = btrfs_inode_sequence(leaf, inode_item);
2494 inode->i_generation = BTRFS_I(inode)->generation;
2496 rdev = btrfs_inode_rdev(leaf, inode_item);
2498 BTRFS_I(inode)->index_cnt = (u64)-1;
2499 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2501 alloc_group_block = btrfs_inode_block_group(leaf, inode_item);
2504 * try to precache a NULL acl entry for files that don't have
2505 * any xattrs or acls
2507 maybe_acls = acls_after_inode_item(leaf, path->slots[0], inode->i_ino);
2509 cache_no_acl(inode);
2511 BTRFS_I(inode)->block_group = btrfs_find_block_group(root, 0,
2512 alloc_group_block, 0);
2513 btrfs_free_path(path);
2516 switch (inode->i_mode & S_IFMT) {
2518 inode->i_mapping->a_ops = &btrfs_aops;
2519 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2520 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2521 inode->i_fop = &btrfs_file_operations;
2522 inode->i_op = &btrfs_file_inode_operations;
2525 inode->i_fop = &btrfs_dir_file_operations;
2526 if (root == root->fs_info->tree_root)
2527 inode->i_op = &btrfs_dir_ro_inode_operations;
2529 inode->i_op = &btrfs_dir_inode_operations;
2532 inode->i_op = &btrfs_symlink_inode_operations;
2533 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2534 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2537 inode->i_op = &btrfs_special_inode_operations;
2538 init_special_inode(inode, inode->i_mode, rdev);
2542 btrfs_update_iflags(inode);
2546 btrfs_free_path(path);
2547 make_bad_inode(inode);
2551 * given a leaf and an inode, copy the inode fields into the leaf
2553 static void fill_inode_item(struct btrfs_trans_handle *trans,
2554 struct extent_buffer *leaf,
2555 struct btrfs_inode_item *item,
2556 struct inode *inode)
2558 btrfs_set_inode_uid(leaf, item, inode->i_uid);
2559 btrfs_set_inode_gid(leaf, item, inode->i_gid);
2560 btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
2561 btrfs_set_inode_mode(leaf, item, inode->i_mode);
2562 btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2564 btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2565 inode->i_atime.tv_sec);
2566 btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2567 inode->i_atime.tv_nsec);
2569 btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2570 inode->i_mtime.tv_sec);
2571 btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2572 inode->i_mtime.tv_nsec);
2574 btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2575 inode->i_ctime.tv_sec);
2576 btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2577 inode->i_ctime.tv_nsec);
2579 btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
2580 btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
2581 btrfs_set_inode_sequence(leaf, item, BTRFS_I(inode)->sequence);
2582 btrfs_set_inode_transid(leaf, item, trans->transid);
2583 btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
2584 btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
2585 btrfs_set_inode_block_group(leaf, item, BTRFS_I(inode)->block_group);
2589 * copy everything in the in-memory inode into the btree.
2591 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2592 struct btrfs_root *root, struct inode *inode)
2594 struct btrfs_inode_item *inode_item;
2595 struct btrfs_path *path;
2596 struct extent_buffer *leaf;
2599 path = btrfs_alloc_path();
2601 path->leave_spinning = 1;
2602 ret = btrfs_lookup_inode(trans, root, path,
2603 &BTRFS_I(inode)->location, 1);
2610 btrfs_unlock_up_safe(path, 1);
2611 leaf = path->nodes[0];
2612 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2613 struct btrfs_inode_item);
2615 fill_inode_item(trans, leaf, inode_item, inode);
2616 btrfs_mark_buffer_dirty(leaf);
2617 btrfs_set_inode_last_trans(trans, inode);
2620 btrfs_free_path(path);
2626 * unlink helper that gets used here in inode.c and in the tree logging
2627 * recovery code. It remove a link in a directory with a given name, and
2628 * also drops the back refs in the inode to the directory
2630 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2631 struct btrfs_root *root,
2632 struct inode *dir, struct inode *inode,
2633 const char *name, int name_len)
2635 struct btrfs_path *path;
2637 struct extent_buffer *leaf;
2638 struct btrfs_dir_item *di;
2639 struct btrfs_key key;
2642 path = btrfs_alloc_path();
2648 path->leave_spinning = 1;
2649 di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2650 name, name_len, -1);
2659 leaf = path->nodes[0];
2660 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2661 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2664 btrfs_release_path(root, path);
2666 ret = btrfs_del_inode_ref(trans, root, name, name_len,
2668 dir->i_ino, &index);
2670 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2671 "inode %lu parent %lu\n", name_len, name,
2672 inode->i_ino, dir->i_ino);
2676 di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
2677 index, name, name_len, -1);
2686 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2687 btrfs_release_path(root, path);
2689 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2691 BUG_ON(ret != 0 && ret != -ENOENT);
2693 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2698 btrfs_free_path(path);
2702 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2703 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2704 btrfs_update_inode(trans, root, dir);
2705 btrfs_drop_nlink(inode);
2706 ret = btrfs_update_inode(trans, root, inode);
2711 /* helper to check if there is any shared block in the path */
2712 static int check_path_shared(struct btrfs_root *root,
2713 struct btrfs_path *path)
2715 struct extent_buffer *eb;
2718 int uninitialized_var(ret);
2720 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2721 if (!path->nodes[level])
2723 eb = path->nodes[level];
2724 if (!btrfs_block_can_be_shared(root, eb))
2726 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2731 return ret; /* XXX callers? */
2735 * helper to start transaction for unlink and rmdir.
2737 * unlink and rmdir are special in btrfs, they do not always free space.
2738 * so in enospc case, we should make sure they will free space before
2739 * allowing them to use the global metadata reservation.
2741 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2742 struct dentry *dentry)
2744 struct btrfs_trans_handle *trans;
2745 struct btrfs_root *root = BTRFS_I(dir)->root;
2746 struct btrfs_path *path;
2747 struct btrfs_inode_ref *ref;
2748 struct btrfs_dir_item *di;
2749 struct inode *inode = dentry->d_inode;
2755 trans = btrfs_start_transaction(root, 10);
2756 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2759 if (inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2760 return ERR_PTR(-ENOSPC);
2762 /* check if there is someone else holds reference */
2763 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2764 return ERR_PTR(-ENOSPC);
2766 if (atomic_read(&inode->i_count) > 2)
2767 return ERR_PTR(-ENOSPC);
2769 if (xchg(&root->fs_info->enospc_unlink, 1))
2770 return ERR_PTR(-ENOSPC);
2772 path = btrfs_alloc_path();
2774 root->fs_info->enospc_unlink = 0;
2775 return ERR_PTR(-ENOMEM);
2778 trans = btrfs_start_transaction(root, 0);
2779 if (IS_ERR(trans)) {
2780 btrfs_free_path(path);
2781 root->fs_info->enospc_unlink = 0;
2785 path->skip_locking = 1;
2786 path->search_commit_root = 1;
2788 ret = btrfs_lookup_inode(trans, root, path,
2789 &BTRFS_I(dir)->location, 0);
2795 if (check_path_shared(root, path))
2800 btrfs_release_path(root, path);
2802 ret = btrfs_lookup_inode(trans, root, path,
2803 &BTRFS_I(inode)->location, 0);
2809 if (check_path_shared(root, path))
2814 btrfs_release_path(root, path);
2816 if (ret == 0 && S_ISREG(inode->i_mode)) {
2817 ret = btrfs_lookup_file_extent(trans, root, path,
2818 inode->i_ino, (u64)-1, 0);
2824 if (check_path_shared(root, path))
2826 btrfs_release_path(root, path);
2834 di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2835 dentry->d_name.name, dentry->d_name.len, 0);
2841 if (check_path_shared(root, path))
2847 btrfs_release_path(root, path);
2849 ref = btrfs_lookup_inode_ref(trans, root, path,
2850 dentry->d_name.name, dentry->d_name.len,
2851 inode->i_ino, dir->i_ino, 0);
2857 if (check_path_shared(root, path))
2859 index = btrfs_inode_ref_index(path->nodes[0], ref);
2860 btrfs_release_path(root, path);
2862 di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino, index,
2863 dentry->d_name.name, dentry->d_name.len, 0);
2868 BUG_ON(ret == -ENOENT);
2869 if (check_path_shared(root, path))
2874 btrfs_free_path(path);
2876 btrfs_end_transaction(trans, root);
2877 root->fs_info->enospc_unlink = 0;
2878 return ERR_PTR(err);
2881 trans->block_rsv = &root->fs_info->global_block_rsv;
2885 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
2886 struct btrfs_root *root)
2888 if (trans->block_rsv == &root->fs_info->global_block_rsv) {
2889 BUG_ON(!root->fs_info->enospc_unlink);
2890 root->fs_info->enospc_unlink = 0;
2892 btrfs_end_transaction_throttle(trans, root);
2895 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
2897 struct btrfs_root *root = BTRFS_I(dir)->root;
2898 struct btrfs_trans_handle *trans;
2899 struct inode *inode = dentry->d_inode;
2901 unsigned long nr = 0;
2903 trans = __unlink_start_trans(dir, dentry);
2905 return PTR_ERR(trans);
2907 btrfs_set_trans_block_group(trans, dir);
2909 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
2911 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2912 dentry->d_name.name, dentry->d_name.len);
2915 if (inode->i_nlink == 0) {
2916 ret = btrfs_orphan_add(trans, inode);
2920 nr = trans->blocks_used;
2921 __unlink_end_trans(trans, root);
2922 btrfs_btree_balance_dirty(root, nr);
2926 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
2927 struct btrfs_root *root,
2928 struct inode *dir, u64 objectid,
2929 const char *name, int name_len)
2931 struct btrfs_path *path;
2932 struct extent_buffer *leaf;
2933 struct btrfs_dir_item *di;
2934 struct btrfs_key key;
2938 path = btrfs_alloc_path();
2942 di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2943 name, name_len, -1);
2944 BUG_ON(!di || IS_ERR(di));
2946 leaf = path->nodes[0];
2947 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2948 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2949 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2951 btrfs_release_path(root, path);
2953 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
2954 objectid, root->root_key.objectid,
2955 dir->i_ino, &index, name, name_len);
2957 BUG_ON(ret != -ENOENT);
2958 di = btrfs_search_dir_index_item(root, path, dir->i_ino,
2960 BUG_ON(!di || IS_ERR(di));
2962 leaf = path->nodes[0];
2963 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2964 btrfs_release_path(root, path);
2968 di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
2969 index, name, name_len, -1);
2970 BUG_ON(!di || IS_ERR(di));
2972 leaf = path->nodes[0];
2973 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2974 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2975 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2977 btrfs_release_path(root, path);
2979 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2980 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2981 ret = btrfs_update_inode(trans, root, dir);
2984 btrfs_free_path(path);
2988 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
2990 struct inode *inode = dentry->d_inode;
2992 struct btrfs_root *root = BTRFS_I(dir)->root;
2993 struct btrfs_trans_handle *trans;
2994 unsigned long nr = 0;
2996 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
2997 inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
3000 trans = __unlink_start_trans(dir, dentry);
3002 return PTR_ERR(trans);
3004 btrfs_set_trans_block_group(trans, dir);
3006 if (unlikely(inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3007 err = btrfs_unlink_subvol(trans, root, dir,
3008 BTRFS_I(inode)->location.objectid,
3009 dentry->d_name.name,
3010 dentry->d_name.len);
3014 err = btrfs_orphan_add(trans, inode);
3018 /* now the directory is empty */
3019 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3020 dentry->d_name.name, dentry->d_name.len);
3022 btrfs_i_size_write(inode, 0);
3024 nr = trans->blocks_used;
3025 __unlink_end_trans(trans, root);
3026 btrfs_btree_balance_dirty(root, nr);
3033 * when truncating bytes in a file, it is possible to avoid reading
3034 * the leaves that contain only checksum items. This can be the
3035 * majority of the IO required to delete a large file, but it must
3036 * be done carefully.
3038 * The keys in the level just above the leaves are checked to make sure
3039 * the lowest key in a given leaf is a csum key, and starts at an offset
3040 * after the new size.
3042 * Then the key for the next leaf is checked to make sure it also has
3043 * a checksum item for the same file. If it does, we know our target leaf
3044 * contains only checksum items, and it can be safely freed without reading
3047 * This is just an optimization targeted at large files. It may do
3048 * nothing. It will return 0 unless things went badly.
3050 static noinline int drop_csum_leaves(struct btrfs_trans_handle *trans,
3051 struct btrfs_root *root,
3052 struct btrfs_path *path,
3053 struct inode *inode, u64 new_size)
3055 struct btrfs_key key;
3058 struct btrfs_key found_key;
3059 struct btrfs_key other_key;
3060 struct btrfs_leaf_ref *ref;
3064 path->lowest_level = 1;
3065 key.objectid = inode->i_ino;
3066 key.type = BTRFS_CSUM_ITEM_KEY;
3067 key.offset = new_size;
3069 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3073 if (path->nodes[1] == NULL) {
3078 btrfs_node_key_to_cpu(path->nodes[1], &found_key, path->slots[1]);
3079 nritems = btrfs_header_nritems(path->nodes[1]);
3084 if (path->slots[1] >= nritems)
3087 /* did we find a key greater than anything we want to delete? */
3088 if (found_key.objectid > inode->i_ino ||
3089 (found_key.objectid == inode->i_ino && found_key.type > key.type))
3092 /* we check the next key in the node to make sure the leave contains
3093 * only checksum items. This comparison doesn't work if our
3094 * leaf is the last one in the node
3096 if (path->slots[1] + 1 >= nritems) {
3098 /* search forward from the last key in the node, this
3099 * will bring us into the next node in the tree
3101 btrfs_node_key_to_cpu(path->nodes[1], &found_key, nritems - 1);
3103 /* unlikely, but we inc below, so check to be safe */
3104 if (found_key.offset == (u64)-1)
3107 /* search_forward needs a path with locks held, do the
3108 * search again for the original key. It is possible
3109 * this will race with a balance and return a path that
3110 * we could modify, but this drop is just an optimization
3111 * and is allowed to miss some leaves.
3113 btrfs_release_path(root, path);
3116 /* setup a max key for search_forward */
3117 other_key.offset = (u64)-1;
3118 other_key.type = key.type;
3119 other_key.objectid = key.objectid;
3121 path->keep_locks = 1;
3122 ret = btrfs_search_forward(root, &found_key, &other_key,
3124 path->keep_locks = 0;
3125 if (ret || found_key.objectid != key.objectid ||
3126 found_key.type != key.type) {
3131 key.offset = found_key.offset;
3132 btrfs_release_path(root, path);
3137 /* we know there's one more slot after us in the tree,
3138 * read that key so we can verify it is also a checksum item
3140 btrfs_node_key_to_cpu(path->nodes[1], &other_key, path->slots[1] + 1);
3142 if (found_key.objectid < inode->i_ino)
3145 if (found_key.type != key.type || found_key.offset < new_size)
3149 * if the key for the next leaf isn't a csum key from this objectid,
3150 * we can't be sure there aren't good items inside this leaf.
3153 if (other_key.objectid != inode->i_ino || other_key.type != key.type)
3156 leaf_start = btrfs_node_blockptr(path->nodes[1], path->slots[1]);
3157 leaf_gen = btrfs_node_ptr_generation(path->nodes[1], path->slots[1]);
3159 * it is safe to delete this leaf, it contains only
3160 * csum items from this inode at an offset >= new_size
3162 ret = btrfs_del_leaf(trans, root, path, leaf_start);
3165 if (root->ref_cows && leaf_gen < trans->transid) {
3166 ref = btrfs_alloc_leaf_ref(root, 0);
3168 ref->root_gen = root->root_key.offset;
3169 ref->bytenr = leaf_start;
3171 ref->generation = leaf_gen;
3174 btrfs_sort_leaf_ref(ref);
3176 ret = btrfs_add_leaf_ref(root, ref, 0);
3178 btrfs_free_leaf_ref(root, ref);
3184 btrfs_release_path(root, path);
3186 if (other_key.objectid == inode->i_ino &&
3187 other_key.type == key.type && other_key.offset > key.offset) {
3188 key.offset = other_key.offset;
3194 /* fixup any changes we've made to the path */
3195 path->lowest_level = 0;
3196 path->keep_locks = 0;
3197 btrfs_release_path(root, path);
3204 * this can truncate away extent items, csum items and directory items.
3205 * It starts at a high offset and removes keys until it can't find
3206 * any higher than new_size
3208 * csum items that cross the new i_size are truncated to the new size
3211 * min_type is the minimum key type to truncate down to. If set to 0, this
3212 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3214 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3215 struct btrfs_root *root,
3216 struct inode *inode,
3217 u64 new_size, u32 min_type)
3219 struct btrfs_path *path;
3220 struct extent_buffer *leaf;
3221 struct btrfs_file_extent_item *fi;
3222 struct btrfs_key key;
3223 struct btrfs_key found_key;
3224 u64 extent_start = 0;
3225 u64 extent_num_bytes = 0;
3226 u64 extent_offset = 0;
3228 u64 mask = root->sectorsize - 1;
3229 u32 found_type = (u8)-1;
3232 int pending_del_nr = 0;
3233 int pending_del_slot = 0;
3234 int extent_type = -1;
3239 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3241 if (root->ref_cows || root == root->fs_info->tree_root)
3242 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
3244 path = btrfs_alloc_path();
3248 key.objectid = inode->i_ino;
3249 key.offset = (u64)-1;
3253 path->leave_spinning = 1;
3254 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3261 /* there are no items in the tree for us to truncate, we're
3264 if (path->slots[0] == 0)
3271 leaf = path->nodes[0];
3272 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3273 found_type = btrfs_key_type(&found_key);
3276 if (found_key.objectid != inode->i_ino)
3279 if (found_type < min_type)
3282 item_end = found_key.offset;
3283 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3284 fi = btrfs_item_ptr(leaf, path->slots[0],
3285 struct btrfs_file_extent_item);
3286 extent_type = btrfs_file_extent_type(leaf, fi);
3287 encoding = btrfs_file_extent_compression(leaf, fi);
3288 encoding |= btrfs_file_extent_encryption(leaf, fi);
3289 encoding |= btrfs_file_extent_other_encoding(leaf, fi);
3291 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3293 btrfs_file_extent_num_bytes(leaf, fi);
3294 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3295 item_end += btrfs_file_extent_inline_len(leaf,
3300 if (found_type > min_type) {
3303 if (item_end < new_size)
3305 if (found_key.offset >= new_size)
3311 /* FIXME, shrink the extent if the ref count is only 1 */
3312 if (found_type != BTRFS_EXTENT_DATA_KEY)
3315 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3317 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3318 if (!del_item && !encoding) {
3319 u64 orig_num_bytes =
3320 btrfs_file_extent_num_bytes(leaf, fi);
3321 extent_num_bytes = new_size -
3322 found_key.offset + root->sectorsize - 1;
3323 extent_num_bytes = extent_num_bytes &
3324 ~((u64)root->sectorsize - 1);
3325 btrfs_set_file_extent_num_bytes(leaf, fi,
3327 num_dec = (orig_num_bytes -
3329 if (root->ref_cows && extent_start != 0)
3330 inode_sub_bytes(inode, num_dec);
3331 btrfs_mark_buffer_dirty(leaf);
3334 btrfs_file_extent_disk_num_bytes(leaf,
3336 extent_offset = found_key.offset -
3337 btrfs_file_extent_offset(leaf, fi);
3339 /* FIXME blocksize != 4096 */
3340 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3341 if (extent_start != 0) {
3344 inode_sub_bytes(inode, num_dec);
3347 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3349 * we can't truncate inline items that have had
3353 btrfs_file_extent_compression(leaf, fi) == 0 &&
3354 btrfs_file_extent_encryption(leaf, fi) == 0 &&
3355 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3356 u32 size = new_size - found_key.offset;
3358 if (root->ref_cows) {
3359 inode_sub_bytes(inode, item_end + 1 -
3363 btrfs_file_extent_calc_inline_size(size);
3364 ret = btrfs_truncate_item(trans, root, path,
3367 } else if (root->ref_cows) {
3368 inode_sub_bytes(inode, item_end + 1 -
3374 if (!pending_del_nr) {
3375 /* no pending yet, add ourselves */
3376 pending_del_slot = path->slots[0];
3378 } else if (pending_del_nr &&
3379 path->slots[0] + 1 == pending_del_slot) {
3380 /* hop on the pending chunk */
3382 pending_del_slot = path->slots[0];
3389 if (found_extent && (root->ref_cows ||
3390 root == root->fs_info->tree_root)) {
3391 btrfs_set_path_blocking(path);
3392 ret = btrfs_free_extent(trans, root, extent_start,
3393 extent_num_bytes, 0,
3394 btrfs_header_owner(leaf),
3395 inode->i_ino, extent_offset);
3399 if (found_type == BTRFS_INODE_ITEM_KEY)
3402 if (path->slots[0] == 0 ||
3403 path->slots[0] != pending_del_slot) {
3404 if (root->ref_cows) {
3408 if (pending_del_nr) {
3409 ret = btrfs_del_items(trans, root, path,
3415 btrfs_release_path(root, path);
3422 if (pending_del_nr) {
3423 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3427 btrfs_free_path(path);
3432 * taken from block_truncate_page, but does cow as it zeros out
3433 * any bytes left in the last page in the file.
3435 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
3437 struct inode *inode = mapping->host;
3438 struct btrfs_root *root = BTRFS_I(inode)->root;
3439 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3440 struct btrfs_ordered_extent *ordered;
3441 struct extent_state *cached_state = NULL;
3443 u32 blocksize = root->sectorsize;
3444 pgoff_t index = from >> PAGE_CACHE_SHIFT;
3445 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3451 if ((offset & (blocksize - 1)) == 0)
3453 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3459 page = grab_cache_page(mapping, index);
3461 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3465 page_start = page_offset(page);
3466 page_end = page_start + PAGE_CACHE_SIZE - 1;
3468 if (!PageUptodate(page)) {
3469 ret = btrfs_readpage(NULL, page);
3471 if (page->mapping != mapping) {
3473 page_cache_release(page);
3476 if (!PageUptodate(page)) {
3481 wait_on_page_writeback(page);
3483 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
3485 set_page_extent_mapped(page);
3487 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3489 unlock_extent_cached(io_tree, page_start, page_end,
3490 &cached_state, GFP_NOFS);
3492 page_cache_release(page);
3493 btrfs_start_ordered_extent(inode, ordered, 1);
3494 btrfs_put_ordered_extent(ordered);
3498 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3499 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
3500 0, 0, &cached_state, GFP_NOFS);
3502 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3505 unlock_extent_cached(io_tree, page_start, page_end,
3506 &cached_state, GFP_NOFS);
3511 if (offset != PAGE_CACHE_SIZE) {
3513 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
3514 flush_dcache_page(page);
3517 ClearPageChecked(page);
3518 set_page_dirty(page);
3519 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3524 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3526 page_cache_release(page);
3531 int btrfs_cont_expand(struct inode *inode, loff_t size)
3533 struct btrfs_trans_handle *trans;
3534 struct btrfs_root *root = BTRFS_I(inode)->root;
3535 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3536 struct extent_map *em = NULL;
3537 struct extent_state *cached_state = NULL;
3538 u64 mask = root->sectorsize - 1;
3539 u64 hole_start = (inode->i_size + mask) & ~mask;
3540 u64 block_end = (size + mask) & ~mask;
3546 if (size <= hole_start)
3550 struct btrfs_ordered_extent *ordered;
3551 btrfs_wait_ordered_range(inode, hole_start,
3552 block_end - hole_start);
3553 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3554 &cached_state, GFP_NOFS);
3555 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3558 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3559 &cached_state, GFP_NOFS);
3560 btrfs_put_ordered_extent(ordered);
3563 cur_offset = hole_start;
3565 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3566 block_end - cur_offset, 0);
3567 BUG_ON(IS_ERR(em) || !em);
3568 last_byte = min(extent_map_end(em), block_end);
3569 last_byte = (last_byte + mask) & ~mask;
3570 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3572 hole_size = last_byte - cur_offset;
3574 trans = btrfs_start_transaction(root, 2);
3575 if (IS_ERR(trans)) {
3576 err = PTR_ERR(trans);
3579 btrfs_set_trans_block_group(trans, inode);
3581 err = btrfs_drop_extents(trans, inode, cur_offset,
3582 cur_offset + hole_size,
3586 err = btrfs_insert_file_extent(trans, root,
3587 inode->i_ino, cur_offset, 0,
3588 0, hole_size, 0, hole_size,
3592 btrfs_drop_extent_cache(inode, hole_start,
3595 btrfs_end_transaction(trans, root);
3597 free_extent_map(em);
3599 cur_offset = last_byte;
3600 if (cur_offset >= block_end)
3604 free_extent_map(em);
3605 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3610 static int btrfs_setattr_size(struct inode *inode, struct iattr *attr)
3612 struct btrfs_root *root = BTRFS_I(inode)->root;
3613 struct btrfs_trans_handle *trans;
3617 if (attr->ia_size == inode->i_size)
3620 if (attr->ia_size > inode->i_size) {
3621 unsigned long limit;
3622 limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
3623 if (attr->ia_size > inode->i_sb->s_maxbytes)
3625 if (limit != RLIM_INFINITY && attr->ia_size > limit) {
3626 send_sig(SIGXFSZ, current, 0);
3631 trans = btrfs_start_transaction(root, 5);
3633 return PTR_ERR(trans);
3635 btrfs_set_trans_block_group(trans, inode);
3637 ret = btrfs_orphan_add(trans, inode);
3640 nr = trans->blocks_used;
3641 btrfs_end_transaction(trans, root);
3642 btrfs_btree_balance_dirty(root, nr);
3644 if (attr->ia_size > inode->i_size) {
3645 ret = btrfs_cont_expand(inode, attr->ia_size);
3647 btrfs_truncate(inode);
3651 i_size_write(inode, attr->ia_size);
3652 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
3654 trans = btrfs_start_transaction(root, 0);
3655 BUG_ON(IS_ERR(trans));
3656 btrfs_set_trans_block_group(trans, inode);
3657 trans->block_rsv = root->orphan_block_rsv;
3658 BUG_ON(!trans->block_rsv);
3660 ret = btrfs_update_inode(trans, root, inode);
3662 if (inode->i_nlink > 0) {
3663 ret = btrfs_orphan_del(trans, inode);
3666 nr = trans->blocks_used;
3667 btrfs_end_transaction(trans, root);
3668 btrfs_btree_balance_dirty(root, nr);
3673 * We're truncating a file that used to have good data down to
3674 * zero. Make sure it gets into the ordered flush list so that
3675 * any new writes get down to disk quickly.
3677 if (attr->ia_size == 0)
3678 BTRFS_I(inode)->ordered_data_close = 1;
3680 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3681 ret = vmtruncate(inode, attr->ia_size);
3687 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3689 struct inode *inode = dentry->d_inode;
3690 struct btrfs_root *root = BTRFS_I(inode)->root;
3693 if (btrfs_root_readonly(root))
3696 err = inode_change_ok(inode, attr);
3700 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3701 err = btrfs_setattr_size(inode, attr);
3706 if (attr->ia_valid) {
3707 setattr_copy(inode, attr);
3708 mark_inode_dirty(inode);
3710 if (attr->ia_valid & ATTR_MODE)
3711 err = btrfs_acl_chmod(inode);
3717 void btrfs_evict_inode(struct inode *inode)
3719 struct btrfs_trans_handle *trans;
3720 struct btrfs_root *root = BTRFS_I(inode)->root;
3724 truncate_inode_pages(&inode->i_data, 0);
3725 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
3726 root == root->fs_info->tree_root))
3729 if (is_bad_inode(inode)) {
3730 btrfs_orphan_del(NULL, inode);
3733 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
3734 btrfs_wait_ordered_range(inode, 0, (u64)-1);
3736 if (root->fs_info->log_root_recovering) {
3737 BUG_ON(!list_empty(&BTRFS_I(inode)->i_orphan));
3741 if (inode->i_nlink > 0) {
3742 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3746 btrfs_i_size_write(inode, 0);
3749 trans = btrfs_start_transaction(root, 0);
3750 BUG_ON(IS_ERR(trans));
3751 btrfs_set_trans_block_group(trans, inode);
3752 trans->block_rsv = root->orphan_block_rsv;
3754 ret = btrfs_block_rsv_check(trans, root,
3755 root->orphan_block_rsv, 0, 5);
3757 BUG_ON(ret != -EAGAIN);
3758 ret = btrfs_commit_transaction(trans, root);
3763 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3767 nr = trans->blocks_used;
3768 btrfs_end_transaction(trans, root);
3770 btrfs_btree_balance_dirty(root, nr);
3775 ret = btrfs_orphan_del(trans, inode);
3779 nr = trans->blocks_used;
3780 btrfs_end_transaction(trans, root);
3781 btrfs_btree_balance_dirty(root, nr);
3783 end_writeback(inode);
3788 * this returns the key found in the dir entry in the location pointer.
3789 * If no dir entries were found, location->objectid is 0.
3791 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3792 struct btrfs_key *location)
3794 const char *name = dentry->d_name.name;
3795 int namelen = dentry->d_name.len;
3796 struct btrfs_dir_item *di;
3797 struct btrfs_path *path;
3798 struct btrfs_root *root = BTRFS_I(dir)->root;
3801 path = btrfs_alloc_path();
3804 di = btrfs_lookup_dir_item(NULL, root, path, dir->i_ino, name,
3809 if (!di || IS_ERR(di))
3812 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
3814 btrfs_free_path(path);
3817 location->objectid = 0;
3822 * when we hit a tree root in a directory, the btrfs part of the inode
3823 * needs to be changed to reflect the root directory of the tree root. This
3824 * is kind of like crossing a mount point.
3826 static int fixup_tree_root_location(struct btrfs_root *root,
3828 struct dentry *dentry,
3829 struct btrfs_key *location,
3830 struct btrfs_root **sub_root)
3832 struct btrfs_path *path;
3833 struct btrfs_root *new_root;
3834 struct btrfs_root_ref *ref;
3835 struct extent_buffer *leaf;
3839 path = btrfs_alloc_path();
3846 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
3847 BTRFS_I(dir)->root->root_key.objectid,
3848 location->objectid);
3855 leaf = path->nodes[0];
3856 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
3857 if (btrfs_root_ref_dirid(leaf, ref) != dir->i_ino ||
3858 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
3861 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
3862 (unsigned long)(ref + 1),
3863 dentry->d_name.len);
3867 btrfs_release_path(root->fs_info->tree_root, path);
3869 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
3870 if (IS_ERR(new_root)) {
3871 err = PTR_ERR(new_root);
3875 if (btrfs_root_refs(&new_root->root_item) == 0) {
3880 *sub_root = new_root;
3881 location->objectid = btrfs_root_dirid(&new_root->root_item);
3882 location->type = BTRFS_INODE_ITEM_KEY;
3883 location->offset = 0;
3886 btrfs_free_path(path);
3890 static void inode_tree_add(struct inode *inode)
3892 struct btrfs_root *root = BTRFS_I(inode)->root;
3893 struct btrfs_inode *entry;
3895 struct rb_node *parent;
3897 p = &root->inode_tree.rb_node;
3900 if (hlist_unhashed(&inode->i_hash))
3903 spin_lock(&root->inode_lock);
3906 entry = rb_entry(parent, struct btrfs_inode, rb_node);
3908 if (inode->i_ino < entry->vfs_inode.i_ino)
3909 p = &parent->rb_left;
3910 else if (inode->i_ino > entry->vfs_inode.i_ino)
3911 p = &parent->rb_right;
3913 WARN_ON(!(entry->vfs_inode.i_state &
3914 (I_WILL_FREE | I_FREEING)));
3915 rb_erase(parent, &root->inode_tree);
3916 RB_CLEAR_NODE(parent);
3917 spin_unlock(&root->inode_lock);
3921 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
3922 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3923 spin_unlock(&root->inode_lock);
3926 static void inode_tree_del(struct inode *inode)
3928 struct btrfs_root *root = BTRFS_I(inode)->root;
3931 spin_lock(&root->inode_lock);
3932 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
3933 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3934 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
3935 empty = RB_EMPTY_ROOT(&root->inode_tree);
3937 spin_unlock(&root->inode_lock);
3940 * Free space cache has inodes in the tree root, but the tree root has a
3941 * root_refs of 0, so this could end up dropping the tree root as a
3942 * snapshot, so we need the extra !root->fs_info->tree_root check to
3943 * make sure we don't drop it.
3945 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
3946 root != root->fs_info->tree_root) {
3947 synchronize_srcu(&root->fs_info->subvol_srcu);
3948 spin_lock(&root->inode_lock);
3949 empty = RB_EMPTY_ROOT(&root->inode_tree);
3950 spin_unlock(&root->inode_lock);
3952 btrfs_add_dead_root(root);
3956 int btrfs_invalidate_inodes(struct btrfs_root *root)
3958 struct rb_node *node;
3959 struct rb_node *prev;
3960 struct btrfs_inode *entry;
3961 struct inode *inode;
3964 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3966 spin_lock(&root->inode_lock);
3968 node = root->inode_tree.rb_node;
3972 entry = rb_entry(node, struct btrfs_inode, rb_node);
3974 if (objectid < entry->vfs_inode.i_ino)
3975 node = node->rb_left;
3976 else if (objectid > entry->vfs_inode.i_ino)
3977 node = node->rb_right;
3983 entry = rb_entry(prev, struct btrfs_inode, rb_node);
3984 if (objectid <= entry->vfs_inode.i_ino) {
3988 prev = rb_next(prev);
3992 entry = rb_entry(node, struct btrfs_inode, rb_node);
3993 objectid = entry->vfs_inode.i_ino + 1;
3994 inode = igrab(&entry->vfs_inode);
3996 spin_unlock(&root->inode_lock);
3997 if (atomic_read(&inode->i_count) > 1)
3998 d_prune_aliases(inode);
4000 * btrfs_drop_inode will have it removed from
4001 * the inode cache when its usage count
4006 spin_lock(&root->inode_lock);
4010 if (cond_resched_lock(&root->inode_lock))
4013 node = rb_next(node);
4015 spin_unlock(&root->inode_lock);
4019 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4021 struct btrfs_iget_args *args = p;
4022 inode->i_ino = args->ino;
4023 BTRFS_I(inode)->root = args->root;
4024 btrfs_set_inode_space_info(args->root, inode);
4028 static int btrfs_find_actor(struct inode *inode, void *opaque)
4030 struct btrfs_iget_args *args = opaque;
4031 return args->ino == inode->i_ino &&
4032 args->root == BTRFS_I(inode)->root;
4035 static struct inode *btrfs_iget_locked(struct super_block *s,
4037 struct btrfs_root *root)
4039 struct inode *inode;
4040 struct btrfs_iget_args args;
4041 args.ino = objectid;
4044 inode = iget5_locked(s, objectid, btrfs_find_actor,
4045 btrfs_init_locked_inode,
4050 /* Get an inode object given its location and corresponding root.
4051 * Returns in *is_new if the inode was read from disk
4053 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4054 struct btrfs_root *root, int *new)
4056 struct inode *inode;
4058 inode = btrfs_iget_locked(s, location->objectid, root);
4060 return ERR_PTR(-ENOMEM);
4062 if (inode->i_state & I_NEW) {
4063 BTRFS_I(inode)->root = root;
4064 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4065 btrfs_read_locked_inode(inode);
4067 inode_tree_add(inode);
4068 unlock_new_inode(inode);
4076 static struct inode *new_simple_dir(struct super_block *s,
4077 struct btrfs_key *key,
4078 struct btrfs_root *root)
4080 struct inode *inode = new_inode(s);
4083 return ERR_PTR(-ENOMEM);
4085 BTRFS_I(inode)->root = root;
4086 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4087 BTRFS_I(inode)->dummy_inode = 1;
4089 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4090 inode->i_op = &simple_dir_inode_operations;
4091 inode->i_fop = &simple_dir_operations;
4092 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4093 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4098 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4100 struct inode *inode;
4101 struct btrfs_root *root = BTRFS_I(dir)->root;
4102 struct btrfs_root *sub_root = root;
4103 struct btrfs_key location;
4107 dentry->d_op = &btrfs_dentry_operations;
4109 if (dentry->d_name.len > BTRFS_NAME_LEN)
4110 return ERR_PTR(-ENAMETOOLONG);
4112 ret = btrfs_inode_by_name(dir, dentry, &location);
4115 return ERR_PTR(ret);
4117 if (location.objectid == 0)
4120 if (location.type == BTRFS_INODE_ITEM_KEY) {
4121 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4125 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4127 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4128 ret = fixup_tree_root_location(root, dir, dentry,
4129 &location, &sub_root);
4132 inode = ERR_PTR(ret);
4134 inode = new_simple_dir(dir->i_sb, &location, sub_root);
4136 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4138 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4140 if (!IS_ERR(inode) && root != sub_root) {
4141 down_read(&root->fs_info->cleanup_work_sem);
4142 if (!(inode->i_sb->s_flags & MS_RDONLY))
4143 btrfs_orphan_cleanup(sub_root);
4144 up_read(&root->fs_info->cleanup_work_sem);
4150 static int btrfs_dentry_delete(struct dentry *dentry)
4152 struct btrfs_root *root;
4154 if (!dentry->d_inode && !IS_ROOT(dentry))
4155 dentry = dentry->d_parent;
4157 if (dentry->d_inode) {
4158 root = BTRFS_I(dentry->d_inode)->root;
4159 if (btrfs_root_refs(&root->root_item) == 0)
4165 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4166 struct nameidata *nd)
4168 struct inode *inode;
4170 inode = btrfs_lookup_dentry(dir, dentry);
4172 return ERR_CAST(inode);
4174 return d_splice_alias(inode, dentry);
4177 static unsigned char btrfs_filetype_table[] = {
4178 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4181 static int btrfs_real_readdir(struct file *filp, void *dirent,
4184 struct inode *inode = filp->f_dentry->d_inode;
4185 struct btrfs_root *root = BTRFS_I(inode)->root;
4186 struct btrfs_item *item;
4187 struct btrfs_dir_item *di;
4188 struct btrfs_key key;
4189 struct btrfs_key found_key;
4190 struct btrfs_path *path;
4193 struct extent_buffer *leaf;
4196 unsigned char d_type;
4201 int key_type = BTRFS_DIR_INDEX_KEY;
4206 /* FIXME, use a real flag for deciding about the key type */
4207 if (root->fs_info->tree_root == root)
4208 key_type = BTRFS_DIR_ITEM_KEY;
4210 /* special case for "." */
4211 if (filp->f_pos == 0) {
4212 over = filldir(dirent, ".", 1,
4219 /* special case for .., just use the back ref */
4220 if (filp->f_pos == 1) {
4221 u64 pino = parent_ino(filp->f_path.dentry);
4222 over = filldir(dirent, "..", 2,
4228 path = btrfs_alloc_path();
4231 btrfs_set_key_type(&key, key_type);
4232 key.offset = filp->f_pos;
4233 key.objectid = inode->i_ino;
4235 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4241 leaf = path->nodes[0];
4242 nritems = btrfs_header_nritems(leaf);
4243 slot = path->slots[0];
4244 if (advance || slot >= nritems) {
4245 if (slot >= nritems - 1) {
4246 ret = btrfs_next_leaf(root, path);
4249 leaf = path->nodes[0];
4250 nritems = btrfs_header_nritems(leaf);
4251 slot = path->slots[0];
4259 item = btrfs_item_nr(leaf, slot);
4260 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4262 if (found_key.objectid != key.objectid)
4264 if (btrfs_key_type(&found_key) != key_type)
4266 if (found_key.offset < filp->f_pos)
4269 filp->f_pos = found_key.offset;
4271 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4273 di_total = btrfs_item_size(leaf, item);
4275 while (di_cur < di_total) {
4276 struct btrfs_key location;
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);
4353 btrfs_set_trans_block_group(trans, inode);
4355 ret = btrfs_end_transaction_nolock(trans, root);
4357 ret = btrfs_commit_transaction(trans, root);
4363 * This is somewhat expensive, updating the tree every time the
4364 * inode changes. But, it is most likely to find the inode in cache.
4365 * FIXME, needs more benchmarking...there are no reasons other than performance
4366 * to keep or drop this code.
4368 void btrfs_dirty_inode(struct inode *inode)
4370 struct btrfs_root *root = BTRFS_I(inode)->root;
4371 struct btrfs_trans_handle *trans;
4374 if (BTRFS_I(inode)->dummy_inode)
4377 trans = btrfs_join_transaction(root, 1);
4378 btrfs_set_trans_block_group(trans, inode);
4380 ret = btrfs_update_inode(trans, root, inode);
4381 if (ret && ret == -ENOSPC) {
4382 /* whoops, lets try again with the full transaction */
4383 btrfs_end_transaction(trans, root);
4384 trans = btrfs_start_transaction(root, 1);
4385 if (IS_ERR(trans)) {
4386 if (printk_ratelimit()) {
4387 printk(KERN_ERR "btrfs: fail to "
4388 "dirty inode %lu error %ld\n",
4389 inode->i_ino, PTR_ERR(trans));
4393 btrfs_set_trans_block_group(trans, inode);
4395 ret = btrfs_update_inode(trans, root, inode);
4397 if (printk_ratelimit()) {
4398 printk(KERN_ERR "btrfs: fail to "
4399 "dirty inode %lu error %d\n",
4404 btrfs_end_transaction(trans, root);
4408 * find the highest existing sequence number in a directory
4409 * and then set the in-memory index_cnt variable to reflect
4410 * free sequence numbers
4412 static int btrfs_set_inode_index_count(struct inode *inode)
4414 struct btrfs_root *root = BTRFS_I(inode)->root;
4415 struct btrfs_key key, found_key;
4416 struct btrfs_path *path;
4417 struct extent_buffer *leaf;
4420 key.objectid = inode->i_ino;
4421 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4422 key.offset = (u64)-1;
4424 path = btrfs_alloc_path();
4428 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4431 /* FIXME: we should be able to handle this */
4437 * MAGIC NUMBER EXPLANATION:
4438 * since we search a directory based on f_pos we have to start at 2
4439 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4440 * else has to start at 2
4442 if (path->slots[0] == 0) {
4443 BTRFS_I(inode)->index_cnt = 2;
4449 leaf = path->nodes[0];
4450 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4452 if (found_key.objectid != inode->i_ino ||
4453 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4454 BTRFS_I(inode)->index_cnt = 2;
4458 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4460 btrfs_free_path(path);
4465 * helper to find a free sequence number in a given directory. This current
4466 * code is very simple, later versions will do smarter things in the btree
4468 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4472 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4473 ret = btrfs_set_inode_index_count(dir);
4478 *index = BTRFS_I(dir)->index_cnt;
4479 BTRFS_I(dir)->index_cnt++;
4484 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4485 struct btrfs_root *root,
4487 const char *name, int name_len,
4488 u64 ref_objectid, u64 objectid,
4489 u64 alloc_hint, int mode, u64 *index)
4491 struct inode *inode;
4492 struct btrfs_inode_item *inode_item;
4493 struct btrfs_key *location;
4494 struct btrfs_path *path;
4495 struct btrfs_inode_ref *ref;
4496 struct btrfs_key key[2];
4502 path = btrfs_alloc_path();
4505 inode = new_inode(root->fs_info->sb);
4507 return ERR_PTR(-ENOMEM);
4510 ret = btrfs_set_inode_index(dir, index);
4513 return ERR_PTR(ret);
4517 * index_cnt is ignored for everything but a dir,
4518 * btrfs_get_inode_index_count has an explanation for the magic
4521 BTRFS_I(inode)->index_cnt = 2;
4522 BTRFS_I(inode)->root = root;
4523 BTRFS_I(inode)->generation = trans->transid;
4524 inode->i_generation = BTRFS_I(inode)->generation;
4525 btrfs_set_inode_space_info(root, inode);
4531 BTRFS_I(inode)->block_group =
4532 btrfs_find_block_group(root, 0, alloc_hint, owner);
4534 key[0].objectid = objectid;
4535 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4538 key[1].objectid = objectid;
4539 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4540 key[1].offset = ref_objectid;
4542 sizes[0] = sizeof(struct btrfs_inode_item);
4543 sizes[1] = name_len + sizeof(*ref);
4545 path->leave_spinning = 1;
4546 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4550 inode_init_owner(inode, dir, mode);
4551 inode->i_ino = objectid;
4552 inode_set_bytes(inode, 0);
4553 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4554 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4555 struct btrfs_inode_item);
4556 fill_inode_item(trans, path->nodes[0], inode_item, inode);
4558 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4559 struct btrfs_inode_ref);
4560 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4561 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4562 ptr = (unsigned long)(ref + 1);
4563 write_extent_buffer(path->nodes[0], name, ptr, name_len);
4565 btrfs_mark_buffer_dirty(path->nodes[0]);
4566 btrfs_free_path(path);
4568 location = &BTRFS_I(inode)->location;
4569 location->objectid = objectid;
4570 location->offset = 0;
4571 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4573 btrfs_inherit_iflags(inode, dir);
4575 if ((mode & S_IFREG)) {
4576 if (btrfs_test_opt(root, NODATASUM))
4577 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4578 if (btrfs_test_opt(root, NODATACOW))
4579 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4582 insert_inode_hash(inode);
4583 inode_tree_add(inode);
4587 BTRFS_I(dir)->index_cnt--;
4588 btrfs_free_path(path);
4590 return ERR_PTR(ret);
4593 static inline u8 btrfs_inode_type(struct inode *inode)
4595 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4599 * utility function to add 'inode' into 'parent_inode' with
4600 * a give name and a given sequence number.
4601 * if 'add_backref' is true, also insert a backref from the
4602 * inode to the parent directory.
4604 int btrfs_add_link(struct btrfs_trans_handle *trans,
4605 struct inode *parent_inode, struct inode *inode,
4606 const char *name, int name_len, int add_backref, u64 index)
4609 struct btrfs_key key;
4610 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4612 if (unlikely(inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4613 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4615 key.objectid = inode->i_ino;
4616 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4620 if (unlikely(inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4621 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4622 key.objectid, root->root_key.objectid,
4623 parent_inode->i_ino,
4624 index, name, name_len);
4625 } else if (add_backref) {
4626 ret = btrfs_insert_inode_ref(trans, root,
4627 name, name_len, inode->i_ino,
4628 parent_inode->i_ino, index);
4632 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4633 parent_inode->i_ino, &key,
4634 btrfs_inode_type(inode), index);
4637 btrfs_i_size_write(parent_inode, parent_inode->i_size +
4639 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4640 ret = btrfs_update_inode(trans, root, parent_inode);
4645 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4646 struct inode *dir, struct dentry *dentry,
4647 struct inode *inode, int backref, u64 index)
4649 int err = btrfs_add_link(trans, dir, inode,
4650 dentry->d_name.name, dentry->d_name.len,
4653 d_instantiate(dentry, inode);
4661 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4662 int mode, dev_t rdev)
4664 struct btrfs_trans_handle *trans;
4665 struct btrfs_root *root = BTRFS_I(dir)->root;
4666 struct inode *inode = NULL;
4670 unsigned long nr = 0;
4673 if (!new_valid_dev(rdev))
4676 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4681 * 2 for inode item and ref
4683 * 1 for xattr if selinux is on
4685 trans = btrfs_start_transaction(root, 5);
4687 return PTR_ERR(trans);
4689 btrfs_set_trans_block_group(trans, dir);
4691 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4692 dentry->d_name.len, dir->i_ino, objectid,
4693 BTRFS_I(dir)->block_group, mode, &index);
4694 err = PTR_ERR(inode);
4698 err = btrfs_init_inode_security(trans, inode, dir);
4704 btrfs_set_trans_block_group(trans, inode);
4705 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4709 inode->i_op = &btrfs_special_inode_operations;
4710 init_special_inode(inode, inode->i_mode, rdev);
4711 btrfs_update_inode(trans, root, inode);
4713 btrfs_update_inode_block_group(trans, inode);
4714 btrfs_update_inode_block_group(trans, dir);
4716 nr = trans->blocks_used;
4717 btrfs_end_transaction_throttle(trans, root);
4718 btrfs_btree_balance_dirty(root, nr);
4720 inode_dec_link_count(inode);
4726 static int btrfs_create(struct inode *dir, struct dentry *dentry,
4727 int mode, struct nameidata *nd)
4729 struct btrfs_trans_handle *trans;
4730 struct btrfs_root *root = BTRFS_I(dir)->root;
4731 struct inode *inode = NULL;
4734 unsigned long nr = 0;
4738 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4742 * 2 for inode item and ref
4744 * 1 for xattr if selinux is on
4746 trans = btrfs_start_transaction(root, 5);
4748 return PTR_ERR(trans);
4750 btrfs_set_trans_block_group(trans, dir);
4752 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4753 dentry->d_name.len, dir->i_ino, objectid,
4754 BTRFS_I(dir)->block_group, mode, &index);
4755 err = PTR_ERR(inode);
4759 err = btrfs_init_inode_security(trans, inode, dir);
4765 btrfs_set_trans_block_group(trans, inode);
4766 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4770 inode->i_mapping->a_ops = &btrfs_aops;
4771 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4772 inode->i_fop = &btrfs_file_operations;
4773 inode->i_op = &btrfs_file_inode_operations;
4774 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
4776 btrfs_update_inode_block_group(trans, inode);
4777 btrfs_update_inode_block_group(trans, dir);
4779 nr = trans->blocks_used;
4780 btrfs_end_transaction_throttle(trans, root);
4782 inode_dec_link_count(inode);
4785 btrfs_btree_balance_dirty(root, nr);
4789 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
4790 struct dentry *dentry)
4792 struct btrfs_trans_handle *trans;
4793 struct btrfs_root *root = BTRFS_I(dir)->root;
4794 struct inode *inode = old_dentry->d_inode;
4796 unsigned long nr = 0;
4800 if (inode->i_nlink == 0)
4803 /* do not allow sys_link's with other subvols of the same device */
4804 if (root->objectid != BTRFS_I(inode)->root->objectid)
4807 btrfs_inc_nlink(inode);
4808 inode->i_ctime = CURRENT_TIME;
4810 err = btrfs_set_inode_index(dir, &index);
4815 * 1 item for inode ref
4816 * 2 items for dir items
4818 trans = btrfs_start_transaction(root, 3);
4819 if (IS_ERR(trans)) {
4820 err = PTR_ERR(trans);
4824 btrfs_set_trans_block_group(trans, dir);
4825 atomic_inc(&inode->i_count);
4827 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
4832 struct dentry *parent = dget_parent(dentry);
4833 btrfs_update_inode_block_group(trans, dir);
4834 err = btrfs_update_inode(trans, root, inode);
4836 btrfs_log_new_name(trans, inode, NULL, parent);
4840 nr = trans->blocks_used;
4841 btrfs_end_transaction_throttle(trans, root);
4844 inode_dec_link_count(inode);
4847 btrfs_btree_balance_dirty(root, nr);
4851 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
4853 struct inode *inode = NULL;
4854 struct btrfs_trans_handle *trans;
4855 struct btrfs_root *root = BTRFS_I(dir)->root;
4857 int drop_on_err = 0;
4860 unsigned long nr = 1;
4862 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4867 * 2 items for inode and ref
4868 * 2 items for dir items
4869 * 1 for xattr if selinux is on
4871 trans = btrfs_start_transaction(root, 5);
4873 return PTR_ERR(trans);
4874 btrfs_set_trans_block_group(trans, dir);
4876 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4877 dentry->d_name.len, dir->i_ino, objectid,
4878 BTRFS_I(dir)->block_group, S_IFDIR | mode,
4880 if (IS_ERR(inode)) {
4881 err = PTR_ERR(inode);
4887 err = btrfs_init_inode_security(trans, inode, dir);
4891 inode->i_op = &btrfs_dir_inode_operations;
4892 inode->i_fop = &btrfs_dir_file_operations;
4893 btrfs_set_trans_block_group(trans, inode);
4895 btrfs_i_size_write(inode, 0);
4896 err = btrfs_update_inode(trans, root, inode);
4900 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
4901 dentry->d_name.len, 0, index);
4905 d_instantiate(dentry, inode);
4907 btrfs_update_inode_block_group(trans, inode);
4908 btrfs_update_inode_block_group(trans, dir);
4911 nr = trans->blocks_used;
4912 btrfs_end_transaction_throttle(trans, root);
4915 btrfs_btree_balance_dirty(root, nr);
4919 /* helper for btfs_get_extent. Given an existing extent in the tree,
4920 * and an extent that you want to insert, deal with overlap and insert
4921 * the new extent into the tree.
4923 static int merge_extent_mapping(struct extent_map_tree *em_tree,
4924 struct extent_map *existing,
4925 struct extent_map *em,
4926 u64 map_start, u64 map_len)
4930 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
4931 start_diff = map_start - em->start;
4932 em->start = map_start;
4934 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
4935 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
4936 em->block_start += start_diff;
4937 em->block_len -= start_diff;
4939 return add_extent_mapping(em_tree, em);
4942 static noinline int uncompress_inline(struct btrfs_path *path,
4943 struct inode *inode, struct page *page,
4944 size_t pg_offset, u64 extent_offset,
4945 struct btrfs_file_extent_item *item)
4948 struct extent_buffer *leaf = path->nodes[0];
4951 unsigned long inline_size;
4955 WARN_ON(pg_offset != 0);
4956 compress_type = btrfs_file_extent_compression(leaf, item);
4957 max_size = btrfs_file_extent_ram_bytes(leaf, item);
4958 inline_size = btrfs_file_extent_inline_item_len(leaf,
4959 btrfs_item_nr(leaf, path->slots[0]));
4960 tmp = kmalloc(inline_size, GFP_NOFS);
4961 ptr = btrfs_file_extent_inline_start(item);
4963 read_extent_buffer(leaf, tmp, ptr, inline_size);
4965 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
4966 ret = btrfs_decompress(compress_type, tmp, page,
4967 extent_offset, inline_size, max_size);
4969 char *kaddr = kmap_atomic(page, KM_USER0);
4970 unsigned long copy_size = min_t(u64,
4971 PAGE_CACHE_SIZE - pg_offset,
4972 max_size - extent_offset);
4973 memset(kaddr + pg_offset, 0, copy_size);
4974 kunmap_atomic(kaddr, KM_USER0);
4981 * a bit scary, this does extent mapping from logical file offset to the disk.
4982 * the ugly parts come from merging extents from the disk with the in-ram
4983 * representation. This gets more complex because of the data=ordered code,
4984 * where the in-ram extents might be locked pending data=ordered completion.
4986 * This also copies inline extents directly into the page.
4989 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
4990 size_t pg_offset, u64 start, u64 len,
4996 u64 extent_start = 0;
4998 u64 objectid = inode->i_ino;
5000 struct btrfs_path *path = NULL;
5001 struct btrfs_root *root = BTRFS_I(inode)->root;
5002 struct btrfs_file_extent_item *item;
5003 struct extent_buffer *leaf;
5004 struct btrfs_key found_key;
5005 struct extent_map *em = NULL;
5006 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5007 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5008 struct btrfs_trans_handle *trans = NULL;
5012 read_lock(&em_tree->lock);
5013 em = lookup_extent_mapping(em_tree, start, len);
5015 em->bdev = root->fs_info->fs_devices->latest_bdev;
5016 read_unlock(&em_tree->lock);
5019 if (em->start > start || em->start + em->len <= start)
5020 free_extent_map(em);
5021 else if (em->block_start == EXTENT_MAP_INLINE && page)
5022 free_extent_map(em);
5026 em = alloc_extent_map(GFP_NOFS);
5031 em->bdev = root->fs_info->fs_devices->latest_bdev;
5032 em->start = EXTENT_MAP_HOLE;
5033 em->orig_start = EXTENT_MAP_HOLE;
5035 em->block_len = (u64)-1;
5038 path = btrfs_alloc_path();
5042 ret = btrfs_lookup_file_extent(trans, root, path,
5043 objectid, start, trans != NULL);
5050 if (path->slots[0] == 0)
5055 leaf = path->nodes[0];
5056 item = btrfs_item_ptr(leaf, path->slots[0],
5057 struct btrfs_file_extent_item);
5058 /* are we inside the extent that was found? */
5059 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5060 found_type = btrfs_key_type(&found_key);
5061 if (found_key.objectid != objectid ||
5062 found_type != BTRFS_EXTENT_DATA_KEY) {
5066 found_type = btrfs_file_extent_type(leaf, item);
5067 extent_start = found_key.offset;
5068 compress_type = btrfs_file_extent_compression(leaf, item);
5069 if (found_type == BTRFS_FILE_EXTENT_REG ||
5070 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5071 extent_end = extent_start +
5072 btrfs_file_extent_num_bytes(leaf, item);
5073 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5075 size = btrfs_file_extent_inline_len(leaf, item);
5076 extent_end = (extent_start + size + root->sectorsize - 1) &
5077 ~((u64)root->sectorsize - 1);
5080 if (start >= extent_end) {
5082 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
5083 ret = btrfs_next_leaf(root, path);
5090 leaf = path->nodes[0];
5092 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5093 if (found_key.objectid != objectid ||
5094 found_key.type != BTRFS_EXTENT_DATA_KEY)
5096 if (start + len <= found_key.offset)
5099 em->len = found_key.offset - start;
5103 if (found_type == BTRFS_FILE_EXTENT_REG ||
5104 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5105 em->start = extent_start;
5106 em->len = extent_end - extent_start;
5107 em->orig_start = extent_start -
5108 btrfs_file_extent_offset(leaf, item);
5109 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5111 em->block_start = EXTENT_MAP_HOLE;
5114 if (compress_type != BTRFS_COMPRESS_NONE) {
5115 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5116 em->compress_type = compress_type;
5117 em->block_start = bytenr;
5118 em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
5121 bytenr += btrfs_file_extent_offset(leaf, item);
5122 em->block_start = bytenr;
5123 em->block_len = em->len;
5124 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5125 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5128 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5132 size_t extent_offset;
5135 em->block_start = EXTENT_MAP_INLINE;
5136 if (!page || create) {
5137 em->start = extent_start;
5138 em->len = extent_end - extent_start;
5142 size = btrfs_file_extent_inline_len(leaf, item);
5143 extent_offset = page_offset(page) + pg_offset - extent_start;
5144 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
5145 size - extent_offset);
5146 em->start = extent_start + extent_offset;
5147 em->len = (copy_size + root->sectorsize - 1) &
5148 ~((u64)root->sectorsize - 1);
5149 em->orig_start = EXTENT_MAP_INLINE;
5150 if (compress_type) {
5151 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5152 em->compress_type = compress_type;
5154 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5155 if (create == 0 && !PageUptodate(page)) {
5156 if (btrfs_file_extent_compression(leaf, item) !=
5157 BTRFS_COMPRESS_NONE) {
5158 ret = uncompress_inline(path, inode, page,
5160 extent_offset, item);
5164 read_extent_buffer(leaf, map + pg_offset, ptr,
5166 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5167 memset(map + pg_offset + copy_size, 0,
5168 PAGE_CACHE_SIZE - pg_offset -
5173 flush_dcache_page(page);
5174 } else if (create && PageUptodate(page)) {
5178 free_extent_map(em);
5180 btrfs_release_path(root, path);
5181 trans = btrfs_join_transaction(root, 1);
5185 write_extent_buffer(leaf, map + pg_offset, ptr,
5188 btrfs_mark_buffer_dirty(leaf);
5190 set_extent_uptodate(io_tree, em->start,
5191 extent_map_end(em) - 1, GFP_NOFS);
5194 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
5201 em->block_start = EXTENT_MAP_HOLE;
5202 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5204 btrfs_release_path(root, path);
5205 if (em->start > start || extent_map_end(em) <= start) {
5206 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5207 "[%llu %llu]\n", (unsigned long long)em->start,
5208 (unsigned long long)em->len,
5209 (unsigned long long)start,
5210 (unsigned long long)len);
5216 write_lock(&em_tree->lock);
5217 ret = add_extent_mapping(em_tree, em);
5218 /* it is possible that someone inserted the extent into the tree
5219 * while we had the lock dropped. It is also possible that
5220 * an overlapping map exists in the tree
5222 if (ret == -EEXIST) {
5223 struct extent_map *existing;
5227 existing = lookup_extent_mapping(em_tree, start, len);
5228 if (existing && (existing->start > start ||
5229 existing->start + existing->len <= start)) {
5230 free_extent_map(existing);
5234 existing = lookup_extent_mapping(em_tree, em->start,
5237 err = merge_extent_mapping(em_tree, existing,
5240 free_extent_map(existing);
5242 free_extent_map(em);
5247 free_extent_map(em);
5251 free_extent_map(em);
5256 write_unlock(&em_tree->lock);
5259 btrfs_free_path(path);
5261 ret = btrfs_end_transaction(trans, root);
5266 free_extent_map(em);
5267 return ERR_PTR(err);
5272 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5275 struct btrfs_root *root = BTRFS_I(inode)->root;
5276 struct btrfs_trans_handle *trans;
5277 struct extent_map *em;
5278 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5279 struct btrfs_key ins;
5283 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
5285 trans = btrfs_join_transaction(root, 0);
5287 return ERR_PTR(-ENOMEM);
5289 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5291 alloc_hint = get_extent_allocation_hint(inode, start, len);
5292 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5293 alloc_hint, (u64)-1, &ins, 1);
5299 em = alloc_extent_map(GFP_NOFS);
5301 em = ERR_PTR(-ENOMEM);
5306 em->orig_start = em->start;
5307 em->len = ins.offset;
5309 em->block_start = ins.objectid;
5310 em->block_len = ins.offset;
5311 em->bdev = root->fs_info->fs_devices->latest_bdev;
5312 set_bit(EXTENT_FLAG_PINNED, &em->flags);
5315 write_lock(&em_tree->lock);
5316 ret = add_extent_mapping(em_tree, em);
5317 write_unlock(&em_tree->lock);
5320 btrfs_drop_extent_cache(inode, start, start + em->len - 1, 0);
5323 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5324 ins.offset, ins.offset, 0);
5326 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5330 btrfs_end_transaction(trans, root);
5335 * returns 1 when the nocow is safe, < 1 on error, 0 if the
5336 * block must be cow'd
5338 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5339 struct inode *inode, u64 offset, u64 len)
5341 struct btrfs_path *path;
5343 struct extent_buffer *leaf;
5344 struct btrfs_root *root = BTRFS_I(inode)->root;
5345 struct btrfs_file_extent_item *fi;
5346 struct btrfs_key key;
5354 path = btrfs_alloc_path();
5358 ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
5363 slot = path->slots[0];
5366 /* can't find the item, must cow */
5373 leaf = path->nodes[0];
5374 btrfs_item_key_to_cpu(leaf, &key, slot);
5375 if (key.objectid != inode->i_ino ||
5376 key.type != BTRFS_EXTENT_DATA_KEY) {
5377 /* not our file or wrong item type, must cow */
5381 if (key.offset > offset) {
5382 /* Wrong offset, must cow */
5386 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5387 found_type = btrfs_file_extent_type(leaf, fi);
5388 if (found_type != BTRFS_FILE_EXTENT_REG &&
5389 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5390 /* not a regular extent, must cow */
5393 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5394 backref_offset = btrfs_file_extent_offset(leaf, fi);
5396 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5397 if (extent_end < offset + len) {
5398 /* extent doesn't include our full range, must cow */
5402 if (btrfs_extent_readonly(root, disk_bytenr))
5406 * look for other files referencing this extent, if we
5407 * find any we must cow
5409 if (btrfs_cross_ref_exist(trans, root, inode->i_ino,
5410 key.offset - backref_offset, disk_bytenr))
5414 * adjust disk_bytenr and num_bytes to cover just the bytes
5415 * in this extent we are about to write. If there
5416 * are any csums in that range we have to cow in order
5417 * to keep the csums correct
5419 disk_bytenr += backref_offset;
5420 disk_bytenr += offset - key.offset;
5421 num_bytes = min(offset + len, extent_end) - offset;
5422 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5425 * all of the above have passed, it is safe to overwrite this extent
5430 btrfs_free_path(path);
5434 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
5435 struct buffer_head *bh_result, int create)
5437 struct extent_map *em;
5438 struct btrfs_root *root = BTRFS_I(inode)->root;
5439 u64 start = iblock << inode->i_blkbits;
5440 u64 len = bh_result->b_size;
5441 struct btrfs_trans_handle *trans;
5443 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
5448 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
5449 * io. INLINE is special, and we could probably kludge it in here, but
5450 * it's still buffered so for safety lets just fall back to the generic
5453 * For COMPRESSED we _have_ to read the entire extent in so we can
5454 * decompress it, so there will be buffering required no matter what we
5455 * do, so go ahead and fallback to buffered.
5457 * We return -ENOTBLK because thats what makes DIO go ahead and go back
5458 * to buffered IO. Don't blame me, this is the price we pay for using
5461 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
5462 em->block_start == EXTENT_MAP_INLINE) {
5463 free_extent_map(em);
5467 /* Just a good old fashioned hole, return */
5468 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
5469 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
5470 free_extent_map(em);
5471 /* DIO will do one hole at a time, so just unlock a sector */
5472 unlock_extent(&BTRFS_I(inode)->io_tree, start,
5473 start + root->sectorsize - 1, GFP_NOFS);
5478 * We don't allocate a new extent in the following cases
5480 * 1) The inode is marked as NODATACOW. In this case we'll just use the
5482 * 2) The extent is marked as PREALLOC. We're good to go here and can
5483 * just use the extent.
5487 len = em->len - (start - em->start);
5491 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
5492 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
5493 em->block_start != EXTENT_MAP_HOLE)) {
5498 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5499 type = BTRFS_ORDERED_PREALLOC;
5501 type = BTRFS_ORDERED_NOCOW;
5502 len = min(len, em->len - (start - em->start));
5503 block_start = em->block_start + (start - em->start);
5506 * we're not going to log anything, but we do need
5507 * to make sure the current transaction stays open
5508 * while we look for nocow cross refs
5510 trans = btrfs_join_transaction(root, 0);
5514 if (can_nocow_odirect(trans, inode, start, len) == 1) {
5515 ret = btrfs_add_ordered_extent_dio(inode, start,
5516 block_start, len, len, type);
5517 btrfs_end_transaction(trans, root);
5519 free_extent_map(em);
5524 btrfs_end_transaction(trans, root);
5528 * this will cow the extent, reset the len in case we changed
5531 len = bh_result->b_size;
5532 free_extent_map(em);
5533 em = btrfs_new_extent_direct(inode, start, len);
5536 len = min(len, em->len - (start - em->start));
5538 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, start + len - 1,
5539 EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DIRTY, 1,
5542 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
5544 bh_result->b_size = len;
5545 bh_result->b_bdev = em->bdev;
5546 set_buffer_mapped(bh_result);
5547 if (create && !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5548 set_buffer_new(bh_result);
5550 free_extent_map(em);
5555 struct btrfs_dio_private {
5556 struct inode *inode;
5563 /* number of bios pending for this dio */
5564 atomic_t pending_bios;
5569 struct bio *orig_bio;
5572 static void btrfs_endio_direct_read(struct bio *bio, int err)
5574 struct btrfs_dio_private *dip = bio->bi_private;
5575 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
5576 struct bio_vec *bvec = bio->bi_io_vec;
5577 struct inode *inode = dip->inode;
5578 struct btrfs_root *root = BTRFS_I(inode)->root;
5580 u32 *private = dip->csums;
5582 start = dip->logical_offset;
5584 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
5585 struct page *page = bvec->bv_page;
5588 unsigned long flags;
5590 local_irq_save(flags);
5591 kaddr = kmap_atomic(page, KM_IRQ0);
5592 csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
5593 csum, bvec->bv_len);
5594 btrfs_csum_final(csum, (char *)&csum);
5595 kunmap_atomic(kaddr, KM_IRQ0);
5596 local_irq_restore(flags);
5598 flush_dcache_page(bvec->bv_page);
5599 if (csum != *private) {
5600 printk(KERN_ERR "btrfs csum failed ino %lu off"
5601 " %llu csum %u private %u\n",
5602 inode->i_ino, (unsigned long long)start,
5608 start += bvec->bv_len;
5611 } while (bvec <= bvec_end);
5613 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
5614 dip->logical_offset + dip->bytes - 1, GFP_NOFS);
5615 bio->bi_private = dip->private;
5619 dio_end_io(bio, err);
5622 static void btrfs_endio_direct_write(struct bio *bio, int err)
5624 struct btrfs_dio_private *dip = bio->bi_private;
5625 struct inode *inode = dip->inode;
5626 struct btrfs_root *root = BTRFS_I(inode)->root;
5627 struct btrfs_trans_handle *trans;
5628 struct btrfs_ordered_extent *ordered = NULL;
5629 struct extent_state *cached_state = NULL;
5630 u64 ordered_offset = dip->logical_offset;
5631 u64 ordered_bytes = dip->bytes;
5637 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
5645 trans = btrfs_join_transaction(root, 1);
5650 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5652 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) {
5653 ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5655 ret = btrfs_update_inode(trans, root, inode);
5660 lock_extent_bits(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5661 ordered->file_offset + ordered->len - 1, 0,
5662 &cached_state, GFP_NOFS);
5664 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags)) {
5665 ret = btrfs_mark_extent_written(trans, inode,
5666 ordered->file_offset,
5667 ordered->file_offset +
5674 ret = insert_reserved_file_extent(trans, inode,
5675 ordered->file_offset,
5681 BTRFS_FILE_EXTENT_REG);
5682 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
5683 ordered->file_offset, ordered->len);
5691 add_pending_csums(trans, inode, ordered->file_offset, &ordered->list);
5692 btrfs_ordered_update_i_size(inode, 0, ordered);
5693 btrfs_update_inode(trans, root, inode);
5695 unlock_extent_cached(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5696 ordered->file_offset + ordered->len - 1,
5697 &cached_state, GFP_NOFS);
5699 btrfs_delalloc_release_metadata(inode, ordered->len);
5700 btrfs_end_transaction(trans, root);
5701 ordered_offset = ordered->file_offset + ordered->len;
5702 btrfs_put_ordered_extent(ordered);
5703 btrfs_put_ordered_extent(ordered);
5707 * our bio might span multiple ordered extents. If we haven't
5708 * completed the accounting for the whole dio, go back and try again
5710 if (ordered_offset < dip->logical_offset + dip->bytes) {
5711 ordered_bytes = dip->logical_offset + dip->bytes -
5716 bio->bi_private = dip->private;
5720 dio_end_io(bio, err);
5723 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
5724 struct bio *bio, int mirror_num,
5725 unsigned long bio_flags, u64 offset)
5728 struct btrfs_root *root = BTRFS_I(inode)->root;
5729 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
5734 static void btrfs_end_dio_bio(struct bio *bio, int err)
5736 struct btrfs_dio_private *dip = bio->bi_private;
5739 printk(KERN_ERR "btrfs direct IO failed ino %lu rw %lu "
5740 "sector %#Lx len %u err no %d\n",
5741 dip->inode->i_ino, bio->bi_rw,
5742 (unsigned long long)bio->bi_sector, bio->bi_size, err);
5746 * before atomic variable goto zero, we must make sure
5747 * dip->errors is perceived to be set.
5749 smp_mb__before_atomic_dec();
5752 /* if there are more bios still pending for this dio, just exit */
5753 if (!atomic_dec_and_test(&dip->pending_bios))
5757 bio_io_error(dip->orig_bio);
5759 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
5760 bio_endio(dip->orig_bio, 0);
5766 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
5767 u64 first_sector, gfp_t gfp_flags)
5769 int nr_vecs = bio_get_nr_vecs(bdev);
5770 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
5773 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
5774 int rw, u64 file_offset, int skip_sum,
5777 int write = rw & REQ_WRITE;
5778 struct btrfs_root *root = BTRFS_I(inode)->root;
5782 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
5786 if (write && !skip_sum) {
5787 ret = btrfs_wq_submit_bio(root->fs_info,
5788 inode, rw, bio, 0, 0,
5790 __btrfs_submit_bio_start_direct_io,
5791 __btrfs_submit_bio_done);
5793 } else if (!skip_sum)
5794 btrfs_lookup_bio_sums_dio(root, inode, bio,
5795 file_offset, csums);
5797 ret = btrfs_map_bio(root, rw, bio, 0, 1);
5803 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
5806 struct inode *inode = dip->inode;
5807 struct btrfs_root *root = BTRFS_I(inode)->root;
5808 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
5810 struct bio *orig_bio = dip->orig_bio;
5811 struct bio_vec *bvec = orig_bio->bi_io_vec;
5812 u64 start_sector = orig_bio->bi_sector;
5813 u64 file_offset = dip->logical_offset;
5817 u32 *csums = dip->csums;
5820 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
5823 bio->bi_private = dip;
5824 bio->bi_end_io = btrfs_end_dio_bio;
5825 atomic_inc(&dip->pending_bios);
5827 map_length = orig_bio->bi_size;
5828 ret = btrfs_map_block(map_tree, READ, start_sector << 9,
5829 &map_length, NULL, 0);
5835 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
5836 if (unlikely(map_length < submit_len + bvec->bv_len ||
5837 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
5838 bvec->bv_offset) < bvec->bv_len)) {
5840 * inc the count before we submit the bio so
5841 * we know the end IO handler won't happen before
5842 * we inc the count. Otherwise, the dip might get freed
5843 * before we're done setting it up
5845 atomic_inc(&dip->pending_bios);
5846 ret = __btrfs_submit_dio_bio(bio, inode, rw,
5847 file_offset, skip_sum,
5851 atomic_dec(&dip->pending_bios);
5856 csums = csums + nr_pages;
5857 start_sector += submit_len >> 9;
5858 file_offset += submit_len;
5863 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
5864 start_sector, GFP_NOFS);
5867 bio->bi_private = dip;
5868 bio->bi_end_io = btrfs_end_dio_bio;
5870 map_length = orig_bio->bi_size;
5871 ret = btrfs_map_block(map_tree, READ, start_sector << 9,
5872 &map_length, NULL, 0);
5878 submit_len += bvec->bv_len;
5884 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
5893 * before atomic variable goto zero, we must
5894 * make sure dip->errors is perceived to be set.
5896 smp_mb__before_atomic_dec();
5897 if (atomic_dec_and_test(&dip->pending_bios))
5898 bio_io_error(dip->orig_bio);
5900 /* bio_end_io() will handle error, so we needn't return it */
5904 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
5907 struct btrfs_root *root = BTRFS_I(inode)->root;
5908 struct btrfs_dio_private *dip;
5909 struct bio_vec *bvec = bio->bi_io_vec;
5911 int write = rw & REQ_WRITE;
5914 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
5916 dip = kmalloc(sizeof(*dip), GFP_NOFS);
5924 dip->csums = kmalloc(sizeof(u32) * bio->bi_vcnt, GFP_NOFS);
5931 dip->private = bio->bi_private;
5933 dip->logical_offset = file_offset;
5937 dip->bytes += bvec->bv_len;
5939 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
5941 dip->disk_bytenr = (u64)bio->bi_sector << 9;
5942 bio->bi_private = dip;
5944 dip->orig_bio = bio;
5945 atomic_set(&dip->pending_bios, 0);
5948 bio->bi_end_io = btrfs_endio_direct_write;
5950 bio->bi_end_io = btrfs_endio_direct_read;
5952 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
5957 * If this is a write, we need to clean up the reserved space and kill
5958 * the ordered extent.
5961 struct btrfs_ordered_extent *ordered;
5962 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
5963 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
5964 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
5965 btrfs_free_reserved_extent(root, ordered->start,
5967 btrfs_put_ordered_extent(ordered);
5968 btrfs_put_ordered_extent(ordered);
5970 bio_endio(bio, ret);
5973 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
5974 const struct iovec *iov, loff_t offset,
5975 unsigned long nr_segs)
5980 unsigned blocksize_mask = root->sectorsize - 1;
5981 ssize_t retval = -EINVAL;
5982 loff_t end = offset;
5984 if (offset & blocksize_mask)
5987 /* Check the memory alignment. Blocks cannot straddle pages */
5988 for (seg = 0; seg < nr_segs; seg++) {
5989 addr = (unsigned long)iov[seg].iov_base;
5990 size = iov[seg].iov_len;
5992 if ((addr & blocksize_mask) || (size & blocksize_mask))
5999 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
6000 const struct iovec *iov, loff_t offset,
6001 unsigned long nr_segs)
6003 struct file *file = iocb->ki_filp;
6004 struct inode *inode = file->f_mapping->host;
6005 struct btrfs_ordered_extent *ordered;
6006 struct extent_state *cached_state = NULL;
6007 u64 lockstart, lockend;
6009 int writing = rw & WRITE;
6011 size_t count = iov_length(iov, nr_segs);
6013 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
6019 lockend = offset + count - 1;
6022 ret = btrfs_delalloc_reserve_space(inode, count);
6028 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6029 0, &cached_state, GFP_NOFS);
6031 * We're concerned with the entire range that we're going to be
6032 * doing DIO to, so we need to make sure theres no ordered
6033 * extents in this range.
6035 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6036 lockend - lockstart + 1);
6039 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6040 &cached_state, GFP_NOFS);
6041 btrfs_start_ordered_extent(inode, ordered, 1);
6042 btrfs_put_ordered_extent(ordered);
6047 * we don't use btrfs_set_extent_delalloc because we don't want
6048 * the dirty or uptodate bits
6051 write_bits = EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING;
6052 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6053 EXTENT_DELALLOC, 0, NULL, &cached_state,
6056 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6057 lockend, EXTENT_LOCKED | write_bits,
6058 1, 0, &cached_state, GFP_NOFS);
6063 free_extent_state(cached_state);
6064 cached_state = NULL;
6066 ret = __blockdev_direct_IO(rw, iocb, inode,
6067 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
6068 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
6069 btrfs_submit_direct, 0);
6071 if (ret < 0 && ret != -EIOCBQUEUED) {
6072 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset,
6073 offset + iov_length(iov, nr_segs) - 1,
6074 EXTENT_LOCKED | write_bits, 1, 0,
6075 &cached_state, GFP_NOFS);
6076 } else if (ret >= 0 && ret < iov_length(iov, nr_segs)) {
6078 * We're falling back to buffered, unlock the section we didn't
6081 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset + ret,
6082 offset + iov_length(iov, nr_segs) - 1,
6083 EXTENT_LOCKED | write_bits, 1, 0,
6084 &cached_state, GFP_NOFS);
6087 free_extent_state(cached_state);
6091 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
6092 __u64 start, __u64 len)
6094 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent);
6097 int btrfs_readpage(struct file *file, struct page *page)
6099 struct extent_io_tree *tree;
6100 tree = &BTRFS_I(page->mapping->host)->io_tree;
6101 return extent_read_full_page(tree, page, btrfs_get_extent);
6104 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
6106 struct extent_io_tree *tree;
6109 if (current->flags & PF_MEMALLOC) {
6110 redirty_page_for_writepage(wbc, page);
6114 tree = &BTRFS_I(page->mapping->host)->io_tree;
6115 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
6118 int btrfs_writepages(struct address_space *mapping,
6119 struct writeback_control *wbc)
6121 struct extent_io_tree *tree;
6123 tree = &BTRFS_I(mapping->host)->io_tree;
6124 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
6128 btrfs_readpages(struct file *file, struct address_space *mapping,
6129 struct list_head *pages, unsigned nr_pages)
6131 struct extent_io_tree *tree;
6132 tree = &BTRFS_I(mapping->host)->io_tree;
6133 return extent_readpages(tree, mapping, pages, nr_pages,
6136 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6138 struct extent_io_tree *tree;
6139 struct extent_map_tree *map;
6142 tree = &BTRFS_I(page->mapping->host)->io_tree;
6143 map = &BTRFS_I(page->mapping->host)->extent_tree;
6144 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
6146 ClearPagePrivate(page);
6147 set_page_private(page, 0);
6148 page_cache_release(page);
6153 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6155 if (PageWriteback(page) || PageDirty(page))
6157 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
6160 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
6162 struct extent_io_tree *tree;
6163 struct btrfs_ordered_extent *ordered;
6164 struct extent_state *cached_state = NULL;
6165 u64 page_start = page_offset(page);
6166 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
6170 * we have the page locked, so new writeback can't start,
6171 * and the dirty bit won't be cleared while we are here.
6173 * Wait for IO on this page so that we can safely clear
6174 * the PagePrivate2 bit and do ordered accounting
6176 wait_on_page_writeback(page);
6178 tree = &BTRFS_I(page->mapping->host)->io_tree;
6180 btrfs_releasepage(page, GFP_NOFS);
6183 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6185 ordered = btrfs_lookup_ordered_extent(page->mapping->host,
6189 * IO on this page will never be started, so we need
6190 * to account for any ordered extents now
6192 clear_extent_bit(tree, page_start, page_end,
6193 EXTENT_DIRTY | EXTENT_DELALLOC |
6194 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
6195 &cached_state, GFP_NOFS);
6197 * whoever cleared the private bit is responsible
6198 * for the finish_ordered_io
6200 if (TestClearPagePrivate2(page)) {
6201 btrfs_finish_ordered_io(page->mapping->host,
6202 page_start, page_end);
6204 btrfs_put_ordered_extent(ordered);
6205 cached_state = NULL;
6206 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6209 clear_extent_bit(tree, page_start, page_end,
6210 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
6211 EXTENT_DO_ACCOUNTING, 1, 1, &cached_state, GFP_NOFS);
6212 __btrfs_releasepage(page, GFP_NOFS);
6214 ClearPageChecked(page);
6215 if (PagePrivate(page)) {
6216 ClearPagePrivate(page);
6217 set_page_private(page, 0);
6218 page_cache_release(page);
6223 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6224 * called from a page fault handler when a page is first dirtied. Hence we must
6225 * be careful to check for EOF conditions here. We set the page up correctly
6226 * for a written page which means we get ENOSPC checking when writing into
6227 * holes and correct delalloc and unwritten extent mapping on filesystems that
6228 * support these features.
6230 * We are not allowed to take the i_mutex here so we have to play games to
6231 * protect against truncate races as the page could now be beyond EOF. Because
6232 * vmtruncate() writes the inode size before removing pages, once we have the
6233 * page lock we can determine safely if the page is beyond EOF. If it is not
6234 * beyond EOF, then the page is guaranteed safe against truncation until we
6237 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
6239 struct page *page = vmf->page;
6240 struct inode *inode = fdentry(vma->vm_file)->d_inode;
6241 struct btrfs_root *root = BTRFS_I(inode)->root;
6242 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6243 struct btrfs_ordered_extent *ordered;
6244 struct extent_state *cached_state = NULL;
6246 unsigned long zero_start;
6252 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
6256 else /* -ENOSPC, -EIO, etc */
6257 ret = VM_FAULT_SIGBUS;
6261 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
6264 size = i_size_read(inode);
6265 page_start = page_offset(page);
6266 page_end = page_start + PAGE_CACHE_SIZE - 1;
6268 if ((page->mapping != inode->i_mapping) ||
6269 (page_start >= size)) {
6270 /* page got truncated out from underneath us */
6273 wait_on_page_writeback(page);
6275 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
6277 set_page_extent_mapped(page);
6280 * we can't set the delalloc bits if there are pending ordered
6281 * extents. Drop our locks and wait for them to finish
6283 ordered = btrfs_lookup_ordered_extent(inode, page_start);
6285 unlock_extent_cached(io_tree, page_start, page_end,
6286 &cached_state, GFP_NOFS);
6288 btrfs_start_ordered_extent(inode, ordered, 1);
6289 btrfs_put_ordered_extent(ordered);
6294 * XXX - page_mkwrite gets called every time the page is dirtied, even
6295 * if it was already dirty, so for space accounting reasons we need to
6296 * clear any delalloc bits for the range we are fixing to save. There
6297 * is probably a better way to do this, but for now keep consistent with
6298 * prepare_pages in the normal write path.
6300 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
6301 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
6302 0, 0, &cached_state, GFP_NOFS);
6304 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6307 unlock_extent_cached(io_tree, page_start, page_end,
6308 &cached_state, GFP_NOFS);
6309 ret = VM_FAULT_SIGBUS;
6314 /* page is wholly or partially inside EOF */
6315 if (page_start + PAGE_CACHE_SIZE > size)
6316 zero_start = size & ~PAGE_CACHE_MASK;
6318 zero_start = PAGE_CACHE_SIZE;
6320 if (zero_start != PAGE_CACHE_SIZE) {
6322 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6323 flush_dcache_page(page);
6326 ClearPageChecked(page);
6327 set_page_dirty(page);
6328 SetPageUptodate(page);
6330 BTRFS_I(inode)->last_trans = root->fs_info->generation;
6331 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6333 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
6337 return VM_FAULT_LOCKED;
6339 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
6344 static void btrfs_truncate(struct inode *inode)
6346 struct btrfs_root *root = BTRFS_I(inode)->root;
6348 struct btrfs_trans_handle *trans;
6350 u64 mask = root->sectorsize - 1;
6352 if (!S_ISREG(inode->i_mode)) {
6357 ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
6361 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
6362 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
6364 trans = btrfs_start_transaction(root, 0);
6365 BUG_ON(IS_ERR(trans));
6366 btrfs_set_trans_block_group(trans, inode);
6367 trans->block_rsv = root->orphan_block_rsv;
6370 * setattr is responsible for setting the ordered_data_close flag,
6371 * but that is only tested during the last file release. That
6372 * could happen well after the next commit, leaving a great big
6373 * window where new writes may get lost if someone chooses to write
6374 * to this file after truncating to zero
6376 * The inode doesn't have any dirty data here, and so if we commit
6377 * this is a noop. If someone immediately starts writing to the inode
6378 * it is very likely we'll catch some of their writes in this
6379 * transaction, and the commit will find this file on the ordered
6380 * data list with good things to send down.
6382 * This is a best effort solution, there is still a window where
6383 * using truncate to replace the contents of the file will
6384 * end up with a zero length file after a crash.
6386 if (inode->i_size == 0 && BTRFS_I(inode)->ordered_data_close)
6387 btrfs_add_ordered_operation(trans, root, inode);
6391 trans = btrfs_start_transaction(root, 0);
6392 BUG_ON(IS_ERR(trans));
6393 btrfs_set_trans_block_group(trans, inode);
6394 trans->block_rsv = root->orphan_block_rsv;
6397 ret = btrfs_block_rsv_check(trans, root,
6398 root->orphan_block_rsv, 0, 5);
6400 BUG_ON(ret != -EAGAIN);
6401 ret = btrfs_commit_transaction(trans, root);
6407 ret = btrfs_truncate_inode_items(trans, root, inode,
6409 BTRFS_EXTENT_DATA_KEY);
6413 ret = btrfs_update_inode(trans, root, inode);
6416 nr = trans->blocks_used;
6417 btrfs_end_transaction(trans, root);
6419 btrfs_btree_balance_dirty(root, nr);
6422 if (ret == 0 && inode->i_nlink > 0) {
6423 ret = btrfs_orphan_del(trans, inode);
6427 ret = btrfs_update_inode(trans, root, inode);
6430 nr = trans->blocks_used;
6431 ret = btrfs_end_transaction_throttle(trans, root);
6433 btrfs_btree_balance_dirty(root, nr);
6437 * create a new subvolume directory/inode (helper for the ioctl).
6439 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
6440 struct btrfs_root *new_root,
6441 u64 new_dirid, u64 alloc_hint)
6443 struct inode *inode;
6447 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
6448 new_dirid, alloc_hint, S_IFDIR | 0700, &index);
6450 return PTR_ERR(inode);
6451 inode->i_op = &btrfs_dir_inode_operations;
6452 inode->i_fop = &btrfs_dir_file_operations;
6455 btrfs_i_size_write(inode, 0);
6457 err = btrfs_update_inode(trans, new_root, inode);
6464 /* helper function for file defrag and space balancing. This
6465 * forces readahead on a given range of bytes in an inode
6467 unsigned long btrfs_force_ra(struct address_space *mapping,
6468 struct file_ra_state *ra, struct file *file,
6469 pgoff_t offset, pgoff_t last_index)
6471 pgoff_t req_size = last_index - offset + 1;
6473 page_cache_sync_readahead(mapping, ra, file, offset, req_size);
6474 return offset + req_size;
6477 struct inode *btrfs_alloc_inode(struct super_block *sb)
6479 struct btrfs_inode *ei;
6480 struct inode *inode;
6482 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
6487 ei->space_info = NULL;
6491 ei->last_sub_trans = 0;
6492 ei->logged_trans = 0;
6493 ei->delalloc_bytes = 0;
6494 ei->reserved_bytes = 0;
6495 ei->disk_i_size = 0;
6497 ei->index_cnt = (u64)-1;
6498 ei->last_unlink_trans = 0;
6500 spin_lock_init(&ei->accounting_lock);
6501 atomic_set(&ei->outstanding_extents, 0);
6502 ei->reserved_extents = 0;
6504 ei->ordered_data_close = 0;
6505 ei->orphan_meta_reserved = 0;
6506 ei->dummy_inode = 0;
6507 ei->force_compress = BTRFS_COMPRESS_NONE;
6509 inode = &ei->vfs_inode;
6510 extent_map_tree_init(&ei->extent_tree, GFP_NOFS);
6511 extent_io_tree_init(&ei->io_tree, &inode->i_data, GFP_NOFS);
6512 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data, GFP_NOFS);
6513 mutex_init(&ei->log_mutex);
6514 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
6515 INIT_LIST_HEAD(&ei->i_orphan);
6516 INIT_LIST_HEAD(&ei->delalloc_inodes);
6517 INIT_LIST_HEAD(&ei->ordered_operations);
6518 RB_CLEAR_NODE(&ei->rb_node);
6523 void btrfs_destroy_inode(struct inode *inode)
6525 struct btrfs_ordered_extent *ordered;
6526 struct btrfs_root *root = BTRFS_I(inode)->root;
6528 WARN_ON(!list_empty(&inode->i_dentry));
6529 WARN_ON(inode->i_data.nrpages);
6530 WARN_ON(atomic_read(&BTRFS_I(inode)->outstanding_extents));
6531 WARN_ON(BTRFS_I(inode)->reserved_extents);
6534 * This can happen where we create an inode, but somebody else also
6535 * created the same inode and we need to destroy the one we already
6542 * Make sure we're properly removed from the ordered operation
6546 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
6547 spin_lock(&root->fs_info->ordered_extent_lock);
6548 list_del_init(&BTRFS_I(inode)->ordered_operations);
6549 spin_unlock(&root->fs_info->ordered_extent_lock);
6552 if (root == root->fs_info->tree_root) {
6553 struct btrfs_block_group_cache *block_group;
6555 block_group = btrfs_lookup_block_group(root->fs_info,
6556 BTRFS_I(inode)->block_group);
6557 if (block_group && block_group->inode == inode) {
6558 spin_lock(&block_group->lock);
6559 block_group->inode = NULL;
6560 spin_unlock(&block_group->lock);
6561 btrfs_put_block_group(block_group);
6562 } else if (block_group) {
6563 btrfs_put_block_group(block_group);
6567 spin_lock(&root->orphan_lock);
6568 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
6569 printk(KERN_INFO "BTRFS: inode %lu still on the orphan list\n",
6571 list_del_init(&BTRFS_I(inode)->i_orphan);
6573 spin_unlock(&root->orphan_lock);
6576 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
6580 printk(KERN_ERR "btrfs found ordered "
6581 "extent %llu %llu on inode cleanup\n",
6582 (unsigned long long)ordered->file_offset,
6583 (unsigned long long)ordered->len);
6584 btrfs_remove_ordered_extent(inode, ordered);
6585 btrfs_put_ordered_extent(ordered);
6586 btrfs_put_ordered_extent(ordered);
6589 inode_tree_del(inode);
6590 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
6592 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
6595 int btrfs_drop_inode(struct inode *inode)
6597 struct btrfs_root *root = BTRFS_I(inode)->root;
6599 if (btrfs_root_refs(&root->root_item) == 0 &&
6600 root != root->fs_info->tree_root)
6603 return generic_drop_inode(inode);
6606 static void init_once(void *foo)
6608 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
6610 inode_init_once(&ei->vfs_inode);
6613 void btrfs_destroy_cachep(void)
6615 if (btrfs_inode_cachep)
6616 kmem_cache_destroy(btrfs_inode_cachep);
6617 if (btrfs_trans_handle_cachep)
6618 kmem_cache_destroy(btrfs_trans_handle_cachep);
6619 if (btrfs_transaction_cachep)
6620 kmem_cache_destroy(btrfs_transaction_cachep);
6621 if (btrfs_path_cachep)
6622 kmem_cache_destroy(btrfs_path_cachep);
6625 int btrfs_init_cachep(void)
6627 btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
6628 sizeof(struct btrfs_inode), 0,
6629 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
6630 if (!btrfs_inode_cachep)
6633 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
6634 sizeof(struct btrfs_trans_handle), 0,
6635 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6636 if (!btrfs_trans_handle_cachep)
6639 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
6640 sizeof(struct btrfs_transaction), 0,
6641 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6642 if (!btrfs_transaction_cachep)
6645 btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
6646 sizeof(struct btrfs_path), 0,
6647 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6648 if (!btrfs_path_cachep)
6653 btrfs_destroy_cachep();
6657 static int btrfs_getattr(struct vfsmount *mnt,
6658 struct dentry *dentry, struct kstat *stat)
6660 struct inode *inode = dentry->d_inode;
6661 generic_fillattr(inode, stat);
6662 stat->dev = BTRFS_I(inode)->root->anon_super.s_dev;
6663 stat->blksize = PAGE_CACHE_SIZE;
6664 stat->blocks = (inode_get_bytes(inode) +
6665 BTRFS_I(inode)->delalloc_bytes) >> 9;
6669 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
6670 struct inode *new_dir, struct dentry *new_dentry)
6672 struct btrfs_trans_handle *trans;
6673 struct btrfs_root *root = BTRFS_I(old_dir)->root;
6674 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
6675 struct inode *new_inode = new_dentry->d_inode;
6676 struct inode *old_inode = old_dentry->d_inode;
6677 struct timespec ctime = CURRENT_TIME;
6682 if (new_dir->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
6685 /* we only allow rename subvolume link between subvolumes */
6686 if (old_inode->i_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
6689 if (old_inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
6690 (new_inode && new_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID))
6693 if (S_ISDIR(old_inode->i_mode) && new_inode &&
6694 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
6697 * we're using rename to replace one file with another.
6698 * and the replacement file is large. Start IO on it now so
6699 * we don't add too much work to the end of the transaction
6701 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
6702 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
6703 filemap_flush(old_inode->i_mapping);
6705 /* close the racy window with snapshot create/destroy ioctl */
6706 if (old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
6707 down_read(&root->fs_info->subvol_sem);
6709 * We want to reserve the absolute worst case amount of items. So if
6710 * both inodes are subvols and we need to unlink them then that would
6711 * require 4 item modifications, but if they are both normal inodes it
6712 * would require 5 item modifications, so we'll assume their normal
6713 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
6714 * should cover the worst case number of items we'll modify.
6716 trans = btrfs_start_transaction(root, 20);
6718 return PTR_ERR(trans);
6720 btrfs_set_trans_block_group(trans, new_dir);
6723 btrfs_record_root_in_trans(trans, dest);
6725 ret = btrfs_set_inode_index(new_dir, &index);
6729 if (unlikely(old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6730 /* force full log commit if subvolume involved. */
6731 root->fs_info->last_trans_log_full_commit = trans->transid;
6733 ret = btrfs_insert_inode_ref(trans, dest,
6734 new_dentry->d_name.name,
6735 new_dentry->d_name.len,
6737 new_dir->i_ino, index);
6741 * this is an ugly little race, but the rename is required
6742 * to make sure that if we crash, the inode is either at the
6743 * old name or the new one. pinning the log transaction lets
6744 * us make sure we don't allow a log commit to come in after
6745 * we unlink the name but before we add the new name back in.
6747 btrfs_pin_log_trans(root);
6750 * make sure the inode gets flushed if it is replacing
6753 if (new_inode && new_inode->i_size &&
6754 old_inode && S_ISREG(old_inode->i_mode)) {
6755 btrfs_add_ordered_operation(trans, root, old_inode);
6758 old_dir->i_ctime = old_dir->i_mtime = ctime;
6759 new_dir->i_ctime = new_dir->i_mtime = ctime;
6760 old_inode->i_ctime = ctime;
6762 if (old_dentry->d_parent != new_dentry->d_parent)
6763 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
6765 if (unlikely(old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6766 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
6767 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
6768 old_dentry->d_name.name,
6769 old_dentry->d_name.len);
6771 btrfs_inc_nlink(old_dentry->d_inode);
6772 ret = btrfs_unlink_inode(trans, root, old_dir,
6773 old_dentry->d_inode,
6774 old_dentry->d_name.name,
6775 old_dentry->d_name.len);
6780 new_inode->i_ctime = CURRENT_TIME;
6781 if (unlikely(new_inode->i_ino ==
6782 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
6783 root_objectid = BTRFS_I(new_inode)->location.objectid;
6784 ret = btrfs_unlink_subvol(trans, dest, new_dir,
6786 new_dentry->d_name.name,
6787 new_dentry->d_name.len);
6788 BUG_ON(new_inode->i_nlink == 0);
6790 ret = btrfs_unlink_inode(trans, dest, new_dir,
6791 new_dentry->d_inode,
6792 new_dentry->d_name.name,
6793 new_dentry->d_name.len);
6796 if (new_inode->i_nlink == 0) {
6797 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
6802 ret = btrfs_add_link(trans, new_dir, old_inode,
6803 new_dentry->d_name.name,
6804 new_dentry->d_name.len, 0, index);
6807 if (old_inode->i_ino != BTRFS_FIRST_FREE_OBJECTID) {
6808 struct dentry *parent = dget_parent(new_dentry);
6809 btrfs_log_new_name(trans, old_inode, old_dir, parent);
6811 btrfs_end_log_trans(root);
6814 btrfs_end_transaction_throttle(trans, root);
6816 if (old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
6817 up_read(&root->fs_info->subvol_sem);
6823 * some fairly slow code that needs optimization. This walks the list
6824 * of all the inodes with pending delalloc and forces them to disk.
6826 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
6828 struct list_head *head = &root->fs_info->delalloc_inodes;
6829 struct btrfs_inode *binode;
6830 struct inode *inode;
6832 if (root->fs_info->sb->s_flags & MS_RDONLY)
6835 spin_lock(&root->fs_info->delalloc_lock);
6836 while (!list_empty(head)) {
6837 binode = list_entry(head->next, struct btrfs_inode,
6839 inode = igrab(&binode->vfs_inode);
6841 list_del_init(&binode->delalloc_inodes);
6842 spin_unlock(&root->fs_info->delalloc_lock);
6844 filemap_flush(inode->i_mapping);
6846 btrfs_add_delayed_iput(inode);
6851 spin_lock(&root->fs_info->delalloc_lock);
6853 spin_unlock(&root->fs_info->delalloc_lock);
6855 /* the filemap_flush will queue IO into the worker threads, but
6856 * we have to make sure the IO is actually started and that
6857 * ordered extents get created before we return
6859 atomic_inc(&root->fs_info->async_submit_draining);
6860 while (atomic_read(&root->fs_info->nr_async_submits) ||
6861 atomic_read(&root->fs_info->async_delalloc_pages)) {
6862 wait_event(root->fs_info->async_submit_wait,
6863 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
6864 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
6866 atomic_dec(&root->fs_info->async_submit_draining);
6870 int btrfs_start_one_delalloc_inode(struct btrfs_root *root, int delay_iput,
6873 struct btrfs_inode *binode;
6874 struct inode *inode = NULL;
6876 spin_lock(&root->fs_info->delalloc_lock);
6877 while (!list_empty(&root->fs_info->delalloc_inodes)) {
6878 binode = list_entry(root->fs_info->delalloc_inodes.next,
6879 struct btrfs_inode, delalloc_inodes);
6880 inode = igrab(&binode->vfs_inode);
6882 list_move_tail(&binode->delalloc_inodes,
6883 &root->fs_info->delalloc_inodes);
6887 list_del_init(&binode->delalloc_inodes);
6888 cond_resched_lock(&root->fs_info->delalloc_lock);
6890 spin_unlock(&root->fs_info->delalloc_lock);
6894 filemap_write_and_wait(inode->i_mapping);
6896 * We have to do this because compression doesn't
6897 * actually set PG_writeback until it submits the pages
6898 * for IO, which happens in an async thread, so we could
6899 * race and not actually wait for any writeback pages
6900 * because they've not been submitted yet. Technically
6901 * this could still be the case for the ordered stuff
6902 * since the async thread may not have started to do its
6903 * work yet. If this becomes the case then we need to
6904 * figure out a way to make sure that in writepage we
6905 * wait for any async pages to be submitted before
6906 * returning so that fdatawait does what its supposed to
6909 btrfs_wait_ordered_range(inode, 0, (u64)-1);
6911 filemap_flush(inode->i_mapping);
6914 btrfs_add_delayed_iput(inode);
6922 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
6923 const char *symname)
6925 struct btrfs_trans_handle *trans;
6926 struct btrfs_root *root = BTRFS_I(dir)->root;
6927 struct btrfs_path *path;
6928 struct btrfs_key key;
6929 struct inode *inode = NULL;
6937 struct btrfs_file_extent_item *ei;
6938 struct extent_buffer *leaf;
6939 unsigned long nr = 0;
6941 name_len = strlen(symname) + 1;
6942 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
6943 return -ENAMETOOLONG;
6945 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
6949 * 2 items for inode item and ref
6950 * 2 items for dir items
6951 * 1 item for xattr if selinux is on
6953 trans = btrfs_start_transaction(root, 5);
6955 return PTR_ERR(trans);
6957 btrfs_set_trans_block_group(trans, dir);
6959 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6960 dentry->d_name.len, dir->i_ino, objectid,
6961 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO,
6963 err = PTR_ERR(inode);
6967 err = btrfs_init_inode_security(trans, inode, dir);
6973 btrfs_set_trans_block_group(trans, inode);
6974 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6978 inode->i_mapping->a_ops = &btrfs_aops;
6979 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
6980 inode->i_fop = &btrfs_file_operations;
6981 inode->i_op = &btrfs_file_inode_operations;
6982 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6984 btrfs_update_inode_block_group(trans, inode);
6985 btrfs_update_inode_block_group(trans, dir);
6989 path = btrfs_alloc_path();
6991 key.objectid = inode->i_ino;
6993 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
6994 datasize = btrfs_file_extent_calc_inline_size(name_len);
6995 err = btrfs_insert_empty_item(trans, root, path, &key,
7001 leaf = path->nodes[0];
7002 ei = btrfs_item_ptr(leaf, path->slots[0],
7003 struct btrfs_file_extent_item);
7004 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
7005 btrfs_set_file_extent_type(leaf, ei,
7006 BTRFS_FILE_EXTENT_INLINE);
7007 btrfs_set_file_extent_encryption(leaf, ei, 0);
7008 btrfs_set_file_extent_compression(leaf, ei, 0);
7009 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
7010 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
7012 ptr = btrfs_file_extent_inline_start(ei);
7013 write_extent_buffer(leaf, symname, ptr, name_len);
7014 btrfs_mark_buffer_dirty(leaf);
7015 btrfs_free_path(path);
7017 inode->i_op = &btrfs_symlink_inode_operations;
7018 inode->i_mapping->a_ops = &btrfs_symlink_aops;
7019 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7020 inode_set_bytes(inode, name_len);
7021 btrfs_i_size_write(inode, name_len - 1);
7022 err = btrfs_update_inode(trans, root, inode);
7027 nr = trans->blocks_used;
7028 btrfs_end_transaction_throttle(trans, root);
7030 inode_dec_link_count(inode);
7033 btrfs_btree_balance_dirty(root, nr);
7037 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
7038 u64 start, u64 num_bytes, u64 min_size,
7039 loff_t actual_len, u64 *alloc_hint,
7040 struct btrfs_trans_handle *trans)
7042 struct btrfs_root *root = BTRFS_I(inode)->root;
7043 struct btrfs_key ins;
7044 u64 cur_offset = start;
7047 bool own_trans = true;
7051 while (num_bytes > 0) {
7053 trans = btrfs_start_transaction(root, 3);
7054 if (IS_ERR(trans)) {
7055 ret = PTR_ERR(trans);
7060 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
7061 0, *alloc_hint, (u64)-1, &ins, 1);
7064 btrfs_end_transaction(trans, root);
7068 ret = insert_reserved_file_extent(trans, inode,
7069 cur_offset, ins.objectid,
7070 ins.offset, ins.offset,
7071 ins.offset, 0, 0, 0,
7072 BTRFS_FILE_EXTENT_PREALLOC);
7074 btrfs_drop_extent_cache(inode, cur_offset,
7075 cur_offset + ins.offset -1, 0);
7077 num_bytes -= ins.offset;
7078 cur_offset += ins.offset;
7079 *alloc_hint = ins.objectid + ins.offset;
7081 inode->i_ctime = CURRENT_TIME;
7082 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
7083 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
7084 (actual_len > inode->i_size) &&
7085 (cur_offset > inode->i_size)) {
7086 if (cur_offset > actual_len)
7087 i_size = actual_len;
7089 i_size = cur_offset;
7090 i_size_write(inode, i_size);
7091 btrfs_ordered_update_i_size(inode, i_size, NULL);
7094 ret = btrfs_update_inode(trans, root, inode);
7098 btrfs_end_transaction(trans, root);
7103 int btrfs_prealloc_file_range(struct inode *inode, int mode,
7104 u64 start, u64 num_bytes, u64 min_size,
7105 loff_t actual_len, u64 *alloc_hint)
7107 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7108 min_size, actual_len, alloc_hint,
7112 int btrfs_prealloc_file_range_trans(struct inode *inode,
7113 struct btrfs_trans_handle *trans, int mode,
7114 u64 start, u64 num_bytes, u64 min_size,
7115 loff_t actual_len, u64 *alloc_hint)
7117 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7118 min_size, actual_len, alloc_hint, trans);
7121 static long btrfs_fallocate(struct inode *inode, int mode,
7122 loff_t offset, loff_t len)
7124 struct extent_state *cached_state = NULL;
7131 u64 mask = BTRFS_I(inode)->root->sectorsize - 1;
7132 struct extent_map *em;
7135 alloc_start = offset & ~mask;
7136 alloc_end = (offset + len + mask) & ~mask;
7139 * wait for ordered IO before we have any locks. We'll loop again
7140 * below with the locks held.
7142 btrfs_wait_ordered_range(inode, alloc_start, alloc_end - alloc_start);
7144 mutex_lock(&inode->i_mutex);
7145 ret = inode_newsize_ok(inode, alloc_end);
7149 if (alloc_start > inode->i_size) {
7150 ret = btrfs_cont_expand(inode, alloc_start);
7155 ret = btrfs_check_data_free_space(inode, alloc_end - alloc_start);
7159 locked_end = alloc_end - 1;
7161 struct btrfs_ordered_extent *ordered;
7163 /* the extent lock is ordered inside the running
7166 lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
7167 locked_end, 0, &cached_state, GFP_NOFS);
7168 ordered = btrfs_lookup_first_ordered_extent(inode,
7171 ordered->file_offset + ordered->len > alloc_start &&
7172 ordered->file_offset < alloc_end) {
7173 btrfs_put_ordered_extent(ordered);
7174 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7175 alloc_start, locked_end,
7176 &cached_state, GFP_NOFS);
7178 * we can't wait on the range with the transaction
7179 * running or with the extent lock held
7181 btrfs_wait_ordered_range(inode, alloc_start,
7182 alloc_end - alloc_start);
7185 btrfs_put_ordered_extent(ordered);
7190 cur_offset = alloc_start;
7192 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
7193 alloc_end - cur_offset, 0);
7194 BUG_ON(IS_ERR(em) || !em);
7195 last_byte = min(extent_map_end(em), alloc_end);
7196 last_byte = (last_byte + mask) & ~mask;
7197 if (em->block_start == EXTENT_MAP_HOLE ||
7198 (cur_offset >= inode->i_size &&
7199 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7200 ret = btrfs_prealloc_file_range(inode, mode, cur_offset,
7201 last_byte - cur_offset,
7202 1 << inode->i_blkbits,
7206 free_extent_map(em);
7210 free_extent_map(em);
7212 cur_offset = last_byte;
7213 if (cur_offset >= alloc_end) {
7218 unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
7219 &cached_state, GFP_NOFS);
7221 btrfs_free_reserved_data_space(inode, alloc_end - alloc_start);
7223 mutex_unlock(&inode->i_mutex);
7227 static int btrfs_set_page_dirty(struct page *page)
7229 return __set_page_dirty_nobuffers(page);
7232 static int btrfs_permission(struct inode *inode, int mask)
7234 struct btrfs_root *root = BTRFS_I(inode)->root;
7236 if (btrfs_root_readonly(root) && (mask & MAY_WRITE))
7238 if ((BTRFS_I(inode)->flags & BTRFS_INODE_READONLY) && (mask & MAY_WRITE))
7240 return generic_permission(inode, mask, btrfs_check_acl);
7243 static const struct inode_operations btrfs_dir_inode_operations = {
7244 .getattr = btrfs_getattr,
7245 .lookup = btrfs_lookup,
7246 .create = btrfs_create,
7247 .unlink = btrfs_unlink,
7249 .mkdir = btrfs_mkdir,
7250 .rmdir = btrfs_rmdir,
7251 .rename = btrfs_rename,
7252 .symlink = btrfs_symlink,
7253 .setattr = btrfs_setattr,
7254 .mknod = btrfs_mknod,
7255 .setxattr = btrfs_setxattr,
7256 .getxattr = btrfs_getxattr,
7257 .listxattr = btrfs_listxattr,
7258 .removexattr = btrfs_removexattr,
7259 .permission = btrfs_permission,
7261 static const struct inode_operations btrfs_dir_ro_inode_operations = {
7262 .lookup = btrfs_lookup,
7263 .permission = btrfs_permission,
7266 static const struct file_operations btrfs_dir_file_operations = {
7267 .llseek = generic_file_llseek,
7268 .read = generic_read_dir,
7269 .readdir = btrfs_real_readdir,
7270 .unlocked_ioctl = btrfs_ioctl,
7271 #ifdef CONFIG_COMPAT
7272 .compat_ioctl = btrfs_ioctl,
7274 .release = btrfs_release_file,
7275 .fsync = btrfs_sync_file,
7278 static struct extent_io_ops btrfs_extent_io_ops = {
7279 .fill_delalloc = run_delalloc_range,
7280 .submit_bio_hook = btrfs_submit_bio_hook,
7281 .merge_bio_hook = btrfs_merge_bio_hook,
7282 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
7283 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
7284 .writepage_start_hook = btrfs_writepage_start_hook,
7285 .readpage_io_failed_hook = btrfs_io_failed_hook,
7286 .set_bit_hook = btrfs_set_bit_hook,
7287 .clear_bit_hook = btrfs_clear_bit_hook,
7288 .merge_extent_hook = btrfs_merge_extent_hook,
7289 .split_extent_hook = btrfs_split_extent_hook,
7293 * btrfs doesn't support the bmap operation because swapfiles
7294 * use bmap to make a mapping of extents in the file. They assume
7295 * these extents won't change over the life of the file and they
7296 * use the bmap result to do IO directly to the drive.
7298 * the btrfs bmap call would return logical addresses that aren't
7299 * suitable for IO and they also will change frequently as COW
7300 * operations happen. So, swapfile + btrfs == corruption.
7302 * For now we're avoiding this by dropping bmap.
7304 static const struct address_space_operations btrfs_aops = {
7305 .readpage = btrfs_readpage,
7306 .writepage = btrfs_writepage,
7307 .writepages = btrfs_writepages,
7308 .readpages = btrfs_readpages,
7309 .sync_page = block_sync_page,
7310 .direct_IO = btrfs_direct_IO,
7311 .invalidatepage = btrfs_invalidatepage,
7312 .releasepage = btrfs_releasepage,
7313 .set_page_dirty = btrfs_set_page_dirty,
7314 .error_remove_page = generic_error_remove_page,
7317 static const struct address_space_operations btrfs_symlink_aops = {
7318 .readpage = btrfs_readpage,
7319 .writepage = btrfs_writepage,
7320 .invalidatepage = btrfs_invalidatepage,
7321 .releasepage = btrfs_releasepage,
7324 static const struct inode_operations btrfs_file_inode_operations = {
7325 .truncate = btrfs_truncate,
7326 .getattr = btrfs_getattr,
7327 .setattr = btrfs_setattr,
7328 .setxattr = btrfs_setxattr,
7329 .getxattr = btrfs_getxattr,
7330 .listxattr = btrfs_listxattr,
7331 .removexattr = btrfs_removexattr,
7332 .permission = btrfs_permission,
7333 .fallocate = btrfs_fallocate,
7334 .fiemap = btrfs_fiemap,
7336 static const struct inode_operations btrfs_special_inode_operations = {
7337 .getattr = btrfs_getattr,
7338 .setattr = btrfs_setattr,
7339 .permission = btrfs_permission,
7340 .setxattr = btrfs_setxattr,
7341 .getxattr = btrfs_getxattr,
7342 .listxattr = btrfs_listxattr,
7343 .removexattr = btrfs_removexattr,
7345 static const struct inode_operations btrfs_symlink_inode_operations = {
7346 .readlink = generic_readlink,
7347 .follow_link = page_follow_link_light,
7348 .put_link = page_put_link,
7349 .getattr = btrfs_getattr,
7350 .permission = btrfs_permission,
7351 .setxattr = btrfs_setxattr,
7352 .getxattr = btrfs_getxattr,
7353 .listxattr = btrfs_listxattr,
7354 .removexattr = btrfs_removexattr,
7357 const struct dentry_operations btrfs_dentry_operations = {
7358 .d_delete = btrfs_dentry_delete,