2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
44 #include "transaction.h"
45 #include "btrfs_inode.h"
47 #include "print-tree.h"
48 #include "ordered-data.h"
52 #include "compression.h"
54 #include "free-space-cache.h"
55 #include "inode-map.h"
57 struct btrfs_iget_args {
59 struct btrfs_root *root;
62 static const struct inode_operations btrfs_dir_inode_operations;
63 static const struct inode_operations btrfs_symlink_inode_operations;
64 static const struct inode_operations btrfs_dir_ro_inode_operations;
65 static const struct inode_operations btrfs_special_inode_operations;
66 static const struct inode_operations btrfs_file_inode_operations;
67 static const struct address_space_operations btrfs_aops;
68 static const struct address_space_operations btrfs_symlink_aops;
69 static const struct file_operations btrfs_dir_file_operations;
70 static struct extent_io_ops btrfs_extent_io_ops;
72 static struct kmem_cache *btrfs_inode_cachep;
73 struct kmem_cache *btrfs_trans_handle_cachep;
74 struct kmem_cache *btrfs_transaction_cachep;
75 struct kmem_cache *btrfs_path_cachep;
76 struct kmem_cache *btrfs_free_space_cachep;
79 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
80 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
81 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
82 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
83 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
84 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
85 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
86 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
89 static int btrfs_setsize(struct inode *inode, loff_t newsize);
90 static int btrfs_truncate(struct inode *inode);
91 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
92 static noinline int cow_file_range(struct inode *inode,
93 struct page *locked_page,
94 u64 start, u64 end, int *page_started,
95 unsigned long *nr_written, int unlock);
96 static noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
97 struct btrfs_root *root, struct inode *inode);
99 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
100 struct inode *inode, struct inode *dir,
101 const struct qstr *qstr)
105 err = btrfs_init_acl(trans, inode, dir);
107 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
112 * this does all the hard work for inserting an inline extent into
113 * the btree. The caller should have done a btrfs_drop_extents so that
114 * no overlapping inline items exist in the btree
116 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
117 struct btrfs_root *root, struct inode *inode,
118 u64 start, size_t size, size_t compressed_size,
120 struct page **compressed_pages)
122 struct btrfs_key key;
123 struct btrfs_path *path;
124 struct extent_buffer *leaf;
125 struct page *page = NULL;
128 struct btrfs_file_extent_item *ei;
131 size_t cur_size = size;
133 unsigned long offset;
135 if (compressed_size && compressed_pages)
136 cur_size = compressed_size;
138 path = btrfs_alloc_path();
142 path->leave_spinning = 1;
144 key.objectid = btrfs_ino(inode);
146 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
147 datasize = btrfs_file_extent_calc_inline_size(cur_size);
149 inode_add_bytes(inode, size);
150 ret = btrfs_insert_empty_item(trans, root, path, &key,
157 leaf = path->nodes[0];
158 ei = btrfs_item_ptr(leaf, path->slots[0],
159 struct btrfs_file_extent_item);
160 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
161 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
162 btrfs_set_file_extent_encryption(leaf, ei, 0);
163 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
164 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
165 ptr = btrfs_file_extent_inline_start(ei);
167 if (compress_type != BTRFS_COMPRESS_NONE) {
170 while (compressed_size > 0) {
171 cpage = compressed_pages[i];
172 cur_size = min_t(unsigned long, compressed_size,
175 kaddr = kmap_atomic(cpage, KM_USER0);
176 write_extent_buffer(leaf, kaddr, ptr, cur_size);
177 kunmap_atomic(kaddr, KM_USER0);
181 compressed_size -= cur_size;
183 btrfs_set_file_extent_compression(leaf, ei,
186 page = find_get_page(inode->i_mapping,
187 start >> PAGE_CACHE_SHIFT);
188 btrfs_set_file_extent_compression(leaf, ei, 0);
189 kaddr = kmap_atomic(page, KM_USER0);
190 offset = start & (PAGE_CACHE_SIZE - 1);
191 write_extent_buffer(leaf, kaddr + offset, ptr, size);
192 kunmap_atomic(kaddr, KM_USER0);
193 page_cache_release(page);
195 btrfs_mark_buffer_dirty(leaf);
196 btrfs_free_path(path);
199 * we're an inline extent, so nobody can
200 * extend the file past i_size without locking
201 * a page we already have locked.
203 * We must do any isize and inode updates
204 * before we unlock the pages. Otherwise we
205 * could end up racing with unlink.
207 BTRFS_I(inode)->disk_i_size = inode->i_size;
208 btrfs_update_inode(trans, root, inode);
212 btrfs_free_path(path);
218 * conditionally insert an inline extent into the file. This
219 * does the checks required to make sure the data is small enough
220 * to fit as an inline extent.
222 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
223 struct btrfs_root *root,
224 struct inode *inode, u64 start, u64 end,
225 size_t compressed_size, int compress_type,
226 struct page **compressed_pages)
228 u64 isize = i_size_read(inode);
229 u64 actual_end = min(end + 1, isize);
230 u64 inline_len = actual_end - start;
231 u64 aligned_end = (end + root->sectorsize - 1) &
232 ~((u64)root->sectorsize - 1);
234 u64 data_len = inline_len;
238 data_len = compressed_size;
241 actual_end >= PAGE_CACHE_SIZE ||
242 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
244 (actual_end & (root->sectorsize - 1)) == 0) ||
246 data_len > root->fs_info->max_inline) {
250 ret = btrfs_drop_extents(trans, inode, start, aligned_end,
254 if (isize > actual_end)
255 inline_len = min_t(u64, isize, actual_end);
256 ret = insert_inline_extent(trans, root, inode, start,
257 inline_len, compressed_size,
258 compress_type, compressed_pages);
260 btrfs_delalloc_release_metadata(inode, end + 1 - start);
261 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
265 struct async_extent {
270 unsigned long nr_pages;
272 struct list_head list;
277 struct btrfs_root *root;
278 struct page *locked_page;
281 struct list_head extents;
282 struct btrfs_work work;
285 static noinline int add_async_extent(struct async_cow *cow,
286 u64 start, u64 ram_size,
289 unsigned long nr_pages,
292 struct async_extent *async_extent;
294 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
295 BUG_ON(!async_extent);
296 async_extent->start = start;
297 async_extent->ram_size = ram_size;
298 async_extent->compressed_size = compressed_size;
299 async_extent->pages = pages;
300 async_extent->nr_pages = nr_pages;
301 async_extent->compress_type = compress_type;
302 list_add_tail(&async_extent->list, &cow->extents);
307 * we create compressed extents in two phases. The first
308 * phase compresses a range of pages that have already been
309 * locked (both pages and state bits are locked).
311 * This is done inside an ordered work queue, and the compression
312 * is spread across many cpus. The actual IO submission is step
313 * two, and the ordered work queue takes care of making sure that
314 * happens in the same order things were put onto the queue by
315 * writepages and friends.
317 * If this code finds it can't get good compression, it puts an
318 * entry onto the work queue to write the uncompressed bytes. This
319 * makes sure that both compressed inodes and uncompressed inodes
320 * are written in the same order that pdflush sent them down.
322 static noinline int compress_file_range(struct inode *inode,
323 struct page *locked_page,
325 struct async_cow *async_cow,
328 struct btrfs_root *root = BTRFS_I(inode)->root;
329 struct btrfs_trans_handle *trans;
331 u64 blocksize = root->sectorsize;
333 u64 isize = i_size_read(inode);
335 struct page **pages = NULL;
336 unsigned long nr_pages;
337 unsigned long nr_pages_ret = 0;
338 unsigned long total_compressed = 0;
339 unsigned long total_in = 0;
340 unsigned long max_compressed = 128 * 1024;
341 unsigned long max_uncompressed = 128 * 1024;
344 int compress_type = root->fs_info->compress_type;
346 /* if this is a small write inside eof, kick off a defragbot */
347 if (end <= BTRFS_I(inode)->disk_i_size && (end - start + 1) < 16 * 1024)
348 btrfs_add_inode_defrag(NULL, inode);
350 actual_end = min_t(u64, isize, end + 1);
353 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
354 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
357 * we don't want to send crud past the end of i_size through
358 * compression, that's just a waste of CPU time. So, if the
359 * end of the file is before the start of our current
360 * requested range of bytes, we bail out to the uncompressed
361 * cleanup code that can deal with all of this.
363 * It isn't really the fastest way to fix things, but this is a
364 * very uncommon corner.
366 if (actual_end <= start)
367 goto cleanup_and_bail_uncompressed;
369 total_compressed = actual_end - start;
371 /* we want to make sure that amount of ram required to uncompress
372 * an extent is reasonable, so we limit the total size in ram
373 * of a compressed extent to 128k. This is a crucial number
374 * because it also controls how easily we can spread reads across
375 * cpus for decompression.
377 * We also want to make sure the amount of IO required to do
378 * a random read is reasonably small, so we limit the size of
379 * a compressed extent to 128k.
381 total_compressed = min(total_compressed, max_uncompressed);
382 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
383 num_bytes = max(blocksize, num_bytes);
388 * we do compression for mount -o compress and when the
389 * inode has not been flagged as nocompress. This flag can
390 * change at any time if we discover bad compression ratios.
392 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
393 (btrfs_test_opt(root, COMPRESS) ||
394 (BTRFS_I(inode)->force_compress) ||
395 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
397 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
399 /* just bail out to the uncompressed code */
403 if (BTRFS_I(inode)->force_compress)
404 compress_type = BTRFS_I(inode)->force_compress;
406 ret = btrfs_compress_pages(compress_type,
407 inode->i_mapping, start,
408 total_compressed, pages,
409 nr_pages, &nr_pages_ret,
415 unsigned long offset = total_compressed &
416 (PAGE_CACHE_SIZE - 1);
417 struct page *page = pages[nr_pages_ret - 1];
420 /* zero the tail end of the last page, we might be
421 * sending it down to disk
424 kaddr = kmap_atomic(page, KM_USER0);
425 memset(kaddr + offset, 0,
426 PAGE_CACHE_SIZE - offset);
427 kunmap_atomic(kaddr, KM_USER0);
434 trans = btrfs_join_transaction(root);
435 BUG_ON(IS_ERR(trans));
436 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
438 /* lets try to make an inline extent */
439 if (ret || total_in < (actual_end - start)) {
440 /* we didn't compress the entire range, try
441 * to make an uncompressed inline extent.
443 ret = cow_file_range_inline(trans, root, inode,
444 start, end, 0, 0, NULL);
446 /* try making a compressed inline extent */
447 ret = cow_file_range_inline(trans, root, inode,
450 compress_type, pages);
454 * inline extent creation worked, we don't need
455 * to create any more async work items. Unlock
456 * and free up our temp pages.
458 extent_clear_unlock_delalloc(inode,
459 &BTRFS_I(inode)->io_tree,
461 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
462 EXTENT_CLEAR_DELALLOC |
463 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
465 btrfs_end_transaction(trans, root);
468 btrfs_end_transaction(trans, root);
473 * we aren't doing an inline extent round the compressed size
474 * up to a block size boundary so the allocator does sane
477 total_compressed = (total_compressed + blocksize - 1) &
481 * one last check to make sure the compression is really a
482 * win, compare the page count read with the blocks on disk
484 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
485 ~(PAGE_CACHE_SIZE - 1);
486 if (total_compressed >= total_in) {
489 num_bytes = total_in;
492 if (!will_compress && pages) {
494 * the compression code ran but failed to make things smaller,
495 * free any pages it allocated and our page pointer array
497 for (i = 0; i < nr_pages_ret; i++) {
498 WARN_ON(pages[i]->mapping);
499 page_cache_release(pages[i]);
503 total_compressed = 0;
506 /* flag the file so we don't compress in the future */
507 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
508 !(BTRFS_I(inode)->force_compress)) {
509 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
515 /* the async work queues will take care of doing actual
516 * allocation on disk for these compressed pages,
517 * and will submit them to the elevator.
519 add_async_extent(async_cow, start, num_bytes,
520 total_compressed, pages, nr_pages_ret,
523 if (start + num_bytes < end) {
530 cleanup_and_bail_uncompressed:
532 * No compression, but we still need to write the pages in
533 * the file we've been given so far. redirty the locked
534 * page if it corresponds to our extent and set things up
535 * for the async work queue to run cow_file_range to do
536 * the normal delalloc dance
538 if (page_offset(locked_page) >= start &&
539 page_offset(locked_page) <= end) {
540 __set_page_dirty_nobuffers(locked_page);
541 /* unlocked later on in the async handlers */
543 add_async_extent(async_cow, start, end - start + 1,
544 0, NULL, 0, BTRFS_COMPRESS_NONE);
552 for (i = 0; i < nr_pages_ret; i++) {
553 WARN_ON(pages[i]->mapping);
554 page_cache_release(pages[i]);
562 * phase two of compressed writeback. This is the ordered portion
563 * of the code, which only gets called in the order the work was
564 * queued. We walk all the async extents created by compress_file_range
565 * and send them down to the disk.
567 static noinline int submit_compressed_extents(struct inode *inode,
568 struct async_cow *async_cow)
570 struct async_extent *async_extent;
572 struct btrfs_trans_handle *trans;
573 struct btrfs_key ins;
574 struct extent_map *em;
575 struct btrfs_root *root = BTRFS_I(inode)->root;
576 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
577 struct extent_io_tree *io_tree;
580 if (list_empty(&async_cow->extents))
584 while (!list_empty(&async_cow->extents)) {
585 async_extent = list_entry(async_cow->extents.next,
586 struct async_extent, list);
587 list_del(&async_extent->list);
589 io_tree = &BTRFS_I(inode)->io_tree;
592 /* did the compression code fall back to uncompressed IO? */
593 if (!async_extent->pages) {
594 int page_started = 0;
595 unsigned long nr_written = 0;
597 lock_extent(io_tree, async_extent->start,
598 async_extent->start +
599 async_extent->ram_size - 1, GFP_NOFS);
601 /* allocate blocks */
602 ret = cow_file_range(inode, async_cow->locked_page,
604 async_extent->start +
605 async_extent->ram_size - 1,
606 &page_started, &nr_written, 0);
609 * if page_started, cow_file_range inserted an
610 * inline extent and took care of all the unlocking
611 * and IO for us. Otherwise, we need to submit
612 * all those pages down to the drive.
614 if (!page_started && !ret)
615 extent_write_locked_range(io_tree,
616 inode, async_extent->start,
617 async_extent->start +
618 async_extent->ram_size - 1,
626 lock_extent(io_tree, async_extent->start,
627 async_extent->start + async_extent->ram_size - 1,
630 trans = btrfs_join_transaction(root);
631 BUG_ON(IS_ERR(trans));
632 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
633 ret = btrfs_reserve_extent(trans, root,
634 async_extent->compressed_size,
635 async_extent->compressed_size,
638 btrfs_end_transaction(trans, root);
642 for (i = 0; i < async_extent->nr_pages; i++) {
643 WARN_ON(async_extent->pages[i]->mapping);
644 page_cache_release(async_extent->pages[i]);
646 kfree(async_extent->pages);
647 async_extent->nr_pages = 0;
648 async_extent->pages = NULL;
649 unlock_extent(io_tree, async_extent->start,
650 async_extent->start +
651 async_extent->ram_size - 1, GFP_NOFS);
656 * here we're doing allocation and writeback of the
659 btrfs_drop_extent_cache(inode, async_extent->start,
660 async_extent->start +
661 async_extent->ram_size - 1, 0);
663 em = alloc_extent_map();
665 em->start = async_extent->start;
666 em->len = async_extent->ram_size;
667 em->orig_start = em->start;
669 em->block_start = ins.objectid;
670 em->block_len = ins.offset;
671 em->bdev = root->fs_info->fs_devices->latest_bdev;
672 em->compress_type = async_extent->compress_type;
673 set_bit(EXTENT_FLAG_PINNED, &em->flags);
674 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
677 write_lock(&em_tree->lock);
678 ret = add_extent_mapping(em_tree, em);
679 write_unlock(&em_tree->lock);
680 if (ret != -EEXIST) {
684 btrfs_drop_extent_cache(inode, async_extent->start,
685 async_extent->start +
686 async_extent->ram_size - 1, 0);
689 ret = btrfs_add_ordered_extent_compress(inode,
692 async_extent->ram_size,
694 BTRFS_ORDERED_COMPRESSED,
695 async_extent->compress_type);
699 * clear dirty, set writeback and unlock the pages.
701 extent_clear_unlock_delalloc(inode,
702 &BTRFS_I(inode)->io_tree,
704 async_extent->start +
705 async_extent->ram_size - 1,
706 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
707 EXTENT_CLEAR_UNLOCK |
708 EXTENT_CLEAR_DELALLOC |
709 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
711 ret = btrfs_submit_compressed_write(inode,
713 async_extent->ram_size,
715 ins.offset, async_extent->pages,
716 async_extent->nr_pages);
719 alloc_hint = ins.objectid + ins.offset;
727 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
730 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
731 struct extent_map *em;
734 read_lock(&em_tree->lock);
735 em = search_extent_mapping(em_tree, start, num_bytes);
738 * if block start isn't an actual block number then find the
739 * first block in this inode and use that as a hint. If that
740 * block is also bogus then just don't worry about it.
742 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
744 em = search_extent_mapping(em_tree, 0, 0);
745 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
746 alloc_hint = em->block_start;
750 alloc_hint = em->block_start;
754 read_unlock(&em_tree->lock);
760 * when extent_io.c finds a delayed allocation range in the file,
761 * the call backs end up in this code. The basic idea is to
762 * allocate extents on disk for the range, and create ordered data structs
763 * in ram to track those extents.
765 * locked_page is the page that writepage had locked already. We use
766 * it to make sure we don't do extra locks or unlocks.
768 * *page_started is set to one if we unlock locked_page and do everything
769 * required to start IO on it. It may be clean and already done with
772 static noinline int cow_file_range(struct inode *inode,
773 struct page *locked_page,
774 u64 start, u64 end, int *page_started,
775 unsigned long *nr_written,
778 struct btrfs_root *root = BTRFS_I(inode)->root;
779 struct btrfs_trans_handle *trans;
782 unsigned long ram_size;
785 u64 blocksize = root->sectorsize;
786 struct btrfs_key ins;
787 struct extent_map *em;
788 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
791 BUG_ON(btrfs_is_free_space_inode(root, inode));
792 trans = btrfs_join_transaction(root);
793 BUG_ON(IS_ERR(trans));
794 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
796 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
797 num_bytes = max(blocksize, num_bytes);
798 disk_num_bytes = num_bytes;
801 /* if this is a small write inside eof, kick off defrag */
802 if (end <= BTRFS_I(inode)->disk_i_size && num_bytes < 64 * 1024)
803 btrfs_add_inode_defrag(trans, inode);
806 /* lets try to make an inline extent */
807 ret = cow_file_range_inline(trans, root, inode,
808 start, end, 0, 0, NULL);
810 extent_clear_unlock_delalloc(inode,
811 &BTRFS_I(inode)->io_tree,
813 EXTENT_CLEAR_UNLOCK_PAGE |
814 EXTENT_CLEAR_UNLOCK |
815 EXTENT_CLEAR_DELALLOC |
817 EXTENT_SET_WRITEBACK |
818 EXTENT_END_WRITEBACK);
820 *nr_written = *nr_written +
821 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
828 BUG_ON(disk_num_bytes >
829 btrfs_super_total_bytes(root->fs_info->super_copy));
831 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
832 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
834 while (disk_num_bytes > 0) {
837 cur_alloc_size = disk_num_bytes;
838 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
839 root->sectorsize, 0, alloc_hint,
843 em = alloc_extent_map();
846 em->orig_start = em->start;
847 ram_size = ins.offset;
848 em->len = ins.offset;
850 em->block_start = ins.objectid;
851 em->block_len = ins.offset;
852 em->bdev = root->fs_info->fs_devices->latest_bdev;
853 set_bit(EXTENT_FLAG_PINNED, &em->flags);
856 write_lock(&em_tree->lock);
857 ret = add_extent_mapping(em_tree, em);
858 write_unlock(&em_tree->lock);
859 if (ret != -EEXIST) {
863 btrfs_drop_extent_cache(inode, start,
864 start + ram_size - 1, 0);
867 cur_alloc_size = ins.offset;
868 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
869 ram_size, cur_alloc_size, 0);
872 if (root->root_key.objectid ==
873 BTRFS_DATA_RELOC_TREE_OBJECTID) {
874 ret = btrfs_reloc_clone_csums(inode, start,
879 if (disk_num_bytes < cur_alloc_size)
882 /* we're not doing compressed IO, don't unlock the first
883 * page (which the caller expects to stay locked), don't
884 * clear any dirty bits and don't set any writeback bits
886 * Do set the Private2 bit so we know this page was properly
887 * setup for writepage
889 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
890 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
893 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
894 start, start + ram_size - 1,
896 disk_num_bytes -= cur_alloc_size;
897 num_bytes -= cur_alloc_size;
898 alloc_hint = ins.objectid + ins.offset;
899 start += cur_alloc_size;
903 btrfs_end_transaction(trans, root);
909 * work queue call back to started compression on a file and pages
911 static noinline void async_cow_start(struct btrfs_work *work)
913 struct async_cow *async_cow;
915 async_cow = container_of(work, struct async_cow, work);
917 compress_file_range(async_cow->inode, async_cow->locked_page,
918 async_cow->start, async_cow->end, async_cow,
921 async_cow->inode = NULL;
925 * work queue call back to submit previously compressed pages
927 static noinline void async_cow_submit(struct btrfs_work *work)
929 struct async_cow *async_cow;
930 struct btrfs_root *root;
931 unsigned long nr_pages;
933 async_cow = container_of(work, struct async_cow, work);
935 root = async_cow->root;
936 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
939 atomic_sub(nr_pages, &root->fs_info->async_delalloc_pages);
941 if (atomic_read(&root->fs_info->async_delalloc_pages) <
943 waitqueue_active(&root->fs_info->async_submit_wait))
944 wake_up(&root->fs_info->async_submit_wait);
946 if (async_cow->inode)
947 submit_compressed_extents(async_cow->inode, async_cow);
950 static noinline void async_cow_free(struct btrfs_work *work)
952 struct async_cow *async_cow;
953 async_cow = container_of(work, struct async_cow, work);
957 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
958 u64 start, u64 end, int *page_started,
959 unsigned long *nr_written)
961 struct async_cow *async_cow;
962 struct btrfs_root *root = BTRFS_I(inode)->root;
963 unsigned long nr_pages;
965 int limit = 10 * 1024 * 1042;
967 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
968 1, 0, NULL, GFP_NOFS);
969 while (start < end) {
970 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
972 async_cow->inode = inode;
973 async_cow->root = root;
974 async_cow->locked_page = locked_page;
975 async_cow->start = start;
977 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
980 cur_end = min(end, start + 512 * 1024 - 1);
982 async_cow->end = cur_end;
983 INIT_LIST_HEAD(&async_cow->extents);
985 async_cow->work.func = async_cow_start;
986 async_cow->work.ordered_func = async_cow_submit;
987 async_cow->work.ordered_free = async_cow_free;
988 async_cow->work.flags = 0;
990 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
992 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
994 btrfs_queue_worker(&root->fs_info->delalloc_workers,
997 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
998 wait_event(root->fs_info->async_submit_wait,
999 (atomic_read(&root->fs_info->async_delalloc_pages) <
1003 while (atomic_read(&root->fs_info->async_submit_draining) &&
1004 atomic_read(&root->fs_info->async_delalloc_pages)) {
1005 wait_event(root->fs_info->async_submit_wait,
1006 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1010 *nr_written += nr_pages;
1011 start = cur_end + 1;
1017 static noinline int csum_exist_in_range(struct btrfs_root *root,
1018 u64 bytenr, u64 num_bytes)
1021 struct btrfs_ordered_sum *sums;
1024 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1025 bytenr + num_bytes - 1, &list, 0);
1026 if (ret == 0 && list_empty(&list))
1029 while (!list_empty(&list)) {
1030 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1031 list_del(&sums->list);
1038 * when nowcow writeback call back. This checks for snapshots or COW copies
1039 * of the extents that exist in the file, and COWs the file as required.
1041 * If no cow copies or snapshots exist, we write directly to the existing
1044 static noinline int run_delalloc_nocow(struct inode *inode,
1045 struct page *locked_page,
1046 u64 start, u64 end, int *page_started, int force,
1047 unsigned long *nr_written)
1049 struct btrfs_root *root = BTRFS_I(inode)->root;
1050 struct btrfs_trans_handle *trans;
1051 struct extent_buffer *leaf;
1052 struct btrfs_path *path;
1053 struct btrfs_file_extent_item *fi;
1054 struct btrfs_key found_key;
1067 u64 ino = btrfs_ino(inode);
1069 path = btrfs_alloc_path();
1073 nolock = btrfs_is_free_space_inode(root, inode);
1076 trans = btrfs_join_transaction_nolock(root);
1078 trans = btrfs_join_transaction(root);
1080 BUG_ON(IS_ERR(trans));
1081 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1083 cow_start = (u64)-1;
1086 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1089 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1090 leaf = path->nodes[0];
1091 btrfs_item_key_to_cpu(leaf, &found_key,
1092 path->slots[0] - 1);
1093 if (found_key.objectid == ino &&
1094 found_key.type == BTRFS_EXTENT_DATA_KEY)
1099 leaf = path->nodes[0];
1100 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1101 ret = btrfs_next_leaf(root, path);
1106 leaf = path->nodes[0];
1112 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1114 if (found_key.objectid > ino ||
1115 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1116 found_key.offset > end)
1119 if (found_key.offset > cur_offset) {
1120 extent_end = found_key.offset;
1125 fi = btrfs_item_ptr(leaf, path->slots[0],
1126 struct btrfs_file_extent_item);
1127 extent_type = btrfs_file_extent_type(leaf, fi);
1129 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1130 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1131 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1132 extent_offset = btrfs_file_extent_offset(leaf, fi);
1133 extent_end = found_key.offset +
1134 btrfs_file_extent_num_bytes(leaf, fi);
1135 if (extent_end <= start) {
1139 if (disk_bytenr == 0)
1141 if (btrfs_file_extent_compression(leaf, fi) ||
1142 btrfs_file_extent_encryption(leaf, fi) ||
1143 btrfs_file_extent_other_encoding(leaf, fi))
1145 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1147 if (btrfs_extent_readonly(root, disk_bytenr))
1149 if (btrfs_cross_ref_exist(trans, root, ino,
1151 extent_offset, disk_bytenr))
1153 disk_bytenr += extent_offset;
1154 disk_bytenr += cur_offset - found_key.offset;
1155 num_bytes = min(end + 1, extent_end) - cur_offset;
1157 * force cow if csum exists in the range.
1158 * this ensure that csum for a given extent are
1159 * either valid or do not exist.
1161 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1164 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1165 extent_end = found_key.offset +
1166 btrfs_file_extent_inline_len(leaf, fi);
1167 extent_end = ALIGN(extent_end, root->sectorsize);
1172 if (extent_end <= start) {
1177 if (cow_start == (u64)-1)
1178 cow_start = cur_offset;
1179 cur_offset = extent_end;
1180 if (cur_offset > end)
1186 btrfs_release_path(path);
1187 if (cow_start != (u64)-1) {
1188 ret = cow_file_range(inode, locked_page, cow_start,
1189 found_key.offset - 1, page_started,
1192 cow_start = (u64)-1;
1195 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1196 struct extent_map *em;
1197 struct extent_map_tree *em_tree;
1198 em_tree = &BTRFS_I(inode)->extent_tree;
1199 em = alloc_extent_map();
1201 em->start = cur_offset;
1202 em->orig_start = em->start;
1203 em->len = num_bytes;
1204 em->block_len = num_bytes;
1205 em->block_start = disk_bytenr;
1206 em->bdev = root->fs_info->fs_devices->latest_bdev;
1207 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1209 write_lock(&em_tree->lock);
1210 ret = add_extent_mapping(em_tree, em);
1211 write_unlock(&em_tree->lock);
1212 if (ret != -EEXIST) {
1213 free_extent_map(em);
1216 btrfs_drop_extent_cache(inode, em->start,
1217 em->start + em->len - 1, 0);
1219 type = BTRFS_ORDERED_PREALLOC;
1221 type = BTRFS_ORDERED_NOCOW;
1224 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1225 num_bytes, num_bytes, type);
1228 if (root->root_key.objectid ==
1229 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1230 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1235 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1236 cur_offset, cur_offset + num_bytes - 1,
1237 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1238 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1239 EXTENT_SET_PRIVATE2);
1240 cur_offset = extent_end;
1241 if (cur_offset > end)
1244 btrfs_release_path(path);
1246 if (cur_offset <= end && cow_start == (u64)-1)
1247 cow_start = cur_offset;
1248 if (cow_start != (u64)-1) {
1249 ret = cow_file_range(inode, locked_page, cow_start, end,
1250 page_started, nr_written, 1);
1255 ret = btrfs_end_transaction_nolock(trans, root);
1258 ret = btrfs_end_transaction(trans, root);
1261 btrfs_free_path(path);
1266 * extent_io.c call back to do delayed allocation processing
1268 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1269 u64 start, u64 end, int *page_started,
1270 unsigned long *nr_written)
1273 struct btrfs_root *root = BTRFS_I(inode)->root;
1275 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)
1276 ret = run_delalloc_nocow(inode, locked_page, start, end,
1277 page_started, 1, nr_written);
1278 else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)
1279 ret = run_delalloc_nocow(inode, locked_page, start, end,
1280 page_started, 0, nr_written);
1281 else if (!btrfs_test_opt(root, COMPRESS) &&
1282 !(BTRFS_I(inode)->force_compress) &&
1283 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))
1284 ret = cow_file_range(inode, locked_page, start, end,
1285 page_started, nr_written, 1);
1287 ret = cow_file_range_async(inode, locked_page, start, end,
1288 page_started, nr_written);
1292 static void btrfs_split_extent_hook(struct inode *inode,
1293 struct extent_state *orig, u64 split)
1295 /* not delalloc, ignore it */
1296 if (!(orig->state & EXTENT_DELALLOC))
1299 spin_lock(&BTRFS_I(inode)->lock);
1300 BTRFS_I(inode)->outstanding_extents++;
1301 spin_unlock(&BTRFS_I(inode)->lock);
1305 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1306 * extents so we can keep track of new extents that are just merged onto old
1307 * extents, such as when we are doing sequential writes, so we can properly
1308 * account for the metadata space we'll need.
1310 static void btrfs_merge_extent_hook(struct inode *inode,
1311 struct extent_state *new,
1312 struct extent_state *other)
1314 /* not delalloc, ignore it */
1315 if (!(other->state & EXTENT_DELALLOC))
1318 spin_lock(&BTRFS_I(inode)->lock);
1319 BTRFS_I(inode)->outstanding_extents--;
1320 spin_unlock(&BTRFS_I(inode)->lock);
1324 * extent_io.c set_bit_hook, used to track delayed allocation
1325 * bytes in this file, and to maintain the list of inodes that
1326 * have pending delalloc work to be done.
1328 static void btrfs_set_bit_hook(struct inode *inode,
1329 struct extent_state *state, int *bits)
1333 * set_bit and clear bit hooks normally require _irqsave/restore
1334 * but in this case, we are only testing for the DELALLOC
1335 * bit, which is only set or cleared with irqs on
1337 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1338 struct btrfs_root *root = BTRFS_I(inode)->root;
1339 u64 len = state->end + 1 - state->start;
1340 bool do_list = !btrfs_is_free_space_inode(root, inode);
1342 if (*bits & EXTENT_FIRST_DELALLOC) {
1343 *bits &= ~EXTENT_FIRST_DELALLOC;
1345 spin_lock(&BTRFS_I(inode)->lock);
1346 BTRFS_I(inode)->outstanding_extents++;
1347 spin_unlock(&BTRFS_I(inode)->lock);
1350 spin_lock(&root->fs_info->delalloc_lock);
1351 BTRFS_I(inode)->delalloc_bytes += len;
1352 root->fs_info->delalloc_bytes += len;
1353 if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1354 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1355 &root->fs_info->delalloc_inodes);
1357 spin_unlock(&root->fs_info->delalloc_lock);
1362 * extent_io.c clear_bit_hook, see set_bit_hook for why
1364 static void btrfs_clear_bit_hook(struct inode *inode,
1365 struct extent_state *state, int *bits)
1368 * set_bit and clear bit hooks normally require _irqsave/restore
1369 * but in this case, we are only testing for the DELALLOC
1370 * bit, which is only set or cleared with irqs on
1372 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1373 struct btrfs_root *root = BTRFS_I(inode)->root;
1374 u64 len = state->end + 1 - state->start;
1375 bool do_list = !btrfs_is_free_space_inode(root, inode);
1377 if (*bits & EXTENT_FIRST_DELALLOC) {
1378 *bits &= ~EXTENT_FIRST_DELALLOC;
1379 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1380 spin_lock(&BTRFS_I(inode)->lock);
1381 BTRFS_I(inode)->outstanding_extents--;
1382 spin_unlock(&BTRFS_I(inode)->lock);
1385 if (*bits & EXTENT_DO_ACCOUNTING)
1386 btrfs_delalloc_release_metadata(inode, len);
1388 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1390 btrfs_free_reserved_data_space(inode, len);
1392 spin_lock(&root->fs_info->delalloc_lock);
1393 root->fs_info->delalloc_bytes -= len;
1394 BTRFS_I(inode)->delalloc_bytes -= len;
1396 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1397 !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1398 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1400 spin_unlock(&root->fs_info->delalloc_lock);
1405 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1406 * we don't create bios that span stripes or chunks
1408 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1409 size_t size, struct bio *bio,
1410 unsigned long bio_flags)
1412 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1413 struct btrfs_mapping_tree *map_tree;
1414 u64 logical = (u64)bio->bi_sector << 9;
1419 if (bio_flags & EXTENT_BIO_COMPRESSED)
1422 length = bio->bi_size;
1423 map_tree = &root->fs_info->mapping_tree;
1424 map_length = length;
1425 ret = btrfs_map_block(map_tree, READ, logical,
1426 &map_length, NULL, 0);
1428 if (map_length < length + size)
1434 * in order to insert checksums into the metadata in large chunks,
1435 * we wait until bio submission time. All the pages in the bio are
1436 * checksummed and sums are attached onto the ordered extent record.
1438 * At IO completion time the cums attached on the ordered extent record
1439 * are inserted into the btree
1441 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1442 struct bio *bio, int mirror_num,
1443 unsigned long bio_flags,
1446 struct btrfs_root *root = BTRFS_I(inode)->root;
1449 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1455 * in order to insert checksums into the metadata in large chunks,
1456 * we wait until bio submission time. All the pages in the bio are
1457 * checksummed and sums are attached onto the ordered extent record.
1459 * At IO completion time the cums attached on the ordered extent record
1460 * are inserted into the btree
1462 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1463 int mirror_num, unsigned long bio_flags,
1466 struct btrfs_root *root = BTRFS_I(inode)->root;
1467 return btrfs_map_bio(root, rw, bio, mirror_num, 1);
1471 * extent_io.c submission hook. This does the right thing for csum calculation
1472 * on write, or reading the csums from the tree before a read
1474 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1475 int mirror_num, unsigned long bio_flags,
1478 struct btrfs_root *root = BTRFS_I(inode)->root;
1482 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1484 if (btrfs_is_free_space_inode(root, inode))
1485 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 2);
1487 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
1490 if (!(rw & REQ_WRITE)) {
1491 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1492 return btrfs_submit_compressed_read(inode, bio,
1493 mirror_num, bio_flags);
1494 } else if (!skip_sum) {
1495 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1500 } else if (!skip_sum) {
1501 /* csum items have already been cloned */
1502 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1504 /* we're doing a write, do the async checksumming */
1505 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1506 inode, rw, bio, mirror_num,
1507 bio_flags, bio_offset,
1508 __btrfs_submit_bio_start,
1509 __btrfs_submit_bio_done);
1513 return btrfs_map_bio(root, rw, bio, mirror_num, 0);
1517 * given a list of ordered sums record them in the inode. This happens
1518 * at IO completion time based on sums calculated at bio submission time.
1520 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1521 struct inode *inode, u64 file_offset,
1522 struct list_head *list)
1524 struct btrfs_ordered_sum *sum;
1526 list_for_each_entry(sum, list, list) {
1527 btrfs_csum_file_blocks(trans,
1528 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1533 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1534 struct extent_state **cached_state)
1536 if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
1538 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1539 cached_state, GFP_NOFS);
1542 /* see btrfs_writepage_start_hook for details on why this is required */
1543 struct btrfs_writepage_fixup {
1545 struct btrfs_work work;
1548 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1550 struct btrfs_writepage_fixup *fixup;
1551 struct btrfs_ordered_extent *ordered;
1552 struct extent_state *cached_state = NULL;
1554 struct inode *inode;
1558 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1562 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1563 ClearPageChecked(page);
1567 inode = page->mapping->host;
1568 page_start = page_offset(page);
1569 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1571 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1572 &cached_state, GFP_NOFS);
1574 /* already ordered? We're done */
1575 if (PagePrivate2(page))
1578 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1580 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1581 page_end, &cached_state, GFP_NOFS);
1583 btrfs_start_ordered_extent(inode, ordered, 1);
1588 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1589 ClearPageChecked(page);
1591 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1592 &cached_state, GFP_NOFS);
1595 page_cache_release(page);
1600 * There are a few paths in the higher layers of the kernel that directly
1601 * set the page dirty bit without asking the filesystem if it is a
1602 * good idea. This causes problems because we want to make sure COW
1603 * properly happens and the data=ordered rules are followed.
1605 * In our case any range that doesn't have the ORDERED bit set
1606 * hasn't been properly setup for IO. We kick off an async process
1607 * to fix it up. The async helper will wait for ordered extents, set
1608 * the delalloc bit and make it safe to write the page.
1610 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1612 struct inode *inode = page->mapping->host;
1613 struct btrfs_writepage_fixup *fixup;
1614 struct btrfs_root *root = BTRFS_I(inode)->root;
1616 /* this page is properly in the ordered list */
1617 if (TestClearPagePrivate2(page))
1620 if (PageChecked(page))
1623 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1627 SetPageChecked(page);
1628 page_cache_get(page);
1629 fixup->work.func = btrfs_writepage_fixup_worker;
1631 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1635 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1636 struct inode *inode, u64 file_pos,
1637 u64 disk_bytenr, u64 disk_num_bytes,
1638 u64 num_bytes, u64 ram_bytes,
1639 u8 compression, u8 encryption,
1640 u16 other_encoding, int extent_type)
1642 struct btrfs_root *root = BTRFS_I(inode)->root;
1643 struct btrfs_file_extent_item *fi;
1644 struct btrfs_path *path;
1645 struct extent_buffer *leaf;
1646 struct btrfs_key ins;
1650 path = btrfs_alloc_path();
1654 path->leave_spinning = 1;
1657 * we may be replacing one extent in the tree with another.
1658 * The new extent is pinned in the extent map, and we don't want
1659 * to drop it from the cache until it is completely in the btree.
1661 * So, tell btrfs_drop_extents to leave this extent in the cache.
1662 * the caller is expected to unpin it and allow it to be merged
1665 ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
1669 ins.objectid = btrfs_ino(inode);
1670 ins.offset = file_pos;
1671 ins.type = BTRFS_EXTENT_DATA_KEY;
1672 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1674 leaf = path->nodes[0];
1675 fi = btrfs_item_ptr(leaf, path->slots[0],
1676 struct btrfs_file_extent_item);
1677 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1678 btrfs_set_file_extent_type(leaf, fi, extent_type);
1679 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1680 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1681 btrfs_set_file_extent_offset(leaf, fi, 0);
1682 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1683 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1684 btrfs_set_file_extent_compression(leaf, fi, compression);
1685 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1686 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1688 btrfs_unlock_up_safe(path, 1);
1689 btrfs_set_lock_blocking(leaf);
1691 btrfs_mark_buffer_dirty(leaf);
1693 inode_add_bytes(inode, num_bytes);
1695 ins.objectid = disk_bytenr;
1696 ins.offset = disk_num_bytes;
1697 ins.type = BTRFS_EXTENT_ITEM_KEY;
1698 ret = btrfs_alloc_reserved_file_extent(trans, root,
1699 root->root_key.objectid,
1700 btrfs_ino(inode), file_pos, &ins);
1702 btrfs_free_path(path);
1708 * helper function for btrfs_finish_ordered_io, this
1709 * just reads in some of the csum leaves to prime them into ram
1710 * before we start the transaction. It limits the amount of btree
1711 * reads required while inside the transaction.
1713 /* as ordered data IO finishes, this gets called so we can finish
1714 * an ordered extent if the range of bytes in the file it covers are
1717 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
1719 struct btrfs_root *root = BTRFS_I(inode)->root;
1720 struct btrfs_trans_handle *trans = NULL;
1721 struct btrfs_ordered_extent *ordered_extent = NULL;
1722 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1723 struct extent_state *cached_state = NULL;
1724 int compress_type = 0;
1728 ret = btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
1732 BUG_ON(!ordered_extent);
1734 nolock = btrfs_is_free_space_inode(root, inode);
1736 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1737 BUG_ON(!list_empty(&ordered_extent->list));
1738 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1741 trans = btrfs_join_transaction_nolock(root);
1743 trans = btrfs_join_transaction(root);
1744 BUG_ON(IS_ERR(trans));
1745 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1746 ret = btrfs_update_inode_fallback(trans, root, inode);
1752 lock_extent_bits(io_tree, ordered_extent->file_offset,
1753 ordered_extent->file_offset + ordered_extent->len - 1,
1754 0, &cached_state, GFP_NOFS);
1757 trans = btrfs_join_transaction_nolock(root);
1759 trans = btrfs_join_transaction(root);
1760 BUG_ON(IS_ERR(trans));
1761 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1763 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1764 compress_type = ordered_extent->compress_type;
1765 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1766 BUG_ON(compress_type);
1767 ret = btrfs_mark_extent_written(trans, inode,
1768 ordered_extent->file_offset,
1769 ordered_extent->file_offset +
1770 ordered_extent->len);
1773 BUG_ON(root == root->fs_info->tree_root);
1774 ret = insert_reserved_file_extent(trans, inode,
1775 ordered_extent->file_offset,
1776 ordered_extent->start,
1777 ordered_extent->disk_len,
1778 ordered_extent->len,
1779 ordered_extent->len,
1780 compress_type, 0, 0,
1781 BTRFS_FILE_EXTENT_REG);
1782 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1783 ordered_extent->file_offset,
1784 ordered_extent->len);
1787 unlock_extent_cached(io_tree, ordered_extent->file_offset,
1788 ordered_extent->file_offset +
1789 ordered_extent->len - 1, &cached_state, GFP_NOFS);
1791 add_pending_csums(trans, inode, ordered_extent->file_offset,
1792 &ordered_extent->list);
1794 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1795 if (!ret || !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1796 ret = btrfs_update_inode_fallback(trans, root, inode);
1801 if (root != root->fs_info->tree_root)
1802 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
1805 btrfs_end_transaction_nolock(trans, root);
1807 btrfs_end_transaction(trans, root);
1811 btrfs_put_ordered_extent(ordered_extent);
1812 /* once for the tree */
1813 btrfs_put_ordered_extent(ordered_extent);
1818 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
1819 struct extent_state *state, int uptodate)
1821 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
1823 ClearPagePrivate2(page);
1824 return btrfs_finish_ordered_io(page->mapping->host, start, end);
1828 * when reads are done, we need to check csums to verify the data is correct
1829 * if there's a match, we allow the bio to finish. If not, the code in
1830 * extent_io.c will try to find good copies for us.
1832 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
1833 struct extent_state *state)
1835 size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
1836 struct inode *inode = page->mapping->host;
1837 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1839 u64 private = ~(u32)0;
1841 struct btrfs_root *root = BTRFS_I(inode)->root;
1844 if (PageChecked(page)) {
1845 ClearPageChecked(page);
1849 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
1852 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
1853 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
1854 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
1859 if (state && state->start == start) {
1860 private = state->private;
1863 ret = get_state_private(io_tree, start, &private);
1865 kaddr = kmap_atomic(page, KM_USER0);
1869 csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
1870 btrfs_csum_final(csum, (char *)&csum);
1871 if (csum != private)
1874 kunmap_atomic(kaddr, KM_USER0);
1879 printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u "
1881 (unsigned long long)btrfs_ino(page->mapping->host),
1882 (unsigned long long)start, csum,
1883 (unsigned long long)private);
1884 memset(kaddr + offset, 1, end - start + 1);
1885 flush_dcache_page(page);
1886 kunmap_atomic(kaddr, KM_USER0);
1892 struct delayed_iput {
1893 struct list_head list;
1894 struct inode *inode;
1897 void btrfs_add_delayed_iput(struct inode *inode)
1899 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
1900 struct delayed_iput *delayed;
1902 if (atomic_add_unless(&inode->i_count, -1, 1))
1905 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
1906 delayed->inode = inode;
1908 spin_lock(&fs_info->delayed_iput_lock);
1909 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
1910 spin_unlock(&fs_info->delayed_iput_lock);
1913 void btrfs_run_delayed_iputs(struct btrfs_root *root)
1916 struct btrfs_fs_info *fs_info = root->fs_info;
1917 struct delayed_iput *delayed;
1920 spin_lock(&fs_info->delayed_iput_lock);
1921 empty = list_empty(&fs_info->delayed_iputs);
1922 spin_unlock(&fs_info->delayed_iput_lock);
1926 down_read(&root->fs_info->cleanup_work_sem);
1927 spin_lock(&fs_info->delayed_iput_lock);
1928 list_splice_init(&fs_info->delayed_iputs, &list);
1929 spin_unlock(&fs_info->delayed_iput_lock);
1931 while (!list_empty(&list)) {
1932 delayed = list_entry(list.next, struct delayed_iput, list);
1933 list_del(&delayed->list);
1934 iput(delayed->inode);
1937 up_read(&root->fs_info->cleanup_work_sem);
1940 enum btrfs_orphan_cleanup_state {
1941 ORPHAN_CLEANUP_STARTED = 1,
1942 ORPHAN_CLEANUP_DONE = 2,
1946 * This is called in transaction commmit time. If there are no orphan
1947 * files in the subvolume, it removes orphan item and frees block_rsv
1950 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
1951 struct btrfs_root *root)
1955 if (!list_empty(&root->orphan_list) ||
1956 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
1959 if (root->orphan_item_inserted &&
1960 btrfs_root_refs(&root->root_item) > 0) {
1961 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
1962 root->root_key.objectid);
1964 root->orphan_item_inserted = 0;
1967 if (root->orphan_block_rsv) {
1968 WARN_ON(root->orphan_block_rsv->size > 0);
1969 btrfs_free_block_rsv(root, root->orphan_block_rsv);
1970 root->orphan_block_rsv = NULL;
1975 * This creates an orphan entry for the given inode in case something goes
1976 * wrong in the middle of an unlink/truncate.
1978 * NOTE: caller of this function should reserve 5 units of metadata for
1981 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
1983 struct btrfs_root *root = BTRFS_I(inode)->root;
1984 struct btrfs_block_rsv *block_rsv = NULL;
1989 if (!root->orphan_block_rsv) {
1990 block_rsv = btrfs_alloc_block_rsv(root);
1995 spin_lock(&root->orphan_lock);
1996 if (!root->orphan_block_rsv) {
1997 root->orphan_block_rsv = block_rsv;
1998 } else if (block_rsv) {
1999 btrfs_free_block_rsv(root, block_rsv);
2003 if (list_empty(&BTRFS_I(inode)->i_orphan)) {
2004 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2007 * For proper ENOSPC handling, we should do orphan
2008 * cleanup when mounting. But this introduces backward
2009 * compatibility issue.
2011 if (!xchg(&root->orphan_item_inserted, 1))
2019 if (!BTRFS_I(inode)->orphan_meta_reserved) {
2020 BTRFS_I(inode)->orphan_meta_reserved = 1;
2023 spin_unlock(&root->orphan_lock);
2025 /* grab metadata reservation from transaction handle */
2027 ret = btrfs_orphan_reserve_metadata(trans, inode);
2031 /* insert an orphan item to track this unlinked/truncated file */
2033 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2037 /* insert an orphan item to track subvolume contains orphan files */
2039 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2040 root->root_key.objectid);
2047 * We have done the truncate/delete so we can go ahead and remove the orphan
2048 * item for this particular inode.
2050 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2052 struct btrfs_root *root = BTRFS_I(inode)->root;
2053 int delete_item = 0;
2054 int release_rsv = 0;
2057 spin_lock(&root->orphan_lock);
2058 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
2059 list_del_init(&BTRFS_I(inode)->i_orphan);
2063 if (BTRFS_I(inode)->orphan_meta_reserved) {
2064 BTRFS_I(inode)->orphan_meta_reserved = 0;
2067 spin_unlock(&root->orphan_lock);
2069 if (trans && delete_item) {
2070 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
2075 btrfs_orphan_release_metadata(inode);
2081 * this cleans up any orphans that may be left on the list from the last use
2084 int btrfs_orphan_cleanup(struct btrfs_root *root)
2086 struct btrfs_path *path;
2087 struct extent_buffer *leaf;
2088 struct btrfs_key key, found_key;
2089 struct btrfs_trans_handle *trans;
2090 struct inode *inode;
2091 u64 last_objectid = 0;
2092 int ret = 0, nr_unlink = 0, nr_truncate = 0;
2094 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2097 path = btrfs_alloc_path();
2104 key.objectid = BTRFS_ORPHAN_OBJECTID;
2105 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2106 key.offset = (u64)-1;
2109 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2114 * if ret == 0 means we found what we were searching for, which
2115 * is weird, but possible, so only screw with path if we didn't
2116 * find the key and see if we have stuff that matches
2120 if (path->slots[0] == 0)
2125 /* pull out the item */
2126 leaf = path->nodes[0];
2127 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2129 /* make sure the item matches what we want */
2130 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2132 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2135 /* release the path since we're done with it */
2136 btrfs_release_path(path);
2139 * this is where we are basically btrfs_lookup, without the
2140 * crossing root thing. we store the inode number in the
2141 * offset of the orphan item.
2144 if (found_key.offset == last_objectid) {
2145 printk(KERN_ERR "btrfs: Error removing orphan entry, "
2146 "stopping orphan cleanup\n");
2151 last_objectid = found_key.offset;
2153 found_key.objectid = found_key.offset;
2154 found_key.type = BTRFS_INODE_ITEM_KEY;
2155 found_key.offset = 0;
2156 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2157 ret = PTR_RET(inode);
2158 if (ret && ret != -ESTALE)
2161 if (ret == -ESTALE && root == root->fs_info->tree_root) {
2162 struct btrfs_root *dead_root;
2163 struct btrfs_fs_info *fs_info = root->fs_info;
2164 int is_dead_root = 0;
2167 * this is an orphan in the tree root. Currently these
2168 * could come from 2 sources:
2169 * a) a snapshot deletion in progress
2170 * b) a free space cache inode
2171 * We need to distinguish those two, as the snapshot
2172 * orphan must not get deleted.
2173 * find_dead_roots already ran before us, so if this
2174 * is a snapshot deletion, we should find the root
2175 * in the dead_roots list
2177 spin_lock(&fs_info->trans_lock);
2178 list_for_each_entry(dead_root, &fs_info->dead_roots,
2180 if (dead_root->root_key.objectid ==
2181 found_key.objectid) {
2186 spin_unlock(&fs_info->trans_lock);
2188 /* prevent this orphan from being found again */
2189 key.offset = found_key.objectid - 1;
2194 * Inode is already gone but the orphan item is still there,
2195 * kill the orphan item.
2197 if (ret == -ESTALE) {
2198 trans = btrfs_start_transaction(root, 1);
2199 if (IS_ERR(trans)) {
2200 ret = PTR_ERR(trans);
2203 ret = btrfs_del_orphan_item(trans, root,
2204 found_key.objectid);
2206 btrfs_end_transaction(trans, root);
2211 * add this inode to the orphan list so btrfs_orphan_del does
2212 * the proper thing when we hit it
2214 spin_lock(&root->orphan_lock);
2215 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2216 spin_unlock(&root->orphan_lock);
2218 /* if we have links, this was a truncate, lets do that */
2219 if (inode->i_nlink) {
2220 if (!S_ISREG(inode->i_mode)) {
2226 ret = btrfs_truncate(inode);
2231 /* this will do delete_inode and everything for us */
2236 /* release the path since we're done with it */
2237 btrfs_release_path(path);
2239 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2241 if (root->orphan_block_rsv)
2242 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2245 if (root->orphan_block_rsv || root->orphan_item_inserted) {
2246 trans = btrfs_join_transaction(root);
2248 btrfs_end_transaction(trans, root);
2252 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2254 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2258 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
2259 btrfs_free_path(path);
2264 * very simple check to peek ahead in the leaf looking for xattrs. If we
2265 * don't find any xattrs, we know there can't be any acls.
2267 * slot is the slot the inode is in, objectid is the objectid of the inode
2269 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2270 int slot, u64 objectid)
2272 u32 nritems = btrfs_header_nritems(leaf);
2273 struct btrfs_key found_key;
2277 while (slot < nritems) {
2278 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2280 /* we found a different objectid, there must not be acls */
2281 if (found_key.objectid != objectid)
2284 /* we found an xattr, assume we've got an acl */
2285 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2289 * we found a key greater than an xattr key, there can't
2290 * be any acls later on
2292 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2299 * it goes inode, inode backrefs, xattrs, extents,
2300 * so if there are a ton of hard links to an inode there can
2301 * be a lot of backrefs. Don't waste time searching too hard,
2302 * this is just an optimization
2307 /* we hit the end of the leaf before we found an xattr or
2308 * something larger than an xattr. We have to assume the inode
2315 * read an inode from the btree into the in-memory inode
2317 static void btrfs_read_locked_inode(struct inode *inode)
2319 struct btrfs_path *path;
2320 struct extent_buffer *leaf;
2321 struct btrfs_inode_item *inode_item;
2322 struct btrfs_timespec *tspec;
2323 struct btrfs_root *root = BTRFS_I(inode)->root;
2324 struct btrfs_key location;
2328 bool filled = false;
2330 ret = btrfs_fill_inode(inode, &rdev);
2334 path = btrfs_alloc_path();
2338 path->leave_spinning = 1;
2339 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2341 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2345 leaf = path->nodes[0];
2350 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2351 struct btrfs_inode_item);
2352 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2353 inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
2354 inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2355 inode->i_gid = btrfs_inode_gid(leaf, inode_item);
2356 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2358 tspec = btrfs_inode_atime(inode_item);
2359 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2360 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2362 tspec = btrfs_inode_mtime(inode_item);
2363 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2364 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2366 tspec = btrfs_inode_ctime(inode_item);
2367 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2368 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2370 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2371 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2372 BTRFS_I(inode)->sequence = btrfs_inode_sequence(leaf, inode_item);
2373 inode->i_generation = BTRFS_I(inode)->generation;
2375 rdev = btrfs_inode_rdev(leaf, inode_item);
2377 BTRFS_I(inode)->index_cnt = (u64)-1;
2378 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2381 * try to precache a NULL acl entry for files that don't have
2382 * any xattrs or acls
2384 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
2387 cache_no_acl(inode);
2389 btrfs_free_path(path);
2391 switch (inode->i_mode & S_IFMT) {
2393 inode->i_mapping->a_ops = &btrfs_aops;
2394 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2395 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2396 inode->i_fop = &btrfs_file_operations;
2397 inode->i_op = &btrfs_file_inode_operations;
2400 inode->i_fop = &btrfs_dir_file_operations;
2401 if (root == root->fs_info->tree_root)
2402 inode->i_op = &btrfs_dir_ro_inode_operations;
2404 inode->i_op = &btrfs_dir_inode_operations;
2407 inode->i_op = &btrfs_symlink_inode_operations;
2408 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2409 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2412 inode->i_op = &btrfs_special_inode_operations;
2413 init_special_inode(inode, inode->i_mode, rdev);
2417 btrfs_update_iflags(inode);
2421 btrfs_free_path(path);
2422 make_bad_inode(inode);
2426 * given a leaf and an inode, copy the inode fields into the leaf
2428 static void fill_inode_item(struct btrfs_trans_handle *trans,
2429 struct extent_buffer *leaf,
2430 struct btrfs_inode_item *item,
2431 struct inode *inode)
2433 btrfs_set_inode_uid(leaf, item, inode->i_uid);
2434 btrfs_set_inode_gid(leaf, item, inode->i_gid);
2435 btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
2436 btrfs_set_inode_mode(leaf, item, inode->i_mode);
2437 btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2439 btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2440 inode->i_atime.tv_sec);
2441 btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2442 inode->i_atime.tv_nsec);
2444 btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2445 inode->i_mtime.tv_sec);
2446 btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2447 inode->i_mtime.tv_nsec);
2449 btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2450 inode->i_ctime.tv_sec);
2451 btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2452 inode->i_ctime.tv_nsec);
2454 btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
2455 btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
2456 btrfs_set_inode_sequence(leaf, item, BTRFS_I(inode)->sequence);
2457 btrfs_set_inode_transid(leaf, item, trans->transid);
2458 btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
2459 btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
2460 btrfs_set_inode_block_group(leaf, item, 0);
2464 * copy everything in the in-memory inode into the btree.
2466 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
2467 struct btrfs_root *root, struct inode *inode)
2469 struct btrfs_inode_item *inode_item;
2470 struct btrfs_path *path;
2471 struct extent_buffer *leaf;
2474 path = btrfs_alloc_path();
2478 path->leave_spinning = 1;
2479 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
2487 btrfs_unlock_up_safe(path, 1);
2488 leaf = path->nodes[0];
2489 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2490 struct btrfs_inode_item);
2492 fill_inode_item(trans, leaf, inode_item, inode);
2493 btrfs_mark_buffer_dirty(leaf);
2494 btrfs_set_inode_last_trans(trans, inode);
2497 btrfs_free_path(path);
2502 * copy everything in the in-memory inode into the btree.
2504 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2505 struct btrfs_root *root, struct inode *inode)
2510 * If the inode is a free space inode, we can deadlock during commit
2511 * if we put it into the delayed code.
2513 * The data relocation inode should also be directly updated
2516 if (!btrfs_is_free_space_inode(root, inode)
2517 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
2518 ret = btrfs_delayed_update_inode(trans, root, inode);
2520 btrfs_set_inode_last_trans(trans, inode);
2524 return btrfs_update_inode_item(trans, root, inode);
2527 static noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
2528 struct btrfs_root *root, struct inode *inode)
2532 ret = btrfs_update_inode(trans, root, inode);
2534 return btrfs_update_inode_item(trans, root, inode);
2539 * unlink helper that gets used here in inode.c and in the tree logging
2540 * recovery code. It remove a link in a directory with a given name, and
2541 * also drops the back refs in the inode to the directory
2543 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2544 struct btrfs_root *root,
2545 struct inode *dir, struct inode *inode,
2546 const char *name, int name_len)
2548 struct btrfs_path *path;
2550 struct extent_buffer *leaf;
2551 struct btrfs_dir_item *di;
2552 struct btrfs_key key;
2554 u64 ino = btrfs_ino(inode);
2555 u64 dir_ino = btrfs_ino(dir);
2557 path = btrfs_alloc_path();
2563 path->leave_spinning = 1;
2564 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2565 name, name_len, -1);
2574 leaf = path->nodes[0];
2575 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2576 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2579 btrfs_release_path(path);
2581 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
2584 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2585 "inode %llu parent %llu\n", name_len, name,
2586 (unsigned long long)ino, (unsigned long long)dir_ino);
2590 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
2594 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2596 BUG_ON(ret != 0 && ret != -ENOENT);
2598 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2603 btrfs_free_path(path);
2607 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2608 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2609 btrfs_update_inode(trans, root, dir);
2614 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2615 struct btrfs_root *root,
2616 struct inode *dir, struct inode *inode,
2617 const char *name, int name_len)
2620 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
2622 btrfs_drop_nlink(inode);
2623 ret = btrfs_update_inode(trans, root, inode);
2629 /* helper to check if there is any shared block in the path */
2630 static int check_path_shared(struct btrfs_root *root,
2631 struct btrfs_path *path)
2633 struct extent_buffer *eb;
2637 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2640 if (!path->nodes[level])
2642 eb = path->nodes[level];
2643 if (!btrfs_block_can_be_shared(root, eb))
2645 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2654 * helper to start transaction for unlink and rmdir.
2656 * unlink and rmdir are special in btrfs, they do not always free space.
2657 * so in enospc case, we should make sure they will free space before
2658 * allowing them to use the global metadata reservation.
2660 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2661 struct dentry *dentry)
2663 struct btrfs_trans_handle *trans;
2664 struct btrfs_root *root = BTRFS_I(dir)->root;
2665 struct btrfs_path *path;
2666 struct btrfs_inode_ref *ref;
2667 struct btrfs_dir_item *di;
2668 struct inode *inode = dentry->d_inode;
2673 u64 ino = btrfs_ino(inode);
2674 u64 dir_ino = btrfs_ino(dir);
2677 * 1 for the possible orphan item
2678 * 1 for the dir item
2679 * 1 for the dir index
2680 * 1 for the inode ref
2681 * 1 for the inode ref in the tree log
2682 * 2 for the dir entries in the log
2685 trans = btrfs_start_transaction(root, 8);
2686 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2689 if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2690 return ERR_PTR(-ENOSPC);
2692 /* check if there is someone else holds reference */
2693 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2694 return ERR_PTR(-ENOSPC);
2696 if (atomic_read(&inode->i_count) > 2)
2697 return ERR_PTR(-ENOSPC);
2699 if (xchg(&root->fs_info->enospc_unlink, 1))
2700 return ERR_PTR(-ENOSPC);
2702 path = btrfs_alloc_path();
2704 root->fs_info->enospc_unlink = 0;
2705 return ERR_PTR(-ENOMEM);
2708 /* 1 for the orphan item */
2709 trans = btrfs_start_transaction(root, 1);
2710 if (IS_ERR(trans)) {
2711 btrfs_free_path(path);
2712 root->fs_info->enospc_unlink = 0;
2716 path->skip_locking = 1;
2717 path->search_commit_root = 1;
2719 ret = btrfs_lookup_inode(trans, root, path,
2720 &BTRFS_I(dir)->location, 0);
2726 if (check_path_shared(root, path))
2731 btrfs_release_path(path);
2733 ret = btrfs_lookup_inode(trans, root, path,
2734 &BTRFS_I(inode)->location, 0);
2740 if (check_path_shared(root, path))
2745 btrfs_release_path(path);
2747 if (ret == 0 && S_ISREG(inode->i_mode)) {
2748 ret = btrfs_lookup_file_extent(trans, root, path,
2755 if (check_path_shared(root, path))
2757 btrfs_release_path(path);
2765 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2766 dentry->d_name.name, dentry->d_name.len, 0);
2772 if (check_path_shared(root, path))
2778 btrfs_release_path(path);
2780 ref = btrfs_lookup_inode_ref(trans, root, path,
2781 dentry->d_name.name, dentry->d_name.len,
2788 if (check_path_shared(root, path))
2790 index = btrfs_inode_ref_index(path->nodes[0], ref);
2791 btrfs_release_path(path);
2794 * This is a commit root search, if we can lookup inode item and other
2795 * relative items in the commit root, it means the transaction of
2796 * dir/file creation has been committed, and the dir index item that we
2797 * delay to insert has also been inserted into the commit root. So
2798 * we needn't worry about the delayed insertion of the dir index item
2801 di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
2802 dentry->d_name.name, dentry->d_name.len, 0);
2807 BUG_ON(ret == -ENOENT);
2808 if (check_path_shared(root, path))
2813 btrfs_free_path(path);
2814 /* Migrate the orphan reservation over */
2816 err = btrfs_block_rsv_migrate(trans->block_rsv,
2817 &root->fs_info->global_block_rsv,
2818 trans->bytes_reserved);
2821 btrfs_end_transaction(trans, root);
2822 root->fs_info->enospc_unlink = 0;
2823 return ERR_PTR(err);
2826 trans->block_rsv = &root->fs_info->global_block_rsv;
2830 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
2831 struct btrfs_root *root)
2833 if (trans->block_rsv == &root->fs_info->global_block_rsv) {
2834 btrfs_block_rsv_release(root, trans->block_rsv,
2835 trans->bytes_reserved);
2836 trans->block_rsv = &root->fs_info->trans_block_rsv;
2837 BUG_ON(!root->fs_info->enospc_unlink);
2838 root->fs_info->enospc_unlink = 0;
2840 btrfs_end_transaction_throttle(trans, root);
2843 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
2845 struct btrfs_root *root = BTRFS_I(dir)->root;
2846 struct btrfs_trans_handle *trans;
2847 struct inode *inode = dentry->d_inode;
2849 unsigned long nr = 0;
2851 trans = __unlink_start_trans(dir, dentry);
2853 return PTR_ERR(trans);
2855 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
2857 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2858 dentry->d_name.name, dentry->d_name.len);
2862 if (inode->i_nlink == 0) {
2863 ret = btrfs_orphan_add(trans, inode);
2869 nr = trans->blocks_used;
2870 __unlink_end_trans(trans, root);
2871 btrfs_btree_balance_dirty(root, nr);
2875 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
2876 struct btrfs_root *root,
2877 struct inode *dir, u64 objectid,
2878 const char *name, int name_len)
2880 struct btrfs_path *path;
2881 struct extent_buffer *leaf;
2882 struct btrfs_dir_item *di;
2883 struct btrfs_key key;
2886 u64 dir_ino = btrfs_ino(dir);
2888 path = btrfs_alloc_path();
2892 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2893 name, name_len, -1);
2894 BUG_ON(IS_ERR_OR_NULL(di));
2896 leaf = path->nodes[0];
2897 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2898 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2899 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2901 btrfs_release_path(path);
2903 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
2904 objectid, root->root_key.objectid,
2905 dir_ino, &index, name, name_len);
2907 BUG_ON(ret != -ENOENT);
2908 di = btrfs_search_dir_index_item(root, path, dir_ino,
2910 BUG_ON(IS_ERR_OR_NULL(di));
2912 leaf = path->nodes[0];
2913 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2914 btrfs_release_path(path);
2917 btrfs_release_path(path);
2919 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
2922 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2923 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2924 ret = btrfs_update_inode(trans, root, dir);
2927 btrfs_free_path(path);
2931 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
2933 struct inode *inode = dentry->d_inode;
2935 struct btrfs_root *root = BTRFS_I(dir)->root;
2936 struct btrfs_trans_handle *trans;
2937 unsigned long nr = 0;
2939 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
2940 btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
2943 trans = __unlink_start_trans(dir, dentry);
2945 return PTR_ERR(trans);
2947 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
2948 err = btrfs_unlink_subvol(trans, root, dir,
2949 BTRFS_I(inode)->location.objectid,
2950 dentry->d_name.name,
2951 dentry->d_name.len);
2955 err = btrfs_orphan_add(trans, inode);
2959 /* now the directory is empty */
2960 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2961 dentry->d_name.name, dentry->d_name.len);
2963 btrfs_i_size_write(inode, 0);
2965 nr = trans->blocks_used;
2966 __unlink_end_trans(trans, root);
2967 btrfs_btree_balance_dirty(root, nr);
2973 * this can truncate away extent items, csum items and directory items.
2974 * It starts at a high offset and removes keys until it can't find
2975 * any higher than new_size
2977 * csum items that cross the new i_size are truncated to the new size
2980 * min_type is the minimum key type to truncate down to. If set to 0, this
2981 * will kill all the items on this inode, including the INODE_ITEM_KEY.
2983 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
2984 struct btrfs_root *root,
2985 struct inode *inode,
2986 u64 new_size, u32 min_type)
2988 struct btrfs_path *path;
2989 struct extent_buffer *leaf;
2990 struct btrfs_file_extent_item *fi;
2991 struct btrfs_key key;
2992 struct btrfs_key found_key;
2993 u64 extent_start = 0;
2994 u64 extent_num_bytes = 0;
2995 u64 extent_offset = 0;
2997 u64 mask = root->sectorsize - 1;
2998 u32 found_type = (u8)-1;
3001 int pending_del_nr = 0;
3002 int pending_del_slot = 0;
3003 int extent_type = -1;
3007 u64 ino = btrfs_ino(inode);
3009 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3011 path = btrfs_alloc_path();
3016 if (root->ref_cows || root == root->fs_info->tree_root)
3017 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
3020 * This function is also used to drop the items in the log tree before
3021 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3022 * it is used to drop the loged items. So we shouldn't kill the delayed
3025 if (min_type == 0 && root == BTRFS_I(inode)->root)
3026 btrfs_kill_delayed_inode_items(inode);
3029 key.offset = (u64)-1;
3033 path->leave_spinning = 1;
3034 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3041 /* there are no items in the tree for us to truncate, we're
3044 if (path->slots[0] == 0)
3051 leaf = path->nodes[0];
3052 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3053 found_type = btrfs_key_type(&found_key);
3056 if (found_key.objectid != ino)
3059 if (found_type < min_type)
3062 item_end = found_key.offset;
3063 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3064 fi = btrfs_item_ptr(leaf, path->slots[0],
3065 struct btrfs_file_extent_item);
3066 extent_type = btrfs_file_extent_type(leaf, fi);
3067 encoding = btrfs_file_extent_compression(leaf, fi);
3068 encoding |= btrfs_file_extent_encryption(leaf, fi);
3069 encoding |= btrfs_file_extent_other_encoding(leaf, fi);
3071 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3073 btrfs_file_extent_num_bytes(leaf, fi);
3074 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3075 item_end += btrfs_file_extent_inline_len(leaf,
3080 if (found_type > min_type) {
3083 if (item_end < new_size)
3085 if (found_key.offset >= new_size)
3091 /* FIXME, shrink the extent if the ref count is only 1 */
3092 if (found_type != BTRFS_EXTENT_DATA_KEY)
3095 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3097 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3098 if (!del_item && !encoding) {
3099 u64 orig_num_bytes =
3100 btrfs_file_extent_num_bytes(leaf, fi);
3101 extent_num_bytes = new_size -
3102 found_key.offset + root->sectorsize - 1;
3103 extent_num_bytes = extent_num_bytes &
3104 ~((u64)root->sectorsize - 1);
3105 btrfs_set_file_extent_num_bytes(leaf, fi,
3107 num_dec = (orig_num_bytes -
3109 if (root->ref_cows && extent_start != 0)
3110 inode_sub_bytes(inode, num_dec);
3111 btrfs_mark_buffer_dirty(leaf);
3114 btrfs_file_extent_disk_num_bytes(leaf,
3116 extent_offset = found_key.offset -
3117 btrfs_file_extent_offset(leaf, fi);
3119 /* FIXME blocksize != 4096 */
3120 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3121 if (extent_start != 0) {
3124 inode_sub_bytes(inode, num_dec);
3127 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3129 * we can't truncate inline items that have had
3133 btrfs_file_extent_compression(leaf, fi) == 0 &&
3134 btrfs_file_extent_encryption(leaf, fi) == 0 &&
3135 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3136 u32 size = new_size - found_key.offset;
3138 if (root->ref_cows) {
3139 inode_sub_bytes(inode, item_end + 1 -
3143 btrfs_file_extent_calc_inline_size(size);
3144 ret = btrfs_truncate_item(trans, root, path,
3146 } else if (root->ref_cows) {
3147 inode_sub_bytes(inode, item_end + 1 -
3153 if (!pending_del_nr) {
3154 /* no pending yet, add ourselves */
3155 pending_del_slot = path->slots[0];
3157 } else if (pending_del_nr &&
3158 path->slots[0] + 1 == pending_del_slot) {
3159 /* hop on the pending chunk */
3161 pending_del_slot = path->slots[0];
3168 if (found_extent && (root->ref_cows ||
3169 root == root->fs_info->tree_root)) {
3170 btrfs_set_path_blocking(path);
3171 ret = btrfs_free_extent(trans, root, extent_start,
3172 extent_num_bytes, 0,
3173 btrfs_header_owner(leaf),
3174 ino, extent_offset);
3178 if (found_type == BTRFS_INODE_ITEM_KEY)
3181 if (path->slots[0] == 0 ||
3182 path->slots[0] != pending_del_slot) {
3183 if (root->ref_cows &&
3184 BTRFS_I(inode)->location.objectid !=
3185 BTRFS_FREE_INO_OBJECTID) {
3189 if (pending_del_nr) {
3190 ret = btrfs_del_items(trans, root, path,
3196 btrfs_release_path(path);
3203 if (pending_del_nr) {
3204 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3208 btrfs_free_path(path);
3213 * taken from block_truncate_page, but does cow as it zeros out
3214 * any bytes left in the last page in the file.
3216 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
3218 struct inode *inode = mapping->host;
3219 struct btrfs_root *root = BTRFS_I(inode)->root;
3220 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3221 struct btrfs_ordered_extent *ordered;
3222 struct extent_state *cached_state = NULL;
3224 u32 blocksize = root->sectorsize;
3225 pgoff_t index = from >> PAGE_CACHE_SHIFT;
3226 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3228 gfp_t mask = btrfs_alloc_write_mask(mapping);
3233 if ((offset & (blocksize - 1)) == 0)
3235 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3241 page = find_or_create_page(mapping, index, mask);
3243 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3247 page_start = page_offset(page);
3248 page_end = page_start + PAGE_CACHE_SIZE - 1;
3250 if (!PageUptodate(page)) {
3251 ret = btrfs_readpage(NULL, page);
3253 if (page->mapping != mapping) {
3255 page_cache_release(page);
3258 if (!PageUptodate(page)) {
3263 wait_on_page_writeback(page);
3265 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
3267 set_page_extent_mapped(page);
3269 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3271 unlock_extent_cached(io_tree, page_start, page_end,
3272 &cached_state, GFP_NOFS);
3274 page_cache_release(page);
3275 btrfs_start_ordered_extent(inode, ordered, 1);
3276 btrfs_put_ordered_extent(ordered);
3280 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3281 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
3282 0, 0, &cached_state, GFP_NOFS);
3284 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3287 unlock_extent_cached(io_tree, page_start, page_end,
3288 &cached_state, GFP_NOFS);
3293 if (offset != PAGE_CACHE_SIZE) {
3295 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
3296 flush_dcache_page(page);
3299 ClearPageChecked(page);
3300 set_page_dirty(page);
3301 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3306 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3308 page_cache_release(page);
3314 * This function puts in dummy file extents for the area we're creating a hole
3315 * for. So if we are truncating this file to a larger size we need to insert
3316 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
3317 * the range between oldsize and size
3319 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
3321 struct btrfs_trans_handle *trans;
3322 struct btrfs_root *root = BTRFS_I(inode)->root;
3323 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3324 struct extent_map *em = NULL;
3325 struct extent_state *cached_state = NULL;
3326 u64 mask = root->sectorsize - 1;
3327 u64 hole_start = (oldsize + mask) & ~mask;
3328 u64 block_end = (size + mask) & ~mask;
3334 if (size <= hole_start)
3338 struct btrfs_ordered_extent *ordered;
3339 btrfs_wait_ordered_range(inode, hole_start,
3340 block_end - hole_start);
3341 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3342 &cached_state, GFP_NOFS);
3343 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3346 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3347 &cached_state, GFP_NOFS);
3348 btrfs_put_ordered_extent(ordered);
3351 cur_offset = hole_start;
3353 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3354 block_end - cur_offset, 0);
3355 BUG_ON(IS_ERR_OR_NULL(em));
3356 last_byte = min(extent_map_end(em), block_end);
3357 last_byte = (last_byte + mask) & ~mask;
3358 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3360 hole_size = last_byte - cur_offset;
3362 trans = btrfs_start_transaction(root, 3);
3363 if (IS_ERR(trans)) {
3364 err = PTR_ERR(trans);
3368 err = btrfs_drop_extents(trans, inode, cur_offset,
3369 cur_offset + hole_size,
3372 btrfs_update_inode(trans, root, inode);
3373 btrfs_end_transaction(trans, root);
3377 err = btrfs_insert_file_extent(trans, root,
3378 btrfs_ino(inode), cur_offset, 0,
3379 0, hole_size, 0, hole_size,
3382 btrfs_update_inode(trans, root, inode);
3383 btrfs_end_transaction(trans, root);
3387 btrfs_drop_extent_cache(inode, hole_start,
3390 btrfs_update_inode(trans, root, inode);
3391 btrfs_end_transaction(trans, root);
3393 free_extent_map(em);
3395 cur_offset = last_byte;
3396 if (cur_offset >= block_end)
3400 free_extent_map(em);
3401 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3406 static int btrfs_setsize(struct inode *inode, loff_t newsize)
3408 struct btrfs_root *root = BTRFS_I(inode)->root;
3409 struct btrfs_trans_handle *trans;
3410 loff_t oldsize = i_size_read(inode);
3413 if (newsize == oldsize)
3416 if (newsize > oldsize) {
3417 truncate_pagecache(inode, oldsize, newsize);
3418 ret = btrfs_cont_expand(inode, oldsize, newsize);
3422 trans = btrfs_start_transaction(root, 1);
3424 return PTR_ERR(trans);
3426 i_size_write(inode, newsize);
3427 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
3428 ret = btrfs_update_inode(trans, root, inode);
3430 btrfs_end_transaction_throttle(trans, root);
3434 * We're truncating a file that used to have good data down to
3435 * zero. Make sure it gets into the ordered flush list so that
3436 * any new writes get down to disk quickly.
3439 BTRFS_I(inode)->ordered_data_close = 1;
3441 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3442 truncate_setsize(inode, newsize);
3443 ret = btrfs_truncate(inode);
3449 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3451 struct inode *inode = dentry->d_inode;
3452 struct btrfs_root *root = BTRFS_I(inode)->root;
3455 if (btrfs_root_readonly(root))
3458 err = inode_change_ok(inode, attr);
3462 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3463 err = btrfs_setsize(inode, attr->ia_size);
3468 if (attr->ia_valid) {
3469 setattr_copy(inode, attr);
3470 mark_inode_dirty(inode);
3472 if (attr->ia_valid & ATTR_MODE)
3473 err = btrfs_acl_chmod(inode);
3479 void btrfs_evict_inode(struct inode *inode)
3481 struct btrfs_trans_handle *trans;
3482 struct btrfs_root *root = BTRFS_I(inode)->root;
3483 struct btrfs_block_rsv *rsv, *global_rsv;
3484 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
3488 trace_btrfs_inode_evict(inode);
3490 truncate_inode_pages(&inode->i_data, 0);
3491 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
3492 btrfs_is_free_space_inode(root, inode)))
3495 if (is_bad_inode(inode)) {
3496 btrfs_orphan_del(NULL, inode);
3499 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
3500 btrfs_wait_ordered_range(inode, 0, (u64)-1);
3502 if (root->fs_info->log_root_recovering) {
3503 BUG_ON(!list_empty(&BTRFS_I(inode)->i_orphan));
3507 if (inode->i_nlink > 0) {
3508 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3512 rsv = btrfs_alloc_block_rsv(root);
3514 btrfs_orphan_del(NULL, inode);
3517 rsv->size = min_size;
3518 global_rsv = &root->fs_info->global_block_rsv;
3520 btrfs_i_size_write(inode, 0);
3523 * This is a bit simpler than btrfs_truncate since
3525 * 1) We've already reserved our space for our orphan item in the
3527 * 2) We're going to delete the inode item, so we don't need to update
3530 * So we just need to reserve some slack space in case we add bytes when
3531 * doing the truncate.
3534 ret = btrfs_block_rsv_refill_noflush(root, rsv, min_size);
3537 * Try and steal from the global reserve since we will
3538 * likely not use this space anyway, we want to try as
3539 * hard as possible to get this to work.
3542 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
3545 printk(KERN_WARNING "Could not get space for a "
3546 "delete, will truncate on mount %d\n", ret);
3547 btrfs_orphan_del(NULL, inode);
3548 btrfs_free_block_rsv(root, rsv);
3552 trans = btrfs_start_transaction(root, 0);
3553 if (IS_ERR(trans)) {
3554 btrfs_orphan_del(NULL, inode);
3555 btrfs_free_block_rsv(root, rsv);
3559 trans->block_rsv = rsv;
3561 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3565 nr = trans->blocks_used;
3566 btrfs_end_transaction(trans, root);
3568 btrfs_btree_balance_dirty(root, nr);
3571 btrfs_free_block_rsv(root, rsv);
3574 trans->block_rsv = root->orphan_block_rsv;
3575 ret = btrfs_orphan_del(trans, inode);
3579 trans->block_rsv = &root->fs_info->trans_block_rsv;
3580 if (!(root == root->fs_info->tree_root ||
3581 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
3582 btrfs_return_ino(root, btrfs_ino(inode));
3584 nr = trans->blocks_used;
3585 btrfs_end_transaction(trans, root);
3586 btrfs_btree_balance_dirty(root, nr);
3588 end_writeback(inode);
3593 * this returns the key found in the dir entry in the location pointer.
3594 * If no dir entries were found, location->objectid is 0.
3596 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3597 struct btrfs_key *location)
3599 const char *name = dentry->d_name.name;
3600 int namelen = dentry->d_name.len;
3601 struct btrfs_dir_item *di;
3602 struct btrfs_path *path;
3603 struct btrfs_root *root = BTRFS_I(dir)->root;
3606 path = btrfs_alloc_path();
3610 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
3615 if (IS_ERR_OR_NULL(di))
3618 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
3620 btrfs_free_path(path);
3623 location->objectid = 0;
3628 * when we hit a tree root in a directory, the btrfs part of the inode
3629 * needs to be changed to reflect the root directory of the tree root. This
3630 * is kind of like crossing a mount point.
3632 static int fixup_tree_root_location(struct btrfs_root *root,
3634 struct dentry *dentry,
3635 struct btrfs_key *location,
3636 struct btrfs_root **sub_root)
3638 struct btrfs_path *path;
3639 struct btrfs_root *new_root;
3640 struct btrfs_root_ref *ref;
3641 struct extent_buffer *leaf;
3645 path = btrfs_alloc_path();
3652 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
3653 BTRFS_I(dir)->root->root_key.objectid,
3654 location->objectid);
3661 leaf = path->nodes[0];
3662 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
3663 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
3664 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
3667 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
3668 (unsigned long)(ref + 1),
3669 dentry->d_name.len);
3673 btrfs_release_path(path);
3675 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
3676 if (IS_ERR(new_root)) {
3677 err = PTR_ERR(new_root);
3681 if (btrfs_root_refs(&new_root->root_item) == 0) {
3686 *sub_root = new_root;
3687 location->objectid = btrfs_root_dirid(&new_root->root_item);
3688 location->type = BTRFS_INODE_ITEM_KEY;
3689 location->offset = 0;
3692 btrfs_free_path(path);
3696 static void inode_tree_add(struct inode *inode)
3698 struct btrfs_root *root = BTRFS_I(inode)->root;
3699 struct btrfs_inode *entry;
3701 struct rb_node *parent;
3702 u64 ino = btrfs_ino(inode);
3704 p = &root->inode_tree.rb_node;
3707 if (inode_unhashed(inode))
3710 spin_lock(&root->inode_lock);
3713 entry = rb_entry(parent, struct btrfs_inode, rb_node);
3715 if (ino < btrfs_ino(&entry->vfs_inode))
3716 p = &parent->rb_left;
3717 else if (ino > btrfs_ino(&entry->vfs_inode))
3718 p = &parent->rb_right;
3720 WARN_ON(!(entry->vfs_inode.i_state &
3721 (I_WILL_FREE | I_FREEING)));
3722 rb_erase(parent, &root->inode_tree);
3723 RB_CLEAR_NODE(parent);
3724 spin_unlock(&root->inode_lock);
3728 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
3729 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3730 spin_unlock(&root->inode_lock);
3733 static void inode_tree_del(struct inode *inode)
3735 struct btrfs_root *root = BTRFS_I(inode)->root;
3738 spin_lock(&root->inode_lock);
3739 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
3740 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3741 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
3742 empty = RB_EMPTY_ROOT(&root->inode_tree);
3744 spin_unlock(&root->inode_lock);
3747 * Free space cache has inodes in the tree root, but the tree root has a
3748 * root_refs of 0, so this could end up dropping the tree root as a
3749 * snapshot, so we need the extra !root->fs_info->tree_root check to
3750 * make sure we don't drop it.
3752 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
3753 root != root->fs_info->tree_root) {
3754 synchronize_srcu(&root->fs_info->subvol_srcu);
3755 spin_lock(&root->inode_lock);
3756 empty = RB_EMPTY_ROOT(&root->inode_tree);
3757 spin_unlock(&root->inode_lock);
3759 btrfs_add_dead_root(root);
3763 int btrfs_invalidate_inodes(struct btrfs_root *root)
3765 struct rb_node *node;
3766 struct rb_node *prev;
3767 struct btrfs_inode *entry;
3768 struct inode *inode;
3771 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3773 spin_lock(&root->inode_lock);
3775 node = root->inode_tree.rb_node;
3779 entry = rb_entry(node, struct btrfs_inode, rb_node);
3781 if (objectid < btrfs_ino(&entry->vfs_inode))
3782 node = node->rb_left;
3783 else if (objectid > btrfs_ino(&entry->vfs_inode))
3784 node = node->rb_right;
3790 entry = rb_entry(prev, struct btrfs_inode, rb_node);
3791 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
3795 prev = rb_next(prev);
3799 entry = rb_entry(node, struct btrfs_inode, rb_node);
3800 objectid = btrfs_ino(&entry->vfs_inode) + 1;
3801 inode = igrab(&entry->vfs_inode);
3803 spin_unlock(&root->inode_lock);
3804 if (atomic_read(&inode->i_count) > 1)
3805 d_prune_aliases(inode);
3807 * btrfs_drop_inode will have it removed from
3808 * the inode cache when its usage count
3813 spin_lock(&root->inode_lock);
3817 if (cond_resched_lock(&root->inode_lock))
3820 node = rb_next(node);
3822 spin_unlock(&root->inode_lock);
3826 static int btrfs_init_locked_inode(struct inode *inode, void *p)
3828 struct btrfs_iget_args *args = p;
3829 inode->i_ino = args->ino;
3830 BTRFS_I(inode)->root = args->root;
3831 btrfs_set_inode_space_info(args->root, inode);
3835 static int btrfs_find_actor(struct inode *inode, void *opaque)
3837 struct btrfs_iget_args *args = opaque;
3838 return args->ino == btrfs_ino(inode) &&
3839 args->root == BTRFS_I(inode)->root;
3842 static struct inode *btrfs_iget_locked(struct super_block *s,
3844 struct btrfs_root *root)
3846 struct inode *inode;
3847 struct btrfs_iget_args args;
3848 args.ino = objectid;
3851 inode = iget5_locked(s, objectid, btrfs_find_actor,
3852 btrfs_init_locked_inode,
3857 /* Get an inode object given its location and corresponding root.
3858 * Returns in *is_new if the inode was read from disk
3860 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
3861 struct btrfs_root *root, int *new)
3863 struct inode *inode;
3865 inode = btrfs_iget_locked(s, location->objectid, root);
3867 return ERR_PTR(-ENOMEM);
3869 if (inode->i_state & I_NEW) {
3870 BTRFS_I(inode)->root = root;
3871 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
3872 btrfs_read_locked_inode(inode);
3873 if (!is_bad_inode(inode)) {
3874 inode_tree_add(inode);
3875 unlock_new_inode(inode);
3879 unlock_new_inode(inode);
3881 inode = ERR_PTR(-ESTALE);
3888 static struct inode *new_simple_dir(struct super_block *s,
3889 struct btrfs_key *key,
3890 struct btrfs_root *root)
3892 struct inode *inode = new_inode(s);
3895 return ERR_PTR(-ENOMEM);
3897 BTRFS_I(inode)->root = root;
3898 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
3899 BTRFS_I(inode)->dummy_inode = 1;
3901 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
3902 inode->i_op = &simple_dir_inode_operations;
3903 inode->i_fop = &simple_dir_operations;
3904 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
3905 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
3910 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
3912 struct inode *inode;
3913 struct btrfs_root *root = BTRFS_I(dir)->root;
3914 struct btrfs_root *sub_root = root;
3915 struct btrfs_key location;
3919 if (dentry->d_name.len > BTRFS_NAME_LEN)
3920 return ERR_PTR(-ENAMETOOLONG);
3922 if (unlikely(d_need_lookup(dentry))) {
3923 memcpy(&location, dentry->d_fsdata, sizeof(struct btrfs_key));
3924 kfree(dentry->d_fsdata);
3925 dentry->d_fsdata = NULL;
3926 /* This thing is hashed, drop it for now */
3929 ret = btrfs_inode_by_name(dir, dentry, &location);
3933 return ERR_PTR(ret);
3935 if (location.objectid == 0)
3938 if (location.type == BTRFS_INODE_ITEM_KEY) {
3939 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
3943 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
3945 index = srcu_read_lock(&root->fs_info->subvol_srcu);
3946 ret = fixup_tree_root_location(root, dir, dentry,
3947 &location, &sub_root);
3950 inode = ERR_PTR(ret);
3952 inode = new_simple_dir(dir->i_sb, &location, sub_root);
3954 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
3956 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
3958 if (!IS_ERR(inode) && root != sub_root) {
3959 down_read(&root->fs_info->cleanup_work_sem);
3960 if (!(inode->i_sb->s_flags & MS_RDONLY))
3961 ret = btrfs_orphan_cleanup(sub_root);
3962 up_read(&root->fs_info->cleanup_work_sem);
3964 inode = ERR_PTR(ret);
3970 static int btrfs_dentry_delete(const struct dentry *dentry)
3972 struct btrfs_root *root;
3974 if (!dentry->d_inode && !IS_ROOT(dentry))
3975 dentry = dentry->d_parent;
3977 if (dentry->d_inode) {
3978 root = BTRFS_I(dentry->d_inode)->root;
3979 if (btrfs_root_refs(&root->root_item) == 0)
3985 static void btrfs_dentry_release(struct dentry *dentry)
3987 if (dentry->d_fsdata)
3988 kfree(dentry->d_fsdata);
3991 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
3992 struct nameidata *nd)
3996 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
3997 if (unlikely(d_need_lookup(dentry))) {
3998 spin_lock(&dentry->d_lock);
3999 dentry->d_flags &= ~DCACHE_NEED_LOOKUP;
4000 spin_unlock(&dentry->d_lock);
4005 unsigned char btrfs_filetype_table[] = {
4006 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4009 static int btrfs_real_readdir(struct file *filp, void *dirent,
4012 struct inode *inode = filp->f_dentry->d_inode;
4013 struct btrfs_root *root = BTRFS_I(inode)->root;
4014 struct btrfs_item *item;
4015 struct btrfs_dir_item *di;
4016 struct btrfs_key key;
4017 struct btrfs_key found_key;
4018 struct btrfs_path *path;
4019 struct list_head ins_list;
4020 struct list_head del_list;
4023 struct extent_buffer *leaf;
4025 unsigned char d_type;
4030 int key_type = BTRFS_DIR_INDEX_KEY;
4034 int is_curr = 0; /* filp->f_pos points to the current index? */
4036 /* FIXME, use a real flag for deciding about the key type */
4037 if (root->fs_info->tree_root == root)
4038 key_type = BTRFS_DIR_ITEM_KEY;
4040 /* special case for "." */
4041 if (filp->f_pos == 0) {
4042 over = filldir(dirent, ".", 1,
4043 filp->f_pos, btrfs_ino(inode), DT_DIR);
4048 /* special case for .., just use the back ref */
4049 if (filp->f_pos == 1) {
4050 u64 pino = parent_ino(filp->f_path.dentry);
4051 over = filldir(dirent, "..", 2,
4052 filp->f_pos, pino, DT_DIR);
4057 path = btrfs_alloc_path();
4063 if (key_type == BTRFS_DIR_INDEX_KEY) {
4064 INIT_LIST_HEAD(&ins_list);
4065 INIT_LIST_HEAD(&del_list);
4066 btrfs_get_delayed_items(inode, &ins_list, &del_list);
4069 btrfs_set_key_type(&key, key_type);
4070 key.offset = filp->f_pos;
4071 key.objectid = btrfs_ino(inode);
4073 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4078 leaf = path->nodes[0];
4079 slot = path->slots[0];
4080 if (slot >= btrfs_header_nritems(leaf)) {
4081 ret = btrfs_next_leaf(root, path);
4089 item = btrfs_item_nr(leaf, slot);
4090 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4092 if (found_key.objectid != key.objectid)
4094 if (btrfs_key_type(&found_key) != key_type)
4096 if (found_key.offset < filp->f_pos)
4098 if (key_type == BTRFS_DIR_INDEX_KEY &&
4099 btrfs_should_delete_dir_index(&del_list,
4103 filp->f_pos = found_key.offset;
4106 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4108 di_total = btrfs_item_size(leaf, item);
4110 while (di_cur < di_total) {
4111 struct btrfs_key location;
4114 if (verify_dir_item(root, leaf, di))
4117 name_len = btrfs_dir_name_len(leaf, di);
4118 if (name_len <= sizeof(tmp_name)) {
4119 name_ptr = tmp_name;
4121 name_ptr = kmalloc(name_len, GFP_NOFS);
4127 read_extent_buffer(leaf, name_ptr,
4128 (unsigned long)(di + 1), name_len);
4130 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4131 btrfs_dir_item_key_to_cpu(leaf, di, &location);
4135 q.hash = full_name_hash(q.name, q.len);
4136 tmp = d_lookup(filp->f_dentry, &q);
4138 struct btrfs_key *newkey;
4140 newkey = kzalloc(sizeof(struct btrfs_key),
4144 tmp = d_alloc(filp->f_dentry, &q);
4150 memcpy(newkey, &location,
4151 sizeof(struct btrfs_key));
4152 tmp->d_fsdata = newkey;
4153 tmp->d_flags |= DCACHE_NEED_LOOKUP;
4160 /* is this a reference to our own snapshot? If so
4163 if (location.type == BTRFS_ROOT_ITEM_KEY &&
4164 location.objectid == root->root_key.objectid) {
4168 over = filldir(dirent, name_ptr, name_len,
4169 found_key.offset, location.objectid,
4173 if (name_ptr != tmp_name)
4178 di_len = btrfs_dir_name_len(leaf, di) +
4179 btrfs_dir_data_len(leaf, di) + sizeof(*di);
4181 di = (struct btrfs_dir_item *)((char *)di + di_len);
4187 if (key_type == BTRFS_DIR_INDEX_KEY) {
4190 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
4196 /* Reached end of directory/root. Bump pos past the last item. */
4197 if (key_type == BTRFS_DIR_INDEX_KEY)
4199 * 32-bit glibc will use getdents64, but then strtol -
4200 * so the last number we can serve is this.
4202 filp->f_pos = 0x7fffffff;
4208 if (key_type == BTRFS_DIR_INDEX_KEY)
4209 btrfs_put_delayed_items(&ins_list, &del_list);
4210 btrfs_free_path(path);
4214 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4216 struct btrfs_root *root = BTRFS_I(inode)->root;
4217 struct btrfs_trans_handle *trans;
4219 bool nolock = false;
4221 if (BTRFS_I(inode)->dummy_inode)
4224 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(root, inode))
4227 if (wbc->sync_mode == WB_SYNC_ALL) {
4229 trans = btrfs_join_transaction_nolock(root);
4231 trans = btrfs_join_transaction(root);
4233 return PTR_ERR(trans);
4235 ret = btrfs_end_transaction_nolock(trans, root);
4237 ret = btrfs_commit_transaction(trans, root);
4243 * This is somewhat expensive, updating the tree every time the
4244 * inode changes. But, it is most likely to find the inode in cache.
4245 * FIXME, needs more benchmarking...there are no reasons other than performance
4246 * to keep or drop this code.
4248 void btrfs_dirty_inode(struct inode *inode, int flags)
4250 struct btrfs_root *root = BTRFS_I(inode)->root;
4251 struct btrfs_trans_handle *trans;
4254 if (BTRFS_I(inode)->dummy_inode)
4257 trans = btrfs_join_transaction(root);
4258 BUG_ON(IS_ERR(trans));
4260 ret = btrfs_update_inode(trans, root, inode);
4261 if (ret && ret == -ENOSPC) {
4262 /* whoops, lets try again with the full transaction */
4263 btrfs_end_transaction(trans, root);
4264 trans = btrfs_start_transaction(root, 1);
4265 if (IS_ERR(trans)) {
4266 printk_ratelimited(KERN_ERR "btrfs: fail to "
4267 "dirty inode %llu error %ld\n",
4268 (unsigned long long)btrfs_ino(inode),
4273 ret = btrfs_update_inode(trans, root, inode);
4275 printk_ratelimited(KERN_ERR "btrfs: fail to "
4276 "dirty inode %llu error %d\n",
4277 (unsigned long long)btrfs_ino(inode),
4281 btrfs_end_transaction(trans, root);
4282 if (BTRFS_I(inode)->delayed_node)
4283 btrfs_balance_delayed_items(root);
4287 * find the highest existing sequence number in a directory
4288 * and then set the in-memory index_cnt variable to reflect
4289 * free sequence numbers
4291 static int btrfs_set_inode_index_count(struct inode *inode)
4293 struct btrfs_root *root = BTRFS_I(inode)->root;
4294 struct btrfs_key key, found_key;
4295 struct btrfs_path *path;
4296 struct extent_buffer *leaf;
4299 key.objectid = btrfs_ino(inode);
4300 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4301 key.offset = (u64)-1;
4303 path = btrfs_alloc_path();
4307 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4310 /* FIXME: we should be able to handle this */
4316 * MAGIC NUMBER EXPLANATION:
4317 * since we search a directory based on f_pos we have to start at 2
4318 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4319 * else has to start at 2
4321 if (path->slots[0] == 0) {
4322 BTRFS_I(inode)->index_cnt = 2;
4328 leaf = path->nodes[0];
4329 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4331 if (found_key.objectid != btrfs_ino(inode) ||
4332 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4333 BTRFS_I(inode)->index_cnt = 2;
4337 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4339 btrfs_free_path(path);
4344 * helper to find a free sequence number in a given directory. This current
4345 * code is very simple, later versions will do smarter things in the btree
4347 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4351 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4352 ret = btrfs_inode_delayed_dir_index_count(dir);
4354 ret = btrfs_set_inode_index_count(dir);
4360 *index = BTRFS_I(dir)->index_cnt;
4361 BTRFS_I(dir)->index_cnt++;
4366 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4367 struct btrfs_root *root,
4369 const char *name, int name_len,
4370 u64 ref_objectid, u64 objectid, int mode,
4373 struct inode *inode;
4374 struct btrfs_inode_item *inode_item;
4375 struct btrfs_key *location;
4376 struct btrfs_path *path;
4377 struct btrfs_inode_ref *ref;
4378 struct btrfs_key key[2];
4384 path = btrfs_alloc_path();
4386 return ERR_PTR(-ENOMEM);
4388 inode = new_inode(root->fs_info->sb);
4390 btrfs_free_path(path);
4391 return ERR_PTR(-ENOMEM);
4395 * we have to initialize this early, so we can reclaim the inode
4396 * number if we fail afterwards in this function.
4398 inode->i_ino = objectid;
4401 trace_btrfs_inode_request(dir);
4403 ret = btrfs_set_inode_index(dir, index);
4405 btrfs_free_path(path);
4407 return ERR_PTR(ret);
4411 * index_cnt is ignored for everything but a dir,
4412 * btrfs_get_inode_index_count has an explanation for the magic
4415 BTRFS_I(inode)->index_cnt = 2;
4416 BTRFS_I(inode)->root = root;
4417 BTRFS_I(inode)->generation = trans->transid;
4418 inode->i_generation = BTRFS_I(inode)->generation;
4419 btrfs_set_inode_space_info(root, inode);
4426 key[0].objectid = objectid;
4427 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4430 key[1].objectid = objectid;
4431 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4432 key[1].offset = ref_objectid;
4434 sizes[0] = sizeof(struct btrfs_inode_item);
4435 sizes[1] = name_len + sizeof(*ref);
4437 path->leave_spinning = 1;
4438 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4442 inode_init_owner(inode, dir, mode);
4443 inode_set_bytes(inode, 0);
4444 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4445 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4446 struct btrfs_inode_item);
4447 fill_inode_item(trans, path->nodes[0], inode_item, inode);
4449 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4450 struct btrfs_inode_ref);
4451 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4452 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4453 ptr = (unsigned long)(ref + 1);
4454 write_extent_buffer(path->nodes[0], name, ptr, name_len);
4456 btrfs_mark_buffer_dirty(path->nodes[0]);
4457 btrfs_free_path(path);
4459 location = &BTRFS_I(inode)->location;
4460 location->objectid = objectid;
4461 location->offset = 0;
4462 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4464 btrfs_inherit_iflags(inode, dir);
4466 if (S_ISREG(mode)) {
4467 if (btrfs_test_opt(root, NODATASUM))
4468 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4469 if (btrfs_test_opt(root, NODATACOW) ||
4470 (BTRFS_I(dir)->flags & BTRFS_INODE_NODATACOW))
4471 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4474 insert_inode_hash(inode);
4475 inode_tree_add(inode);
4477 trace_btrfs_inode_new(inode);
4478 btrfs_set_inode_last_trans(trans, inode);
4483 BTRFS_I(dir)->index_cnt--;
4484 btrfs_free_path(path);
4486 return ERR_PTR(ret);
4489 static inline u8 btrfs_inode_type(struct inode *inode)
4491 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4495 * utility function to add 'inode' into 'parent_inode' with
4496 * a give name and a given sequence number.
4497 * if 'add_backref' is true, also insert a backref from the
4498 * inode to the parent directory.
4500 int btrfs_add_link(struct btrfs_trans_handle *trans,
4501 struct inode *parent_inode, struct inode *inode,
4502 const char *name, int name_len, int add_backref, u64 index)
4505 struct btrfs_key key;
4506 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4507 u64 ino = btrfs_ino(inode);
4508 u64 parent_ino = btrfs_ino(parent_inode);
4510 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4511 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4514 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4518 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4519 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4520 key.objectid, root->root_key.objectid,
4521 parent_ino, index, name, name_len);
4522 } else if (add_backref) {
4523 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
4528 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4530 btrfs_inode_type(inode), index);
4533 btrfs_i_size_write(parent_inode, parent_inode->i_size +
4535 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4536 ret = btrfs_update_inode(trans, root, parent_inode);
4541 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4542 struct inode *dir, struct dentry *dentry,
4543 struct inode *inode, int backref, u64 index)
4545 int err = btrfs_add_link(trans, dir, inode,
4546 dentry->d_name.name, dentry->d_name.len,
4549 d_instantiate(dentry, inode);
4557 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4558 int mode, dev_t rdev)
4560 struct btrfs_trans_handle *trans;
4561 struct btrfs_root *root = BTRFS_I(dir)->root;
4562 struct inode *inode = NULL;
4566 unsigned long nr = 0;
4569 if (!new_valid_dev(rdev))
4573 * 2 for inode item and ref
4575 * 1 for xattr if selinux is on
4577 trans = btrfs_start_transaction(root, 5);
4579 return PTR_ERR(trans);
4581 err = btrfs_find_free_ino(root, &objectid);
4585 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4586 dentry->d_name.len, btrfs_ino(dir), objectid,
4588 if (IS_ERR(inode)) {
4589 err = PTR_ERR(inode);
4593 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4600 * If the active LSM wants to access the inode during
4601 * d_instantiate it needs these. Smack checks to see
4602 * if the filesystem supports xattrs by looking at the
4606 inode->i_op = &btrfs_special_inode_operations;
4607 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4611 init_special_inode(inode, inode->i_mode, rdev);
4612 btrfs_update_inode(trans, root, inode);
4615 nr = trans->blocks_used;
4616 btrfs_end_transaction_throttle(trans, root);
4617 btrfs_btree_balance_dirty(root, nr);
4619 inode_dec_link_count(inode);
4625 static int btrfs_create(struct inode *dir, struct dentry *dentry,
4626 int mode, struct nameidata *nd)
4628 struct btrfs_trans_handle *trans;
4629 struct btrfs_root *root = BTRFS_I(dir)->root;
4630 struct inode *inode = NULL;
4633 unsigned long nr = 0;
4638 * 2 for inode item and ref
4640 * 1 for xattr if selinux is on
4642 trans = btrfs_start_transaction(root, 5);
4644 return PTR_ERR(trans);
4646 err = btrfs_find_free_ino(root, &objectid);
4650 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4651 dentry->d_name.len, btrfs_ino(dir), objectid,
4653 if (IS_ERR(inode)) {
4654 err = PTR_ERR(inode);
4658 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4665 * If the active LSM wants to access the inode during
4666 * d_instantiate it needs these. Smack checks to see
4667 * if the filesystem supports xattrs by looking at the
4670 inode->i_fop = &btrfs_file_operations;
4671 inode->i_op = &btrfs_file_inode_operations;
4673 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4677 inode->i_mapping->a_ops = &btrfs_aops;
4678 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4679 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
4682 nr = trans->blocks_used;
4683 btrfs_end_transaction_throttle(trans, root);
4685 inode_dec_link_count(inode);
4688 btrfs_btree_balance_dirty(root, nr);
4692 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
4693 struct dentry *dentry)
4695 struct btrfs_trans_handle *trans;
4696 struct btrfs_root *root = BTRFS_I(dir)->root;
4697 struct inode *inode = old_dentry->d_inode;
4699 unsigned long nr = 0;
4703 /* do not allow sys_link's with other subvols of the same device */
4704 if (root->objectid != BTRFS_I(inode)->root->objectid)
4707 if (inode->i_nlink == ~0U)
4710 err = btrfs_set_inode_index(dir, &index);
4715 * 2 items for inode and inode ref
4716 * 2 items for dir items
4717 * 1 item for parent inode
4719 trans = btrfs_start_transaction(root, 5);
4720 if (IS_ERR(trans)) {
4721 err = PTR_ERR(trans);
4725 btrfs_inc_nlink(inode);
4726 inode->i_ctime = CURRENT_TIME;
4729 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
4734 struct dentry *parent = dentry->d_parent;
4735 err = btrfs_update_inode(trans, root, inode);
4737 btrfs_log_new_name(trans, inode, NULL, parent);
4740 nr = trans->blocks_used;
4741 btrfs_end_transaction_throttle(trans, root);
4744 inode_dec_link_count(inode);
4747 btrfs_btree_balance_dirty(root, nr);
4751 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
4753 struct inode *inode = NULL;
4754 struct btrfs_trans_handle *trans;
4755 struct btrfs_root *root = BTRFS_I(dir)->root;
4757 int drop_on_err = 0;
4760 unsigned long nr = 1;
4763 * 2 items for inode and ref
4764 * 2 items for dir items
4765 * 1 for xattr if selinux is on
4767 trans = btrfs_start_transaction(root, 5);
4769 return PTR_ERR(trans);
4771 err = btrfs_find_free_ino(root, &objectid);
4775 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4776 dentry->d_name.len, btrfs_ino(dir), objectid,
4777 S_IFDIR | mode, &index);
4778 if (IS_ERR(inode)) {
4779 err = PTR_ERR(inode);
4785 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4789 inode->i_op = &btrfs_dir_inode_operations;
4790 inode->i_fop = &btrfs_dir_file_operations;
4792 btrfs_i_size_write(inode, 0);
4793 err = btrfs_update_inode(trans, root, inode);
4797 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
4798 dentry->d_name.len, 0, index);
4802 d_instantiate(dentry, inode);
4806 nr = trans->blocks_used;
4807 btrfs_end_transaction_throttle(trans, root);
4810 btrfs_btree_balance_dirty(root, nr);
4814 /* helper for btfs_get_extent. Given an existing extent in the tree,
4815 * and an extent that you want to insert, deal with overlap and insert
4816 * the new extent into the tree.
4818 static int merge_extent_mapping(struct extent_map_tree *em_tree,
4819 struct extent_map *existing,
4820 struct extent_map *em,
4821 u64 map_start, u64 map_len)
4825 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
4826 start_diff = map_start - em->start;
4827 em->start = map_start;
4829 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
4830 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
4831 em->block_start += start_diff;
4832 em->block_len -= start_diff;
4834 return add_extent_mapping(em_tree, em);
4837 static noinline int uncompress_inline(struct btrfs_path *path,
4838 struct inode *inode, struct page *page,
4839 size_t pg_offset, u64 extent_offset,
4840 struct btrfs_file_extent_item *item)
4843 struct extent_buffer *leaf = path->nodes[0];
4846 unsigned long inline_size;
4850 WARN_ON(pg_offset != 0);
4851 compress_type = btrfs_file_extent_compression(leaf, item);
4852 max_size = btrfs_file_extent_ram_bytes(leaf, item);
4853 inline_size = btrfs_file_extent_inline_item_len(leaf,
4854 btrfs_item_nr(leaf, path->slots[0]));
4855 tmp = kmalloc(inline_size, GFP_NOFS);
4858 ptr = btrfs_file_extent_inline_start(item);
4860 read_extent_buffer(leaf, tmp, ptr, inline_size);
4862 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
4863 ret = btrfs_decompress(compress_type, tmp, page,
4864 extent_offset, inline_size, max_size);
4866 char *kaddr = kmap_atomic(page, KM_USER0);
4867 unsigned long copy_size = min_t(u64,
4868 PAGE_CACHE_SIZE - pg_offset,
4869 max_size - extent_offset);
4870 memset(kaddr + pg_offset, 0, copy_size);
4871 kunmap_atomic(kaddr, KM_USER0);
4878 * a bit scary, this does extent mapping from logical file offset to the disk.
4879 * the ugly parts come from merging extents from the disk with the in-ram
4880 * representation. This gets more complex because of the data=ordered code,
4881 * where the in-ram extents might be locked pending data=ordered completion.
4883 * This also copies inline extents directly into the page.
4886 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
4887 size_t pg_offset, u64 start, u64 len,
4893 u64 extent_start = 0;
4895 u64 objectid = btrfs_ino(inode);
4897 struct btrfs_path *path = NULL;
4898 struct btrfs_root *root = BTRFS_I(inode)->root;
4899 struct btrfs_file_extent_item *item;
4900 struct extent_buffer *leaf;
4901 struct btrfs_key found_key;
4902 struct extent_map *em = NULL;
4903 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4904 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4905 struct btrfs_trans_handle *trans = NULL;
4909 read_lock(&em_tree->lock);
4910 em = lookup_extent_mapping(em_tree, start, len);
4912 em->bdev = root->fs_info->fs_devices->latest_bdev;
4913 read_unlock(&em_tree->lock);
4916 if (em->start > start || em->start + em->len <= start)
4917 free_extent_map(em);
4918 else if (em->block_start == EXTENT_MAP_INLINE && page)
4919 free_extent_map(em);
4923 em = alloc_extent_map();
4928 em->bdev = root->fs_info->fs_devices->latest_bdev;
4929 em->start = EXTENT_MAP_HOLE;
4930 em->orig_start = EXTENT_MAP_HOLE;
4932 em->block_len = (u64)-1;
4935 path = btrfs_alloc_path();
4941 * Chances are we'll be called again, so go ahead and do
4947 ret = btrfs_lookup_file_extent(trans, root, path,
4948 objectid, start, trans != NULL);
4955 if (path->slots[0] == 0)
4960 leaf = path->nodes[0];
4961 item = btrfs_item_ptr(leaf, path->slots[0],
4962 struct btrfs_file_extent_item);
4963 /* are we inside the extent that was found? */
4964 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4965 found_type = btrfs_key_type(&found_key);
4966 if (found_key.objectid != objectid ||
4967 found_type != BTRFS_EXTENT_DATA_KEY) {
4971 found_type = btrfs_file_extent_type(leaf, item);
4972 extent_start = found_key.offset;
4973 compress_type = btrfs_file_extent_compression(leaf, item);
4974 if (found_type == BTRFS_FILE_EXTENT_REG ||
4975 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
4976 extent_end = extent_start +
4977 btrfs_file_extent_num_bytes(leaf, item);
4978 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
4980 size = btrfs_file_extent_inline_len(leaf, item);
4981 extent_end = (extent_start + size + root->sectorsize - 1) &
4982 ~((u64)root->sectorsize - 1);
4985 if (start >= extent_end) {
4987 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
4988 ret = btrfs_next_leaf(root, path);
4995 leaf = path->nodes[0];
4997 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4998 if (found_key.objectid != objectid ||
4999 found_key.type != BTRFS_EXTENT_DATA_KEY)
5001 if (start + len <= found_key.offset)
5004 em->len = found_key.offset - start;
5008 if (found_type == BTRFS_FILE_EXTENT_REG ||
5009 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5010 em->start = extent_start;
5011 em->len = extent_end - extent_start;
5012 em->orig_start = extent_start -
5013 btrfs_file_extent_offset(leaf, item);
5014 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5016 em->block_start = EXTENT_MAP_HOLE;
5019 if (compress_type != BTRFS_COMPRESS_NONE) {
5020 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5021 em->compress_type = compress_type;
5022 em->block_start = bytenr;
5023 em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
5026 bytenr += btrfs_file_extent_offset(leaf, item);
5027 em->block_start = bytenr;
5028 em->block_len = em->len;
5029 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5030 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5033 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5037 size_t extent_offset;
5040 em->block_start = EXTENT_MAP_INLINE;
5041 if (!page || create) {
5042 em->start = extent_start;
5043 em->len = extent_end - extent_start;
5047 size = btrfs_file_extent_inline_len(leaf, item);
5048 extent_offset = page_offset(page) + pg_offset - extent_start;
5049 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
5050 size - extent_offset);
5051 em->start = extent_start + extent_offset;
5052 em->len = (copy_size + root->sectorsize - 1) &
5053 ~((u64)root->sectorsize - 1);
5054 em->orig_start = EXTENT_MAP_INLINE;
5055 if (compress_type) {
5056 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5057 em->compress_type = compress_type;
5059 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5060 if (create == 0 && !PageUptodate(page)) {
5061 if (btrfs_file_extent_compression(leaf, item) !=
5062 BTRFS_COMPRESS_NONE) {
5063 ret = uncompress_inline(path, inode, page,
5065 extent_offset, item);
5069 read_extent_buffer(leaf, map + pg_offset, ptr,
5071 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5072 memset(map + pg_offset + copy_size, 0,
5073 PAGE_CACHE_SIZE - pg_offset -
5078 flush_dcache_page(page);
5079 } else if (create && PageUptodate(page)) {
5083 free_extent_map(em);
5086 btrfs_release_path(path);
5087 trans = btrfs_join_transaction(root);
5090 return ERR_CAST(trans);
5094 write_extent_buffer(leaf, map + pg_offset, ptr,
5097 btrfs_mark_buffer_dirty(leaf);
5099 set_extent_uptodate(io_tree, em->start,
5100 extent_map_end(em) - 1, NULL, GFP_NOFS);
5103 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
5110 em->block_start = EXTENT_MAP_HOLE;
5111 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5113 btrfs_release_path(path);
5114 if (em->start > start || extent_map_end(em) <= start) {
5115 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5116 "[%llu %llu]\n", (unsigned long long)em->start,
5117 (unsigned long long)em->len,
5118 (unsigned long long)start,
5119 (unsigned long long)len);
5125 write_lock(&em_tree->lock);
5126 ret = add_extent_mapping(em_tree, em);
5127 /* it is possible that someone inserted the extent into the tree
5128 * while we had the lock dropped. It is also possible that
5129 * an overlapping map exists in the tree
5131 if (ret == -EEXIST) {
5132 struct extent_map *existing;
5136 existing = lookup_extent_mapping(em_tree, start, len);
5137 if (existing && (existing->start > start ||
5138 existing->start + existing->len <= start)) {
5139 free_extent_map(existing);
5143 existing = lookup_extent_mapping(em_tree, em->start,
5146 err = merge_extent_mapping(em_tree, existing,
5149 free_extent_map(existing);
5151 free_extent_map(em);
5156 free_extent_map(em);
5160 free_extent_map(em);
5165 write_unlock(&em_tree->lock);
5168 trace_btrfs_get_extent(root, em);
5171 btrfs_free_path(path);
5173 ret = btrfs_end_transaction(trans, root);
5178 free_extent_map(em);
5179 return ERR_PTR(err);
5184 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
5185 size_t pg_offset, u64 start, u64 len,
5188 struct extent_map *em;
5189 struct extent_map *hole_em = NULL;
5190 u64 range_start = start;
5196 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
5201 * if our em maps to a hole, there might
5202 * actually be delalloc bytes behind it
5204 if (em->block_start != EXTENT_MAP_HOLE)
5210 /* check to see if we've wrapped (len == -1 or similar) */
5219 /* ok, we didn't find anything, lets look for delalloc */
5220 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
5221 end, len, EXTENT_DELALLOC, 1);
5222 found_end = range_start + found;
5223 if (found_end < range_start)
5224 found_end = (u64)-1;
5227 * we didn't find anything useful, return
5228 * the original results from get_extent()
5230 if (range_start > end || found_end <= start) {
5236 /* adjust the range_start to make sure it doesn't
5237 * go backwards from the start they passed in
5239 range_start = max(start,range_start);
5240 found = found_end - range_start;
5243 u64 hole_start = start;
5246 em = alloc_extent_map();
5252 * when btrfs_get_extent can't find anything it
5253 * returns one huge hole
5255 * make sure what it found really fits our range, and
5256 * adjust to make sure it is based on the start from
5260 u64 calc_end = extent_map_end(hole_em);
5262 if (calc_end <= start || (hole_em->start > end)) {
5263 free_extent_map(hole_em);
5266 hole_start = max(hole_em->start, start);
5267 hole_len = calc_end - hole_start;
5271 if (hole_em && range_start > hole_start) {
5272 /* our hole starts before our delalloc, so we
5273 * have to return just the parts of the hole
5274 * that go until the delalloc starts
5276 em->len = min(hole_len,
5277 range_start - hole_start);
5278 em->start = hole_start;
5279 em->orig_start = hole_start;
5281 * don't adjust block start at all,
5282 * it is fixed at EXTENT_MAP_HOLE
5284 em->block_start = hole_em->block_start;
5285 em->block_len = hole_len;
5287 em->start = range_start;
5289 em->orig_start = range_start;
5290 em->block_start = EXTENT_MAP_DELALLOC;
5291 em->block_len = found;
5293 } else if (hole_em) {
5298 free_extent_map(hole_em);
5300 free_extent_map(em);
5301 return ERR_PTR(err);
5306 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5307 struct extent_map *em,
5310 struct btrfs_root *root = BTRFS_I(inode)->root;
5311 struct btrfs_trans_handle *trans;
5312 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5313 struct btrfs_key ins;
5316 bool insert = false;
5319 * Ok if the extent map we looked up is a hole and is for the exact
5320 * range we want, there is no reason to allocate a new one, however if
5321 * it is not right then we need to free this one and drop the cache for
5324 if (em->block_start != EXTENT_MAP_HOLE || em->start != start ||
5326 free_extent_map(em);
5329 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
5332 trans = btrfs_join_transaction(root);
5334 return ERR_CAST(trans);
5336 if (start <= BTRFS_I(inode)->disk_i_size && len < 64 * 1024)
5337 btrfs_add_inode_defrag(trans, inode);
5339 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5341 alloc_hint = get_extent_allocation_hint(inode, start, len);
5342 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5343 alloc_hint, (u64)-1, &ins, 1);
5350 em = alloc_extent_map();
5352 em = ERR_PTR(-ENOMEM);
5358 em->orig_start = em->start;
5359 em->len = ins.offset;
5361 em->block_start = ins.objectid;
5362 em->block_len = ins.offset;
5363 em->bdev = root->fs_info->fs_devices->latest_bdev;
5366 * We need to do this because if we're using the original em we searched
5367 * for, we could have EXTENT_FLAG_VACANCY set, and we don't want that.
5370 set_bit(EXTENT_FLAG_PINNED, &em->flags);
5373 write_lock(&em_tree->lock);
5374 ret = add_extent_mapping(em_tree, em);
5375 write_unlock(&em_tree->lock);
5378 btrfs_drop_extent_cache(inode, start, start + em->len - 1, 0);
5381 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5382 ins.offset, ins.offset, 0);
5384 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5388 btrfs_end_transaction(trans, root);
5393 * returns 1 when the nocow is safe, < 1 on error, 0 if the
5394 * block must be cow'd
5396 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5397 struct inode *inode, u64 offset, u64 len)
5399 struct btrfs_path *path;
5401 struct extent_buffer *leaf;
5402 struct btrfs_root *root = BTRFS_I(inode)->root;
5403 struct btrfs_file_extent_item *fi;
5404 struct btrfs_key key;
5412 path = btrfs_alloc_path();
5416 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
5421 slot = path->slots[0];
5424 /* can't find the item, must cow */
5431 leaf = path->nodes[0];
5432 btrfs_item_key_to_cpu(leaf, &key, slot);
5433 if (key.objectid != btrfs_ino(inode) ||
5434 key.type != BTRFS_EXTENT_DATA_KEY) {
5435 /* not our file or wrong item type, must cow */
5439 if (key.offset > offset) {
5440 /* Wrong offset, must cow */
5444 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5445 found_type = btrfs_file_extent_type(leaf, fi);
5446 if (found_type != BTRFS_FILE_EXTENT_REG &&
5447 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5448 /* not a regular extent, must cow */
5451 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5452 backref_offset = btrfs_file_extent_offset(leaf, fi);
5454 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5455 if (extent_end < offset + len) {
5456 /* extent doesn't include our full range, must cow */
5460 if (btrfs_extent_readonly(root, disk_bytenr))
5464 * look for other files referencing this extent, if we
5465 * find any we must cow
5467 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
5468 key.offset - backref_offset, disk_bytenr))
5472 * adjust disk_bytenr and num_bytes to cover just the bytes
5473 * in this extent we are about to write. If there
5474 * are any csums in that range we have to cow in order
5475 * to keep the csums correct
5477 disk_bytenr += backref_offset;
5478 disk_bytenr += offset - key.offset;
5479 num_bytes = min(offset + len, extent_end) - offset;
5480 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5483 * all of the above have passed, it is safe to overwrite this extent
5488 btrfs_free_path(path);
5492 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
5493 struct buffer_head *bh_result, int create)
5495 struct extent_map *em;
5496 struct btrfs_root *root = BTRFS_I(inode)->root;
5497 u64 start = iblock << inode->i_blkbits;
5498 u64 len = bh_result->b_size;
5499 struct btrfs_trans_handle *trans;
5501 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
5506 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
5507 * io. INLINE is special, and we could probably kludge it in here, but
5508 * it's still buffered so for safety lets just fall back to the generic
5511 * For COMPRESSED we _have_ to read the entire extent in so we can
5512 * decompress it, so there will be buffering required no matter what we
5513 * do, so go ahead and fallback to buffered.
5515 * We return -ENOTBLK because thats what makes DIO go ahead and go back
5516 * to buffered IO. Don't blame me, this is the price we pay for using
5519 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
5520 em->block_start == EXTENT_MAP_INLINE) {
5521 free_extent_map(em);
5525 /* Just a good old fashioned hole, return */
5526 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
5527 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
5528 free_extent_map(em);
5529 /* DIO will do one hole at a time, so just unlock a sector */
5530 unlock_extent(&BTRFS_I(inode)->io_tree, start,
5531 start + root->sectorsize - 1, GFP_NOFS);
5536 * We don't allocate a new extent in the following cases
5538 * 1) The inode is marked as NODATACOW. In this case we'll just use the
5540 * 2) The extent is marked as PREALLOC. We're good to go here and can
5541 * just use the extent.
5545 len = em->len - (start - em->start);
5549 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
5550 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
5551 em->block_start != EXTENT_MAP_HOLE)) {
5556 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5557 type = BTRFS_ORDERED_PREALLOC;
5559 type = BTRFS_ORDERED_NOCOW;
5560 len = min(len, em->len - (start - em->start));
5561 block_start = em->block_start + (start - em->start);
5564 * we're not going to log anything, but we do need
5565 * to make sure the current transaction stays open
5566 * while we look for nocow cross refs
5568 trans = btrfs_join_transaction(root);
5572 if (can_nocow_odirect(trans, inode, start, len) == 1) {
5573 ret = btrfs_add_ordered_extent_dio(inode, start,
5574 block_start, len, len, type);
5575 btrfs_end_transaction(trans, root);
5577 free_extent_map(em);
5582 btrfs_end_transaction(trans, root);
5586 * this will cow the extent, reset the len in case we changed
5589 len = bh_result->b_size;
5590 em = btrfs_new_extent_direct(inode, em, start, len);
5593 len = min(len, em->len - (start - em->start));
5595 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, start + len - 1,
5596 EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DIRTY, 1,
5599 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
5601 bh_result->b_size = len;
5602 bh_result->b_bdev = em->bdev;
5603 set_buffer_mapped(bh_result);
5604 if (create && !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5605 set_buffer_new(bh_result);
5607 free_extent_map(em);
5612 struct btrfs_dio_private {
5613 struct inode *inode;
5620 /* number of bios pending for this dio */
5621 atomic_t pending_bios;
5626 struct bio *orig_bio;
5629 static void btrfs_endio_direct_read(struct bio *bio, int err)
5631 struct btrfs_dio_private *dip = bio->bi_private;
5632 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
5633 struct bio_vec *bvec = bio->bi_io_vec;
5634 struct inode *inode = dip->inode;
5635 struct btrfs_root *root = BTRFS_I(inode)->root;
5637 u32 *private = dip->csums;
5639 start = dip->logical_offset;
5641 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
5642 struct page *page = bvec->bv_page;
5645 unsigned long flags;
5647 local_irq_save(flags);
5648 kaddr = kmap_atomic(page, KM_IRQ0);
5649 csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
5650 csum, bvec->bv_len);
5651 btrfs_csum_final(csum, (char *)&csum);
5652 kunmap_atomic(kaddr, KM_IRQ0);
5653 local_irq_restore(flags);
5655 flush_dcache_page(bvec->bv_page);
5656 if (csum != *private) {
5657 printk(KERN_ERR "btrfs csum failed ino %llu off"
5658 " %llu csum %u private %u\n",
5659 (unsigned long long)btrfs_ino(inode),
5660 (unsigned long long)start,
5666 start += bvec->bv_len;
5669 } while (bvec <= bvec_end);
5671 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
5672 dip->logical_offset + dip->bytes - 1, GFP_NOFS);
5673 bio->bi_private = dip->private;
5678 /* If we had a csum failure make sure to clear the uptodate flag */
5680 clear_bit(BIO_UPTODATE, &bio->bi_flags);
5681 dio_end_io(bio, err);
5684 static void btrfs_endio_direct_write(struct bio *bio, int err)
5686 struct btrfs_dio_private *dip = bio->bi_private;
5687 struct inode *inode = dip->inode;
5688 struct btrfs_root *root = BTRFS_I(inode)->root;
5689 struct btrfs_trans_handle *trans;
5690 struct btrfs_ordered_extent *ordered = NULL;
5691 struct extent_state *cached_state = NULL;
5692 u64 ordered_offset = dip->logical_offset;
5693 u64 ordered_bytes = dip->bytes;
5699 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
5707 trans = btrfs_join_transaction(root);
5708 if (IS_ERR(trans)) {
5712 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5714 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) {
5715 ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5717 err = btrfs_update_inode_fallback(trans, root, inode);
5721 lock_extent_bits(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5722 ordered->file_offset + ordered->len - 1, 0,
5723 &cached_state, GFP_NOFS);
5725 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags)) {
5726 ret = btrfs_mark_extent_written(trans, inode,
5727 ordered->file_offset,
5728 ordered->file_offset +
5735 ret = insert_reserved_file_extent(trans, inode,
5736 ordered->file_offset,
5742 BTRFS_FILE_EXTENT_REG);
5743 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
5744 ordered->file_offset, ordered->len);
5752 add_pending_csums(trans, inode, ordered->file_offset, &ordered->list);
5753 ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5754 if (!ret || !test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags))
5755 btrfs_update_inode_fallback(trans, root, inode);
5758 unlock_extent_cached(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5759 ordered->file_offset + ordered->len - 1,
5760 &cached_state, GFP_NOFS);
5762 btrfs_delalloc_release_metadata(inode, ordered->len);
5763 btrfs_end_transaction(trans, root);
5764 ordered_offset = ordered->file_offset + ordered->len;
5765 btrfs_put_ordered_extent(ordered);
5766 btrfs_put_ordered_extent(ordered);
5770 * our bio might span multiple ordered extents. If we haven't
5771 * completed the accounting for the whole dio, go back and try again
5773 if (ordered_offset < dip->logical_offset + dip->bytes) {
5774 ordered_bytes = dip->logical_offset + dip->bytes -
5779 bio->bi_private = dip->private;
5784 /* If we had an error make sure to clear the uptodate flag */
5786 clear_bit(BIO_UPTODATE, &bio->bi_flags);
5787 dio_end_io(bio, err);
5790 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
5791 struct bio *bio, int mirror_num,
5792 unsigned long bio_flags, u64 offset)
5795 struct btrfs_root *root = BTRFS_I(inode)->root;
5796 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
5801 static void btrfs_end_dio_bio(struct bio *bio, int err)
5803 struct btrfs_dio_private *dip = bio->bi_private;
5806 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
5807 "sector %#Lx len %u err no %d\n",
5808 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
5809 (unsigned long long)bio->bi_sector, bio->bi_size, err);
5813 * before atomic variable goto zero, we must make sure
5814 * dip->errors is perceived to be set.
5816 smp_mb__before_atomic_dec();
5819 /* if there are more bios still pending for this dio, just exit */
5820 if (!atomic_dec_and_test(&dip->pending_bios))
5824 bio_io_error(dip->orig_bio);
5826 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
5827 bio_endio(dip->orig_bio, 0);
5833 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
5834 u64 first_sector, gfp_t gfp_flags)
5836 int nr_vecs = bio_get_nr_vecs(bdev);
5837 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
5840 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
5841 int rw, u64 file_offset, int skip_sum,
5842 u32 *csums, int async_submit)
5844 int write = rw & REQ_WRITE;
5845 struct btrfs_root *root = BTRFS_I(inode)->root;
5849 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
5856 if (write && async_submit) {
5857 ret = btrfs_wq_submit_bio(root->fs_info,
5858 inode, rw, bio, 0, 0,
5860 __btrfs_submit_bio_start_direct_io,
5861 __btrfs_submit_bio_done);
5865 * If we aren't doing async submit, calculate the csum of the
5868 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
5871 } else if (!skip_sum) {
5872 ret = btrfs_lookup_bio_sums_dio(root, inode, bio,
5873 file_offset, csums);
5879 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
5885 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
5888 struct inode *inode = dip->inode;
5889 struct btrfs_root *root = BTRFS_I(inode)->root;
5890 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
5892 struct bio *orig_bio = dip->orig_bio;
5893 struct bio_vec *bvec = orig_bio->bi_io_vec;
5894 u64 start_sector = orig_bio->bi_sector;
5895 u64 file_offset = dip->logical_offset;
5899 u32 *csums = dip->csums;
5901 int async_submit = 0;
5902 int write = rw & REQ_WRITE;
5904 map_length = orig_bio->bi_size;
5905 ret = btrfs_map_block(map_tree, READ, start_sector << 9,
5906 &map_length, NULL, 0);
5912 if (map_length >= orig_bio->bi_size) {
5918 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
5921 bio->bi_private = dip;
5922 bio->bi_end_io = btrfs_end_dio_bio;
5923 atomic_inc(&dip->pending_bios);
5925 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
5926 if (unlikely(map_length < submit_len + bvec->bv_len ||
5927 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
5928 bvec->bv_offset) < bvec->bv_len)) {
5930 * inc the count before we submit the bio so
5931 * we know the end IO handler won't happen before
5932 * we inc the count. Otherwise, the dip might get freed
5933 * before we're done setting it up
5935 atomic_inc(&dip->pending_bios);
5936 ret = __btrfs_submit_dio_bio(bio, inode, rw,
5937 file_offset, skip_sum,
5938 csums, async_submit);
5941 atomic_dec(&dip->pending_bios);
5945 /* Write's use the ordered csums */
5946 if (!write && !skip_sum)
5947 csums = csums + nr_pages;
5948 start_sector += submit_len >> 9;
5949 file_offset += submit_len;
5954 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
5955 start_sector, GFP_NOFS);
5958 bio->bi_private = dip;
5959 bio->bi_end_io = btrfs_end_dio_bio;
5961 map_length = orig_bio->bi_size;
5962 ret = btrfs_map_block(map_tree, READ, start_sector << 9,
5963 &map_length, NULL, 0);
5969 submit_len += bvec->bv_len;
5976 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
5977 csums, async_submit);
5985 * before atomic variable goto zero, we must
5986 * make sure dip->errors is perceived to be set.
5988 smp_mb__before_atomic_dec();
5989 if (atomic_dec_and_test(&dip->pending_bios))
5990 bio_io_error(dip->orig_bio);
5992 /* bio_end_io() will handle error, so we needn't return it */
5996 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
5999 struct btrfs_root *root = BTRFS_I(inode)->root;
6000 struct btrfs_dio_private *dip;
6001 struct bio_vec *bvec = bio->bi_io_vec;
6003 int write = rw & REQ_WRITE;
6006 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
6008 dip = kmalloc(sizeof(*dip), GFP_NOFS);
6015 /* Write's use the ordered csum stuff, so we don't need dip->csums */
6016 if (!write && !skip_sum) {
6017 dip->csums = kmalloc(sizeof(u32) * bio->bi_vcnt, GFP_NOFS);
6025 dip->private = bio->bi_private;
6027 dip->logical_offset = file_offset;
6031 dip->bytes += bvec->bv_len;
6033 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
6035 dip->disk_bytenr = (u64)bio->bi_sector << 9;
6036 bio->bi_private = dip;
6038 dip->orig_bio = bio;
6039 atomic_set(&dip->pending_bios, 0);
6042 bio->bi_end_io = btrfs_endio_direct_write;
6044 bio->bi_end_io = btrfs_endio_direct_read;
6046 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
6051 * If this is a write, we need to clean up the reserved space and kill
6052 * the ordered extent.
6055 struct btrfs_ordered_extent *ordered;
6056 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
6057 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
6058 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
6059 btrfs_free_reserved_extent(root, ordered->start,
6061 btrfs_put_ordered_extent(ordered);
6062 btrfs_put_ordered_extent(ordered);
6064 bio_endio(bio, ret);
6067 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
6068 const struct iovec *iov, loff_t offset,
6069 unsigned long nr_segs)
6075 unsigned blocksize_mask = root->sectorsize - 1;
6076 ssize_t retval = -EINVAL;
6077 loff_t end = offset;
6079 if (offset & blocksize_mask)
6082 /* Check the memory alignment. Blocks cannot straddle pages */
6083 for (seg = 0; seg < nr_segs; seg++) {
6084 addr = (unsigned long)iov[seg].iov_base;
6085 size = iov[seg].iov_len;
6087 if ((addr & blocksize_mask) || (size & blocksize_mask))
6090 /* If this is a write we don't need to check anymore */
6095 * Check to make sure we don't have duplicate iov_base's in this
6096 * iovec, if so return EINVAL, otherwise we'll get csum errors
6097 * when reading back.
6099 for (i = seg + 1; i < nr_segs; i++) {
6100 if (iov[seg].iov_base == iov[i].iov_base)
6108 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
6109 const struct iovec *iov, loff_t offset,
6110 unsigned long nr_segs)
6112 struct file *file = iocb->ki_filp;
6113 struct inode *inode = file->f_mapping->host;
6114 struct btrfs_ordered_extent *ordered;
6115 struct extent_state *cached_state = NULL;
6116 u64 lockstart, lockend;
6118 int writing = rw & WRITE;
6120 size_t count = iov_length(iov, nr_segs);
6122 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
6128 lockend = offset + count - 1;
6131 ret = btrfs_delalloc_reserve_space(inode, count);
6137 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6138 0, &cached_state, GFP_NOFS);
6140 * We're concerned with the entire range that we're going to be
6141 * doing DIO to, so we need to make sure theres no ordered
6142 * extents in this range.
6144 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6145 lockend - lockstart + 1);
6148 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6149 &cached_state, GFP_NOFS);
6150 btrfs_start_ordered_extent(inode, ordered, 1);
6151 btrfs_put_ordered_extent(ordered);
6156 * we don't use btrfs_set_extent_delalloc because we don't want
6157 * the dirty or uptodate bits
6160 write_bits = EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING;
6161 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6162 EXTENT_DELALLOC, 0, NULL, &cached_state,
6165 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6166 lockend, EXTENT_LOCKED | write_bits,
6167 1, 0, &cached_state, GFP_NOFS);
6172 free_extent_state(cached_state);
6173 cached_state = NULL;
6175 ret = __blockdev_direct_IO(rw, iocb, inode,
6176 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
6177 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
6178 btrfs_submit_direct, 0);
6180 if (ret < 0 && ret != -EIOCBQUEUED) {
6181 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset,
6182 offset + iov_length(iov, nr_segs) - 1,
6183 EXTENT_LOCKED | write_bits, 1, 0,
6184 &cached_state, GFP_NOFS);
6185 } else if (ret >= 0 && ret < iov_length(iov, nr_segs)) {
6187 * We're falling back to buffered, unlock the section we didn't
6190 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset + ret,
6191 offset + iov_length(iov, nr_segs) - 1,
6192 EXTENT_LOCKED | write_bits, 1, 0,
6193 &cached_state, GFP_NOFS);
6196 free_extent_state(cached_state);
6200 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
6201 __u64 start, __u64 len)
6203 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
6206 int btrfs_readpage(struct file *file, struct page *page)
6208 struct extent_io_tree *tree;
6209 tree = &BTRFS_I(page->mapping->host)->io_tree;
6210 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
6213 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
6215 struct extent_io_tree *tree;
6218 if (current->flags & PF_MEMALLOC) {
6219 redirty_page_for_writepage(wbc, page);
6223 tree = &BTRFS_I(page->mapping->host)->io_tree;
6224 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
6227 int btrfs_writepages(struct address_space *mapping,
6228 struct writeback_control *wbc)
6230 struct extent_io_tree *tree;
6232 tree = &BTRFS_I(mapping->host)->io_tree;
6233 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
6237 btrfs_readpages(struct file *file, struct address_space *mapping,
6238 struct list_head *pages, unsigned nr_pages)
6240 struct extent_io_tree *tree;
6241 tree = &BTRFS_I(mapping->host)->io_tree;
6242 return extent_readpages(tree, mapping, pages, nr_pages,
6245 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6247 struct extent_io_tree *tree;
6248 struct extent_map_tree *map;
6251 tree = &BTRFS_I(page->mapping->host)->io_tree;
6252 map = &BTRFS_I(page->mapping->host)->extent_tree;
6253 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
6255 ClearPagePrivate(page);
6256 set_page_private(page, 0);
6257 page_cache_release(page);
6262 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6264 if (PageWriteback(page) || PageDirty(page))
6266 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
6269 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
6271 struct extent_io_tree *tree;
6272 struct btrfs_ordered_extent *ordered;
6273 struct extent_state *cached_state = NULL;
6274 u64 page_start = page_offset(page);
6275 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
6279 * we have the page locked, so new writeback can't start,
6280 * and the dirty bit won't be cleared while we are here.
6282 * Wait for IO on this page so that we can safely clear
6283 * the PagePrivate2 bit and do ordered accounting
6285 wait_on_page_writeback(page);
6287 tree = &BTRFS_I(page->mapping->host)->io_tree;
6289 btrfs_releasepage(page, GFP_NOFS);
6292 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6294 ordered = btrfs_lookup_ordered_extent(page->mapping->host,
6298 * IO on this page will never be started, so we need
6299 * to account for any ordered extents now
6301 clear_extent_bit(tree, page_start, page_end,
6302 EXTENT_DIRTY | EXTENT_DELALLOC |
6303 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
6304 &cached_state, GFP_NOFS);
6306 * whoever cleared the private bit is responsible
6307 * for the finish_ordered_io
6309 if (TestClearPagePrivate2(page)) {
6310 btrfs_finish_ordered_io(page->mapping->host,
6311 page_start, page_end);
6313 btrfs_put_ordered_extent(ordered);
6314 cached_state = NULL;
6315 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6318 clear_extent_bit(tree, page_start, page_end,
6319 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
6320 EXTENT_DO_ACCOUNTING, 1, 1, &cached_state, GFP_NOFS);
6321 __btrfs_releasepage(page, GFP_NOFS);
6323 ClearPageChecked(page);
6324 if (PagePrivate(page)) {
6325 ClearPagePrivate(page);
6326 set_page_private(page, 0);
6327 page_cache_release(page);
6332 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6333 * called from a page fault handler when a page is first dirtied. Hence we must
6334 * be careful to check for EOF conditions here. We set the page up correctly
6335 * for a written page which means we get ENOSPC checking when writing into
6336 * holes and correct delalloc and unwritten extent mapping on filesystems that
6337 * support these features.
6339 * We are not allowed to take the i_mutex here so we have to play games to
6340 * protect against truncate races as the page could now be beyond EOF. Because
6341 * vmtruncate() writes the inode size before removing pages, once we have the
6342 * page lock we can determine safely if the page is beyond EOF. If it is not
6343 * beyond EOF, then the page is guaranteed safe against truncation until we
6346 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
6348 struct page *page = vmf->page;
6349 struct inode *inode = fdentry(vma->vm_file)->d_inode;
6350 struct btrfs_root *root = BTRFS_I(inode)->root;
6351 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6352 struct btrfs_ordered_extent *ordered;
6353 struct extent_state *cached_state = NULL;
6355 unsigned long zero_start;
6361 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
6365 else /* -ENOSPC, -EIO, etc */
6366 ret = VM_FAULT_SIGBUS;
6370 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
6373 size = i_size_read(inode);
6374 page_start = page_offset(page);
6375 page_end = page_start + PAGE_CACHE_SIZE - 1;
6377 if ((page->mapping != inode->i_mapping) ||
6378 (page_start >= size)) {
6379 /* page got truncated out from underneath us */
6382 wait_on_page_writeback(page);
6384 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
6386 set_page_extent_mapped(page);
6389 * we can't set the delalloc bits if there are pending ordered
6390 * extents. Drop our locks and wait for them to finish
6392 ordered = btrfs_lookup_ordered_extent(inode, page_start);
6394 unlock_extent_cached(io_tree, page_start, page_end,
6395 &cached_state, GFP_NOFS);
6397 btrfs_start_ordered_extent(inode, ordered, 1);
6398 btrfs_put_ordered_extent(ordered);
6403 * XXX - page_mkwrite gets called every time the page is dirtied, even
6404 * if it was already dirty, so for space accounting reasons we need to
6405 * clear any delalloc bits for the range we are fixing to save. There
6406 * is probably a better way to do this, but for now keep consistent with
6407 * prepare_pages in the normal write path.
6409 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
6410 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
6411 0, 0, &cached_state, GFP_NOFS);
6413 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6416 unlock_extent_cached(io_tree, page_start, page_end,
6417 &cached_state, GFP_NOFS);
6418 ret = VM_FAULT_SIGBUS;
6423 /* page is wholly or partially inside EOF */
6424 if (page_start + PAGE_CACHE_SIZE > size)
6425 zero_start = size & ~PAGE_CACHE_MASK;
6427 zero_start = PAGE_CACHE_SIZE;
6429 if (zero_start != PAGE_CACHE_SIZE) {
6431 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6432 flush_dcache_page(page);
6435 ClearPageChecked(page);
6436 set_page_dirty(page);
6437 SetPageUptodate(page);
6439 BTRFS_I(inode)->last_trans = root->fs_info->generation;
6440 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6442 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
6446 return VM_FAULT_LOCKED;
6448 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
6453 static int btrfs_truncate(struct inode *inode)
6455 struct btrfs_root *root = BTRFS_I(inode)->root;
6456 struct btrfs_block_rsv *rsv;
6459 struct btrfs_trans_handle *trans;
6461 u64 mask = root->sectorsize - 1;
6462 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
6464 ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
6468 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
6469 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
6472 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
6473 * 3 things going on here
6475 * 1) We need to reserve space for our orphan item and the space to
6476 * delete our orphan item. Lord knows we don't want to have a dangling
6477 * orphan item because we didn't reserve space to remove it.
6479 * 2) We need to reserve space to update our inode.
6481 * 3) We need to have something to cache all the space that is going to
6482 * be free'd up by the truncate operation, but also have some slack
6483 * space reserved in case it uses space during the truncate (thank you
6484 * very much snapshotting).
6486 * And we need these to all be seperate. The fact is we can use alot of
6487 * space doing the truncate, and we have no earthly idea how much space
6488 * we will use, so we need the truncate reservation to be seperate so it
6489 * doesn't end up using space reserved for updating the inode or
6490 * removing the orphan item. We also need to be able to stop the
6491 * transaction and start a new one, which means we need to be able to
6492 * update the inode several times, and we have no idea of knowing how
6493 * many times that will be, so we can't just reserve 1 item for the
6494 * entirety of the opration, so that has to be done seperately as well.
6495 * Then there is the orphan item, which does indeed need to be held on
6496 * to for the whole operation, and we need nobody to touch this reserved
6497 * space except the orphan code.
6499 * So that leaves us with
6501 * 1) root->orphan_block_rsv - for the orphan deletion.
6502 * 2) rsv - for the truncate reservation, which we will steal from the
6503 * transaction reservation.
6504 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
6505 * updating the inode.
6507 rsv = btrfs_alloc_block_rsv(root);
6510 rsv->size = min_size;
6513 * 1 for the truncate slack space
6514 * 1 for the orphan item we're going to add
6515 * 1 for the orphan item deletion
6516 * 1 for updating the inode.
6518 trans = btrfs_start_transaction(root, 4);
6519 if (IS_ERR(trans)) {
6520 err = PTR_ERR(trans);
6524 /* Migrate the slack space for the truncate to our reserve */
6525 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
6529 ret = btrfs_orphan_add(trans, inode);
6531 btrfs_end_transaction(trans, root);
6536 * setattr is responsible for setting the ordered_data_close flag,
6537 * but that is only tested during the last file release. That
6538 * could happen well after the next commit, leaving a great big
6539 * window where new writes may get lost if someone chooses to write
6540 * to this file after truncating to zero
6542 * The inode doesn't have any dirty data here, and so if we commit
6543 * this is a noop. If someone immediately starts writing to the inode
6544 * it is very likely we'll catch some of their writes in this
6545 * transaction, and the commit will find this file on the ordered
6546 * data list with good things to send down.
6548 * This is a best effort solution, there is still a window where
6549 * using truncate to replace the contents of the file will
6550 * end up with a zero length file after a crash.
6552 if (inode->i_size == 0 && BTRFS_I(inode)->ordered_data_close)
6553 btrfs_add_ordered_operation(trans, root, inode);
6556 ret = btrfs_block_rsv_refill(root, rsv, min_size);
6559 * This can only happen with the original transaction we
6560 * started above, every other time we shouldn't have a
6561 * transaction started yet.
6570 /* Just need the 1 for updating the inode */
6571 trans = btrfs_start_transaction(root, 1);
6572 if (IS_ERR(trans)) {
6573 err = PTR_ERR(trans);
6578 trans->block_rsv = rsv;
6580 ret = btrfs_truncate_inode_items(trans, root, inode,
6582 BTRFS_EXTENT_DATA_KEY);
6583 if (ret != -EAGAIN) {
6588 trans->block_rsv = &root->fs_info->trans_block_rsv;
6589 ret = btrfs_update_inode(trans, root, inode);
6595 nr = trans->blocks_used;
6596 btrfs_end_transaction(trans, root);
6598 btrfs_btree_balance_dirty(root, nr);
6601 if (ret == 0 && inode->i_nlink > 0) {
6602 trans->block_rsv = root->orphan_block_rsv;
6603 ret = btrfs_orphan_del(trans, inode);
6606 } else if (ret && inode->i_nlink > 0) {
6608 * Failed to do the truncate, remove us from the in memory
6611 ret = btrfs_orphan_del(NULL, inode);
6615 trans->block_rsv = &root->fs_info->trans_block_rsv;
6616 ret = btrfs_update_inode(trans, root, inode);
6620 nr = trans->blocks_used;
6621 ret = btrfs_end_transaction_throttle(trans, root);
6622 btrfs_btree_balance_dirty(root, nr);
6626 btrfs_free_block_rsv(root, rsv);
6635 * create a new subvolume directory/inode (helper for the ioctl).
6637 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
6638 struct btrfs_root *new_root, u64 new_dirid)
6640 struct inode *inode;
6644 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
6645 new_dirid, S_IFDIR | 0700, &index);
6647 return PTR_ERR(inode);
6648 inode->i_op = &btrfs_dir_inode_operations;
6649 inode->i_fop = &btrfs_dir_file_operations;
6652 btrfs_i_size_write(inode, 0);
6654 err = btrfs_update_inode(trans, new_root, inode);
6661 struct inode *btrfs_alloc_inode(struct super_block *sb)
6663 struct btrfs_inode *ei;
6664 struct inode *inode;
6666 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
6671 ei->space_info = NULL;
6675 ei->last_sub_trans = 0;
6676 ei->logged_trans = 0;
6677 ei->delalloc_bytes = 0;
6678 ei->disk_i_size = 0;
6681 ei->index_cnt = (u64)-1;
6682 ei->last_unlink_trans = 0;
6684 spin_lock_init(&ei->lock);
6685 ei->outstanding_extents = 0;
6686 ei->reserved_extents = 0;
6688 ei->ordered_data_close = 0;
6689 ei->orphan_meta_reserved = 0;
6690 ei->dummy_inode = 0;
6692 ei->delalloc_meta_reserved = 0;
6693 ei->force_compress = BTRFS_COMPRESS_NONE;
6695 ei->delayed_node = NULL;
6697 inode = &ei->vfs_inode;
6698 extent_map_tree_init(&ei->extent_tree);
6699 extent_io_tree_init(&ei->io_tree, &inode->i_data);
6700 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
6701 mutex_init(&ei->log_mutex);
6702 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
6703 INIT_LIST_HEAD(&ei->i_orphan);
6704 INIT_LIST_HEAD(&ei->delalloc_inodes);
6705 INIT_LIST_HEAD(&ei->ordered_operations);
6706 RB_CLEAR_NODE(&ei->rb_node);
6711 static void btrfs_i_callback(struct rcu_head *head)
6713 struct inode *inode = container_of(head, struct inode, i_rcu);
6714 INIT_LIST_HEAD(&inode->i_dentry);
6715 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
6718 void btrfs_destroy_inode(struct inode *inode)
6720 struct btrfs_ordered_extent *ordered;
6721 struct btrfs_root *root = BTRFS_I(inode)->root;
6723 WARN_ON(!list_empty(&inode->i_dentry));
6724 WARN_ON(inode->i_data.nrpages);
6725 WARN_ON(BTRFS_I(inode)->outstanding_extents);
6726 WARN_ON(BTRFS_I(inode)->reserved_extents);
6727 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
6728 WARN_ON(BTRFS_I(inode)->csum_bytes);
6731 * This can happen where we create an inode, but somebody else also
6732 * created the same inode and we need to destroy the one we already
6739 * Make sure we're properly removed from the ordered operation
6743 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
6744 spin_lock(&root->fs_info->ordered_extent_lock);
6745 list_del_init(&BTRFS_I(inode)->ordered_operations);
6746 spin_unlock(&root->fs_info->ordered_extent_lock);
6749 spin_lock(&root->orphan_lock);
6750 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
6751 printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n",
6752 (unsigned long long)btrfs_ino(inode));
6753 list_del_init(&BTRFS_I(inode)->i_orphan);
6755 spin_unlock(&root->orphan_lock);
6758 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
6762 printk(KERN_ERR "btrfs found ordered "
6763 "extent %llu %llu on inode cleanup\n",
6764 (unsigned long long)ordered->file_offset,
6765 (unsigned long long)ordered->len);
6766 btrfs_remove_ordered_extent(inode, ordered);
6767 btrfs_put_ordered_extent(ordered);
6768 btrfs_put_ordered_extent(ordered);
6771 inode_tree_del(inode);
6772 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
6774 btrfs_remove_delayed_node(inode);
6775 call_rcu(&inode->i_rcu, btrfs_i_callback);
6778 int btrfs_drop_inode(struct inode *inode)
6780 struct btrfs_root *root = BTRFS_I(inode)->root;
6782 if (btrfs_root_refs(&root->root_item) == 0 &&
6783 !btrfs_is_free_space_inode(root, inode))
6786 return generic_drop_inode(inode);
6789 static void init_once(void *foo)
6791 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
6793 inode_init_once(&ei->vfs_inode);
6796 void btrfs_destroy_cachep(void)
6798 if (btrfs_inode_cachep)
6799 kmem_cache_destroy(btrfs_inode_cachep);
6800 if (btrfs_trans_handle_cachep)
6801 kmem_cache_destroy(btrfs_trans_handle_cachep);
6802 if (btrfs_transaction_cachep)
6803 kmem_cache_destroy(btrfs_transaction_cachep);
6804 if (btrfs_path_cachep)
6805 kmem_cache_destroy(btrfs_path_cachep);
6806 if (btrfs_free_space_cachep)
6807 kmem_cache_destroy(btrfs_free_space_cachep);
6810 int btrfs_init_cachep(void)
6812 btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
6813 sizeof(struct btrfs_inode), 0,
6814 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
6815 if (!btrfs_inode_cachep)
6818 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
6819 sizeof(struct btrfs_trans_handle), 0,
6820 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6821 if (!btrfs_trans_handle_cachep)
6824 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
6825 sizeof(struct btrfs_transaction), 0,
6826 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6827 if (!btrfs_transaction_cachep)
6830 btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
6831 sizeof(struct btrfs_path), 0,
6832 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6833 if (!btrfs_path_cachep)
6836 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space_cache",
6837 sizeof(struct btrfs_free_space), 0,
6838 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6839 if (!btrfs_free_space_cachep)
6844 btrfs_destroy_cachep();
6848 static int btrfs_getattr(struct vfsmount *mnt,
6849 struct dentry *dentry, struct kstat *stat)
6851 struct inode *inode = dentry->d_inode;
6852 u32 blocksize = inode->i_sb->s_blocksize;
6854 generic_fillattr(inode, stat);
6855 stat->dev = BTRFS_I(inode)->root->anon_dev;
6856 stat->blksize = PAGE_CACHE_SIZE;
6857 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
6858 ALIGN(BTRFS_I(inode)->delalloc_bytes, blocksize)) >> 9;
6863 * If a file is moved, it will inherit the cow and compression flags of the new
6866 static void fixup_inode_flags(struct inode *dir, struct inode *inode)
6868 struct btrfs_inode *b_dir = BTRFS_I(dir);
6869 struct btrfs_inode *b_inode = BTRFS_I(inode);
6871 if (b_dir->flags & BTRFS_INODE_NODATACOW)
6872 b_inode->flags |= BTRFS_INODE_NODATACOW;
6874 b_inode->flags &= ~BTRFS_INODE_NODATACOW;
6876 if (b_dir->flags & BTRFS_INODE_COMPRESS)
6877 b_inode->flags |= BTRFS_INODE_COMPRESS;
6879 b_inode->flags &= ~BTRFS_INODE_COMPRESS;
6882 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
6883 struct inode *new_dir, struct dentry *new_dentry)
6885 struct btrfs_trans_handle *trans;
6886 struct btrfs_root *root = BTRFS_I(old_dir)->root;
6887 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
6888 struct inode *new_inode = new_dentry->d_inode;
6889 struct inode *old_inode = old_dentry->d_inode;
6890 struct timespec ctime = CURRENT_TIME;
6894 u64 old_ino = btrfs_ino(old_inode);
6896 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
6899 /* we only allow rename subvolume link between subvolumes */
6900 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
6903 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
6904 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
6907 if (S_ISDIR(old_inode->i_mode) && new_inode &&
6908 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
6911 * we're using rename to replace one file with another.
6912 * and the replacement file is large. Start IO on it now so
6913 * we don't add too much work to the end of the transaction
6915 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
6916 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
6917 filemap_flush(old_inode->i_mapping);
6919 /* close the racy window with snapshot create/destroy ioctl */
6920 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
6921 down_read(&root->fs_info->subvol_sem);
6923 * We want to reserve the absolute worst case amount of items. So if
6924 * both inodes are subvols and we need to unlink them then that would
6925 * require 4 item modifications, but if they are both normal inodes it
6926 * would require 5 item modifications, so we'll assume their normal
6927 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
6928 * should cover the worst case number of items we'll modify.
6930 trans = btrfs_start_transaction(root, 20);
6931 if (IS_ERR(trans)) {
6932 ret = PTR_ERR(trans);
6937 btrfs_record_root_in_trans(trans, dest);
6939 ret = btrfs_set_inode_index(new_dir, &index);
6943 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6944 /* force full log commit if subvolume involved. */
6945 root->fs_info->last_trans_log_full_commit = trans->transid;
6947 ret = btrfs_insert_inode_ref(trans, dest,
6948 new_dentry->d_name.name,
6949 new_dentry->d_name.len,
6951 btrfs_ino(new_dir), index);
6955 * this is an ugly little race, but the rename is required
6956 * to make sure that if we crash, the inode is either at the
6957 * old name or the new one. pinning the log transaction lets
6958 * us make sure we don't allow a log commit to come in after
6959 * we unlink the name but before we add the new name back in.
6961 btrfs_pin_log_trans(root);
6964 * make sure the inode gets flushed if it is replacing
6967 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
6968 btrfs_add_ordered_operation(trans, root, old_inode);
6970 old_dir->i_ctime = old_dir->i_mtime = ctime;
6971 new_dir->i_ctime = new_dir->i_mtime = ctime;
6972 old_inode->i_ctime = ctime;
6974 if (old_dentry->d_parent != new_dentry->d_parent)
6975 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
6977 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6978 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
6979 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
6980 old_dentry->d_name.name,
6981 old_dentry->d_name.len);
6983 ret = __btrfs_unlink_inode(trans, root, old_dir,
6984 old_dentry->d_inode,
6985 old_dentry->d_name.name,
6986 old_dentry->d_name.len);
6988 ret = btrfs_update_inode(trans, root, old_inode);
6993 new_inode->i_ctime = CURRENT_TIME;
6994 if (unlikely(btrfs_ino(new_inode) ==
6995 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
6996 root_objectid = BTRFS_I(new_inode)->location.objectid;
6997 ret = btrfs_unlink_subvol(trans, dest, new_dir,
6999 new_dentry->d_name.name,
7000 new_dentry->d_name.len);
7001 BUG_ON(new_inode->i_nlink == 0);
7003 ret = btrfs_unlink_inode(trans, dest, new_dir,
7004 new_dentry->d_inode,
7005 new_dentry->d_name.name,
7006 new_dentry->d_name.len);
7009 if (new_inode->i_nlink == 0) {
7010 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
7015 fixup_inode_flags(new_dir, old_inode);
7017 ret = btrfs_add_link(trans, new_dir, old_inode,
7018 new_dentry->d_name.name,
7019 new_dentry->d_name.len, 0, index);
7022 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
7023 struct dentry *parent = new_dentry->d_parent;
7024 btrfs_log_new_name(trans, old_inode, old_dir, parent);
7025 btrfs_end_log_trans(root);
7028 btrfs_end_transaction_throttle(trans, root);
7030 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7031 up_read(&root->fs_info->subvol_sem);
7037 * some fairly slow code that needs optimization. This walks the list
7038 * of all the inodes with pending delalloc and forces them to disk.
7040 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
7042 struct list_head *head = &root->fs_info->delalloc_inodes;
7043 struct btrfs_inode *binode;
7044 struct inode *inode;
7046 if (root->fs_info->sb->s_flags & MS_RDONLY)
7049 spin_lock(&root->fs_info->delalloc_lock);
7050 while (!list_empty(head)) {
7051 binode = list_entry(head->next, struct btrfs_inode,
7053 inode = igrab(&binode->vfs_inode);
7055 list_del_init(&binode->delalloc_inodes);
7056 spin_unlock(&root->fs_info->delalloc_lock);
7058 filemap_flush(inode->i_mapping);
7060 btrfs_add_delayed_iput(inode);
7065 spin_lock(&root->fs_info->delalloc_lock);
7067 spin_unlock(&root->fs_info->delalloc_lock);
7069 /* the filemap_flush will queue IO into the worker threads, but
7070 * we have to make sure the IO is actually started and that
7071 * ordered extents get created before we return
7073 atomic_inc(&root->fs_info->async_submit_draining);
7074 while (atomic_read(&root->fs_info->nr_async_submits) ||
7075 atomic_read(&root->fs_info->async_delalloc_pages)) {
7076 wait_event(root->fs_info->async_submit_wait,
7077 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
7078 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
7080 atomic_dec(&root->fs_info->async_submit_draining);
7084 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
7085 const char *symname)
7087 struct btrfs_trans_handle *trans;
7088 struct btrfs_root *root = BTRFS_I(dir)->root;
7089 struct btrfs_path *path;
7090 struct btrfs_key key;
7091 struct inode *inode = NULL;
7099 struct btrfs_file_extent_item *ei;
7100 struct extent_buffer *leaf;
7101 unsigned long nr = 0;
7103 name_len = strlen(symname) + 1;
7104 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
7105 return -ENAMETOOLONG;
7108 * 2 items for inode item and ref
7109 * 2 items for dir items
7110 * 1 item for xattr if selinux is on
7112 trans = btrfs_start_transaction(root, 5);
7114 return PTR_ERR(trans);
7116 err = btrfs_find_free_ino(root, &objectid);
7120 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
7121 dentry->d_name.len, btrfs_ino(dir), objectid,
7122 S_IFLNK|S_IRWXUGO, &index);
7123 if (IS_ERR(inode)) {
7124 err = PTR_ERR(inode);
7128 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
7135 * If the active LSM wants to access the inode during
7136 * d_instantiate it needs these. Smack checks to see
7137 * if the filesystem supports xattrs by looking at the
7140 inode->i_fop = &btrfs_file_operations;
7141 inode->i_op = &btrfs_file_inode_operations;
7143 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
7147 inode->i_mapping->a_ops = &btrfs_aops;
7148 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7149 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
7154 path = btrfs_alloc_path();
7160 key.objectid = btrfs_ino(inode);
7162 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
7163 datasize = btrfs_file_extent_calc_inline_size(name_len);
7164 err = btrfs_insert_empty_item(trans, root, path, &key,
7168 btrfs_free_path(path);
7171 leaf = path->nodes[0];
7172 ei = btrfs_item_ptr(leaf, path->slots[0],
7173 struct btrfs_file_extent_item);
7174 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
7175 btrfs_set_file_extent_type(leaf, ei,
7176 BTRFS_FILE_EXTENT_INLINE);
7177 btrfs_set_file_extent_encryption(leaf, ei, 0);
7178 btrfs_set_file_extent_compression(leaf, ei, 0);
7179 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
7180 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
7182 ptr = btrfs_file_extent_inline_start(ei);
7183 write_extent_buffer(leaf, symname, ptr, name_len);
7184 btrfs_mark_buffer_dirty(leaf);
7185 btrfs_free_path(path);
7187 inode->i_op = &btrfs_symlink_inode_operations;
7188 inode->i_mapping->a_ops = &btrfs_symlink_aops;
7189 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7190 inode_set_bytes(inode, name_len);
7191 btrfs_i_size_write(inode, name_len - 1);
7192 err = btrfs_update_inode(trans, root, inode);
7197 nr = trans->blocks_used;
7198 btrfs_end_transaction_throttle(trans, root);
7200 inode_dec_link_count(inode);
7203 btrfs_btree_balance_dirty(root, nr);
7207 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
7208 u64 start, u64 num_bytes, u64 min_size,
7209 loff_t actual_len, u64 *alloc_hint,
7210 struct btrfs_trans_handle *trans)
7212 struct btrfs_root *root = BTRFS_I(inode)->root;
7213 struct btrfs_key ins;
7214 u64 cur_offset = start;
7217 bool own_trans = true;
7221 while (num_bytes > 0) {
7223 trans = btrfs_start_transaction(root, 3);
7224 if (IS_ERR(trans)) {
7225 ret = PTR_ERR(trans);
7230 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
7231 0, *alloc_hint, (u64)-1, &ins, 1);
7234 btrfs_end_transaction(trans, root);
7238 ret = insert_reserved_file_extent(trans, inode,
7239 cur_offset, ins.objectid,
7240 ins.offset, ins.offset,
7241 ins.offset, 0, 0, 0,
7242 BTRFS_FILE_EXTENT_PREALLOC);
7244 btrfs_drop_extent_cache(inode, cur_offset,
7245 cur_offset + ins.offset -1, 0);
7247 num_bytes -= ins.offset;
7248 cur_offset += ins.offset;
7249 *alloc_hint = ins.objectid + ins.offset;
7251 inode->i_ctime = CURRENT_TIME;
7252 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
7253 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
7254 (actual_len > inode->i_size) &&
7255 (cur_offset > inode->i_size)) {
7256 if (cur_offset > actual_len)
7257 i_size = actual_len;
7259 i_size = cur_offset;
7260 i_size_write(inode, i_size);
7261 btrfs_ordered_update_i_size(inode, i_size, NULL);
7264 ret = btrfs_update_inode(trans, root, inode);
7268 btrfs_end_transaction(trans, root);
7273 int btrfs_prealloc_file_range(struct inode *inode, int mode,
7274 u64 start, u64 num_bytes, u64 min_size,
7275 loff_t actual_len, u64 *alloc_hint)
7277 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7278 min_size, actual_len, alloc_hint,
7282 int btrfs_prealloc_file_range_trans(struct inode *inode,
7283 struct btrfs_trans_handle *trans, int mode,
7284 u64 start, u64 num_bytes, u64 min_size,
7285 loff_t actual_len, u64 *alloc_hint)
7287 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7288 min_size, actual_len, alloc_hint, trans);
7291 static int btrfs_set_page_dirty(struct page *page)
7293 return __set_page_dirty_nobuffers(page);
7296 static int btrfs_permission(struct inode *inode, int mask)
7298 struct btrfs_root *root = BTRFS_I(inode)->root;
7299 umode_t mode = inode->i_mode;
7301 if (mask & MAY_WRITE &&
7302 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
7303 if (btrfs_root_readonly(root))
7305 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
7308 return generic_permission(inode, mask);
7311 static const struct inode_operations btrfs_dir_inode_operations = {
7312 .getattr = btrfs_getattr,
7313 .lookup = btrfs_lookup,
7314 .create = btrfs_create,
7315 .unlink = btrfs_unlink,
7317 .mkdir = btrfs_mkdir,
7318 .rmdir = btrfs_rmdir,
7319 .rename = btrfs_rename,
7320 .symlink = btrfs_symlink,
7321 .setattr = btrfs_setattr,
7322 .mknod = btrfs_mknod,
7323 .setxattr = btrfs_setxattr,
7324 .getxattr = btrfs_getxattr,
7325 .listxattr = btrfs_listxattr,
7326 .removexattr = btrfs_removexattr,
7327 .permission = btrfs_permission,
7328 .get_acl = btrfs_get_acl,
7330 static const struct inode_operations btrfs_dir_ro_inode_operations = {
7331 .lookup = btrfs_lookup,
7332 .permission = btrfs_permission,
7333 .get_acl = btrfs_get_acl,
7336 static const struct file_operations btrfs_dir_file_operations = {
7337 .llseek = generic_file_llseek,
7338 .read = generic_read_dir,
7339 .readdir = btrfs_real_readdir,
7340 .unlocked_ioctl = btrfs_ioctl,
7341 #ifdef CONFIG_COMPAT
7342 .compat_ioctl = btrfs_ioctl,
7344 .release = btrfs_release_file,
7345 .fsync = btrfs_sync_file,
7348 static struct extent_io_ops btrfs_extent_io_ops = {
7349 .fill_delalloc = run_delalloc_range,
7350 .submit_bio_hook = btrfs_submit_bio_hook,
7351 .merge_bio_hook = btrfs_merge_bio_hook,
7352 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
7353 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
7354 .writepage_start_hook = btrfs_writepage_start_hook,
7355 .set_bit_hook = btrfs_set_bit_hook,
7356 .clear_bit_hook = btrfs_clear_bit_hook,
7357 .merge_extent_hook = btrfs_merge_extent_hook,
7358 .split_extent_hook = btrfs_split_extent_hook,
7362 * btrfs doesn't support the bmap operation because swapfiles
7363 * use bmap to make a mapping of extents in the file. They assume
7364 * these extents won't change over the life of the file and they
7365 * use the bmap result to do IO directly to the drive.
7367 * the btrfs bmap call would return logical addresses that aren't
7368 * suitable for IO and they also will change frequently as COW
7369 * operations happen. So, swapfile + btrfs == corruption.
7371 * For now we're avoiding this by dropping bmap.
7373 static const struct address_space_operations btrfs_aops = {
7374 .readpage = btrfs_readpage,
7375 .writepage = btrfs_writepage,
7376 .writepages = btrfs_writepages,
7377 .readpages = btrfs_readpages,
7378 .direct_IO = btrfs_direct_IO,
7379 .invalidatepage = btrfs_invalidatepage,
7380 .releasepage = btrfs_releasepage,
7381 .set_page_dirty = btrfs_set_page_dirty,
7382 .error_remove_page = generic_error_remove_page,
7385 static const struct address_space_operations btrfs_symlink_aops = {
7386 .readpage = btrfs_readpage,
7387 .writepage = btrfs_writepage,
7388 .invalidatepage = btrfs_invalidatepage,
7389 .releasepage = btrfs_releasepage,
7392 static const struct inode_operations btrfs_file_inode_operations = {
7393 .getattr = btrfs_getattr,
7394 .setattr = btrfs_setattr,
7395 .setxattr = btrfs_setxattr,
7396 .getxattr = btrfs_getxattr,
7397 .listxattr = btrfs_listxattr,
7398 .removexattr = btrfs_removexattr,
7399 .permission = btrfs_permission,
7400 .fiemap = btrfs_fiemap,
7401 .get_acl = btrfs_get_acl,
7403 static const struct inode_operations btrfs_special_inode_operations = {
7404 .getattr = btrfs_getattr,
7405 .setattr = btrfs_setattr,
7406 .permission = btrfs_permission,
7407 .setxattr = btrfs_setxattr,
7408 .getxattr = btrfs_getxattr,
7409 .listxattr = btrfs_listxattr,
7410 .removexattr = btrfs_removexattr,
7411 .get_acl = btrfs_get_acl,
7413 static const struct inode_operations btrfs_symlink_inode_operations = {
7414 .readlink = generic_readlink,
7415 .follow_link = page_follow_link_light,
7416 .put_link = page_put_link,
7417 .getattr = btrfs_getattr,
7418 .permission = btrfs_permission,
7419 .setxattr = btrfs_setxattr,
7420 .getxattr = btrfs_getxattr,
7421 .listxattr = btrfs_listxattr,
7422 .removexattr = btrfs_removexattr,
7423 .get_acl = btrfs_get_acl,
7426 const struct dentry_operations btrfs_dentry_operations = {
7427 .d_delete = btrfs_dentry_delete,
7428 .d_release = btrfs_dentry_release,