2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
41 #include <linux/mount.h>
42 #include <linux/aio.h>
46 #include "transaction.h"
47 #include "btrfs_inode.h"
49 #include "print-tree.h"
50 #include "ordered-data.h"
54 #include "compression.h"
56 #include "free-space-cache.h"
57 #include "inode-map.h"
59 struct btrfs_iget_args {
61 struct btrfs_root *root;
64 static const struct inode_operations btrfs_dir_inode_operations;
65 static const struct inode_operations btrfs_symlink_inode_operations;
66 static const struct inode_operations btrfs_dir_ro_inode_operations;
67 static const struct inode_operations btrfs_special_inode_operations;
68 static const struct inode_operations btrfs_file_inode_operations;
69 static const struct address_space_operations btrfs_aops;
70 static const struct address_space_operations btrfs_symlink_aops;
71 static const struct file_operations btrfs_dir_file_operations;
72 static struct extent_io_ops btrfs_extent_io_ops;
74 static struct kmem_cache *btrfs_inode_cachep;
75 static struct kmem_cache *btrfs_delalloc_work_cachep;
76 struct kmem_cache *btrfs_trans_handle_cachep;
77 struct kmem_cache *btrfs_transaction_cachep;
78 struct kmem_cache *btrfs_path_cachep;
79 struct kmem_cache *btrfs_free_space_cachep;
82 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
83 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
84 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
85 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
86 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
87 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
88 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
89 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
92 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
93 static int btrfs_truncate(struct inode *inode);
94 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
95 static noinline int cow_file_range(struct inode *inode,
96 struct page *locked_page,
97 u64 start, u64 end, int *page_started,
98 unsigned long *nr_written, int unlock);
99 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
100 u64 len, u64 orig_start,
101 u64 block_start, u64 block_len,
102 u64 orig_block_len, int type);
104 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
105 struct inode *inode, struct inode *dir,
106 const struct qstr *qstr)
110 err = btrfs_init_acl(trans, inode, dir);
112 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
117 * this does all the hard work for inserting an inline extent into
118 * the btree. The caller should have done a btrfs_drop_extents so that
119 * no overlapping inline items exist in the btree
121 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
122 struct btrfs_root *root, struct inode *inode,
123 u64 start, size_t size, size_t compressed_size,
125 struct page **compressed_pages)
127 struct btrfs_key key;
128 struct btrfs_path *path;
129 struct extent_buffer *leaf;
130 struct page *page = NULL;
133 struct btrfs_file_extent_item *ei;
136 size_t cur_size = size;
138 unsigned long offset;
140 if (compressed_size && compressed_pages)
141 cur_size = compressed_size;
143 path = btrfs_alloc_path();
147 path->leave_spinning = 1;
149 key.objectid = btrfs_ino(inode);
151 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
152 datasize = btrfs_file_extent_calc_inline_size(cur_size);
154 inode_add_bytes(inode, size);
155 ret = btrfs_insert_empty_item(trans, root, path, &key,
161 leaf = path->nodes[0];
162 ei = btrfs_item_ptr(leaf, path->slots[0],
163 struct btrfs_file_extent_item);
164 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
165 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
166 btrfs_set_file_extent_encryption(leaf, ei, 0);
167 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
168 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
169 ptr = btrfs_file_extent_inline_start(ei);
171 if (compress_type != BTRFS_COMPRESS_NONE) {
174 while (compressed_size > 0) {
175 cpage = compressed_pages[i];
176 cur_size = min_t(unsigned long, compressed_size,
179 kaddr = kmap_atomic(cpage);
180 write_extent_buffer(leaf, kaddr, ptr, cur_size);
181 kunmap_atomic(kaddr);
185 compressed_size -= cur_size;
187 btrfs_set_file_extent_compression(leaf, ei,
190 page = find_get_page(inode->i_mapping,
191 start >> PAGE_CACHE_SHIFT);
192 btrfs_set_file_extent_compression(leaf, ei, 0);
193 kaddr = kmap_atomic(page);
194 offset = start & (PAGE_CACHE_SIZE - 1);
195 write_extent_buffer(leaf, kaddr + offset, ptr, size);
196 kunmap_atomic(kaddr);
197 page_cache_release(page);
199 btrfs_mark_buffer_dirty(leaf);
200 btrfs_free_path(path);
203 * we're an inline extent, so nobody can
204 * extend the file past i_size without locking
205 * a page we already have locked.
207 * We must do any isize and inode updates
208 * before we unlock the pages. Otherwise we
209 * could end up racing with unlink.
211 BTRFS_I(inode)->disk_i_size = inode->i_size;
212 ret = btrfs_update_inode(trans, root, inode);
216 btrfs_free_path(path);
222 * conditionally insert an inline extent into the file. This
223 * does the checks required to make sure the data is small enough
224 * to fit as an inline extent.
226 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
227 struct btrfs_root *root,
228 struct inode *inode, u64 start, u64 end,
229 size_t compressed_size, int compress_type,
230 struct page **compressed_pages)
232 u64 isize = i_size_read(inode);
233 u64 actual_end = min(end + 1, isize);
234 u64 inline_len = actual_end - start;
235 u64 aligned_end = (end + root->sectorsize - 1) &
236 ~((u64)root->sectorsize - 1);
237 u64 data_len = inline_len;
241 data_len = compressed_size;
244 actual_end >= PAGE_CACHE_SIZE ||
245 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
247 (actual_end & (root->sectorsize - 1)) == 0) ||
249 data_len > root->fs_info->max_inline) {
253 ret = btrfs_drop_extents(trans, root, inode, start, aligned_end, 1);
257 if (isize > actual_end)
258 inline_len = min_t(u64, isize, actual_end);
259 ret = insert_inline_extent(trans, root, inode, start,
260 inline_len, compressed_size,
261 compress_type, compressed_pages);
262 if (ret && ret != -ENOSPC) {
263 btrfs_abort_transaction(trans, root, ret);
265 } else if (ret == -ENOSPC) {
269 btrfs_delalloc_release_metadata(inode, end + 1 - start);
270 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
274 struct async_extent {
279 unsigned long nr_pages;
281 struct list_head list;
286 struct btrfs_root *root;
287 struct page *locked_page;
290 struct list_head extents;
291 struct btrfs_work work;
294 static noinline int add_async_extent(struct async_cow *cow,
295 u64 start, u64 ram_size,
298 unsigned long nr_pages,
301 struct async_extent *async_extent;
303 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
304 BUG_ON(!async_extent); /* -ENOMEM */
305 async_extent->start = start;
306 async_extent->ram_size = ram_size;
307 async_extent->compressed_size = compressed_size;
308 async_extent->pages = pages;
309 async_extent->nr_pages = nr_pages;
310 async_extent->compress_type = compress_type;
311 list_add_tail(&async_extent->list, &cow->extents);
316 * we create compressed extents in two phases. The first
317 * phase compresses a range of pages that have already been
318 * locked (both pages and state bits are locked).
320 * This is done inside an ordered work queue, and the compression
321 * is spread across many cpus. The actual IO submission is step
322 * two, and the ordered work queue takes care of making sure that
323 * happens in the same order things were put onto the queue by
324 * writepages and friends.
326 * If this code finds it can't get good compression, it puts an
327 * entry onto the work queue to write the uncompressed bytes. This
328 * makes sure that both compressed inodes and uncompressed inodes
329 * are written in the same order that the flusher thread sent them
332 static noinline int compress_file_range(struct inode *inode,
333 struct page *locked_page,
335 struct async_cow *async_cow,
338 struct btrfs_root *root = BTRFS_I(inode)->root;
339 struct btrfs_trans_handle *trans;
341 u64 blocksize = root->sectorsize;
343 u64 isize = i_size_read(inode);
345 struct page **pages = NULL;
346 unsigned long nr_pages;
347 unsigned long nr_pages_ret = 0;
348 unsigned long total_compressed = 0;
349 unsigned long total_in = 0;
350 unsigned long max_compressed = 128 * 1024;
351 unsigned long max_uncompressed = 128 * 1024;
354 int compress_type = root->fs_info->compress_type;
356 /* if this is a small write inside eof, kick off a defrag */
357 if ((end - start + 1) < 16 * 1024 &&
358 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
359 btrfs_add_inode_defrag(NULL, inode);
361 actual_end = min_t(u64, isize, end + 1);
364 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
365 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
368 * we don't want to send crud past the end of i_size through
369 * compression, that's just a waste of CPU time. So, if the
370 * end of the file is before the start of our current
371 * requested range of bytes, we bail out to the uncompressed
372 * cleanup code that can deal with all of this.
374 * It isn't really the fastest way to fix things, but this is a
375 * very uncommon corner.
377 if (actual_end <= start)
378 goto cleanup_and_bail_uncompressed;
380 total_compressed = actual_end - start;
382 /* we want to make sure that amount of ram required to uncompress
383 * an extent is reasonable, so we limit the total size in ram
384 * of a compressed extent to 128k. This is a crucial number
385 * because it also controls how easily we can spread reads across
386 * cpus for decompression.
388 * We also want to make sure the amount of IO required to do
389 * a random read is reasonably small, so we limit the size of
390 * a compressed extent to 128k.
392 total_compressed = min(total_compressed, max_uncompressed);
393 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
394 num_bytes = max(blocksize, num_bytes);
399 * we do compression for mount -o compress and when the
400 * inode has not been flagged as nocompress. This flag can
401 * change at any time if we discover bad compression ratios.
403 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
404 (btrfs_test_opt(root, COMPRESS) ||
405 (BTRFS_I(inode)->force_compress) ||
406 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
408 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
410 /* just bail out to the uncompressed code */
414 if (BTRFS_I(inode)->force_compress)
415 compress_type = BTRFS_I(inode)->force_compress;
417 ret = btrfs_compress_pages(compress_type,
418 inode->i_mapping, start,
419 total_compressed, pages,
420 nr_pages, &nr_pages_ret,
426 unsigned long offset = total_compressed &
427 (PAGE_CACHE_SIZE - 1);
428 struct page *page = pages[nr_pages_ret - 1];
431 /* zero the tail end of the last page, we might be
432 * sending it down to disk
435 kaddr = kmap_atomic(page);
436 memset(kaddr + offset, 0,
437 PAGE_CACHE_SIZE - offset);
438 kunmap_atomic(kaddr);
445 trans = btrfs_join_transaction(root);
447 ret = PTR_ERR(trans);
449 goto cleanup_and_out;
451 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
453 /* lets try to make an inline extent */
454 if (ret || total_in < (actual_end - start)) {
455 /* we didn't compress the entire range, try
456 * to make an uncompressed inline extent.
458 ret = cow_file_range_inline(trans, root, inode,
459 start, end, 0, 0, NULL);
461 /* try making a compressed inline extent */
462 ret = cow_file_range_inline(trans, root, inode,
465 compress_type, pages);
469 * inline extent creation worked or returned error,
470 * we don't need to create any more async work items.
471 * Unlock and free up our temp pages.
473 extent_clear_unlock_delalloc(inode,
474 &BTRFS_I(inode)->io_tree,
476 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
477 EXTENT_CLEAR_DELALLOC |
478 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
480 btrfs_end_transaction(trans, root);
483 btrfs_end_transaction(trans, root);
488 * we aren't doing an inline extent round the compressed size
489 * up to a block size boundary so the allocator does sane
492 total_compressed = (total_compressed + blocksize - 1) &
496 * one last check to make sure the compression is really a
497 * win, compare the page count read with the blocks on disk
499 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
500 ~(PAGE_CACHE_SIZE - 1);
501 if (total_compressed >= total_in) {
504 num_bytes = total_in;
507 if (!will_compress && pages) {
509 * the compression code ran but failed to make things smaller,
510 * free any pages it allocated and our page pointer array
512 for (i = 0; i < nr_pages_ret; i++) {
513 WARN_ON(pages[i]->mapping);
514 page_cache_release(pages[i]);
518 total_compressed = 0;
521 /* flag the file so we don't compress in the future */
522 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
523 !(BTRFS_I(inode)->force_compress)) {
524 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
530 /* the async work queues will take care of doing actual
531 * allocation on disk for these compressed pages,
532 * and will submit them to the elevator.
534 add_async_extent(async_cow, start, num_bytes,
535 total_compressed, pages, nr_pages_ret,
538 if (start + num_bytes < end) {
545 cleanup_and_bail_uncompressed:
547 * No compression, but we still need to write the pages in
548 * the file we've been given so far. redirty the locked
549 * page if it corresponds to our extent and set things up
550 * for the async work queue to run cow_file_range to do
551 * the normal delalloc dance
553 if (page_offset(locked_page) >= start &&
554 page_offset(locked_page) <= end) {
555 __set_page_dirty_nobuffers(locked_page);
556 /* unlocked later on in the async handlers */
558 add_async_extent(async_cow, start, end - start + 1,
559 0, NULL, 0, BTRFS_COMPRESS_NONE);
567 for (i = 0; i < nr_pages_ret; i++) {
568 WARN_ON(pages[i]->mapping);
569 page_cache_release(pages[i]);
576 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
578 EXTENT_CLEAR_UNLOCK_PAGE |
580 EXTENT_CLEAR_DELALLOC |
581 EXTENT_SET_WRITEBACK |
582 EXTENT_END_WRITEBACK);
583 if (!trans || IS_ERR(trans))
584 btrfs_error(root->fs_info, ret, "Failed to join transaction");
586 btrfs_abort_transaction(trans, root, ret);
591 * phase two of compressed writeback. This is the ordered portion
592 * of the code, which only gets called in the order the work was
593 * queued. We walk all the async extents created by compress_file_range
594 * and send them down to the disk.
596 static noinline int submit_compressed_extents(struct inode *inode,
597 struct async_cow *async_cow)
599 struct async_extent *async_extent;
601 struct btrfs_trans_handle *trans;
602 struct btrfs_key ins;
603 struct extent_map *em;
604 struct btrfs_root *root = BTRFS_I(inode)->root;
605 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
606 struct extent_io_tree *io_tree;
609 if (list_empty(&async_cow->extents))
613 while (!list_empty(&async_cow->extents)) {
614 async_extent = list_entry(async_cow->extents.next,
615 struct async_extent, list);
616 list_del(&async_extent->list);
618 io_tree = &BTRFS_I(inode)->io_tree;
621 /* did the compression code fall back to uncompressed IO? */
622 if (!async_extent->pages) {
623 int page_started = 0;
624 unsigned long nr_written = 0;
626 lock_extent(io_tree, async_extent->start,
627 async_extent->start +
628 async_extent->ram_size - 1);
630 /* allocate blocks */
631 ret = cow_file_range(inode, async_cow->locked_page,
633 async_extent->start +
634 async_extent->ram_size - 1,
635 &page_started, &nr_written, 0);
640 * if page_started, cow_file_range inserted an
641 * inline extent and took care of all the unlocking
642 * and IO for us. Otherwise, we need to submit
643 * all those pages down to the drive.
645 if (!page_started && !ret)
646 extent_write_locked_range(io_tree,
647 inode, async_extent->start,
648 async_extent->start +
649 async_extent->ram_size - 1,
657 lock_extent(io_tree, async_extent->start,
658 async_extent->start + async_extent->ram_size - 1);
660 trans = btrfs_join_transaction(root);
662 ret = PTR_ERR(trans);
664 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
665 ret = btrfs_reserve_extent(trans, root,
666 async_extent->compressed_size,
667 async_extent->compressed_size,
668 0, alloc_hint, &ins, 1);
669 if (ret && ret != -ENOSPC)
670 btrfs_abort_transaction(trans, root, ret);
671 btrfs_end_transaction(trans, root);
676 for (i = 0; i < async_extent->nr_pages; i++) {
677 WARN_ON(async_extent->pages[i]->mapping);
678 page_cache_release(async_extent->pages[i]);
680 kfree(async_extent->pages);
681 async_extent->nr_pages = 0;
682 async_extent->pages = NULL;
683 unlock_extent(io_tree, async_extent->start,
684 async_extent->start +
685 async_extent->ram_size - 1);
688 goto out_free; /* JDM: Requeue? */
692 * here we're doing allocation and writeback of the
695 btrfs_drop_extent_cache(inode, async_extent->start,
696 async_extent->start +
697 async_extent->ram_size - 1, 0);
699 em = alloc_extent_map();
700 BUG_ON(!em); /* -ENOMEM */
701 em->start = async_extent->start;
702 em->len = async_extent->ram_size;
703 em->orig_start = em->start;
705 em->block_start = ins.objectid;
706 em->block_len = ins.offset;
707 em->orig_block_len = ins.offset;
708 em->bdev = root->fs_info->fs_devices->latest_bdev;
709 em->compress_type = async_extent->compress_type;
710 set_bit(EXTENT_FLAG_PINNED, &em->flags);
711 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
715 write_lock(&em_tree->lock);
716 ret = add_extent_mapping(em_tree, em);
719 &em_tree->modified_extents);
720 write_unlock(&em_tree->lock);
721 if (ret != -EEXIST) {
725 btrfs_drop_extent_cache(inode, async_extent->start,
726 async_extent->start +
727 async_extent->ram_size - 1, 0);
730 ret = btrfs_add_ordered_extent_compress(inode,
733 async_extent->ram_size,
735 BTRFS_ORDERED_COMPRESSED,
736 async_extent->compress_type);
737 BUG_ON(ret); /* -ENOMEM */
740 * clear dirty, set writeback and unlock the pages.
742 extent_clear_unlock_delalloc(inode,
743 &BTRFS_I(inode)->io_tree,
745 async_extent->start +
746 async_extent->ram_size - 1,
747 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
748 EXTENT_CLEAR_UNLOCK |
749 EXTENT_CLEAR_DELALLOC |
750 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
752 ret = btrfs_submit_compressed_write(inode,
754 async_extent->ram_size,
756 ins.offset, async_extent->pages,
757 async_extent->nr_pages);
759 BUG_ON(ret); /* -ENOMEM */
760 alloc_hint = ins.objectid + ins.offset;
772 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
775 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
776 struct extent_map *em;
779 read_lock(&em_tree->lock);
780 em = search_extent_mapping(em_tree, start, num_bytes);
783 * if block start isn't an actual block number then find the
784 * first block in this inode and use that as a hint. If that
785 * block is also bogus then just don't worry about it.
787 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
789 em = search_extent_mapping(em_tree, 0, 0);
790 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
791 alloc_hint = em->block_start;
795 alloc_hint = em->block_start;
799 read_unlock(&em_tree->lock);
805 * when extent_io.c finds a delayed allocation range in the file,
806 * the call backs end up in this code. The basic idea is to
807 * allocate extents on disk for the range, and create ordered data structs
808 * in ram to track those extents.
810 * locked_page is the page that writepage had locked already. We use
811 * it to make sure we don't do extra locks or unlocks.
813 * *page_started is set to one if we unlock locked_page and do everything
814 * required to start IO on it. It may be clean and already done with
817 static noinline int __cow_file_range(struct btrfs_trans_handle *trans,
819 struct btrfs_root *root,
820 struct page *locked_page,
821 u64 start, u64 end, int *page_started,
822 unsigned long *nr_written,
827 unsigned long ram_size;
830 u64 blocksize = root->sectorsize;
831 struct btrfs_key ins;
832 struct extent_map *em;
833 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
836 BUG_ON(btrfs_is_free_space_inode(inode));
838 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
839 num_bytes = max(blocksize, num_bytes);
840 disk_num_bytes = num_bytes;
842 /* if this is a small write inside eof, kick off defrag */
843 if (num_bytes < 64 * 1024 &&
844 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
845 btrfs_add_inode_defrag(trans, inode);
848 /* lets try to make an inline extent */
849 ret = cow_file_range_inline(trans, root, inode,
850 start, end, 0, 0, NULL);
852 extent_clear_unlock_delalloc(inode,
853 &BTRFS_I(inode)->io_tree,
855 EXTENT_CLEAR_UNLOCK_PAGE |
856 EXTENT_CLEAR_UNLOCK |
857 EXTENT_CLEAR_DELALLOC |
859 EXTENT_SET_WRITEBACK |
860 EXTENT_END_WRITEBACK);
862 *nr_written = *nr_written +
863 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
866 } else if (ret < 0) {
867 btrfs_abort_transaction(trans, root, ret);
872 BUG_ON(disk_num_bytes >
873 btrfs_super_total_bytes(root->fs_info->super_copy));
875 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
876 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
878 while (disk_num_bytes > 0) {
881 cur_alloc_size = disk_num_bytes;
882 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
883 root->sectorsize, 0, alloc_hint,
886 btrfs_abort_transaction(trans, root, ret);
890 em = alloc_extent_map();
891 BUG_ON(!em); /* -ENOMEM */
893 em->orig_start = em->start;
894 ram_size = ins.offset;
895 em->len = ins.offset;
897 em->block_start = ins.objectid;
898 em->block_len = ins.offset;
899 em->orig_block_len = ins.offset;
900 em->bdev = root->fs_info->fs_devices->latest_bdev;
901 set_bit(EXTENT_FLAG_PINNED, &em->flags);
905 write_lock(&em_tree->lock);
906 ret = add_extent_mapping(em_tree, em);
909 &em_tree->modified_extents);
910 write_unlock(&em_tree->lock);
911 if (ret != -EEXIST) {
915 btrfs_drop_extent_cache(inode, start,
916 start + ram_size - 1, 0);
919 cur_alloc_size = ins.offset;
920 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
921 ram_size, cur_alloc_size, 0);
922 BUG_ON(ret); /* -ENOMEM */
924 if (root->root_key.objectid ==
925 BTRFS_DATA_RELOC_TREE_OBJECTID) {
926 ret = btrfs_reloc_clone_csums(inode, start,
929 btrfs_abort_transaction(trans, root, ret);
934 if (disk_num_bytes < cur_alloc_size)
937 /* we're not doing compressed IO, don't unlock the first
938 * page (which the caller expects to stay locked), don't
939 * clear any dirty bits and don't set any writeback bits
941 * Do set the Private2 bit so we know this page was properly
942 * setup for writepage
944 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
945 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
948 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
949 start, start + ram_size - 1,
951 disk_num_bytes -= cur_alloc_size;
952 num_bytes -= cur_alloc_size;
953 alloc_hint = ins.objectid + ins.offset;
954 start += cur_alloc_size;
960 extent_clear_unlock_delalloc(inode,
961 &BTRFS_I(inode)->io_tree,
962 start, end, locked_page,
963 EXTENT_CLEAR_UNLOCK_PAGE |
964 EXTENT_CLEAR_UNLOCK |
965 EXTENT_CLEAR_DELALLOC |
967 EXTENT_SET_WRITEBACK |
968 EXTENT_END_WRITEBACK);
973 static noinline int cow_file_range(struct inode *inode,
974 struct page *locked_page,
975 u64 start, u64 end, int *page_started,
976 unsigned long *nr_written,
979 struct btrfs_trans_handle *trans;
980 struct btrfs_root *root = BTRFS_I(inode)->root;
983 trans = btrfs_join_transaction(root);
985 extent_clear_unlock_delalloc(inode,
986 &BTRFS_I(inode)->io_tree,
987 start, end, locked_page,
988 EXTENT_CLEAR_UNLOCK_PAGE |
989 EXTENT_CLEAR_UNLOCK |
990 EXTENT_CLEAR_DELALLOC |
992 EXTENT_SET_WRITEBACK |
993 EXTENT_END_WRITEBACK);
994 return PTR_ERR(trans);
996 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
998 ret = __cow_file_range(trans, inode, root, locked_page, start, end,
999 page_started, nr_written, unlock);
1001 btrfs_end_transaction(trans, root);
1007 * work queue call back to started compression on a file and pages
1009 static noinline void async_cow_start(struct btrfs_work *work)
1011 struct async_cow *async_cow;
1013 async_cow = container_of(work, struct async_cow, work);
1015 compress_file_range(async_cow->inode, async_cow->locked_page,
1016 async_cow->start, async_cow->end, async_cow,
1018 if (num_added == 0) {
1019 btrfs_add_delayed_iput(async_cow->inode);
1020 async_cow->inode = NULL;
1025 * work queue call back to submit previously compressed pages
1027 static noinline void async_cow_submit(struct btrfs_work *work)
1029 struct async_cow *async_cow;
1030 struct btrfs_root *root;
1031 unsigned long nr_pages;
1033 async_cow = container_of(work, struct async_cow, work);
1035 root = async_cow->root;
1036 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1039 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1041 waitqueue_active(&root->fs_info->async_submit_wait))
1042 wake_up(&root->fs_info->async_submit_wait);
1044 if (async_cow->inode)
1045 submit_compressed_extents(async_cow->inode, async_cow);
1048 static noinline void async_cow_free(struct btrfs_work *work)
1050 struct async_cow *async_cow;
1051 async_cow = container_of(work, struct async_cow, work);
1052 if (async_cow->inode)
1053 btrfs_add_delayed_iput(async_cow->inode);
1057 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1058 u64 start, u64 end, int *page_started,
1059 unsigned long *nr_written)
1061 struct async_cow *async_cow;
1062 struct btrfs_root *root = BTRFS_I(inode)->root;
1063 unsigned long nr_pages;
1065 int limit = 10 * 1024 * 1024;
1067 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1068 1, 0, NULL, GFP_NOFS);
1069 while (start < end) {
1070 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1071 BUG_ON(!async_cow); /* -ENOMEM */
1072 async_cow->inode = igrab(inode);
1073 async_cow->root = root;
1074 async_cow->locked_page = locked_page;
1075 async_cow->start = start;
1077 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1080 cur_end = min(end, start + 512 * 1024 - 1);
1082 async_cow->end = cur_end;
1083 INIT_LIST_HEAD(&async_cow->extents);
1085 async_cow->work.func = async_cow_start;
1086 async_cow->work.ordered_func = async_cow_submit;
1087 async_cow->work.ordered_free = async_cow_free;
1088 async_cow->work.flags = 0;
1090 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1092 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1094 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1097 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1098 wait_event(root->fs_info->async_submit_wait,
1099 (atomic_read(&root->fs_info->async_delalloc_pages) <
1103 while (atomic_read(&root->fs_info->async_submit_draining) &&
1104 atomic_read(&root->fs_info->async_delalloc_pages)) {
1105 wait_event(root->fs_info->async_submit_wait,
1106 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1110 *nr_written += nr_pages;
1111 start = cur_end + 1;
1117 static noinline int csum_exist_in_range(struct btrfs_root *root,
1118 u64 bytenr, u64 num_bytes)
1121 struct btrfs_ordered_sum *sums;
1124 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1125 bytenr + num_bytes - 1, &list, 0);
1126 if (ret == 0 && list_empty(&list))
1129 while (!list_empty(&list)) {
1130 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1131 list_del(&sums->list);
1138 * when nowcow writeback call back. This checks for snapshots or COW copies
1139 * of the extents that exist in the file, and COWs the file as required.
1141 * If no cow copies or snapshots exist, we write directly to the existing
1144 static noinline int run_delalloc_nocow(struct inode *inode,
1145 struct page *locked_page,
1146 u64 start, u64 end, int *page_started, int force,
1147 unsigned long *nr_written)
1149 struct btrfs_root *root = BTRFS_I(inode)->root;
1150 struct btrfs_trans_handle *trans;
1151 struct extent_buffer *leaf;
1152 struct btrfs_path *path;
1153 struct btrfs_file_extent_item *fi;
1154 struct btrfs_key found_key;
1168 u64 ino = btrfs_ino(inode);
1170 path = btrfs_alloc_path();
1172 extent_clear_unlock_delalloc(inode,
1173 &BTRFS_I(inode)->io_tree,
1174 start, end, locked_page,
1175 EXTENT_CLEAR_UNLOCK_PAGE |
1176 EXTENT_CLEAR_UNLOCK |
1177 EXTENT_CLEAR_DELALLOC |
1178 EXTENT_CLEAR_DIRTY |
1179 EXTENT_SET_WRITEBACK |
1180 EXTENT_END_WRITEBACK);
1184 nolock = btrfs_is_free_space_inode(inode);
1187 trans = btrfs_join_transaction_nolock(root);
1189 trans = btrfs_join_transaction(root);
1191 if (IS_ERR(trans)) {
1192 extent_clear_unlock_delalloc(inode,
1193 &BTRFS_I(inode)->io_tree,
1194 start, end, locked_page,
1195 EXTENT_CLEAR_UNLOCK_PAGE |
1196 EXTENT_CLEAR_UNLOCK |
1197 EXTENT_CLEAR_DELALLOC |
1198 EXTENT_CLEAR_DIRTY |
1199 EXTENT_SET_WRITEBACK |
1200 EXTENT_END_WRITEBACK);
1201 btrfs_free_path(path);
1202 return PTR_ERR(trans);
1205 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1207 cow_start = (u64)-1;
1210 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1213 btrfs_abort_transaction(trans, root, ret);
1216 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1217 leaf = path->nodes[0];
1218 btrfs_item_key_to_cpu(leaf, &found_key,
1219 path->slots[0] - 1);
1220 if (found_key.objectid == ino &&
1221 found_key.type == BTRFS_EXTENT_DATA_KEY)
1226 leaf = path->nodes[0];
1227 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1228 ret = btrfs_next_leaf(root, path);
1230 btrfs_abort_transaction(trans, root, ret);
1235 leaf = path->nodes[0];
1241 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1243 if (found_key.objectid > ino ||
1244 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1245 found_key.offset > end)
1248 if (found_key.offset > cur_offset) {
1249 extent_end = found_key.offset;
1254 fi = btrfs_item_ptr(leaf, path->slots[0],
1255 struct btrfs_file_extent_item);
1256 extent_type = btrfs_file_extent_type(leaf, fi);
1258 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1259 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1260 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1261 extent_offset = btrfs_file_extent_offset(leaf, fi);
1262 extent_end = found_key.offset +
1263 btrfs_file_extent_num_bytes(leaf, fi);
1265 btrfs_file_extent_disk_num_bytes(leaf, fi);
1266 if (extent_end <= start) {
1270 if (disk_bytenr == 0)
1272 if (btrfs_file_extent_compression(leaf, fi) ||
1273 btrfs_file_extent_encryption(leaf, fi) ||
1274 btrfs_file_extent_other_encoding(leaf, fi))
1276 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1278 if (btrfs_extent_readonly(root, disk_bytenr))
1280 if (btrfs_cross_ref_exist(trans, root, ino,
1282 extent_offset, disk_bytenr))
1284 disk_bytenr += extent_offset;
1285 disk_bytenr += cur_offset - found_key.offset;
1286 num_bytes = min(end + 1, extent_end) - cur_offset;
1288 * force cow if csum exists in the range.
1289 * this ensure that csum for a given extent are
1290 * either valid or do not exist.
1292 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1295 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1296 extent_end = found_key.offset +
1297 btrfs_file_extent_inline_len(leaf, fi);
1298 extent_end = ALIGN(extent_end, root->sectorsize);
1303 if (extent_end <= start) {
1308 if (cow_start == (u64)-1)
1309 cow_start = cur_offset;
1310 cur_offset = extent_end;
1311 if (cur_offset > end)
1317 btrfs_release_path(path);
1318 if (cow_start != (u64)-1) {
1319 ret = __cow_file_range(trans, inode, root, locked_page,
1320 cow_start, found_key.offset - 1,
1321 page_started, nr_written, 1);
1323 btrfs_abort_transaction(trans, root, ret);
1326 cow_start = (u64)-1;
1329 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1330 struct extent_map *em;
1331 struct extent_map_tree *em_tree;
1332 em_tree = &BTRFS_I(inode)->extent_tree;
1333 em = alloc_extent_map();
1334 BUG_ON(!em); /* -ENOMEM */
1335 em->start = cur_offset;
1336 em->orig_start = found_key.offset - extent_offset;
1337 em->len = num_bytes;
1338 em->block_len = num_bytes;
1339 em->block_start = disk_bytenr;
1340 em->orig_block_len = disk_num_bytes;
1341 em->bdev = root->fs_info->fs_devices->latest_bdev;
1342 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1343 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1344 em->generation = -1;
1346 write_lock(&em_tree->lock);
1347 ret = add_extent_mapping(em_tree, em);
1349 list_move(&em->list,
1350 &em_tree->modified_extents);
1351 write_unlock(&em_tree->lock);
1352 if (ret != -EEXIST) {
1353 free_extent_map(em);
1356 btrfs_drop_extent_cache(inode, em->start,
1357 em->start + em->len - 1, 0);
1359 type = BTRFS_ORDERED_PREALLOC;
1361 type = BTRFS_ORDERED_NOCOW;
1364 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1365 num_bytes, num_bytes, type);
1366 BUG_ON(ret); /* -ENOMEM */
1368 if (root->root_key.objectid ==
1369 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1370 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1373 btrfs_abort_transaction(trans, root, ret);
1378 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1379 cur_offset, cur_offset + num_bytes - 1,
1380 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1381 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1382 EXTENT_SET_PRIVATE2);
1383 cur_offset = extent_end;
1384 if (cur_offset > end)
1387 btrfs_release_path(path);
1389 if (cur_offset <= end && cow_start == (u64)-1) {
1390 cow_start = cur_offset;
1394 if (cow_start != (u64)-1) {
1395 ret = __cow_file_range(trans, inode, root, locked_page,
1397 page_started, nr_written, 1);
1399 btrfs_abort_transaction(trans, root, ret);
1405 err = btrfs_end_transaction(trans, root);
1409 if (ret && cur_offset < end)
1410 extent_clear_unlock_delalloc(inode,
1411 &BTRFS_I(inode)->io_tree,
1412 cur_offset, end, locked_page,
1413 EXTENT_CLEAR_UNLOCK_PAGE |
1414 EXTENT_CLEAR_UNLOCK |
1415 EXTENT_CLEAR_DELALLOC |
1416 EXTENT_CLEAR_DIRTY |
1417 EXTENT_SET_WRITEBACK |
1418 EXTENT_END_WRITEBACK);
1420 btrfs_free_path(path);
1425 * extent_io.c call back to do delayed allocation processing
1427 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1428 u64 start, u64 end, int *page_started,
1429 unsigned long *nr_written)
1432 struct btrfs_root *root = BTRFS_I(inode)->root;
1434 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1435 ret = run_delalloc_nocow(inode, locked_page, start, end,
1436 page_started, 1, nr_written);
1437 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1438 ret = run_delalloc_nocow(inode, locked_page, start, end,
1439 page_started, 0, nr_written);
1440 } else if (!btrfs_test_opt(root, COMPRESS) &&
1441 !(BTRFS_I(inode)->force_compress) &&
1442 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1443 ret = cow_file_range(inode, locked_page, start, end,
1444 page_started, nr_written, 1);
1446 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1447 &BTRFS_I(inode)->runtime_flags);
1448 ret = cow_file_range_async(inode, locked_page, start, end,
1449 page_started, nr_written);
1454 static void btrfs_split_extent_hook(struct inode *inode,
1455 struct extent_state *orig, u64 split)
1457 /* not delalloc, ignore it */
1458 if (!(orig->state & EXTENT_DELALLOC))
1461 spin_lock(&BTRFS_I(inode)->lock);
1462 BTRFS_I(inode)->outstanding_extents++;
1463 spin_unlock(&BTRFS_I(inode)->lock);
1467 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1468 * extents so we can keep track of new extents that are just merged onto old
1469 * extents, such as when we are doing sequential writes, so we can properly
1470 * account for the metadata space we'll need.
1472 static void btrfs_merge_extent_hook(struct inode *inode,
1473 struct extent_state *new,
1474 struct extent_state *other)
1476 /* not delalloc, ignore it */
1477 if (!(other->state & EXTENT_DELALLOC))
1480 spin_lock(&BTRFS_I(inode)->lock);
1481 BTRFS_I(inode)->outstanding_extents--;
1482 spin_unlock(&BTRFS_I(inode)->lock);
1486 * extent_io.c set_bit_hook, used to track delayed allocation
1487 * bytes in this file, and to maintain the list of inodes that
1488 * have pending delalloc work to be done.
1490 static void btrfs_set_bit_hook(struct inode *inode,
1491 struct extent_state *state, int *bits)
1495 * set_bit and clear bit hooks normally require _irqsave/restore
1496 * but in this case, we are only testing for the DELALLOC
1497 * bit, which is only set or cleared with irqs on
1499 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1500 struct btrfs_root *root = BTRFS_I(inode)->root;
1501 u64 len = state->end + 1 - state->start;
1502 bool do_list = !btrfs_is_free_space_inode(inode);
1504 if (*bits & EXTENT_FIRST_DELALLOC) {
1505 *bits &= ~EXTENT_FIRST_DELALLOC;
1507 spin_lock(&BTRFS_I(inode)->lock);
1508 BTRFS_I(inode)->outstanding_extents++;
1509 spin_unlock(&BTRFS_I(inode)->lock);
1512 spin_lock(&root->fs_info->delalloc_lock);
1513 BTRFS_I(inode)->delalloc_bytes += len;
1514 root->fs_info->delalloc_bytes += len;
1515 if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1516 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1517 &root->fs_info->delalloc_inodes);
1519 spin_unlock(&root->fs_info->delalloc_lock);
1524 * extent_io.c clear_bit_hook, see set_bit_hook for why
1526 static void btrfs_clear_bit_hook(struct inode *inode,
1527 struct extent_state *state, int *bits)
1530 * set_bit and clear bit hooks normally require _irqsave/restore
1531 * but in this case, we are only testing for the DELALLOC
1532 * bit, which is only set or cleared with irqs on
1534 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1535 struct btrfs_root *root = BTRFS_I(inode)->root;
1536 u64 len = state->end + 1 - state->start;
1537 bool do_list = !btrfs_is_free_space_inode(inode);
1539 if (*bits & EXTENT_FIRST_DELALLOC) {
1540 *bits &= ~EXTENT_FIRST_DELALLOC;
1541 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1542 spin_lock(&BTRFS_I(inode)->lock);
1543 BTRFS_I(inode)->outstanding_extents--;
1544 spin_unlock(&BTRFS_I(inode)->lock);
1547 if (*bits & EXTENT_DO_ACCOUNTING)
1548 btrfs_delalloc_release_metadata(inode, len);
1550 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1552 btrfs_free_reserved_data_space(inode, len);
1554 spin_lock(&root->fs_info->delalloc_lock);
1555 root->fs_info->delalloc_bytes -= len;
1556 BTRFS_I(inode)->delalloc_bytes -= len;
1558 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1559 !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1560 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1562 spin_unlock(&root->fs_info->delalloc_lock);
1567 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1568 * we don't create bios that span stripes or chunks
1570 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1571 size_t size, struct bio *bio,
1572 unsigned long bio_flags)
1574 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1575 u64 logical = (u64)bio->bi_sector << 9;
1580 if (bio_flags & EXTENT_BIO_COMPRESSED)
1583 length = bio->bi_size;
1584 map_length = length;
1585 ret = btrfs_map_block(root->fs_info, READ, logical,
1586 &map_length, NULL, 0);
1587 /* Will always return 0 with map_multi == NULL */
1589 if (map_length < length + size)
1595 * in order to insert checksums into the metadata in large chunks,
1596 * we wait until bio submission time. All the pages in the bio are
1597 * checksummed and sums are attached onto the ordered extent record.
1599 * At IO completion time the cums attached on the ordered extent record
1600 * are inserted into the btree
1602 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1603 struct bio *bio, int mirror_num,
1604 unsigned long bio_flags,
1607 struct btrfs_root *root = BTRFS_I(inode)->root;
1610 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1611 BUG_ON(ret); /* -ENOMEM */
1616 * in order to insert checksums into the metadata in large chunks,
1617 * we wait until bio submission time. All the pages in the bio are
1618 * checksummed and sums are attached onto the ordered extent record.
1620 * At IO completion time the cums attached on the ordered extent record
1621 * are inserted into the btree
1623 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1624 int mirror_num, unsigned long bio_flags,
1627 struct btrfs_root *root = BTRFS_I(inode)->root;
1630 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1632 bio_endio(bio, ret);
1637 * extent_io.c submission hook. This does the right thing for csum calculation
1638 * on write, or reading the csums from the tree before a read
1640 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1641 int mirror_num, unsigned long bio_flags,
1644 struct btrfs_root *root = BTRFS_I(inode)->root;
1648 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1650 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1652 if (btrfs_is_free_space_inode(inode))
1655 if (!(rw & REQ_WRITE)) {
1656 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1660 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1661 ret = btrfs_submit_compressed_read(inode, bio,
1665 } else if (!skip_sum) {
1666 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1671 } else if (async && !skip_sum) {
1672 /* csum items have already been cloned */
1673 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1675 /* we're doing a write, do the async checksumming */
1676 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1677 inode, rw, bio, mirror_num,
1678 bio_flags, bio_offset,
1679 __btrfs_submit_bio_start,
1680 __btrfs_submit_bio_done);
1682 } else if (!skip_sum) {
1683 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1689 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1693 bio_endio(bio, ret);
1698 * given a list of ordered sums record them in the inode. This happens
1699 * at IO completion time based on sums calculated at bio submission time.
1701 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1702 struct inode *inode, u64 file_offset,
1703 struct list_head *list)
1705 struct btrfs_ordered_sum *sum;
1707 list_for_each_entry(sum, list, list) {
1708 btrfs_csum_file_blocks(trans,
1709 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1714 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1715 struct extent_state **cached_state)
1717 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1718 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1719 cached_state, GFP_NOFS);
1722 /* see btrfs_writepage_start_hook for details on why this is required */
1723 struct btrfs_writepage_fixup {
1725 struct btrfs_work work;
1728 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1730 struct btrfs_writepage_fixup *fixup;
1731 struct btrfs_ordered_extent *ordered;
1732 struct extent_state *cached_state = NULL;
1734 struct inode *inode;
1739 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1743 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1744 ClearPageChecked(page);
1748 inode = page->mapping->host;
1749 page_start = page_offset(page);
1750 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1752 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1755 /* already ordered? We're done */
1756 if (PagePrivate2(page))
1759 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1761 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1762 page_end, &cached_state, GFP_NOFS);
1764 btrfs_start_ordered_extent(inode, ordered, 1);
1765 btrfs_put_ordered_extent(ordered);
1769 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1771 mapping_set_error(page->mapping, ret);
1772 end_extent_writepage(page, ret, page_start, page_end);
1773 ClearPageChecked(page);
1777 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1778 ClearPageChecked(page);
1779 set_page_dirty(page);
1781 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1782 &cached_state, GFP_NOFS);
1785 page_cache_release(page);
1790 * There are a few paths in the higher layers of the kernel that directly
1791 * set the page dirty bit without asking the filesystem if it is a
1792 * good idea. This causes problems because we want to make sure COW
1793 * properly happens and the data=ordered rules are followed.
1795 * In our case any range that doesn't have the ORDERED bit set
1796 * hasn't been properly setup for IO. We kick off an async process
1797 * to fix it up. The async helper will wait for ordered extents, set
1798 * the delalloc bit and make it safe to write the page.
1800 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1802 struct inode *inode = page->mapping->host;
1803 struct btrfs_writepage_fixup *fixup;
1804 struct btrfs_root *root = BTRFS_I(inode)->root;
1806 /* this page is properly in the ordered list */
1807 if (TestClearPagePrivate2(page))
1810 if (PageChecked(page))
1813 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1817 SetPageChecked(page);
1818 page_cache_get(page);
1819 fixup->work.func = btrfs_writepage_fixup_worker;
1821 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1825 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1826 struct inode *inode, u64 file_pos,
1827 u64 disk_bytenr, u64 disk_num_bytes,
1828 u64 num_bytes, u64 ram_bytes,
1829 u8 compression, u8 encryption,
1830 u16 other_encoding, int extent_type)
1832 struct btrfs_root *root = BTRFS_I(inode)->root;
1833 struct btrfs_file_extent_item *fi;
1834 struct btrfs_path *path;
1835 struct extent_buffer *leaf;
1836 struct btrfs_key ins;
1839 path = btrfs_alloc_path();
1843 path->leave_spinning = 1;
1846 * we may be replacing one extent in the tree with another.
1847 * The new extent is pinned in the extent map, and we don't want
1848 * to drop it from the cache until it is completely in the btree.
1850 * So, tell btrfs_drop_extents to leave this extent in the cache.
1851 * the caller is expected to unpin it and allow it to be merged
1854 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1855 file_pos + num_bytes, 0);
1859 ins.objectid = btrfs_ino(inode);
1860 ins.offset = file_pos;
1861 ins.type = BTRFS_EXTENT_DATA_KEY;
1862 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1865 leaf = path->nodes[0];
1866 fi = btrfs_item_ptr(leaf, path->slots[0],
1867 struct btrfs_file_extent_item);
1868 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1869 btrfs_set_file_extent_type(leaf, fi, extent_type);
1870 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1871 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1872 btrfs_set_file_extent_offset(leaf, fi, 0);
1873 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1874 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1875 btrfs_set_file_extent_compression(leaf, fi, compression);
1876 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1877 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1879 btrfs_mark_buffer_dirty(leaf);
1880 btrfs_release_path(path);
1882 inode_add_bytes(inode, num_bytes);
1884 ins.objectid = disk_bytenr;
1885 ins.offset = disk_num_bytes;
1886 ins.type = BTRFS_EXTENT_ITEM_KEY;
1887 ret = btrfs_alloc_reserved_file_extent(trans, root,
1888 root->root_key.objectid,
1889 btrfs_ino(inode), file_pos, &ins);
1891 btrfs_free_path(path);
1897 * helper function for btrfs_finish_ordered_io, this
1898 * just reads in some of the csum leaves to prime them into ram
1899 * before we start the transaction. It limits the amount of btree
1900 * reads required while inside the transaction.
1902 /* as ordered data IO finishes, this gets called so we can finish
1903 * an ordered extent if the range of bytes in the file it covers are
1906 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
1908 struct inode *inode = ordered_extent->inode;
1909 struct btrfs_root *root = BTRFS_I(inode)->root;
1910 struct btrfs_trans_handle *trans = NULL;
1911 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1912 struct extent_state *cached_state = NULL;
1913 int compress_type = 0;
1917 nolock = btrfs_is_free_space_inode(inode);
1919 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
1924 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1925 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
1926 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1928 trans = btrfs_join_transaction_nolock(root);
1930 trans = btrfs_join_transaction(root);
1931 if (IS_ERR(trans)) {
1932 ret = PTR_ERR(trans);
1936 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1937 ret = btrfs_update_inode_fallback(trans, root, inode);
1938 if (ret) /* -ENOMEM or corruption */
1939 btrfs_abort_transaction(trans, root, ret);
1943 lock_extent_bits(io_tree, ordered_extent->file_offset,
1944 ordered_extent->file_offset + ordered_extent->len - 1,
1948 trans = btrfs_join_transaction_nolock(root);
1950 trans = btrfs_join_transaction(root);
1951 if (IS_ERR(trans)) {
1952 ret = PTR_ERR(trans);
1956 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1958 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1959 compress_type = ordered_extent->compress_type;
1960 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1961 BUG_ON(compress_type);
1962 ret = btrfs_mark_extent_written(trans, inode,
1963 ordered_extent->file_offset,
1964 ordered_extent->file_offset +
1965 ordered_extent->len);
1967 BUG_ON(root == root->fs_info->tree_root);
1968 ret = insert_reserved_file_extent(trans, inode,
1969 ordered_extent->file_offset,
1970 ordered_extent->start,
1971 ordered_extent->disk_len,
1972 ordered_extent->len,
1973 ordered_extent->len,
1974 compress_type, 0, 0,
1975 BTRFS_FILE_EXTENT_REG);
1977 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1978 ordered_extent->file_offset, ordered_extent->len,
1981 btrfs_abort_transaction(trans, root, ret);
1985 add_pending_csums(trans, inode, ordered_extent->file_offset,
1986 &ordered_extent->list);
1988 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1989 ret = btrfs_update_inode_fallback(trans, root, inode);
1990 if (ret) { /* -ENOMEM or corruption */
1991 btrfs_abort_transaction(trans, root, ret);
1996 unlock_extent_cached(io_tree, ordered_extent->file_offset,
1997 ordered_extent->file_offset +
1998 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2000 if (root != root->fs_info->tree_root)
2001 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2003 btrfs_end_transaction(trans, root);
2006 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
2007 ordered_extent->file_offset +
2008 ordered_extent->len - 1, NULL, GFP_NOFS);
2011 * This needs to be done to make sure anybody waiting knows we are done
2012 * updating everything for this ordered extent.
2014 btrfs_remove_ordered_extent(inode, ordered_extent);
2017 btrfs_put_ordered_extent(ordered_extent);
2018 /* once for the tree */
2019 btrfs_put_ordered_extent(ordered_extent);
2024 static void finish_ordered_fn(struct btrfs_work *work)
2026 struct btrfs_ordered_extent *ordered_extent;
2027 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2028 btrfs_finish_ordered_io(ordered_extent);
2031 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2032 struct extent_state *state, int uptodate)
2034 struct inode *inode = page->mapping->host;
2035 struct btrfs_root *root = BTRFS_I(inode)->root;
2036 struct btrfs_ordered_extent *ordered_extent = NULL;
2037 struct btrfs_workers *workers;
2039 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2041 ClearPagePrivate2(page);
2042 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2043 end - start + 1, uptodate))
2046 ordered_extent->work.func = finish_ordered_fn;
2047 ordered_extent->work.flags = 0;
2049 if (btrfs_is_free_space_inode(inode))
2050 workers = &root->fs_info->endio_freespace_worker;
2052 workers = &root->fs_info->endio_write_workers;
2053 btrfs_queue_worker(workers, &ordered_extent->work);
2059 * when reads are done, we need to check csums to verify the data is correct
2060 * if there's a match, we allow the bio to finish. If not, the code in
2061 * extent_io.c will try to find good copies for us.
2063 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
2064 struct extent_state *state, int mirror)
2066 size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
2067 struct inode *inode = page->mapping->host;
2068 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2070 u64 private = ~(u32)0;
2072 struct btrfs_root *root = BTRFS_I(inode)->root;
2075 if (PageChecked(page)) {
2076 ClearPageChecked(page);
2080 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2083 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2084 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2085 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2090 if (state && state->start == start) {
2091 private = state->private;
2094 ret = get_state_private(io_tree, start, &private);
2096 kaddr = kmap_atomic(page);
2100 csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
2101 btrfs_csum_final(csum, (char *)&csum);
2102 if (csum != private)
2105 kunmap_atomic(kaddr);
2110 printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u "
2112 (unsigned long long)btrfs_ino(page->mapping->host),
2113 (unsigned long long)start, csum,
2114 (unsigned long long)private);
2115 memset(kaddr + offset, 1, end - start + 1);
2116 flush_dcache_page(page);
2117 kunmap_atomic(kaddr);
2123 struct delayed_iput {
2124 struct list_head list;
2125 struct inode *inode;
2128 /* JDM: If this is fs-wide, why can't we add a pointer to
2129 * btrfs_inode instead and avoid the allocation? */
2130 void btrfs_add_delayed_iput(struct inode *inode)
2132 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2133 struct delayed_iput *delayed;
2135 if (atomic_add_unless(&inode->i_count, -1, 1))
2138 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2139 delayed->inode = inode;
2141 spin_lock(&fs_info->delayed_iput_lock);
2142 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2143 spin_unlock(&fs_info->delayed_iput_lock);
2146 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2149 struct btrfs_fs_info *fs_info = root->fs_info;
2150 struct delayed_iput *delayed;
2153 spin_lock(&fs_info->delayed_iput_lock);
2154 empty = list_empty(&fs_info->delayed_iputs);
2155 spin_unlock(&fs_info->delayed_iput_lock);
2159 spin_lock(&fs_info->delayed_iput_lock);
2160 list_splice_init(&fs_info->delayed_iputs, &list);
2161 spin_unlock(&fs_info->delayed_iput_lock);
2163 while (!list_empty(&list)) {
2164 delayed = list_entry(list.next, struct delayed_iput, list);
2165 list_del(&delayed->list);
2166 iput(delayed->inode);
2171 enum btrfs_orphan_cleanup_state {
2172 ORPHAN_CLEANUP_STARTED = 1,
2173 ORPHAN_CLEANUP_DONE = 2,
2177 * This is called in transaction commit time. If there are no orphan
2178 * files in the subvolume, it removes orphan item and frees block_rsv
2181 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2182 struct btrfs_root *root)
2184 struct btrfs_block_rsv *block_rsv;
2187 if (atomic_read(&root->orphan_inodes) ||
2188 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2191 spin_lock(&root->orphan_lock);
2192 if (atomic_read(&root->orphan_inodes)) {
2193 spin_unlock(&root->orphan_lock);
2197 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2198 spin_unlock(&root->orphan_lock);
2202 block_rsv = root->orphan_block_rsv;
2203 root->orphan_block_rsv = NULL;
2204 spin_unlock(&root->orphan_lock);
2206 if (root->orphan_item_inserted &&
2207 btrfs_root_refs(&root->root_item) > 0) {
2208 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2209 root->root_key.objectid);
2211 root->orphan_item_inserted = 0;
2215 WARN_ON(block_rsv->size > 0);
2216 btrfs_free_block_rsv(root, block_rsv);
2221 * This creates an orphan entry for the given inode in case something goes
2222 * wrong in the middle of an unlink/truncate.
2224 * NOTE: caller of this function should reserve 5 units of metadata for
2227 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2229 struct btrfs_root *root = BTRFS_I(inode)->root;
2230 struct btrfs_block_rsv *block_rsv = NULL;
2235 if (!root->orphan_block_rsv) {
2236 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2241 spin_lock(&root->orphan_lock);
2242 if (!root->orphan_block_rsv) {
2243 root->orphan_block_rsv = block_rsv;
2244 } else if (block_rsv) {
2245 btrfs_free_block_rsv(root, block_rsv);
2249 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2250 &BTRFS_I(inode)->runtime_flags)) {
2253 * For proper ENOSPC handling, we should do orphan
2254 * cleanup when mounting. But this introduces backward
2255 * compatibility issue.
2257 if (!xchg(&root->orphan_item_inserted, 1))
2263 atomic_inc(&root->orphan_inodes);
2266 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2267 &BTRFS_I(inode)->runtime_flags))
2269 spin_unlock(&root->orphan_lock);
2271 /* grab metadata reservation from transaction handle */
2273 ret = btrfs_orphan_reserve_metadata(trans, inode);
2274 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
2277 /* insert an orphan item to track this unlinked/truncated file */
2279 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2280 if (ret && ret != -EEXIST) {
2281 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2282 &BTRFS_I(inode)->runtime_flags);
2283 btrfs_abort_transaction(trans, root, ret);
2289 /* insert an orphan item to track subvolume contains orphan files */
2291 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2292 root->root_key.objectid);
2293 if (ret && ret != -EEXIST) {
2294 btrfs_abort_transaction(trans, root, ret);
2302 * We have done the truncate/delete so we can go ahead and remove the orphan
2303 * item for this particular inode.
2305 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2307 struct btrfs_root *root = BTRFS_I(inode)->root;
2308 int delete_item = 0;
2309 int release_rsv = 0;
2312 spin_lock(&root->orphan_lock);
2313 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2314 &BTRFS_I(inode)->runtime_flags))
2317 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2318 &BTRFS_I(inode)->runtime_flags))
2320 spin_unlock(&root->orphan_lock);
2322 if (trans && delete_item) {
2323 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
2324 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
2328 btrfs_orphan_release_metadata(inode);
2329 atomic_dec(&root->orphan_inodes);
2336 * this cleans up any orphans that may be left on the list from the last use
2339 int btrfs_orphan_cleanup(struct btrfs_root *root)
2341 struct btrfs_path *path;
2342 struct extent_buffer *leaf;
2343 struct btrfs_key key, found_key;
2344 struct btrfs_trans_handle *trans;
2345 struct inode *inode;
2346 u64 last_objectid = 0;
2347 int ret = 0, nr_unlink = 0, nr_truncate = 0;
2349 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2352 path = btrfs_alloc_path();
2359 key.objectid = BTRFS_ORPHAN_OBJECTID;
2360 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2361 key.offset = (u64)-1;
2364 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2369 * if ret == 0 means we found what we were searching for, which
2370 * is weird, but possible, so only screw with path if we didn't
2371 * find the key and see if we have stuff that matches
2375 if (path->slots[0] == 0)
2380 /* pull out the item */
2381 leaf = path->nodes[0];
2382 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2384 /* make sure the item matches what we want */
2385 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2387 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2390 /* release the path since we're done with it */
2391 btrfs_release_path(path);
2394 * this is where we are basically btrfs_lookup, without the
2395 * crossing root thing. we store the inode number in the
2396 * offset of the orphan item.
2399 if (found_key.offset == last_objectid) {
2400 printk(KERN_ERR "btrfs: Error removing orphan entry, "
2401 "stopping orphan cleanup\n");
2406 last_objectid = found_key.offset;
2408 found_key.objectid = found_key.offset;
2409 found_key.type = BTRFS_INODE_ITEM_KEY;
2410 found_key.offset = 0;
2411 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2412 ret = PTR_RET(inode);
2413 if (ret && ret != -ESTALE)
2416 if (ret == -ESTALE && root == root->fs_info->tree_root) {
2417 struct btrfs_root *dead_root;
2418 struct btrfs_fs_info *fs_info = root->fs_info;
2419 int is_dead_root = 0;
2422 * this is an orphan in the tree root. Currently these
2423 * could come from 2 sources:
2424 * a) a snapshot deletion in progress
2425 * b) a free space cache inode
2426 * We need to distinguish those two, as the snapshot
2427 * orphan must not get deleted.
2428 * find_dead_roots already ran before us, so if this
2429 * is a snapshot deletion, we should find the root
2430 * in the dead_roots list
2432 spin_lock(&fs_info->trans_lock);
2433 list_for_each_entry(dead_root, &fs_info->dead_roots,
2435 if (dead_root->root_key.objectid ==
2436 found_key.objectid) {
2441 spin_unlock(&fs_info->trans_lock);
2443 /* prevent this orphan from being found again */
2444 key.offset = found_key.objectid - 1;
2449 * Inode is already gone but the orphan item is still there,
2450 * kill the orphan item.
2452 if (ret == -ESTALE) {
2453 trans = btrfs_start_transaction(root, 1);
2454 if (IS_ERR(trans)) {
2455 ret = PTR_ERR(trans);
2458 printk(KERN_ERR "auto deleting %Lu\n",
2459 found_key.objectid);
2460 ret = btrfs_del_orphan_item(trans, root,
2461 found_key.objectid);
2462 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
2463 btrfs_end_transaction(trans, root);
2468 * add this inode to the orphan list so btrfs_orphan_del does
2469 * the proper thing when we hit it
2471 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2472 &BTRFS_I(inode)->runtime_flags);
2474 /* if we have links, this was a truncate, lets do that */
2475 if (inode->i_nlink) {
2476 if (!S_ISREG(inode->i_mode)) {
2483 /* 1 for the orphan item deletion. */
2484 trans = btrfs_start_transaction(root, 1);
2485 if (IS_ERR(trans)) {
2486 ret = PTR_ERR(trans);
2489 ret = btrfs_orphan_add(trans, inode);
2490 btrfs_end_transaction(trans, root);
2494 ret = btrfs_truncate(inode);
2499 /* this will do delete_inode and everything for us */
2504 /* release the path since we're done with it */
2505 btrfs_release_path(path);
2507 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2509 if (root->orphan_block_rsv)
2510 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2513 if (root->orphan_block_rsv || root->orphan_item_inserted) {
2514 trans = btrfs_join_transaction(root);
2516 btrfs_end_transaction(trans, root);
2520 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2522 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2526 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
2527 btrfs_free_path(path);
2532 * very simple check to peek ahead in the leaf looking for xattrs. If we
2533 * don't find any xattrs, we know there can't be any acls.
2535 * slot is the slot the inode is in, objectid is the objectid of the inode
2537 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2538 int slot, u64 objectid)
2540 u32 nritems = btrfs_header_nritems(leaf);
2541 struct btrfs_key found_key;
2545 while (slot < nritems) {
2546 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2548 /* we found a different objectid, there must not be acls */
2549 if (found_key.objectid != objectid)
2552 /* we found an xattr, assume we've got an acl */
2553 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2557 * we found a key greater than an xattr key, there can't
2558 * be any acls later on
2560 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2567 * it goes inode, inode backrefs, xattrs, extents,
2568 * so if there are a ton of hard links to an inode there can
2569 * be a lot of backrefs. Don't waste time searching too hard,
2570 * this is just an optimization
2575 /* we hit the end of the leaf before we found an xattr or
2576 * something larger than an xattr. We have to assume the inode
2583 * read an inode from the btree into the in-memory inode
2585 static void btrfs_read_locked_inode(struct inode *inode)
2587 struct btrfs_path *path;
2588 struct extent_buffer *leaf;
2589 struct btrfs_inode_item *inode_item;
2590 struct btrfs_timespec *tspec;
2591 struct btrfs_root *root = BTRFS_I(inode)->root;
2592 struct btrfs_key location;
2596 bool filled = false;
2598 ret = btrfs_fill_inode(inode, &rdev);
2602 path = btrfs_alloc_path();
2606 path->leave_spinning = 1;
2607 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2609 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2613 leaf = path->nodes[0];
2618 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2619 struct btrfs_inode_item);
2620 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2621 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
2622 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
2623 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
2624 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2626 tspec = btrfs_inode_atime(inode_item);
2627 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2628 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2630 tspec = btrfs_inode_mtime(inode_item);
2631 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2632 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2634 tspec = btrfs_inode_ctime(inode_item);
2635 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2636 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2638 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2639 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2640 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
2643 * If we were modified in the current generation and evicted from memory
2644 * and then re-read we need to do a full sync since we don't have any
2645 * idea about which extents were modified before we were evicted from
2648 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
2649 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2650 &BTRFS_I(inode)->runtime_flags);
2652 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
2653 inode->i_generation = BTRFS_I(inode)->generation;
2655 rdev = btrfs_inode_rdev(leaf, inode_item);
2657 BTRFS_I(inode)->index_cnt = (u64)-1;
2658 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2661 * try to precache a NULL acl entry for files that don't have
2662 * any xattrs or acls
2664 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
2667 cache_no_acl(inode);
2669 btrfs_free_path(path);
2671 switch (inode->i_mode & S_IFMT) {
2673 inode->i_mapping->a_ops = &btrfs_aops;
2674 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2675 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2676 inode->i_fop = &btrfs_file_operations;
2677 inode->i_op = &btrfs_file_inode_operations;
2680 inode->i_fop = &btrfs_dir_file_operations;
2681 if (root == root->fs_info->tree_root)
2682 inode->i_op = &btrfs_dir_ro_inode_operations;
2684 inode->i_op = &btrfs_dir_inode_operations;
2687 inode->i_op = &btrfs_symlink_inode_operations;
2688 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2689 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2692 inode->i_op = &btrfs_special_inode_operations;
2693 init_special_inode(inode, inode->i_mode, rdev);
2697 btrfs_update_iflags(inode);
2701 btrfs_free_path(path);
2702 make_bad_inode(inode);
2706 * given a leaf and an inode, copy the inode fields into the leaf
2708 static void fill_inode_item(struct btrfs_trans_handle *trans,
2709 struct extent_buffer *leaf,
2710 struct btrfs_inode_item *item,
2711 struct inode *inode)
2713 btrfs_set_inode_uid(leaf, item, i_uid_read(inode));
2714 btrfs_set_inode_gid(leaf, item, i_gid_read(inode));
2715 btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
2716 btrfs_set_inode_mode(leaf, item, inode->i_mode);
2717 btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2719 btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2720 inode->i_atime.tv_sec);
2721 btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2722 inode->i_atime.tv_nsec);
2724 btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2725 inode->i_mtime.tv_sec);
2726 btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2727 inode->i_mtime.tv_nsec);
2729 btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2730 inode->i_ctime.tv_sec);
2731 btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2732 inode->i_ctime.tv_nsec);
2734 btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
2735 btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
2736 btrfs_set_inode_sequence(leaf, item, inode->i_version);
2737 btrfs_set_inode_transid(leaf, item, trans->transid);
2738 btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
2739 btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
2740 btrfs_set_inode_block_group(leaf, item, 0);
2744 * copy everything in the in-memory inode into the btree.
2746 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
2747 struct btrfs_root *root, struct inode *inode)
2749 struct btrfs_inode_item *inode_item;
2750 struct btrfs_path *path;
2751 struct extent_buffer *leaf;
2754 path = btrfs_alloc_path();
2758 path->leave_spinning = 1;
2759 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
2767 btrfs_unlock_up_safe(path, 1);
2768 leaf = path->nodes[0];
2769 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2770 struct btrfs_inode_item);
2772 fill_inode_item(trans, leaf, inode_item, inode);
2773 btrfs_mark_buffer_dirty(leaf);
2774 btrfs_set_inode_last_trans(trans, inode);
2777 btrfs_free_path(path);
2782 * copy everything in the in-memory inode into the btree.
2784 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2785 struct btrfs_root *root, struct inode *inode)
2790 * If the inode is a free space inode, we can deadlock during commit
2791 * if we put it into the delayed code.
2793 * The data relocation inode should also be directly updated
2796 if (!btrfs_is_free_space_inode(inode)
2797 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
2798 btrfs_update_root_times(trans, root);
2800 ret = btrfs_delayed_update_inode(trans, root, inode);
2802 btrfs_set_inode_last_trans(trans, inode);
2806 return btrfs_update_inode_item(trans, root, inode);
2809 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
2810 struct btrfs_root *root,
2811 struct inode *inode)
2815 ret = btrfs_update_inode(trans, root, inode);
2817 return btrfs_update_inode_item(trans, root, inode);
2822 * unlink helper that gets used here in inode.c and in the tree logging
2823 * recovery code. It remove a link in a directory with a given name, and
2824 * also drops the back refs in the inode to the directory
2826 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2827 struct btrfs_root *root,
2828 struct inode *dir, struct inode *inode,
2829 const char *name, int name_len)
2831 struct btrfs_path *path;
2833 struct extent_buffer *leaf;
2834 struct btrfs_dir_item *di;
2835 struct btrfs_key key;
2837 u64 ino = btrfs_ino(inode);
2838 u64 dir_ino = btrfs_ino(dir);
2840 path = btrfs_alloc_path();
2846 path->leave_spinning = 1;
2847 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2848 name, name_len, -1);
2857 leaf = path->nodes[0];
2858 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2859 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2862 btrfs_release_path(path);
2864 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
2867 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2868 "inode %llu parent %llu\n", name_len, name,
2869 (unsigned long long)ino, (unsigned long long)dir_ino);
2870 btrfs_abort_transaction(trans, root, ret);
2874 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
2876 btrfs_abort_transaction(trans, root, ret);
2880 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2882 if (ret != 0 && ret != -ENOENT) {
2883 btrfs_abort_transaction(trans, root, ret);
2887 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2892 btrfs_free_path(path);
2896 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2897 inode_inc_iversion(inode);
2898 inode_inc_iversion(dir);
2899 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2900 ret = btrfs_update_inode(trans, root, dir);
2905 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2906 struct btrfs_root *root,
2907 struct inode *dir, struct inode *inode,
2908 const char *name, int name_len)
2911 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
2913 btrfs_drop_nlink(inode);
2914 ret = btrfs_update_inode(trans, root, inode);
2920 /* helper to check if there is any shared block in the path */
2921 static int check_path_shared(struct btrfs_root *root,
2922 struct btrfs_path *path)
2924 struct extent_buffer *eb;
2928 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2931 if (!path->nodes[level])
2933 eb = path->nodes[level];
2934 if (!btrfs_block_can_be_shared(root, eb))
2936 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2945 * helper to start transaction for unlink and rmdir.
2947 * unlink and rmdir are special in btrfs, they do not always free space.
2948 * so in enospc case, we should make sure they will free space before
2949 * allowing them to use the global metadata reservation.
2951 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2952 struct dentry *dentry)
2954 struct btrfs_trans_handle *trans;
2955 struct btrfs_root *root = BTRFS_I(dir)->root;
2956 struct btrfs_path *path;
2957 struct btrfs_dir_item *di;
2958 struct inode *inode = dentry->d_inode;
2963 u64 ino = btrfs_ino(inode);
2964 u64 dir_ino = btrfs_ino(dir);
2967 * 1 for the possible orphan item
2968 * 1 for the dir item
2969 * 1 for the dir index
2970 * 1 for the inode ref
2971 * 1 for the inode ref in the tree log
2972 * 2 for the dir entries in the log
2975 trans = btrfs_start_transaction(root, 8);
2976 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2979 if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2980 return ERR_PTR(-ENOSPC);
2982 /* check if there is someone else holds reference */
2983 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2984 return ERR_PTR(-ENOSPC);
2986 if (atomic_read(&inode->i_count) > 2)
2987 return ERR_PTR(-ENOSPC);
2989 if (xchg(&root->fs_info->enospc_unlink, 1))
2990 return ERR_PTR(-ENOSPC);
2992 path = btrfs_alloc_path();
2994 root->fs_info->enospc_unlink = 0;
2995 return ERR_PTR(-ENOMEM);
2998 /* 1 for the orphan item */
2999 trans = btrfs_start_transaction(root, 1);
3000 if (IS_ERR(trans)) {
3001 btrfs_free_path(path);
3002 root->fs_info->enospc_unlink = 0;
3006 path->skip_locking = 1;
3007 path->search_commit_root = 1;
3009 ret = btrfs_lookup_inode(trans, root, path,
3010 &BTRFS_I(dir)->location, 0);
3016 if (check_path_shared(root, path))
3021 btrfs_release_path(path);
3023 ret = btrfs_lookup_inode(trans, root, path,
3024 &BTRFS_I(inode)->location, 0);
3030 if (check_path_shared(root, path))
3035 btrfs_release_path(path);
3037 if (ret == 0 && S_ISREG(inode->i_mode)) {
3038 ret = btrfs_lookup_file_extent(trans, root, path,
3044 BUG_ON(ret == 0); /* Corruption */
3045 if (check_path_shared(root, path))
3047 btrfs_release_path(path);
3055 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3056 dentry->d_name.name, dentry->d_name.len, 0);
3062 if (check_path_shared(root, path))
3068 btrfs_release_path(path);
3070 ret = btrfs_get_inode_ref_index(trans, root, path, dentry->d_name.name,
3071 dentry->d_name.len, ino, dir_ino, 0,
3078 if (check_path_shared(root, path))
3081 btrfs_release_path(path);
3084 * This is a commit root search, if we can lookup inode item and other
3085 * relative items in the commit root, it means the transaction of
3086 * dir/file creation has been committed, and the dir index item that we
3087 * delay to insert has also been inserted into the commit root. So
3088 * we needn't worry about the delayed insertion of the dir index item
3091 di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
3092 dentry->d_name.name, dentry->d_name.len, 0);
3097 BUG_ON(ret == -ENOENT);
3098 if (check_path_shared(root, path))
3103 btrfs_free_path(path);
3104 /* Migrate the orphan reservation over */
3106 err = btrfs_block_rsv_migrate(trans->block_rsv,
3107 &root->fs_info->global_block_rsv,
3108 trans->bytes_reserved);
3111 btrfs_end_transaction(trans, root);
3112 root->fs_info->enospc_unlink = 0;
3113 return ERR_PTR(err);
3116 trans->block_rsv = &root->fs_info->global_block_rsv;
3120 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
3121 struct btrfs_root *root)
3123 if (trans->block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL) {
3124 btrfs_block_rsv_release(root, trans->block_rsv,
3125 trans->bytes_reserved);
3126 trans->block_rsv = &root->fs_info->trans_block_rsv;
3127 BUG_ON(!root->fs_info->enospc_unlink);
3128 root->fs_info->enospc_unlink = 0;
3130 btrfs_end_transaction(trans, root);
3133 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3135 struct btrfs_root *root = BTRFS_I(dir)->root;
3136 struct btrfs_trans_handle *trans;
3137 struct inode *inode = dentry->d_inode;
3140 trans = __unlink_start_trans(dir, dentry);
3142 return PTR_ERR(trans);
3144 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3146 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3147 dentry->d_name.name, dentry->d_name.len);
3151 if (inode->i_nlink == 0) {
3152 ret = btrfs_orphan_add(trans, inode);
3158 __unlink_end_trans(trans, root);
3159 btrfs_btree_balance_dirty(root);
3163 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3164 struct btrfs_root *root,
3165 struct inode *dir, u64 objectid,
3166 const char *name, int name_len)
3168 struct btrfs_path *path;
3169 struct extent_buffer *leaf;
3170 struct btrfs_dir_item *di;
3171 struct btrfs_key key;
3174 u64 dir_ino = btrfs_ino(dir);
3176 path = btrfs_alloc_path();
3180 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3181 name, name_len, -1);
3182 if (IS_ERR_OR_NULL(di)) {
3190 leaf = path->nodes[0];
3191 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3192 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3193 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3195 btrfs_abort_transaction(trans, root, ret);
3198 btrfs_release_path(path);
3200 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3201 objectid, root->root_key.objectid,
3202 dir_ino, &index, name, name_len);
3204 if (ret != -ENOENT) {
3205 btrfs_abort_transaction(trans, root, ret);
3208 di = btrfs_search_dir_index_item(root, path, dir_ino,
3210 if (IS_ERR_OR_NULL(di)) {
3215 btrfs_abort_transaction(trans, root, ret);
3219 leaf = path->nodes[0];
3220 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3221 btrfs_release_path(path);
3224 btrfs_release_path(path);
3226 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3228 btrfs_abort_transaction(trans, root, ret);
3232 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3233 inode_inc_iversion(dir);
3234 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3235 ret = btrfs_update_inode_fallback(trans, root, dir);
3237 btrfs_abort_transaction(trans, root, ret);
3239 btrfs_free_path(path);
3243 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3245 struct inode *inode = dentry->d_inode;
3247 struct btrfs_root *root = BTRFS_I(dir)->root;
3248 struct btrfs_trans_handle *trans;
3250 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3252 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3255 trans = __unlink_start_trans(dir, dentry);
3257 return PTR_ERR(trans);
3259 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3260 err = btrfs_unlink_subvol(trans, root, dir,
3261 BTRFS_I(inode)->location.objectid,
3262 dentry->d_name.name,
3263 dentry->d_name.len);
3267 err = btrfs_orphan_add(trans, inode);
3271 /* now the directory is empty */
3272 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3273 dentry->d_name.name, dentry->d_name.len);
3275 btrfs_i_size_write(inode, 0);
3277 __unlink_end_trans(trans, root);
3278 btrfs_btree_balance_dirty(root);
3284 * this can truncate away extent items, csum items and directory items.
3285 * It starts at a high offset and removes keys until it can't find
3286 * any higher than new_size
3288 * csum items that cross the new i_size are truncated to the new size
3291 * min_type is the minimum key type to truncate down to. If set to 0, this
3292 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3294 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3295 struct btrfs_root *root,
3296 struct inode *inode,
3297 u64 new_size, u32 min_type)
3299 struct btrfs_path *path;
3300 struct extent_buffer *leaf;
3301 struct btrfs_file_extent_item *fi;
3302 struct btrfs_key key;
3303 struct btrfs_key found_key;
3304 u64 extent_start = 0;
3305 u64 extent_num_bytes = 0;
3306 u64 extent_offset = 0;
3308 u64 mask = root->sectorsize - 1;
3309 u32 found_type = (u8)-1;
3312 int pending_del_nr = 0;
3313 int pending_del_slot = 0;
3314 int extent_type = -1;
3317 u64 ino = btrfs_ino(inode);
3319 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3321 path = btrfs_alloc_path();
3327 * We want to drop from the next block forward in case this new size is
3328 * not block aligned since we will be keeping the last block of the
3329 * extent just the way it is.
3331 if (root->ref_cows || root == root->fs_info->tree_root)
3332 btrfs_drop_extent_cache(inode, (new_size + mask) & (~mask), (u64)-1, 0);
3335 * This function is also used to drop the items in the log tree before
3336 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3337 * it is used to drop the loged items. So we shouldn't kill the delayed
3340 if (min_type == 0 && root == BTRFS_I(inode)->root)
3341 btrfs_kill_delayed_inode_items(inode);
3344 key.offset = (u64)-1;
3348 path->leave_spinning = 1;
3349 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3356 /* there are no items in the tree for us to truncate, we're
3359 if (path->slots[0] == 0)
3366 leaf = path->nodes[0];
3367 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3368 found_type = btrfs_key_type(&found_key);
3370 if (found_key.objectid != ino)
3373 if (found_type < min_type)
3376 item_end = found_key.offset;
3377 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3378 fi = btrfs_item_ptr(leaf, path->slots[0],
3379 struct btrfs_file_extent_item);
3380 extent_type = btrfs_file_extent_type(leaf, fi);
3381 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3383 btrfs_file_extent_num_bytes(leaf, fi);
3384 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3385 item_end += btrfs_file_extent_inline_len(leaf,
3390 if (found_type > min_type) {
3393 if (item_end < new_size)
3395 if (found_key.offset >= new_size)
3401 /* FIXME, shrink the extent if the ref count is only 1 */
3402 if (found_type != BTRFS_EXTENT_DATA_KEY)
3405 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3407 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3409 u64 orig_num_bytes =
3410 btrfs_file_extent_num_bytes(leaf, fi);
3411 extent_num_bytes = new_size -
3412 found_key.offset + root->sectorsize - 1;
3413 extent_num_bytes = extent_num_bytes &
3414 ~((u64)root->sectorsize - 1);
3415 btrfs_set_file_extent_num_bytes(leaf, fi,
3417 num_dec = (orig_num_bytes -
3419 if (root->ref_cows && extent_start != 0)
3420 inode_sub_bytes(inode, num_dec);
3421 btrfs_mark_buffer_dirty(leaf);
3424 btrfs_file_extent_disk_num_bytes(leaf,
3426 extent_offset = found_key.offset -
3427 btrfs_file_extent_offset(leaf, fi);
3429 /* FIXME blocksize != 4096 */
3430 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3431 if (extent_start != 0) {
3434 inode_sub_bytes(inode, num_dec);
3437 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3439 * we can't truncate inline items that have had
3443 btrfs_file_extent_compression(leaf, fi) == 0 &&
3444 btrfs_file_extent_encryption(leaf, fi) == 0 &&
3445 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3446 u32 size = new_size - found_key.offset;
3448 if (root->ref_cows) {
3449 inode_sub_bytes(inode, item_end + 1 -
3453 btrfs_file_extent_calc_inline_size(size);
3454 btrfs_truncate_item(trans, root, path,
3456 } else if (root->ref_cows) {
3457 inode_sub_bytes(inode, item_end + 1 -
3463 if (!pending_del_nr) {
3464 /* no pending yet, add ourselves */
3465 pending_del_slot = path->slots[0];
3467 } else if (pending_del_nr &&
3468 path->slots[0] + 1 == pending_del_slot) {
3469 /* hop on the pending chunk */
3471 pending_del_slot = path->slots[0];
3478 if (found_extent && (root->ref_cows ||
3479 root == root->fs_info->tree_root)) {
3480 btrfs_set_path_blocking(path);
3481 ret = btrfs_free_extent(trans, root, extent_start,
3482 extent_num_bytes, 0,
3483 btrfs_header_owner(leaf),
3484 ino, extent_offset, 0);
3488 if (found_type == BTRFS_INODE_ITEM_KEY)
3491 if (path->slots[0] == 0 ||
3492 path->slots[0] != pending_del_slot) {
3493 if (pending_del_nr) {
3494 ret = btrfs_del_items(trans, root, path,
3498 btrfs_abort_transaction(trans,
3504 btrfs_release_path(path);
3511 if (pending_del_nr) {
3512 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3515 btrfs_abort_transaction(trans, root, ret);
3518 btrfs_free_path(path);
3523 * btrfs_truncate_page - read, zero a chunk and write a page
3524 * @inode - inode that we're zeroing
3525 * @from - the offset to start zeroing
3526 * @len - the length to zero, 0 to zero the entire range respective to the
3528 * @front - zero up to the offset instead of from the offset on
3530 * This will find the page for the "from" offset and cow the page and zero the
3531 * part we want to zero. This is used with truncate and hole punching.
3533 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
3536 struct address_space *mapping = inode->i_mapping;
3537 struct btrfs_root *root = BTRFS_I(inode)->root;
3538 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3539 struct btrfs_ordered_extent *ordered;
3540 struct extent_state *cached_state = NULL;
3542 u32 blocksize = root->sectorsize;
3543 pgoff_t index = from >> PAGE_CACHE_SHIFT;
3544 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3546 gfp_t mask = btrfs_alloc_write_mask(mapping);
3551 if ((offset & (blocksize - 1)) == 0 &&
3552 (!len || ((len & (blocksize - 1)) == 0)))
3554 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3559 page = find_or_create_page(mapping, index, mask);
3561 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3566 page_start = page_offset(page);
3567 page_end = page_start + PAGE_CACHE_SIZE - 1;
3569 if (!PageUptodate(page)) {
3570 ret = btrfs_readpage(NULL, page);
3572 if (page->mapping != mapping) {
3574 page_cache_release(page);
3577 if (!PageUptodate(page)) {
3582 wait_on_page_writeback(page);
3584 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
3585 set_page_extent_mapped(page);
3587 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3589 unlock_extent_cached(io_tree, page_start, page_end,
3590 &cached_state, GFP_NOFS);
3592 page_cache_release(page);
3593 btrfs_start_ordered_extent(inode, ordered, 1);
3594 btrfs_put_ordered_extent(ordered);
3598 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3599 EXTENT_DIRTY | EXTENT_DELALLOC |
3600 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
3601 0, 0, &cached_state, GFP_NOFS);
3603 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3606 unlock_extent_cached(io_tree, page_start, page_end,
3607 &cached_state, GFP_NOFS);
3611 if (offset != PAGE_CACHE_SIZE) {
3613 len = PAGE_CACHE_SIZE - offset;
3616 memset(kaddr, 0, offset);
3618 memset(kaddr + offset, 0, len);
3619 flush_dcache_page(page);
3622 ClearPageChecked(page);
3623 set_page_dirty(page);
3624 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3629 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3631 page_cache_release(page);
3637 * This function puts in dummy file extents for the area we're creating a hole
3638 * for. So if we are truncating this file to a larger size we need to insert
3639 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
3640 * the range between oldsize and size
3642 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
3644 struct btrfs_trans_handle *trans;
3645 struct btrfs_root *root = BTRFS_I(inode)->root;
3646 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3647 struct extent_map *em = NULL;
3648 struct extent_state *cached_state = NULL;
3649 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
3650 u64 mask = root->sectorsize - 1;
3651 u64 hole_start = (oldsize + mask) & ~mask;
3652 u64 block_end = (size + mask) & ~mask;
3658 if (size <= hole_start)
3662 struct btrfs_ordered_extent *ordered;
3663 btrfs_wait_ordered_range(inode, hole_start,
3664 block_end - hole_start);
3665 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3667 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3670 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3671 &cached_state, GFP_NOFS);
3672 btrfs_put_ordered_extent(ordered);
3675 cur_offset = hole_start;
3677 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3678 block_end - cur_offset, 0);
3684 last_byte = min(extent_map_end(em), block_end);
3685 last_byte = (last_byte + mask) & ~mask;
3686 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3687 struct extent_map *hole_em;
3688 hole_size = last_byte - cur_offset;
3690 trans = btrfs_start_transaction(root, 3);
3691 if (IS_ERR(trans)) {
3692 err = PTR_ERR(trans);
3696 err = btrfs_drop_extents(trans, root, inode,
3698 cur_offset + hole_size, 1);
3700 btrfs_abort_transaction(trans, root, err);
3701 btrfs_end_transaction(trans, root);
3705 err = btrfs_insert_file_extent(trans, root,
3706 btrfs_ino(inode), cur_offset, 0,
3707 0, hole_size, 0, hole_size,
3710 btrfs_abort_transaction(trans, root, err);
3711 btrfs_end_transaction(trans, root);
3715 btrfs_drop_extent_cache(inode, cur_offset,
3716 cur_offset + hole_size - 1, 0);
3717 hole_em = alloc_extent_map();
3719 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3720 &BTRFS_I(inode)->runtime_flags);
3723 hole_em->start = cur_offset;
3724 hole_em->len = hole_size;
3725 hole_em->orig_start = cur_offset;
3727 hole_em->block_start = EXTENT_MAP_HOLE;
3728 hole_em->block_len = 0;
3729 hole_em->orig_block_len = 0;
3730 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
3731 hole_em->compress_type = BTRFS_COMPRESS_NONE;
3732 hole_em->generation = trans->transid;
3735 write_lock(&em_tree->lock);
3736 err = add_extent_mapping(em_tree, hole_em);
3738 list_move(&hole_em->list,
3739 &em_tree->modified_extents);
3740 write_unlock(&em_tree->lock);
3743 btrfs_drop_extent_cache(inode, cur_offset,
3747 free_extent_map(hole_em);
3749 btrfs_update_inode(trans, root, inode);
3750 btrfs_end_transaction(trans, root);
3752 free_extent_map(em);
3754 cur_offset = last_byte;
3755 if (cur_offset >= block_end)
3759 free_extent_map(em);
3760 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3765 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
3767 struct btrfs_root *root = BTRFS_I(inode)->root;
3768 struct btrfs_trans_handle *trans;
3769 loff_t oldsize = i_size_read(inode);
3770 loff_t newsize = attr->ia_size;
3771 int mask = attr->ia_valid;
3774 if (newsize == oldsize)
3778 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
3779 * special case where we need to update the times despite not having
3780 * these flags set. For all other operations the VFS set these flags
3781 * explicitly if it wants a timestamp update.
3783 if (newsize != oldsize && (!(mask & (ATTR_CTIME | ATTR_MTIME))))
3784 inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb);
3786 if (newsize > oldsize) {
3787 truncate_pagecache(inode, oldsize, newsize);
3788 ret = btrfs_cont_expand(inode, oldsize, newsize);
3792 trans = btrfs_start_transaction(root, 1);
3794 return PTR_ERR(trans);
3796 i_size_write(inode, newsize);
3797 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
3798 ret = btrfs_update_inode(trans, root, inode);
3799 btrfs_end_transaction(trans, root);
3803 * We're truncating a file that used to have good data down to
3804 * zero. Make sure it gets into the ordered flush list so that
3805 * any new writes get down to disk quickly.
3808 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
3809 &BTRFS_I(inode)->runtime_flags);
3812 * 1 for the orphan item we're going to add
3813 * 1 for the orphan item deletion.
3815 trans = btrfs_start_transaction(root, 2);
3817 return PTR_ERR(trans);
3820 * We need to do this in case we fail at _any_ point during the
3821 * actual truncate. Once we do the truncate_setsize we could
3822 * invalidate pages which forces any outstanding ordered io to
3823 * be instantly completed which will give us extents that need
3824 * to be truncated. If we fail to get an orphan inode down we
3825 * could have left over extents that were never meant to live,
3826 * so we need to garuntee from this point on that everything
3827 * will be consistent.
3829 ret = btrfs_orphan_add(trans, inode);
3830 btrfs_end_transaction(trans, root);
3834 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3835 truncate_setsize(inode, newsize);
3836 ret = btrfs_truncate(inode);
3837 if (ret && inode->i_nlink)
3838 btrfs_orphan_del(NULL, inode);
3844 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3846 struct inode *inode = dentry->d_inode;
3847 struct btrfs_root *root = BTRFS_I(inode)->root;
3850 if (btrfs_root_readonly(root))
3853 err = inode_change_ok(inode, attr);
3857 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3858 err = btrfs_setsize(inode, attr);
3863 if (attr->ia_valid) {
3864 setattr_copy(inode, attr);
3865 inode_inc_iversion(inode);
3866 err = btrfs_dirty_inode(inode);
3868 if (!err && attr->ia_valid & ATTR_MODE)
3869 err = btrfs_acl_chmod(inode);
3875 void btrfs_evict_inode(struct inode *inode)
3877 struct btrfs_trans_handle *trans;
3878 struct btrfs_root *root = BTRFS_I(inode)->root;
3879 struct btrfs_block_rsv *rsv, *global_rsv;
3880 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
3883 trace_btrfs_inode_evict(inode);
3885 truncate_inode_pages(&inode->i_data, 0);
3886 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
3887 btrfs_is_free_space_inode(inode)))
3890 if (is_bad_inode(inode)) {
3891 btrfs_orphan_del(NULL, inode);
3894 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
3895 btrfs_wait_ordered_range(inode, 0, (u64)-1);
3897 if (root->fs_info->log_root_recovering) {
3898 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3899 &BTRFS_I(inode)->runtime_flags));
3903 if (inode->i_nlink > 0) {
3904 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3908 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3910 btrfs_orphan_del(NULL, inode);
3913 rsv->size = min_size;
3915 global_rsv = &root->fs_info->global_block_rsv;
3917 btrfs_i_size_write(inode, 0);
3920 * This is a bit simpler than btrfs_truncate since we've already
3921 * reserved our space for our orphan item in the unlink, so we just
3922 * need to reserve some slack space in case we add bytes and update
3923 * inode item when doing the truncate.
3926 ret = btrfs_block_rsv_refill(root, rsv, min_size,
3927 BTRFS_RESERVE_FLUSH_LIMIT);
3930 * Try and steal from the global reserve since we will
3931 * likely not use this space anyway, we want to try as
3932 * hard as possible to get this to work.
3935 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
3938 printk(KERN_WARNING "Could not get space for a "
3939 "delete, will truncate on mount %d\n", ret);
3940 btrfs_orphan_del(NULL, inode);
3941 btrfs_free_block_rsv(root, rsv);
3945 trans = btrfs_start_transaction_lflush(root, 1);
3946 if (IS_ERR(trans)) {
3947 btrfs_orphan_del(NULL, inode);
3948 btrfs_free_block_rsv(root, rsv);
3952 trans->block_rsv = rsv;
3954 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3958 trans->block_rsv = &root->fs_info->trans_block_rsv;
3959 ret = btrfs_update_inode(trans, root, inode);
3962 btrfs_end_transaction(trans, root);
3964 btrfs_btree_balance_dirty(root);
3967 btrfs_free_block_rsv(root, rsv);
3970 trans->block_rsv = root->orphan_block_rsv;
3971 ret = btrfs_orphan_del(trans, inode);
3975 trans->block_rsv = &root->fs_info->trans_block_rsv;
3976 if (!(root == root->fs_info->tree_root ||
3977 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
3978 btrfs_return_ino(root, btrfs_ino(inode));
3980 btrfs_end_transaction(trans, root);
3981 btrfs_btree_balance_dirty(root);
3988 * this returns the key found in the dir entry in the location pointer.
3989 * If no dir entries were found, location->objectid is 0.
3991 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3992 struct btrfs_key *location)
3994 const char *name = dentry->d_name.name;
3995 int namelen = dentry->d_name.len;
3996 struct btrfs_dir_item *di;
3997 struct btrfs_path *path;
3998 struct btrfs_root *root = BTRFS_I(dir)->root;
4001 path = btrfs_alloc_path();
4005 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4010 if (IS_ERR_OR_NULL(di))
4013 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4015 btrfs_free_path(path);
4018 location->objectid = 0;
4023 * when we hit a tree root in a directory, the btrfs part of the inode
4024 * needs to be changed to reflect the root directory of the tree root. This
4025 * is kind of like crossing a mount point.
4027 static int fixup_tree_root_location(struct btrfs_root *root,
4029 struct dentry *dentry,
4030 struct btrfs_key *location,
4031 struct btrfs_root **sub_root)
4033 struct btrfs_path *path;
4034 struct btrfs_root *new_root;
4035 struct btrfs_root_ref *ref;
4036 struct extent_buffer *leaf;
4040 path = btrfs_alloc_path();
4047 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
4048 BTRFS_I(dir)->root->root_key.objectid,
4049 location->objectid);
4056 leaf = path->nodes[0];
4057 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4058 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4059 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4062 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4063 (unsigned long)(ref + 1),
4064 dentry->d_name.len);
4068 btrfs_release_path(path);
4070 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4071 if (IS_ERR(new_root)) {
4072 err = PTR_ERR(new_root);
4076 if (btrfs_root_refs(&new_root->root_item) == 0) {
4081 *sub_root = new_root;
4082 location->objectid = btrfs_root_dirid(&new_root->root_item);
4083 location->type = BTRFS_INODE_ITEM_KEY;
4084 location->offset = 0;
4087 btrfs_free_path(path);
4091 static void inode_tree_add(struct inode *inode)
4093 struct btrfs_root *root = BTRFS_I(inode)->root;
4094 struct btrfs_inode *entry;
4096 struct rb_node *parent;
4097 u64 ino = btrfs_ino(inode);
4099 p = &root->inode_tree.rb_node;
4102 if (inode_unhashed(inode))
4105 spin_lock(&root->inode_lock);
4108 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4110 if (ino < btrfs_ino(&entry->vfs_inode))
4111 p = &parent->rb_left;
4112 else if (ino > btrfs_ino(&entry->vfs_inode))
4113 p = &parent->rb_right;
4115 WARN_ON(!(entry->vfs_inode.i_state &
4116 (I_WILL_FREE | I_FREEING)));
4117 rb_erase(parent, &root->inode_tree);
4118 RB_CLEAR_NODE(parent);
4119 spin_unlock(&root->inode_lock);
4123 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
4124 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4125 spin_unlock(&root->inode_lock);
4128 static void inode_tree_del(struct inode *inode)
4130 struct btrfs_root *root = BTRFS_I(inode)->root;
4133 spin_lock(&root->inode_lock);
4134 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4135 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4136 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4137 empty = RB_EMPTY_ROOT(&root->inode_tree);
4139 spin_unlock(&root->inode_lock);
4142 * Free space cache has inodes in the tree root, but the tree root has a
4143 * root_refs of 0, so this could end up dropping the tree root as a
4144 * snapshot, so we need the extra !root->fs_info->tree_root check to
4145 * make sure we don't drop it.
4147 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4148 root != root->fs_info->tree_root) {
4149 synchronize_srcu(&root->fs_info->subvol_srcu);
4150 spin_lock(&root->inode_lock);
4151 empty = RB_EMPTY_ROOT(&root->inode_tree);
4152 spin_unlock(&root->inode_lock);
4154 btrfs_add_dead_root(root);
4158 void btrfs_invalidate_inodes(struct btrfs_root *root)
4160 struct rb_node *node;
4161 struct rb_node *prev;
4162 struct btrfs_inode *entry;
4163 struct inode *inode;
4166 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4168 spin_lock(&root->inode_lock);
4170 node = root->inode_tree.rb_node;
4174 entry = rb_entry(node, struct btrfs_inode, rb_node);
4176 if (objectid < btrfs_ino(&entry->vfs_inode))
4177 node = node->rb_left;
4178 else if (objectid > btrfs_ino(&entry->vfs_inode))
4179 node = node->rb_right;
4185 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4186 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4190 prev = rb_next(prev);
4194 entry = rb_entry(node, struct btrfs_inode, rb_node);
4195 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4196 inode = igrab(&entry->vfs_inode);
4198 spin_unlock(&root->inode_lock);
4199 if (atomic_read(&inode->i_count) > 1)
4200 d_prune_aliases(inode);
4202 * btrfs_drop_inode will have it removed from
4203 * the inode cache when its usage count
4208 spin_lock(&root->inode_lock);
4212 if (cond_resched_lock(&root->inode_lock))
4215 node = rb_next(node);
4217 spin_unlock(&root->inode_lock);
4220 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4222 struct btrfs_iget_args *args = p;
4223 inode->i_ino = args->ino;
4224 BTRFS_I(inode)->root = args->root;
4228 static int btrfs_find_actor(struct inode *inode, void *opaque)
4230 struct btrfs_iget_args *args = opaque;
4231 return args->ino == btrfs_ino(inode) &&
4232 args->root == BTRFS_I(inode)->root;
4235 static struct inode *btrfs_iget_locked(struct super_block *s,
4237 struct btrfs_root *root)
4239 struct inode *inode;
4240 struct btrfs_iget_args args;
4241 args.ino = objectid;
4244 inode = iget5_locked(s, objectid, btrfs_find_actor,
4245 btrfs_init_locked_inode,
4250 /* Get an inode object given its location and corresponding root.
4251 * Returns in *is_new if the inode was read from disk
4253 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4254 struct btrfs_root *root, int *new)
4256 struct inode *inode;
4258 inode = btrfs_iget_locked(s, location->objectid, root);
4260 return ERR_PTR(-ENOMEM);
4262 if (inode->i_state & I_NEW) {
4263 BTRFS_I(inode)->root = root;
4264 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4265 btrfs_read_locked_inode(inode);
4266 if (!is_bad_inode(inode)) {
4267 inode_tree_add(inode);
4268 unlock_new_inode(inode);
4272 unlock_new_inode(inode);
4274 inode = ERR_PTR(-ESTALE);
4281 static struct inode *new_simple_dir(struct super_block *s,
4282 struct btrfs_key *key,
4283 struct btrfs_root *root)
4285 struct inode *inode = new_inode(s);
4288 return ERR_PTR(-ENOMEM);
4290 BTRFS_I(inode)->root = root;
4291 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4292 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4294 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4295 inode->i_op = &btrfs_dir_ro_inode_operations;
4296 inode->i_fop = &simple_dir_operations;
4297 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4298 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4303 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4305 struct inode *inode;
4306 struct btrfs_root *root = BTRFS_I(dir)->root;
4307 struct btrfs_root *sub_root = root;
4308 struct btrfs_key location;
4312 if (dentry->d_name.len > BTRFS_NAME_LEN)
4313 return ERR_PTR(-ENAMETOOLONG);
4315 ret = btrfs_inode_by_name(dir, dentry, &location);
4317 return ERR_PTR(ret);
4319 if (location.objectid == 0)
4322 if (location.type == BTRFS_INODE_ITEM_KEY) {
4323 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4327 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4329 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4330 ret = fixup_tree_root_location(root, dir, dentry,
4331 &location, &sub_root);
4334 inode = ERR_PTR(ret);
4336 inode = new_simple_dir(dir->i_sb, &location, sub_root);
4338 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4340 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4342 if (!IS_ERR(inode) && root != sub_root) {
4343 down_read(&root->fs_info->cleanup_work_sem);
4344 if (!(inode->i_sb->s_flags & MS_RDONLY))
4345 ret = btrfs_orphan_cleanup(sub_root);
4346 up_read(&root->fs_info->cleanup_work_sem);
4348 inode = ERR_PTR(ret);
4354 static int btrfs_dentry_delete(const struct dentry *dentry)
4356 struct btrfs_root *root;
4357 struct inode *inode = dentry->d_inode;
4359 if (!inode && !IS_ROOT(dentry))
4360 inode = dentry->d_parent->d_inode;
4363 root = BTRFS_I(inode)->root;
4364 if (btrfs_root_refs(&root->root_item) == 0)
4367 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
4373 static void btrfs_dentry_release(struct dentry *dentry)
4375 if (dentry->d_fsdata)
4376 kfree(dentry->d_fsdata);
4379 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4384 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
4388 unsigned char btrfs_filetype_table[] = {
4389 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4392 static int btrfs_real_readdir(struct file *filp, void *dirent,
4395 struct inode *inode = filp->f_dentry->d_inode;
4396 struct btrfs_root *root = BTRFS_I(inode)->root;
4397 struct btrfs_item *item;
4398 struct btrfs_dir_item *di;
4399 struct btrfs_key key;
4400 struct btrfs_key found_key;
4401 struct btrfs_path *path;
4402 struct list_head ins_list;
4403 struct list_head del_list;
4405 struct extent_buffer *leaf;
4407 unsigned char d_type;
4412 int key_type = BTRFS_DIR_INDEX_KEY;
4416 int is_curr = 0; /* filp->f_pos points to the current index? */
4418 /* FIXME, use a real flag for deciding about the key type */
4419 if (root->fs_info->tree_root == root)
4420 key_type = BTRFS_DIR_ITEM_KEY;
4422 /* special case for "." */
4423 if (filp->f_pos == 0) {
4424 over = filldir(dirent, ".", 1,
4425 filp->f_pos, btrfs_ino(inode), DT_DIR);
4430 /* special case for .., just use the back ref */
4431 if (filp->f_pos == 1) {
4432 u64 pino = parent_ino(filp->f_path.dentry);
4433 over = filldir(dirent, "..", 2,
4434 filp->f_pos, pino, DT_DIR);
4439 path = btrfs_alloc_path();
4445 if (key_type == BTRFS_DIR_INDEX_KEY) {
4446 INIT_LIST_HEAD(&ins_list);
4447 INIT_LIST_HEAD(&del_list);
4448 btrfs_get_delayed_items(inode, &ins_list, &del_list);
4451 btrfs_set_key_type(&key, key_type);
4452 key.offset = filp->f_pos;
4453 key.objectid = btrfs_ino(inode);
4455 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4460 leaf = path->nodes[0];
4461 slot = path->slots[0];
4462 if (slot >= btrfs_header_nritems(leaf)) {
4463 ret = btrfs_next_leaf(root, path);
4471 item = btrfs_item_nr(leaf, slot);
4472 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4474 if (found_key.objectid != key.objectid)
4476 if (btrfs_key_type(&found_key) != key_type)
4478 if (found_key.offset < filp->f_pos)
4480 if (key_type == BTRFS_DIR_INDEX_KEY &&
4481 btrfs_should_delete_dir_index(&del_list,
4485 filp->f_pos = found_key.offset;
4488 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4490 di_total = btrfs_item_size(leaf, item);
4492 while (di_cur < di_total) {
4493 struct btrfs_key location;
4495 if (verify_dir_item(root, leaf, di))
4498 name_len = btrfs_dir_name_len(leaf, di);
4499 if (name_len <= sizeof(tmp_name)) {
4500 name_ptr = tmp_name;
4502 name_ptr = kmalloc(name_len, GFP_NOFS);
4508 read_extent_buffer(leaf, name_ptr,
4509 (unsigned long)(di + 1), name_len);
4511 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4512 btrfs_dir_item_key_to_cpu(leaf, di, &location);
4515 /* is this a reference to our own snapshot? If so
4518 * In contrast to old kernels, we insert the snapshot's
4519 * dir item and dir index after it has been created, so
4520 * we won't find a reference to our own snapshot. We
4521 * still keep the following code for backward
4524 if (location.type == BTRFS_ROOT_ITEM_KEY &&
4525 location.objectid == root->root_key.objectid) {
4529 over = filldir(dirent, name_ptr, name_len,
4530 found_key.offset, location.objectid,
4534 if (name_ptr != tmp_name)
4539 di_len = btrfs_dir_name_len(leaf, di) +
4540 btrfs_dir_data_len(leaf, di) + sizeof(*di);
4542 di = (struct btrfs_dir_item *)((char *)di + di_len);
4548 if (key_type == BTRFS_DIR_INDEX_KEY) {
4551 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
4557 /* Reached end of directory/root. Bump pos past the last item. */
4558 if (key_type == BTRFS_DIR_INDEX_KEY)
4560 * 32-bit glibc will use getdents64, but then strtol -
4561 * so the last number we can serve is this.
4563 filp->f_pos = 0x7fffffff;
4569 if (key_type == BTRFS_DIR_INDEX_KEY)
4570 btrfs_put_delayed_items(&ins_list, &del_list);
4571 btrfs_free_path(path);
4575 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4577 struct btrfs_root *root = BTRFS_I(inode)->root;
4578 struct btrfs_trans_handle *trans;
4580 bool nolock = false;
4582 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4585 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
4588 if (wbc->sync_mode == WB_SYNC_ALL) {
4590 trans = btrfs_join_transaction_nolock(root);
4592 trans = btrfs_join_transaction(root);
4594 return PTR_ERR(trans);
4595 ret = btrfs_commit_transaction(trans, root);
4601 * This is somewhat expensive, updating the tree every time the
4602 * inode changes. But, it is most likely to find the inode in cache.
4603 * FIXME, needs more benchmarking...there are no reasons other than performance
4604 * to keep or drop this code.
4606 int btrfs_dirty_inode(struct inode *inode)
4608 struct btrfs_root *root = BTRFS_I(inode)->root;
4609 struct btrfs_trans_handle *trans;
4612 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4615 trans = btrfs_join_transaction(root);
4617 return PTR_ERR(trans);
4619 ret = btrfs_update_inode(trans, root, inode);
4620 if (ret && ret == -ENOSPC) {
4621 /* whoops, lets try again with the full transaction */
4622 btrfs_end_transaction(trans, root);
4623 trans = btrfs_start_transaction(root, 1);
4625 return PTR_ERR(trans);
4627 ret = btrfs_update_inode(trans, root, inode);
4629 btrfs_end_transaction(trans, root);
4630 if (BTRFS_I(inode)->delayed_node)
4631 btrfs_balance_delayed_items(root);
4637 * This is a copy of file_update_time. We need this so we can return error on
4638 * ENOSPC for updating the inode in the case of file write and mmap writes.
4640 static int btrfs_update_time(struct inode *inode, struct timespec *now,
4643 struct btrfs_root *root = BTRFS_I(inode)->root;
4645 if (btrfs_root_readonly(root))
4648 if (flags & S_VERSION)
4649 inode_inc_iversion(inode);
4650 if (flags & S_CTIME)
4651 inode->i_ctime = *now;
4652 if (flags & S_MTIME)
4653 inode->i_mtime = *now;
4654 if (flags & S_ATIME)
4655 inode->i_atime = *now;
4656 return btrfs_dirty_inode(inode);
4660 * find the highest existing sequence number in a directory
4661 * and then set the in-memory index_cnt variable to reflect
4662 * free sequence numbers
4664 static int btrfs_set_inode_index_count(struct inode *inode)
4666 struct btrfs_root *root = BTRFS_I(inode)->root;
4667 struct btrfs_key key, found_key;
4668 struct btrfs_path *path;
4669 struct extent_buffer *leaf;
4672 key.objectid = btrfs_ino(inode);
4673 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4674 key.offset = (u64)-1;
4676 path = btrfs_alloc_path();
4680 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4683 /* FIXME: we should be able to handle this */
4689 * MAGIC NUMBER EXPLANATION:
4690 * since we search a directory based on f_pos we have to start at 2
4691 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4692 * else has to start at 2
4694 if (path->slots[0] == 0) {
4695 BTRFS_I(inode)->index_cnt = 2;
4701 leaf = path->nodes[0];
4702 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4704 if (found_key.objectid != btrfs_ino(inode) ||
4705 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4706 BTRFS_I(inode)->index_cnt = 2;
4710 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4712 btrfs_free_path(path);
4717 * helper to find a free sequence number in a given directory. This current
4718 * code is very simple, later versions will do smarter things in the btree
4720 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4724 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4725 ret = btrfs_inode_delayed_dir_index_count(dir);
4727 ret = btrfs_set_inode_index_count(dir);
4733 *index = BTRFS_I(dir)->index_cnt;
4734 BTRFS_I(dir)->index_cnt++;
4739 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4740 struct btrfs_root *root,
4742 const char *name, int name_len,
4743 u64 ref_objectid, u64 objectid,
4744 umode_t mode, u64 *index)
4746 struct inode *inode;
4747 struct btrfs_inode_item *inode_item;
4748 struct btrfs_key *location;
4749 struct btrfs_path *path;
4750 struct btrfs_inode_ref *ref;
4751 struct btrfs_key key[2];
4757 path = btrfs_alloc_path();
4759 return ERR_PTR(-ENOMEM);
4761 inode = new_inode(root->fs_info->sb);
4763 btrfs_free_path(path);
4764 return ERR_PTR(-ENOMEM);
4768 * we have to initialize this early, so we can reclaim the inode
4769 * number if we fail afterwards in this function.
4771 inode->i_ino = objectid;
4774 trace_btrfs_inode_request(dir);
4776 ret = btrfs_set_inode_index(dir, index);
4778 btrfs_free_path(path);
4780 return ERR_PTR(ret);
4784 * index_cnt is ignored for everything but a dir,
4785 * btrfs_get_inode_index_count has an explanation for the magic
4788 BTRFS_I(inode)->index_cnt = 2;
4789 BTRFS_I(inode)->root = root;
4790 BTRFS_I(inode)->generation = trans->transid;
4791 inode->i_generation = BTRFS_I(inode)->generation;
4794 * We could have gotten an inode number from somebody who was fsynced
4795 * and then removed in this same transaction, so let's just set full
4796 * sync since it will be a full sync anyway and this will blow away the
4797 * old info in the log.
4799 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
4806 key[0].objectid = objectid;
4807 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4811 * Start new inodes with an inode_ref. This is slightly more
4812 * efficient for small numbers of hard links since they will
4813 * be packed into one item. Extended refs will kick in if we
4814 * add more hard links than can fit in the ref item.
4816 key[1].objectid = objectid;
4817 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4818 key[1].offset = ref_objectid;
4820 sizes[0] = sizeof(struct btrfs_inode_item);
4821 sizes[1] = name_len + sizeof(*ref);
4823 path->leave_spinning = 1;
4824 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4828 inode_init_owner(inode, dir, mode);
4829 inode_set_bytes(inode, 0);
4830 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4831 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4832 struct btrfs_inode_item);
4833 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
4834 sizeof(*inode_item));
4835 fill_inode_item(trans, path->nodes[0], inode_item, inode);
4837 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4838 struct btrfs_inode_ref);
4839 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4840 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4841 ptr = (unsigned long)(ref + 1);
4842 write_extent_buffer(path->nodes[0], name, ptr, name_len);
4844 btrfs_mark_buffer_dirty(path->nodes[0]);
4845 btrfs_free_path(path);
4847 location = &BTRFS_I(inode)->location;
4848 location->objectid = objectid;
4849 location->offset = 0;
4850 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4852 btrfs_inherit_iflags(inode, dir);
4854 if (S_ISREG(mode)) {
4855 if (btrfs_test_opt(root, NODATASUM))
4856 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4857 if (btrfs_test_opt(root, NODATACOW))
4858 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4861 insert_inode_hash(inode);
4862 inode_tree_add(inode);
4864 trace_btrfs_inode_new(inode);
4865 btrfs_set_inode_last_trans(trans, inode);
4867 btrfs_update_root_times(trans, root);
4872 BTRFS_I(dir)->index_cnt--;
4873 btrfs_free_path(path);
4875 return ERR_PTR(ret);
4878 static inline u8 btrfs_inode_type(struct inode *inode)
4880 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4884 * utility function to add 'inode' into 'parent_inode' with
4885 * a give name and a given sequence number.
4886 * if 'add_backref' is true, also insert a backref from the
4887 * inode to the parent directory.
4889 int btrfs_add_link(struct btrfs_trans_handle *trans,
4890 struct inode *parent_inode, struct inode *inode,
4891 const char *name, int name_len, int add_backref, u64 index)
4894 struct btrfs_key key;
4895 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4896 u64 ino = btrfs_ino(inode);
4897 u64 parent_ino = btrfs_ino(parent_inode);
4899 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4900 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4903 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4907 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4908 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4909 key.objectid, root->root_key.objectid,
4910 parent_ino, index, name, name_len);
4911 } else if (add_backref) {
4912 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
4916 /* Nothing to clean up yet */
4920 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4922 btrfs_inode_type(inode), index);
4923 if (ret == -EEXIST || ret == -EOVERFLOW)
4926 btrfs_abort_transaction(trans, root, ret);
4930 btrfs_i_size_write(parent_inode, parent_inode->i_size +
4932 inode_inc_iversion(parent_inode);
4933 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4934 ret = btrfs_update_inode(trans, root, parent_inode);
4936 btrfs_abort_transaction(trans, root, ret);
4940 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4943 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4944 key.objectid, root->root_key.objectid,
4945 parent_ino, &local_index, name, name_len);
4947 } else if (add_backref) {
4951 err = btrfs_del_inode_ref(trans, root, name, name_len,
4952 ino, parent_ino, &local_index);
4957 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4958 struct inode *dir, struct dentry *dentry,
4959 struct inode *inode, int backref, u64 index)
4961 int err = btrfs_add_link(trans, dir, inode,
4962 dentry->d_name.name, dentry->d_name.len,
4969 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4970 umode_t mode, dev_t rdev)
4972 struct btrfs_trans_handle *trans;
4973 struct btrfs_root *root = BTRFS_I(dir)->root;
4974 struct inode *inode = NULL;
4980 if (!new_valid_dev(rdev))
4984 * 2 for inode item and ref
4986 * 1 for xattr if selinux is on
4988 trans = btrfs_start_transaction(root, 5);
4990 return PTR_ERR(trans);
4992 err = btrfs_find_free_ino(root, &objectid);
4996 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4997 dentry->d_name.len, btrfs_ino(dir), objectid,
4999 if (IS_ERR(inode)) {
5000 err = PTR_ERR(inode);
5004 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5010 err = btrfs_update_inode(trans, root, inode);
5017 * If the active LSM wants to access the inode during
5018 * d_instantiate it needs these. Smack checks to see
5019 * if the filesystem supports xattrs by looking at the
5023 inode->i_op = &btrfs_special_inode_operations;
5024 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5028 init_special_inode(inode, inode->i_mode, rdev);
5029 btrfs_update_inode(trans, root, inode);
5030 d_instantiate(dentry, inode);
5033 btrfs_end_transaction(trans, root);
5034 btrfs_btree_balance_dirty(root);
5036 inode_dec_link_count(inode);
5042 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5043 umode_t mode, bool excl)
5045 struct btrfs_trans_handle *trans;
5046 struct btrfs_root *root = BTRFS_I(dir)->root;
5047 struct inode *inode = NULL;
5048 int drop_inode_on_err = 0;
5054 * 2 for inode item and ref
5056 * 1 for xattr if selinux is on
5058 trans = btrfs_start_transaction(root, 5);
5060 return PTR_ERR(trans);
5062 err = btrfs_find_free_ino(root, &objectid);
5066 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5067 dentry->d_name.len, btrfs_ino(dir), objectid,
5069 if (IS_ERR(inode)) {
5070 err = PTR_ERR(inode);
5073 drop_inode_on_err = 1;
5075 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5079 err = btrfs_update_inode(trans, root, inode);
5084 * If the active LSM wants to access the inode during
5085 * d_instantiate it needs these. Smack checks to see
5086 * if the filesystem supports xattrs by looking at the
5089 inode->i_fop = &btrfs_file_operations;
5090 inode->i_op = &btrfs_file_inode_operations;
5092 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5096 inode->i_mapping->a_ops = &btrfs_aops;
5097 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5098 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5099 d_instantiate(dentry, inode);
5102 btrfs_end_transaction(trans, root);
5103 if (err && drop_inode_on_err) {
5104 inode_dec_link_count(inode);
5107 btrfs_btree_balance_dirty(root);
5111 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5112 struct dentry *dentry)
5114 struct btrfs_trans_handle *trans;
5115 struct btrfs_root *root = BTRFS_I(dir)->root;
5116 struct inode *inode = old_dentry->d_inode;
5121 /* do not allow sys_link's with other subvols of the same device */
5122 if (root->objectid != BTRFS_I(inode)->root->objectid)
5125 if (inode->i_nlink >= BTRFS_LINK_MAX)
5128 err = btrfs_set_inode_index(dir, &index);
5133 * 2 items for inode and inode ref
5134 * 2 items for dir items
5135 * 1 item for parent inode
5137 trans = btrfs_start_transaction(root, 5);
5138 if (IS_ERR(trans)) {
5139 err = PTR_ERR(trans);
5143 btrfs_inc_nlink(inode);
5144 inode_inc_iversion(inode);
5145 inode->i_ctime = CURRENT_TIME;
5147 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5149 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5154 struct dentry *parent = dentry->d_parent;
5155 err = btrfs_update_inode(trans, root, inode);
5158 d_instantiate(dentry, inode);
5159 btrfs_log_new_name(trans, inode, NULL, parent);
5162 btrfs_end_transaction(trans, root);
5165 inode_dec_link_count(inode);
5168 btrfs_btree_balance_dirty(root);
5172 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5174 struct inode *inode = NULL;
5175 struct btrfs_trans_handle *trans;
5176 struct btrfs_root *root = BTRFS_I(dir)->root;
5178 int drop_on_err = 0;
5183 * 2 items for inode and ref
5184 * 2 items for dir items
5185 * 1 for xattr if selinux is on
5187 trans = btrfs_start_transaction(root, 5);
5189 return PTR_ERR(trans);
5191 err = btrfs_find_free_ino(root, &objectid);
5195 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5196 dentry->d_name.len, btrfs_ino(dir), objectid,
5197 S_IFDIR | mode, &index);
5198 if (IS_ERR(inode)) {
5199 err = PTR_ERR(inode);
5205 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5209 inode->i_op = &btrfs_dir_inode_operations;
5210 inode->i_fop = &btrfs_dir_file_operations;
5212 btrfs_i_size_write(inode, 0);
5213 err = btrfs_update_inode(trans, root, inode);
5217 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5218 dentry->d_name.len, 0, index);
5222 d_instantiate(dentry, inode);
5226 btrfs_end_transaction(trans, root);
5229 btrfs_btree_balance_dirty(root);
5233 /* helper for btfs_get_extent. Given an existing extent in the tree,
5234 * and an extent that you want to insert, deal with overlap and insert
5235 * the new extent into the tree.
5237 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5238 struct extent_map *existing,
5239 struct extent_map *em,
5240 u64 map_start, u64 map_len)
5244 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5245 start_diff = map_start - em->start;
5246 em->start = map_start;
5248 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5249 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5250 em->block_start += start_diff;
5251 em->block_len -= start_diff;
5253 return add_extent_mapping(em_tree, em);
5256 static noinline int uncompress_inline(struct btrfs_path *path,
5257 struct inode *inode, struct page *page,
5258 size_t pg_offset, u64 extent_offset,
5259 struct btrfs_file_extent_item *item)
5262 struct extent_buffer *leaf = path->nodes[0];
5265 unsigned long inline_size;
5269 WARN_ON(pg_offset != 0);
5270 compress_type = btrfs_file_extent_compression(leaf, item);
5271 max_size = btrfs_file_extent_ram_bytes(leaf, item);
5272 inline_size = btrfs_file_extent_inline_item_len(leaf,
5273 btrfs_item_nr(leaf, path->slots[0]));
5274 tmp = kmalloc(inline_size, GFP_NOFS);
5277 ptr = btrfs_file_extent_inline_start(item);
5279 read_extent_buffer(leaf, tmp, ptr, inline_size);
5281 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
5282 ret = btrfs_decompress(compress_type, tmp, page,
5283 extent_offset, inline_size, max_size);
5285 char *kaddr = kmap_atomic(page);
5286 unsigned long copy_size = min_t(u64,
5287 PAGE_CACHE_SIZE - pg_offset,
5288 max_size - extent_offset);
5289 memset(kaddr + pg_offset, 0, copy_size);
5290 kunmap_atomic(kaddr);
5297 * a bit scary, this does extent mapping from logical file offset to the disk.
5298 * the ugly parts come from merging extents from the disk with the in-ram
5299 * representation. This gets more complex because of the data=ordered code,
5300 * where the in-ram extents might be locked pending data=ordered completion.
5302 * This also copies inline extents directly into the page.
5305 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
5306 size_t pg_offset, u64 start, u64 len,
5312 u64 extent_start = 0;
5314 u64 objectid = btrfs_ino(inode);
5316 struct btrfs_path *path = NULL;
5317 struct btrfs_root *root = BTRFS_I(inode)->root;
5318 struct btrfs_file_extent_item *item;
5319 struct extent_buffer *leaf;
5320 struct btrfs_key found_key;
5321 struct extent_map *em = NULL;
5322 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5323 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5324 struct btrfs_trans_handle *trans = NULL;
5328 read_lock(&em_tree->lock);
5329 em = lookup_extent_mapping(em_tree, start, len);
5331 em->bdev = root->fs_info->fs_devices->latest_bdev;
5332 read_unlock(&em_tree->lock);
5335 if (em->start > start || em->start + em->len <= start)
5336 free_extent_map(em);
5337 else if (em->block_start == EXTENT_MAP_INLINE && page)
5338 free_extent_map(em);
5342 em = alloc_extent_map();
5347 em->bdev = root->fs_info->fs_devices->latest_bdev;
5348 em->start = EXTENT_MAP_HOLE;
5349 em->orig_start = EXTENT_MAP_HOLE;
5351 em->block_len = (u64)-1;
5354 path = btrfs_alloc_path();
5360 * Chances are we'll be called again, so go ahead and do
5366 ret = btrfs_lookup_file_extent(trans, root, path,
5367 objectid, start, trans != NULL);
5374 if (path->slots[0] == 0)
5379 leaf = path->nodes[0];
5380 item = btrfs_item_ptr(leaf, path->slots[0],
5381 struct btrfs_file_extent_item);
5382 /* are we inside the extent that was found? */
5383 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5384 found_type = btrfs_key_type(&found_key);
5385 if (found_key.objectid != objectid ||
5386 found_type != BTRFS_EXTENT_DATA_KEY) {
5390 found_type = btrfs_file_extent_type(leaf, item);
5391 extent_start = found_key.offset;
5392 compress_type = btrfs_file_extent_compression(leaf, item);
5393 if (found_type == BTRFS_FILE_EXTENT_REG ||
5394 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5395 extent_end = extent_start +
5396 btrfs_file_extent_num_bytes(leaf, item);
5397 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5399 size = btrfs_file_extent_inline_len(leaf, item);
5400 extent_end = (extent_start + size + root->sectorsize - 1) &
5401 ~((u64)root->sectorsize - 1);
5404 if (start >= extent_end) {
5406 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
5407 ret = btrfs_next_leaf(root, path);
5414 leaf = path->nodes[0];
5416 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5417 if (found_key.objectid != objectid ||
5418 found_key.type != BTRFS_EXTENT_DATA_KEY)
5420 if (start + len <= found_key.offset)
5423 em->orig_start = start;
5424 em->len = found_key.offset - start;
5428 if (found_type == BTRFS_FILE_EXTENT_REG ||
5429 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5430 em->start = extent_start;
5431 em->len = extent_end - extent_start;
5432 em->orig_start = extent_start -
5433 btrfs_file_extent_offset(leaf, item);
5434 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
5436 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5438 em->block_start = EXTENT_MAP_HOLE;
5441 if (compress_type != BTRFS_COMPRESS_NONE) {
5442 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5443 em->compress_type = compress_type;
5444 em->block_start = bytenr;
5445 em->block_len = em->orig_block_len;
5447 bytenr += btrfs_file_extent_offset(leaf, item);
5448 em->block_start = bytenr;
5449 em->block_len = em->len;
5450 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5451 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5454 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5458 size_t extent_offset;
5461 em->block_start = EXTENT_MAP_INLINE;
5462 if (!page || create) {
5463 em->start = extent_start;
5464 em->len = extent_end - extent_start;
5468 size = btrfs_file_extent_inline_len(leaf, item);
5469 extent_offset = page_offset(page) + pg_offset - extent_start;
5470 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
5471 size - extent_offset);
5472 em->start = extent_start + extent_offset;
5473 em->len = (copy_size + root->sectorsize - 1) &
5474 ~((u64)root->sectorsize - 1);
5475 em->orig_block_len = em->len;
5476 em->orig_start = em->start;
5477 if (compress_type) {
5478 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5479 em->compress_type = compress_type;
5481 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5482 if (create == 0 && !PageUptodate(page)) {
5483 if (btrfs_file_extent_compression(leaf, item) !=
5484 BTRFS_COMPRESS_NONE) {
5485 ret = uncompress_inline(path, inode, page,
5487 extent_offset, item);
5488 BUG_ON(ret); /* -ENOMEM */
5491 read_extent_buffer(leaf, map + pg_offset, ptr,
5493 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5494 memset(map + pg_offset + copy_size, 0,
5495 PAGE_CACHE_SIZE - pg_offset -
5500 flush_dcache_page(page);
5501 } else if (create && PageUptodate(page)) {
5505 free_extent_map(em);
5508 btrfs_release_path(path);
5509 trans = btrfs_join_transaction(root);
5512 return ERR_CAST(trans);
5516 write_extent_buffer(leaf, map + pg_offset, ptr,
5519 btrfs_mark_buffer_dirty(leaf);
5521 set_extent_uptodate(io_tree, em->start,
5522 extent_map_end(em) - 1, NULL, GFP_NOFS);
5525 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
5529 em->orig_start = start;
5532 em->block_start = EXTENT_MAP_HOLE;
5533 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5535 btrfs_release_path(path);
5536 if (em->start > start || extent_map_end(em) <= start) {
5537 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5538 "[%llu %llu]\n", (unsigned long long)em->start,
5539 (unsigned long long)em->len,
5540 (unsigned long long)start,
5541 (unsigned long long)len);
5547 write_lock(&em_tree->lock);
5548 ret = add_extent_mapping(em_tree, em);
5549 /* it is possible that someone inserted the extent into the tree
5550 * while we had the lock dropped. It is also possible that
5551 * an overlapping map exists in the tree
5553 if (ret == -EEXIST) {
5554 struct extent_map *existing;
5558 existing = lookup_extent_mapping(em_tree, start, len);
5559 if (existing && (existing->start > start ||
5560 existing->start + existing->len <= start)) {
5561 free_extent_map(existing);
5565 existing = lookup_extent_mapping(em_tree, em->start,
5568 err = merge_extent_mapping(em_tree, existing,
5571 free_extent_map(existing);
5573 free_extent_map(em);
5578 free_extent_map(em);
5582 free_extent_map(em);
5587 write_unlock(&em_tree->lock);
5591 trace_btrfs_get_extent(root, em);
5594 btrfs_free_path(path);
5596 ret = btrfs_end_transaction(trans, root);
5601 free_extent_map(em);
5602 return ERR_PTR(err);
5604 BUG_ON(!em); /* Error is always set */
5608 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
5609 size_t pg_offset, u64 start, u64 len,
5612 struct extent_map *em;
5613 struct extent_map *hole_em = NULL;
5614 u64 range_start = start;
5620 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
5627 * - a pre-alloc extent,
5628 * there might actually be delalloc bytes behind it.
5630 if (em->block_start != EXTENT_MAP_HOLE &&
5631 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5637 /* check to see if we've wrapped (len == -1 or similar) */
5646 /* ok, we didn't find anything, lets look for delalloc */
5647 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
5648 end, len, EXTENT_DELALLOC, 1);
5649 found_end = range_start + found;
5650 if (found_end < range_start)
5651 found_end = (u64)-1;
5654 * we didn't find anything useful, return
5655 * the original results from get_extent()
5657 if (range_start > end || found_end <= start) {
5663 /* adjust the range_start to make sure it doesn't
5664 * go backwards from the start they passed in
5666 range_start = max(start,range_start);
5667 found = found_end - range_start;
5670 u64 hole_start = start;
5673 em = alloc_extent_map();
5679 * when btrfs_get_extent can't find anything it
5680 * returns one huge hole
5682 * make sure what it found really fits our range, and
5683 * adjust to make sure it is based on the start from
5687 u64 calc_end = extent_map_end(hole_em);
5689 if (calc_end <= start || (hole_em->start > end)) {
5690 free_extent_map(hole_em);
5693 hole_start = max(hole_em->start, start);
5694 hole_len = calc_end - hole_start;
5698 if (hole_em && range_start > hole_start) {
5699 /* our hole starts before our delalloc, so we
5700 * have to return just the parts of the hole
5701 * that go until the delalloc starts
5703 em->len = min(hole_len,
5704 range_start - hole_start);
5705 em->start = hole_start;
5706 em->orig_start = hole_start;
5708 * don't adjust block start at all,
5709 * it is fixed at EXTENT_MAP_HOLE
5711 em->block_start = hole_em->block_start;
5712 em->block_len = hole_len;
5713 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
5714 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5716 em->start = range_start;
5718 em->orig_start = range_start;
5719 em->block_start = EXTENT_MAP_DELALLOC;
5720 em->block_len = found;
5722 } else if (hole_em) {
5727 free_extent_map(hole_em);
5729 free_extent_map(em);
5730 return ERR_PTR(err);
5735 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5738 struct btrfs_root *root = BTRFS_I(inode)->root;
5739 struct btrfs_trans_handle *trans;
5740 struct extent_map *em;
5741 struct btrfs_key ins;
5745 trans = btrfs_join_transaction(root);
5747 return ERR_CAST(trans);
5749 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5751 alloc_hint = get_extent_allocation_hint(inode, start, len);
5752 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5753 alloc_hint, &ins, 1);
5759 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
5760 ins.offset, ins.offset, 0);
5764 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5765 ins.offset, ins.offset, 0);
5767 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5771 btrfs_end_transaction(trans, root);
5776 * returns 1 when the nocow is safe, < 1 on error, 0 if the
5777 * block must be cow'd
5779 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5780 struct inode *inode, u64 offset, u64 len)
5782 struct btrfs_path *path;
5784 struct extent_buffer *leaf;
5785 struct btrfs_root *root = BTRFS_I(inode)->root;
5786 struct btrfs_file_extent_item *fi;
5787 struct btrfs_key key;
5795 path = btrfs_alloc_path();
5799 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
5804 slot = path->slots[0];
5807 /* can't find the item, must cow */
5814 leaf = path->nodes[0];
5815 btrfs_item_key_to_cpu(leaf, &key, slot);
5816 if (key.objectid != btrfs_ino(inode) ||
5817 key.type != BTRFS_EXTENT_DATA_KEY) {
5818 /* not our file or wrong item type, must cow */
5822 if (key.offset > offset) {
5823 /* Wrong offset, must cow */
5827 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5828 found_type = btrfs_file_extent_type(leaf, fi);
5829 if (found_type != BTRFS_FILE_EXTENT_REG &&
5830 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5831 /* not a regular extent, must cow */
5834 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5835 backref_offset = btrfs_file_extent_offset(leaf, fi);
5837 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5838 if (extent_end < offset + len) {
5839 /* extent doesn't include our full range, must cow */
5843 if (btrfs_extent_readonly(root, disk_bytenr))
5847 * look for other files referencing this extent, if we
5848 * find any we must cow
5850 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
5851 key.offset - backref_offset, disk_bytenr))
5855 * adjust disk_bytenr and num_bytes to cover just the bytes
5856 * in this extent we are about to write. If there
5857 * are any csums in that range we have to cow in order
5858 * to keep the csums correct
5860 disk_bytenr += backref_offset;
5861 disk_bytenr += offset - key.offset;
5862 num_bytes = min(offset + len, extent_end) - offset;
5863 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5866 * all of the above have passed, it is safe to overwrite this extent
5871 btrfs_free_path(path);
5875 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
5876 struct extent_state **cached_state, int writing)
5878 struct btrfs_ordered_extent *ordered;
5882 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5885 * We're concerned with the entire range that we're going to be
5886 * doing DIO to, so we need to make sure theres no ordered
5887 * extents in this range.
5889 ordered = btrfs_lookup_ordered_range(inode, lockstart,
5890 lockend - lockstart + 1);
5893 * We need to make sure there are no buffered pages in this
5894 * range either, we could have raced between the invalidate in
5895 * generic_file_direct_write and locking the extent. The
5896 * invalidate needs to happen so that reads after a write do not
5899 if (!ordered && (!writing ||
5900 !test_range_bit(&BTRFS_I(inode)->io_tree,
5901 lockstart, lockend, EXTENT_UPTODATE, 0,
5905 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5906 cached_state, GFP_NOFS);
5909 btrfs_start_ordered_extent(inode, ordered, 1);
5910 btrfs_put_ordered_extent(ordered);
5912 /* Screw you mmap */
5913 ret = filemap_write_and_wait_range(inode->i_mapping,
5920 * If we found a page that couldn't be invalidated just
5921 * fall back to buffered.
5923 ret = invalidate_inode_pages2_range(inode->i_mapping,
5924 lockstart >> PAGE_CACHE_SHIFT,
5925 lockend >> PAGE_CACHE_SHIFT);
5936 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
5937 u64 len, u64 orig_start,
5938 u64 block_start, u64 block_len,
5939 u64 orig_block_len, int type)
5941 struct extent_map_tree *em_tree;
5942 struct extent_map *em;
5943 struct btrfs_root *root = BTRFS_I(inode)->root;
5946 em_tree = &BTRFS_I(inode)->extent_tree;
5947 em = alloc_extent_map();
5949 return ERR_PTR(-ENOMEM);
5952 em->orig_start = orig_start;
5954 em->block_len = block_len;
5955 em->block_start = block_start;
5956 em->bdev = root->fs_info->fs_devices->latest_bdev;
5957 em->orig_block_len = orig_block_len;
5958 em->generation = -1;
5959 set_bit(EXTENT_FLAG_PINNED, &em->flags);
5960 if (type == BTRFS_ORDERED_PREALLOC)
5961 set_bit(EXTENT_FLAG_FILLING, &em->flags);
5964 btrfs_drop_extent_cache(inode, em->start,
5965 em->start + em->len - 1, 0);
5966 write_lock(&em_tree->lock);
5967 ret = add_extent_mapping(em_tree, em);
5969 list_move(&em->list,
5970 &em_tree->modified_extents);
5971 write_unlock(&em_tree->lock);
5972 } while (ret == -EEXIST);
5975 free_extent_map(em);
5976 return ERR_PTR(ret);
5983 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
5984 struct buffer_head *bh_result, int create)
5986 struct extent_map *em;
5987 struct btrfs_root *root = BTRFS_I(inode)->root;
5988 struct extent_state *cached_state = NULL;
5989 u64 start = iblock << inode->i_blkbits;
5990 u64 lockstart, lockend;
5991 u64 len = bh_result->b_size;
5992 struct btrfs_trans_handle *trans;
5993 int unlock_bits = EXTENT_LOCKED;
5997 ret = btrfs_delalloc_reserve_space(inode, len);
6000 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6002 len = min_t(u64, len, root->sectorsize);
6006 lockend = start + len - 1;
6009 * If this errors out it's because we couldn't invalidate pagecache for
6010 * this range and we need to fallback to buffered.
6012 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6016 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6017 lockend, EXTENT_DELALLOC, NULL,
6018 &cached_state, GFP_NOFS);
6023 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6030 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6031 * io. INLINE is special, and we could probably kludge it in here, but
6032 * it's still buffered so for safety lets just fall back to the generic
6035 * For COMPRESSED we _have_ to read the entire extent in so we can
6036 * decompress it, so there will be buffering required no matter what we
6037 * do, so go ahead and fallback to buffered.
6039 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6040 * to buffered IO. Don't blame me, this is the price we pay for using
6043 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6044 em->block_start == EXTENT_MAP_INLINE) {
6045 free_extent_map(em);
6050 /* Just a good old fashioned hole, return */
6051 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6052 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6053 free_extent_map(em);
6059 * We don't allocate a new extent in the following cases
6061 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6063 * 2) The extent is marked as PREALLOC. We're good to go here and can
6064 * just use the extent.
6068 len = min(len, em->len - (start - em->start));
6069 lockstart = start + len;
6073 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6074 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6075 em->block_start != EXTENT_MAP_HOLE)) {
6080 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6081 type = BTRFS_ORDERED_PREALLOC;
6083 type = BTRFS_ORDERED_NOCOW;
6084 len = min(len, em->len - (start - em->start));
6085 block_start = em->block_start + (start - em->start);
6088 * we're not going to log anything, but we do need
6089 * to make sure the current transaction stays open
6090 * while we look for nocow cross refs
6092 trans = btrfs_join_transaction(root);
6096 if (can_nocow_odirect(trans, inode, start, len) == 1) {
6097 u64 orig_start = em->orig_start;
6098 u64 orig_block_len = em->orig_block_len;
6100 if (type == BTRFS_ORDERED_PREALLOC) {
6101 free_extent_map(em);
6102 em = create_pinned_em(inode, start, len,
6105 orig_block_len, type);
6107 btrfs_end_transaction(trans, root);
6112 ret = btrfs_add_ordered_extent_dio(inode, start,
6113 block_start, len, len, type);
6114 btrfs_end_transaction(trans, root);
6116 free_extent_map(em);
6121 btrfs_end_transaction(trans, root);
6125 * this will cow the extent, reset the len in case we changed
6128 len = bh_result->b_size;
6129 free_extent_map(em);
6130 em = btrfs_new_extent_direct(inode, start, len);
6135 len = min(len, em->len - (start - em->start));
6137 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6139 bh_result->b_size = len;
6140 bh_result->b_bdev = em->bdev;
6141 set_buffer_mapped(bh_result);
6143 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6144 set_buffer_new(bh_result);
6147 * Need to update the i_size under the extent lock so buffered
6148 * readers will get the updated i_size when we unlock.
6150 if (start + len > i_size_read(inode))
6151 i_size_write(inode, start + len);
6155 * In the case of write we need to clear and unlock the entire range,
6156 * in the case of read we need to unlock only the end area that we
6157 * aren't using if there is any left over space.
6159 if (lockstart < lockend) {
6160 if (create && len < lockend - lockstart) {
6161 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6162 lockstart + len - 1,
6163 unlock_bits | EXTENT_DEFRAG, 1, 0,
6164 &cached_state, GFP_NOFS);
6166 * Beside unlock, we also need to cleanup reserved space
6167 * for the left range by attaching EXTENT_DO_ACCOUNTING.
6169 clear_extent_bit(&BTRFS_I(inode)->io_tree,
6170 lockstart + len, lockend,
6171 unlock_bits | EXTENT_DO_ACCOUNTING |
6172 EXTENT_DEFRAG, 1, 0, NULL, GFP_NOFS);
6174 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6175 lockend, unlock_bits, 1, 0,
6176 &cached_state, GFP_NOFS);
6179 free_extent_state(cached_state);
6182 free_extent_map(em);
6188 unlock_bits |= EXTENT_DO_ACCOUNTING;
6190 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6191 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6195 struct btrfs_dio_private {
6196 struct inode *inode;
6202 /* number of bios pending for this dio */
6203 atomic_t pending_bios;
6208 struct bio *orig_bio;
6211 static void btrfs_endio_direct_read(struct bio *bio, int err)
6213 struct btrfs_dio_private *dip = bio->bi_private;
6214 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6215 struct bio_vec *bvec = bio->bi_io_vec;
6216 struct inode *inode = dip->inode;
6217 struct btrfs_root *root = BTRFS_I(inode)->root;
6220 start = dip->logical_offset;
6222 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6223 struct page *page = bvec->bv_page;
6226 u64 private = ~(u32)0;
6227 unsigned long flags;
6229 if (get_state_private(&BTRFS_I(inode)->io_tree,
6232 local_irq_save(flags);
6233 kaddr = kmap_atomic(page);
6234 csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
6235 csum, bvec->bv_len);
6236 btrfs_csum_final(csum, (char *)&csum);
6237 kunmap_atomic(kaddr);
6238 local_irq_restore(flags);
6240 flush_dcache_page(bvec->bv_page);
6241 if (csum != private) {
6243 printk(KERN_ERR "btrfs csum failed ino %llu off"
6244 " %llu csum %u private %u\n",
6245 (unsigned long long)btrfs_ino(inode),
6246 (unsigned long long)start,
6247 csum, (unsigned)private);
6252 start += bvec->bv_len;
6254 } while (bvec <= bvec_end);
6256 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6257 dip->logical_offset + dip->bytes - 1);
6258 bio->bi_private = dip->private;
6262 /* If we had a csum failure make sure to clear the uptodate flag */
6264 clear_bit(BIO_UPTODATE, &bio->bi_flags);
6265 dio_end_io(bio, err);
6268 static void btrfs_endio_direct_write(struct bio *bio, int err)
6270 struct btrfs_dio_private *dip = bio->bi_private;
6271 struct inode *inode = dip->inode;
6272 struct btrfs_root *root = BTRFS_I(inode)->root;
6273 struct btrfs_ordered_extent *ordered = NULL;
6274 u64 ordered_offset = dip->logical_offset;
6275 u64 ordered_bytes = dip->bytes;
6281 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
6283 ordered_bytes, !err);
6287 ordered->work.func = finish_ordered_fn;
6288 ordered->work.flags = 0;
6289 btrfs_queue_worker(&root->fs_info->endio_write_workers,
6293 * our bio might span multiple ordered extents. If we haven't
6294 * completed the accounting for the whole dio, go back and try again
6296 if (ordered_offset < dip->logical_offset + dip->bytes) {
6297 ordered_bytes = dip->logical_offset + dip->bytes -
6303 bio->bi_private = dip->private;
6307 /* If we had an error make sure to clear the uptodate flag */
6309 clear_bit(BIO_UPTODATE, &bio->bi_flags);
6310 dio_end_io(bio, err);
6313 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
6314 struct bio *bio, int mirror_num,
6315 unsigned long bio_flags, u64 offset)
6318 struct btrfs_root *root = BTRFS_I(inode)->root;
6319 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
6320 BUG_ON(ret); /* -ENOMEM */
6324 static void btrfs_end_dio_bio(struct bio *bio, int err)
6326 struct btrfs_dio_private *dip = bio->bi_private;
6329 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
6330 "sector %#Lx len %u err no %d\n",
6331 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
6332 (unsigned long long)bio->bi_sector, bio->bi_size, err);
6336 * before atomic variable goto zero, we must make sure
6337 * dip->errors is perceived to be set.
6339 smp_mb__before_atomic_dec();
6342 /* if there are more bios still pending for this dio, just exit */
6343 if (!atomic_dec_and_test(&dip->pending_bios))
6347 bio_io_error(dip->orig_bio);
6349 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
6350 bio_endio(dip->orig_bio, 0);
6356 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
6357 u64 first_sector, gfp_t gfp_flags)
6359 int nr_vecs = bio_get_nr_vecs(bdev);
6360 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
6363 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
6364 int rw, u64 file_offset, int skip_sum,
6367 int write = rw & REQ_WRITE;
6368 struct btrfs_root *root = BTRFS_I(inode)->root;
6372 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
6377 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
6385 if (write && async_submit) {
6386 ret = btrfs_wq_submit_bio(root->fs_info,
6387 inode, rw, bio, 0, 0,
6389 __btrfs_submit_bio_start_direct_io,
6390 __btrfs_submit_bio_done);
6394 * If we aren't doing async submit, calculate the csum of the
6397 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
6400 } else if (!skip_sum) {
6401 ret = btrfs_lookup_bio_sums_dio(root, inode, bio, file_offset);
6407 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
6413 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
6416 struct inode *inode = dip->inode;
6417 struct btrfs_root *root = BTRFS_I(inode)->root;
6419 struct bio *orig_bio = dip->orig_bio;
6420 struct bio_vec *bvec = orig_bio->bi_io_vec;
6421 u64 start_sector = orig_bio->bi_sector;
6422 u64 file_offset = dip->logical_offset;
6427 int async_submit = 0;
6429 map_length = orig_bio->bi_size;
6430 ret = btrfs_map_block(root->fs_info, READ, start_sector << 9,
6431 &map_length, NULL, 0);
6437 if (map_length >= orig_bio->bi_size) {
6443 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
6446 bio->bi_private = dip;
6447 bio->bi_end_io = btrfs_end_dio_bio;
6448 atomic_inc(&dip->pending_bios);
6450 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
6451 if (unlikely(map_length < submit_len + bvec->bv_len ||
6452 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
6453 bvec->bv_offset) < bvec->bv_len)) {
6455 * inc the count before we submit the bio so
6456 * we know the end IO handler won't happen before
6457 * we inc the count. Otherwise, the dip might get freed
6458 * before we're done setting it up
6460 atomic_inc(&dip->pending_bios);
6461 ret = __btrfs_submit_dio_bio(bio, inode, rw,
6462 file_offset, skip_sum,
6466 atomic_dec(&dip->pending_bios);
6470 start_sector += submit_len >> 9;
6471 file_offset += submit_len;
6476 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
6477 start_sector, GFP_NOFS);
6480 bio->bi_private = dip;
6481 bio->bi_end_io = btrfs_end_dio_bio;
6483 map_length = orig_bio->bi_size;
6484 ret = btrfs_map_block(root->fs_info, READ,
6486 &map_length, NULL, 0);
6492 submit_len += bvec->bv_len;
6499 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
6508 * before atomic variable goto zero, we must
6509 * make sure dip->errors is perceived to be set.
6511 smp_mb__before_atomic_dec();
6512 if (atomic_dec_and_test(&dip->pending_bios))
6513 bio_io_error(dip->orig_bio);
6515 /* bio_end_io() will handle error, so we needn't return it */
6519 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
6522 struct btrfs_root *root = BTRFS_I(inode)->root;
6523 struct btrfs_dio_private *dip;
6524 struct bio_vec *bvec = bio->bi_io_vec;
6526 int write = rw & REQ_WRITE;
6529 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
6531 dip = kmalloc(sizeof(*dip), GFP_NOFS);
6537 dip->private = bio->bi_private;
6539 dip->logical_offset = file_offset;
6543 dip->bytes += bvec->bv_len;
6545 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
6547 dip->disk_bytenr = (u64)bio->bi_sector << 9;
6548 bio->bi_private = dip;
6550 dip->orig_bio = bio;
6551 atomic_set(&dip->pending_bios, 0);
6554 bio->bi_end_io = btrfs_endio_direct_write;
6556 bio->bi_end_io = btrfs_endio_direct_read;
6558 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
6563 * If this is a write, we need to clean up the reserved space and kill
6564 * the ordered extent.
6567 struct btrfs_ordered_extent *ordered;
6568 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
6569 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
6570 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
6571 btrfs_free_reserved_extent(root, ordered->start,
6573 btrfs_put_ordered_extent(ordered);
6574 btrfs_put_ordered_extent(ordered);
6576 bio_endio(bio, ret);
6579 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
6580 const struct iovec *iov, loff_t offset,
6581 unsigned long nr_segs)
6587 unsigned blocksize_mask = root->sectorsize - 1;
6588 ssize_t retval = -EINVAL;
6589 loff_t end = offset;
6591 if (offset & blocksize_mask)
6594 /* Check the memory alignment. Blocks cannot straddle pages */
6595 for (seg = 0; seg < nr_segs; seg++) {
6596 addr = (unsigned long)iov[seg].iov_base;
6597 size = iov[seg].iov_len;
6599 if ((addr & blocksize_mask) || (size & blocksize_mask))
6602 /* If this is a write we don't need to check anymore */
6607 * Check to make sure we don't have duplicate iov_base's in this
6608 * iovec, if so return EINVAL, otherwise we'll get csum errors
6609 * when reading back.
6611 for (i = seg + 1; i < nr_segs; i++) {
6612 if (iov[seg].iov_base == iov[i].iov_base)
6621 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
6622 const struct iovec *iov, loff_t offset,
6623 unsigned long nr_segs)
6625 struct file *file = iocb->ki_filp;
6626 struct inode *inode = file->f_mapping->host;
6628 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
6632 return __blockdev_direct_IO(rw, iocb, inode,
6633 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
6634 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
6635 btrfs_submit_direct, 0);
6638 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
6640 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
6641 __u64 start, __u64 len)
6645 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
6649 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
6652 int btrfs_readpage(struct file *file, struct page *page)
6654 struct extent_io_tree *tree;
6655 tree = &BTRFS_I(page->mapping->host)->io_tree;
6656 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
6659 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
6661 struct extent_io_tree *tree;
6664 if (current->flags & PF_MEMALLOC) {
6665 redirty_page_for_writepage(wbc, page);
6669 tree = &BTRFS_I(page->mapping->host)->io_tree;
6670 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
6673 int btrfs_writepages(struct address_space *mapping,
6674 struct writeback_control *wbc)
6676 struct extent_io_tree *tree;
6678 tree = &BTRFS_I(mapping->host)->io_tree;
6679 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
6683 btrfs_readpages(struct file *file, struct address_space *mapping,
6684 struct list_head *pages, unsigned nr_pages)
6686 struct extent_io_tree *tree;
6687 tree = &BTRFS_I(mapping->host)->io_tree;
6688 return extent_readpages(tree, mapping, pages, nr_pages,
6691 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6693 struct extent_io_tree *tree;
6694 struct extent_map_tree *map;
6697 tree = &BTRFS_I(page->mapping->host)->io_tree;
6698 map = &BTRFS_I(page->mapping->host)->extent_tree;
6699 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
6701 ClearPagePrivate(page);
6702 set_page_private(page, 0);
6703 page_cache_release(page);
6708 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6710 if (PageWriteback(page) || PageDirty(page))
6712 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
6715 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
6717 struct inode *inode = page->mapping->host;
6718 struct extent_io_tree *tree;
6719 struct btrfs_ordered_extent *ordered;
6720 struct extent_state *cached_state = NULL;
6721 u64 page_start = page_offset(page);
6722 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
6725 * we have the page locked, so new writeback can't start,
6726 * and the dirty bit won't be cleared while we are here.
6728 * Wait for IO on this page so that we can safely clear
6729 * the PagePrivate2 bit and do ordered accounting
6731 wait_on_page_writeback(page);
6733 tree = &BTRFS_I(inode)->io_tree;
6735 btrfs_releasepage(page, GFP_NOFS);
6738 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
6739 ordered = btrfs_lookup_ordered_extent(inode,
6743 * IO on this page will never be started, so we need
6744 * to account for any ordered extents now
6746 clear_extent_bit(tree, page_start, page_end,
6747 EXTENT_DIRTY | EXTENT_DELALLOC |
6748 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
6749 EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS);
6751 * whoever cleared the private bit is responsible
6752 * for the finish_ordered_io
6754 if (TestClearPagePrivate2(page) &&
6755 btrfs_dec_test_ordered_pending(inode, &ordered, page_start,
6756 PAGE_CACHE_SIZE, 1)) {
6757 btrfs_finish_ordered_io(ordered);
6759 btrfs_put_ordered_extent(ordered);
6760 cached_state = NULL;
6761 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
6763 clear_extent_bit(tree, page_start, page_end,
6764 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
6765 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
6766 &cached_state, GFP_NOFS);
6767 __btrfs_releasepage(page, GFP_NOFS);
6769 ClearPageChecked(page);
6770 if (PagePrivate(page)) {
6771 ClearPagePrivate(page);
6772 set_page_private(page, 0);
6773 page_cache_release(page);
6778 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6779 * called from a page fault handler when a page is first dirtied. Hence we must
6780 * be careful to check for EOF conditions here. We set the page up correctly
6781 * for a written page which means we get ENOSPC checking when writing into
6782 * holes and correct delalloc and unwritten extent mapping on filesystems that
6783 * support these features.
6785 * We are not allowed to take the i_mutex here so we have to play games to
6786 * protect against truncate races as the page could now be beyond EOF. Because
6787 * vmtruncate() writes the inode size before removing pages, once we have the
6788 * page lock we can determine safely if the page is beyond EOF. If it is not
6789 * beyond EOF, then the page is guaranteed safe against truncation until we
6792 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
6794 struct page *page = vmf->page;
6795 struct inode *inode = fdentry(vma->vm_file)->d_inode;
6796 struct btrfs_root *root = BTRFS_I(inode)->root;
6797 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6798 struct btrfs_ordered_extent *ordered;
6799 struct extent_state *cached_state = NULL;
6801 unsigned long zero_start;
6808 sb_start_pagefault(inode->i_sb);
6809 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
6811 ret = file_update_time(vma->vm_file);
6817 else /* -ENOSPC, -EIO, etc */
6818 ret = VM_FAULT_SIGBUS;
6824 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
6827 size = i_size_read(inode);
6828 page_start = page_offset(page);
6829 page_end = page_start + PAGE_CACHE_SIZE - 1;
6831 if ((page->mapping != inode->i_mapping) ||
6832 (page_start >= size)) {
6833 /* page got truncated out from underneath us */
6836 wait_on_page_writeback(page);
6838 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
6839 set_page_extent_mapped(page);
6842 * we can't set the delalloc bits if there are pending ordered
6843 * extents. Drop our locks and wait for them to finish
6845 ordered = btrfs_lookup_ordered_extent(inode, page_start);
6847 unlock_extent_cached(io_tree, page_start, page_end,
6848 &cached_state, GFP_NOFS);
6850 btrfs_start_ordered_extent(inode, ordered, 1);
6851 btrfs_put_ordered_extent(ordered);
6856 * XXX - page_mkwrite gets called every time the page is dirtied, even
6857 * if it was already dirty, so for space accounting reasons we need to
6858 * clear any delalloc bits for the range we are fixing to save. There
6859 * is probably a better way to do this, but for now keep consistent with
6860 * prepare_pages in the normal write path.
6862 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
6863 EXTENT_DIRTY | EXTENT_DELALLOC |
6864 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
6865 0, 0, &cached_state, GFP_NOFS);
6867 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6870 unlock_extent_cached(io_tree, page_start, page_end,
6871 &cached_state, GFP_NOFS);
6872 ret = VM_FAULT_SIGBUS;
6877 /* page is wholly or partially inside EOF */
6878 if (page_start + PAGE_CACHE_SIZE > size)
6879 zero_start = size & ~PAGE_CACHE_MASK;
6881 zero_start = PAGE_CACHE_SIZE;
6883 if (zero_start != PAGE_CACHE_SIZE) {
6885 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6886 flush_dcache_page(page);
6889 ClearPageChecked(page);
6890 set_page_dirty(page);
6891 SetPageUptodate(page);
6893 BTRFS_I(inode)->last_trans = root->fs_info->generation;
6894 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6895 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
6897 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
6901 sb_end_pagefault(inode->i_sb);
6902 return VM_FAULT_LOCKED;
6906 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
6908 sb_end_pagefault(inode->i_sb);
6912 static int btrfs_truncate(struct inode *inode)
6914 struct btrfs_root *root = BTRFS_I(inode)->root;
6915 struct btrfs_block_rsv *rsv;
6918 struct btrfs_trans_handle *trans;
6919 u64 mask = root->sectorsize - 1;
6920 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
6922 ret = btrfs_truncate_page(inode, inode->i_size, 0, 0);
6926 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
6927 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
6930 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
6931 * 3 things going on here
6933 * 1) We need to reserve space for our orphan item and the space to
6934 * delete our orphan item. Lord knows we don't want to have a dangling
6935 * orphan item because we didn't reserve space to remove it.
6937 * 2) We need to reserve space to update our inode.
6939 * 3) We need to have something to cache all the space that is going to
6940 * be free'd up by the truncate operation, but also have some slack
6941 * space reserved in case it uses space during the truncate (thank you
6942 * very much snapshotting).
6944 * And we need these to all be seperate. The fact is we can use alot of
6945 * space doing the truncate, and we have no earthly idea how much space
6946 * we will use, so we need the truncate reservation to be seperate so it
6947 * doesn't end up using space reserved for updating the inode or
6948 * removing the orphan item. We also need to be able to stop the
6949 * transaction and start a new one, which means we need to be able to
6950 * update the inode several times, and we have no idea of knowing how
6951 * many times that will be, so we can't just reserve 1 item for the
6952 * entirety of the opration, so that has to be done seperately as well.
6953 * Then there is the orphan item, which does indeed need to be held on
6954 * to for the whole operation, and we need nobody to touch this reserved
6955 * space except the orphan code.
6957 * So that leaves us with
6959 * 1) root->orphan_block_rsv - for the orphan deletion.
6960 * 2) rsv - for the truncate reservation, which we will steal from the
6961 * transaction reservation.
6962 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
6963 * updating the inode.
6965 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
6968 rsv->size = min_size;
6972 * 1 for the truncate slack space
6973 * 1 for updating the inode.
6975 trans = btrfs_start_transaction(root, 2);
6976 if (IS_ERR(trans)) {
6977 err = PTR_ERR(trans);
6981 /* Migrate the slack space for the truncate to our reserve */
6982 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
6987 * setattr is responsible for setting the ordered_data_close flag,
6988 * but that is only tested during the last file release. That
6989 * could happen well after the next commit, leaving a great big
6990 * window where new writes may get lost if someone chooses to write
6991 * to this file after truncating to zero
6993 * The inode doesn't have any dirty data here, and so if we commit
6994 * this is a noop. If someone immediately starts writing to the inode
6995 * it is very likely we'll catch some of their writes in this
6996 * transaction, and the commit will find this file on the ordered
6997 * data list with good things to send down.
6999 * This is a best effort solution, there is still a window where
7000 * using truncate to replace the contents of the file will
7001 * end up with a zero length file after a crash.
7003 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7004 &BTRFS_I(inode)->runtime_flags))
7005 btrfs_add_ordered_operation(trans, root, inode);
7008 * So if we truncate and then write and fsync we normally would just
7009 * write the extents that changed, which is a problem if we need to
7010 * first truncate that entire inode. So set this flag so we write out
7011 * all of the extents in the inode to the sync log so we're completely
7014 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7015 trans->block_rsv = rsv;
7018 ret = btrfs_truncate_inode_items(trans, root, inode,
7020 BTRFS_EXTENT_DATA_KEY);
7021 if (ret != -ENOSPC) {
7026 trans->block_rsv = &root->fs_info->trans_block_rsv;
7027 ret = btrfs_update_inode(trans, root, inode);
7033 btrfs_end_transaction(trans, root);
7034 btrfs_btree_balance_dirty(root);
7036 trans = btrfs_start_transaction(root, 2);
7037 if (IS_ERR(trans)) {
7038 ret = err = PTR_ERR(trans);
7043 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7045 BUG_ON(ret); /* shouldn't happen */
7046 trans->block_rsv = rsv;
7049 if (ret == 0 && inode->i_nlink > 0) {
7050 trans->block_rsv = root->orphan_block_rsv;
7051 ret = btrfs_orphan_del(trans, inode);
7057 trans->block_rsv = &root->fs_info->trans_block_rsv;
7058 ret = btrfs_update_inode(trans, root, inode);
7062 ret = btrfs_end_transaction(trans, root);
7063 btrfs_btree_balance_dirty(root);
7067 btrfs_free_block_rsv(root, rsv);
7076 * create a new subvolume directory/inode (helper for the ioctl).
7078 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7079 struct btrfs_root *new_root, u64 new_dirid)
7081 struct inode *inode;
7085 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7086 new_dirid, new_dirid,
7087 S_IFDIR | (~current_umask() & S_IRWXUGO),
7090 return PTR_ERR(inode);
7091 inode->i_op = &btrfs_dir_inode_operations;
7092 inode->i_fop = &btrfs_dir_file_operations;
7094 set_nlink(inode, 1);
7095 btrfs_i_size_write(inode, 0);
7097 err = btrfs_update_inode(trans, new_root, inode);
7103 struct inode *btrfs_alloc_inode(struct super_block *sb)
7105 struct btrfs_inode *ei;
7106 struct inode *inode;
7108 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7115 ei->last_sub_trans = 0;
7116 ei->logged_trans = 0;
7117 ei->delalloc_bytes = 0;
7118 ei->disk_i_size = 0;
7121 ei->index_cnt = (u64)-1;
7122 ei->last_unlink_trans = 0;
7123 ei->last_log_commit = 0;
7125 spin_lock_init(&ei->lock);
7126 ei->outstanding_extents = 0;
7127 ei->reserved_extents = 0;
7129 ei->runtime_flags = 0;
7130 ei->force_compress = BTRFS_COMPRESS_NONE;
7132 ei->delayed_node = NULL;
7134 inode = &ei->vfs_inode;
7135 extent_map_tree_init(&ei->extent_tree);
7136 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7137 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7138 ei->io_tree.track_uptodate = 1;
7139 ei->io_failure_tree.track_uptodate = 1;
7140 atomic_set(&ei->sync_writers, 0);
7141 mutex_init(&ei->log_mutex);
7142 mutex_init(&ei->delalloc_mutex);
7143 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7144 INIT_LIST_HEAD(&ei->delalloc_inodes);
7145 INIT_LIST_HEAD(&ei->ordered_operations);
7146 RB_CLEAR_NODE(&ei->rb_node);
7151 static void btrfs_i_callback(struct rcu_head *head)
7153 struct inode *inode = container_of(head, struct inode, i_rcu);
7154 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7157 void btrfs_destroy_inode(struct inode *inode)
7159 struct btrfs_ordered_extent *ordered;
7160 struct btrfs_root *root = BTRFS_I(inode)->root;
7162 WARN_ON(!hlist_empty(&inode->i_dentry));
7163 WARN_ON(inode->i_data.nrpages);
7164 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7165 WARN_ON(BTRFS_I(inode)->reserved_extents);
7166 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7167 WARN_ON(BTRFS_I(inode)->csum_bytes);
7170 * This can happen where we create an inode, but somebody else also
7171 * created the same inode and we need to destroy the one we already
7178 * Make sure we're properly removed from the ordered operation
7182 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7183 spin_lock(&root->fs_info->ordered_extent_lock);
7184 list_del_init(&BTRFS_I(inode)->ordered_operations);
7185 spin_unlock(&root->fs_info->ordered_extent_lock);
7188 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7189 &BTRFS_I(inode)->runtime_flags)) {
7190 printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n",
7191 (unsigned long long)btrfs_ino(inode));
7192 atomic_dec(&root->orphan_inodes);
7196 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7200 printk(KERN_ERR "btrfs found ordered "
7201 "extent %llu %llu on inode cleanup\n",
7202 (unsigned long long)ordered->file_offset,
7203 (unsigned long long)ordered->len);
7204 btrfs_remove_ordered_extent(inode, ordered);
7205 btrfs_put_ordered_extent(ordered);
7206 btrfs_put_ordered_extent(ordered);
7209 inode_tree_del(inode);
7210 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7212 btrfs_remove_delayed_node(inode);
7213 call_rcu(&inode->i_rcu, btrfs_i_callback);
7216 int btrfs_drop_inode(struct inode *inode)
7218 struct btrfs_root *root = BTRFS_I(inode)->root;
7220 if (btrfs_root_refs(&root->root_item) == 0 &&
7221 !btrfs_is_free_space_inode(inode))
7224 return generic_drop_inode(inode);
7227 static void init_once(void *foo)
7229 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
7231 inode_init_once(&ei->vfs_inode);
7234 void btrfs_destroy_cachep(void)
7237 * Make sure all delayed rcu free inodes are flushed before we
7241 if (btrfs_inode_cachep)
7242 kmem_cache_destroy(btrfs_inode_cachep);
7243 if (btrfs_trans_handle_cachep)
7244 kmem_cache_destroy(btrfs_trans_handle_cachep);
7245 if (btrfs_transaction_cachep)
7246 kmem_cache_destroy(btrfs_transaction_cachep);
7247 if (btrfs_path_cachep)
7248 kmem_cache_destroy(btrfs_path_cachep);
7249 if (btrfs_free_space_cachep)
7250 kmem_cache_destroy(btrfs_free_space_cachep);
7251 if (btrfs_delalloc_work_cachep)
7252 kmem_cache_destroy(btrfs_delalloc_work_cachep);
7255 int btrfs_init_cachep(void)
7257 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
7258 sizeof(struct btrfs_inode), 0,
7259 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
7260 if (!btrfs_inode_cachep)
7263 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
7264 sizeof(struct btrfs_trans_handle), 0,
7265 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7266 if (!btrfs_trans_handle_cachep)
7269 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
7270 sizeof(struct btrfs_transaction), 0,
7271 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7272 if (!btrfs_transaction_cachep)
7275 btrfs_path_cachep = kmem_cache_create("btrfs_path",
7276 sizeof(struct btrfs_path), 0,
7277 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7278 if (!btrfs_path_cachep)
7281 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
7282 sizeof(struct btrfs_free_space), 0,
7283 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7284 if (!btrfs_free_space_cachep)
7287 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
7288 sizeof(struct btrfs_delalloc_work), 0,
7289 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
7291 if (!btrfs_delalloc_work_cachep)
7296 btrfs_destroy_cachep();
7300 static int btrfs_getattr(struct vfsmount *mnt,
7301 struct dentry *dentry, struct kstat *stat)
7303 struct inode *inode = dentry->d_inode;
7304 u32 blocksize = inode->i_sb->s_blocksize;
7306 generic_fillattr(inode, stat);
7307 stat->dev = BTRFS_I(inode)->root->anon_dev;
7308 stat->blksize = PAGE_CACHE_SIZE;
7309 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
7310 ALIGN(BTRFS_I(inode)->delalloc_bytes, blocksize)) >> 9;
7315 * If a file is moved, it will inherit the cow and compression flags of the new
7318 static void fixup_inode_flags(struct inode *dir, struct inode *inode)
7320 struct btrfs_inode *b_dir = BTRFS_I(dir);
7321 struct btrfs_inode *b_inode = BTRFS_I(inode);
7323 if (b_dir->flags & BTRFS_INODE_NODATACOW)
7324 b_inode->flags |= BTRFS_INODE_NODATACOW;
7326 b_inode->flags &= ~BTRFS_INODE_NODATACOW;
7328 if (b_dir->flags & BTRFS_INODE_COMPRESS) {
7329 b_inode->flags |= BTRFS_INODE_COMPRESS;
7330 b_inode->flags &= ~BTRFS_INODE_NOCOMPRESS;
7332 b_inode->flags &= ~(BTRFS_INODE_COMPRESS |
7333 BTRFS_INODE_NOCOMPRESS);
7337 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
7338 struct inode *new_dir, struct dentry *new_dentry)
7340 struct btrfs_trans_handle *trans;
7341 struct btrfs_root *root = BTRFS_I(old_dir)->root;
7342 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
7343 struct inode *new_inode = new_dentry->d_inode;
7344 struct inode *old_inode = old_dentry->d_inode;
7345 struct timespec ctime = CURRENT_TIME;
7349 u64 old_ino = btrfs_ino(old_inode);
7351 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
7354 /* we only allow rename subvolume link between subvolumes */
7355 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
7358 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
7359 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
7362 if (S_ISDIR(old_inode->i_mode) && new_inode &&
7363 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
7367 /* check for collisions, even if the name isn't there */
7368 ret = btrfs_check_dir_item_collision(root, new_dir->i_ino,
7369 new_dentry->d_name.name,
7370 new_dentry->d_name.len);
7373 if (ret == -EEXIST) {
7375 * eexist without a new_inode */
7381 /* maybe -EOVERFLOW */
7388 * we're using rename to replace one file with another.
7389 * and the replacement file is large. Start IO on it now so
7390 * we don't add too much work to the end of the transaction
7392 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
7393 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
7394 filemap_flush(old_inode->i_mapping);
7396 /* close the racy window with snapshot create/destroy ioctl */
7397 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7398 down_read(&root->fs_info->subvol_sem);
7400 * We want to reserve the absolute worst case amount of items. So if
7401 * both inodes are subvols and we need to unlink them then that would
7402 * require 4 item modifications, but if they are both normal inodes it
7403 * would require 5 item modifications, so we'll assume their normal
7404 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
7405 * should cover the worst case number of items we'll modify.
7407 trans = btrfs_start_transaction(root, 20);
7408 if (IS_ERR(trans)) {
7409 ret = PTR_ERR(trans);
7414 btrfs_record_root_in_trans(trans, dest);
7416 ret = btrfs_set_inode_index(new_dir, &index);
7420 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
7421 /* force full log commit if subvolume involved. */
7422 root->fs_info->last_trans_log_full_commit = trans->transid;
7424 ret = btrfs_insert_inode_ref(trans, dest,
7425 new_dentry->d_name.name,
7426 new_dentry->d_name.len,
7428 btrfs_ino(new_dir), index);
7432 * this is an ugly little race, but the rename is required
7433 * to make sure that if we crash, the inode is either at the
7434 * old name or the new one. pinning the log transaction lets
7435 * us make sure we don't allow a log commit to come in after
7436 * we unlink the name but before we add the new name back in.
7438 btrfs_pin_log_trans(root);
7441 * make sure the inode gets flushed if it is replacing
7444 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
7445 btrfs_add_ordered_operation(trans, root, old_inode);
7447 inode_inc_iversion(old_dir);
7448 inode_inc_iversion(new_dir);
7449 inode_inc_iversion(old_inode);
7450 old_dir->i_ctime = old_dir->i_mtime = ctime;
7451 new_dir->i_ctime = new_dir->i_mtime = ctime;
7452 old_inode->i_ctime = ctime;
7454 if (old_dentry->d_parent != new_dentry->d_parent)
7455 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
7457 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
7458 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
7459 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
7460 old_dentry->d_name.name,
7461 old_dentry->d_name.len);
7463 ret = __btrfs_unlink_inode(trans, root, old_dir,
7464 old_dentry->d_inode,
7465 old_dentry->d_name.name,
7466 old_dentry->d_name.len);
7468 ret = btrfs_update_inode(trans, root, old_inode);
7471 btrfs_abort_transaction(trans, root, ret);
7476 inode_inc_iversion(new_inode);
7477 new_inode->i_ctime = CURRENT_TIME;
7478 if (unlikely(btrfs_ino(new_inode) ==
7479 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
7480 root_objectid = BTRFS_I(new_inode)->location.objectid;
7481 ret = btrfs_unlink_subvol(trans, dest, new_dir,
7483 new_dentry->d_name.name,
7484 new_dentry->d_name.len);
7485 BUG_ON(new_inode->i_nlink == 0);
7487 ret = btrfs_unlink_inode(trans, dest, new_dir,
7488 new_dentry->d_inode,
7489 new_dentry->d_name.name,
7490 new_dentry->d_name.len);
7492 if (!ret && new_inode->i_nlink == 0) {
7493 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
7497 btrfs_abort_transaction(trans, root, ret);
7502 fixup_inode_flags(new_dir, old_inode);
7504 ret = btrfs_add_link(trans, new_dir, old_inode,
7505 new_dentry->d_name.name,
7506 new_dentry->d_name.len, 0, index);
7508 btrfs_abort_transaction(trans, root, ret);
7512 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
7513 struct dentry *parent = new_dentry->d_parent;
7514 btrfs_log_new_name(trans, old_inode, old_dir, parent);
7515 btrfs_end_log_trans(root);
7518 btrfs_end_transaction(trans, root);
7520 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7521 up_read(&root->fs_info->subvol_sem);
7526 static void btrfs_run_delalloc_work(struct btrfs_work *work)
7528 struct btrfs_delalloc_work *delalloc_work;
7530 delalloc_work = container_of(work, struct btrfs_delalloc_work,
7532 if (delalloc_work->wait)
7533 btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1);
7535 filemap_flush(delalloc_work->inode->i_mapping);
7537 if (delalloc_work->delay_iput)
7538 btrfs_add_delayed_iput(delalloc_work->inode);
7540 iput(delalloc_work->inode);
7541 complete(&delalloc_work->completion);
7544 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
7545 int wait, int delay_iput)
7547 struct btrfs_delalloc_work *work;
7549 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
7553 init_completion(&work->completion);
7554 INIT_LIST_HEAD(&work->list);
7555 work->inode = inode;
7557 work->delay_iput = delay_iput;
7558 work->work.func = btrfs_run_delalloc_work;
7563 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
7565 wait_for_completion(&work->completion);
7566 kmem_cache_free(btrfs_delalloc_work_cachep, work);
7570 * some fairly slow code that needs optimization. This walks the list
7571 * of all the inodes with pending delalloc and forces them to disk.
7573 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
7575 struct btrfs_inode *binode;
7576 struct inode *inode;
7577 struct btrfs_delalloc_work *work, *next;
7578 struct list_head works;
7579 struct list_head splice;
7582 if (root->fs_info->sb->s_flags & MS_RDONLY)
7585 INIT_LIST_HEAD(&works);
7586 INIT_LIST_HEAD(&splice);
7588 spin_lock(&root->fs_info->delalloc_lock);
7589 list_splice_init(&root->fs_info->delalloc_inodes, &splice);
7590 while (!list_empty(&splice)) {
7591 binode = list_entry(splice.next, struct btrfs_inode,
7594 list_del_init(&binode->delalloc_inodes);
7596 inode = igrab(&binode->vfs_inode);
7600 list_add_tail(&binode->delalloc_inodes,
7601 &root->fs_info->delalloc_inodes);
7602 spin_unlock(&root->fs_info->delalloc_lock);
7604 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
7605 if (unlikely(!work)) {
7609 list_add_tail(&work->list, &works);
7610 btrfs_queue_worker(&root->fs_info->flush_workers,
7614 spin_lock(&root->fs_info->delalloc_lock);
7616 spin_unlock(&root->fs_info->delalloc_lock);
7618 list_for_each_entry_safe(work, next, &works, list) {
7619 list_del_init(&work->list);
7620 btrfs_wait_and_free_delalloc_work(work);
7623 spin_lock(&root->fs_info->delalloc_lock);
7624 if (!list_empty(&root->fs_info->delalloc_inodes)) {
7625 spin_unlock(&root->fs_info->delalloc_lock);
7628 spin_unlock(&root->fs_info->delalloc_lock);
7630 /* the filemap_flush will queue IO into the worker threads, but
7631 * we have to make sure the IO is actually started and that
7632 * ordered extents get created before we return
7634 atomic_inc(&root->fs_info->async_submit_draining);
7635 while (atomic_read(&root->fs_info->nr_async_submits) ||
7636 atomic_read(&root->fs_info->async_delalloc_pages)) {
7637 wait_event(root->fs_info->async_submit_wait,
7638 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
7639 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
7641 atomic_dec(&root->fs_info->async_submit_draining);
7644 list_for_each_entry_safe(work, next, &works, list) {
7645 list_del_init(&work->list);
7646 btrfs_wait_and_free_delalloc_work(work);
7649 if (!list_empty_careful(&splice)) {
7650 spin_lock(&root->fs_info->delalloc_lock);
7651 list_splice_tail(&splice, &root->fs_info->delalloc_inodes);
7652 spin_unlock(&root->fs_info->delalloc_lock);
7657 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
7658 const char *symname)
7660 struct btrfs_trans_handle *trans;
7661 struct btrfs_root *root = BTRFS_I(dir)->root;
7662 struct btrfs_path *path;
7663 struct btrfs_key key;
7664 struct inode *inode = NULL;
7672 struct btrfs_file_extent_item *ei;
7673 struct extent_buffer *leaf;
7675 name_len = strlen(symname) + 1;
7676 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
7677 return -ENAMETOOLONG;
7680 * 2 items for inode item and ref
7681 * 2 items for dir items
7682 * 1 item for xattr if selinux is on
7684 trans = btrfs_start_transaction(root, 5);
7686 return PTR_ERR(trans);
7688 err = btrfs_find_free_ino(root, &objectid);
7692 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
7693 dentry->d_name.len, btrfs_ino(dir), objectid,
7694 S_IFLNK|S_IRWXUGO, &index);
7695 if (IS_ERR(inode)) {
7696 err = PTR_ERR(inode);
7700 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
7707 * If the active LSM wants to access the inode during
7708 * d_instantiate it needs these. Smack checks to see
7709 * if the filesystem supports xattrs by looking at the
7712 inode->i_fop = &btrfs_file_operations;
7713 inode->i_op = &btrfs_file_inode_operations;
7715 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
7719 inode->i_mapping->a_ops = &btrfs_aops;
7720 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7721 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
7726 path = btrfs_alloc_path();
7732 key.objectid = btrfs_ino(inode);
7734 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
7735 datasize = btrfs_file_extent_calc_inline_size(name_len);
7736 err = btrfs_insert_empty_item(trans, root, path, &key,
7740 btrfs_free_path(path);
7743 leaf = path->nodes[0];
7744 ei = btrfs_item_ptr(leaf, path->slots[0],
7745 struct btrfs_file_extent_item);
7746 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
7747 btrfs_set_file_extent_type(leaf, ei,
7748 BTRFS_FILE_EXTENT_INLINE);
7749 btrfs_set_file_extent_encryption(leaf, ei, 0);
7750 btrfs_set_file_extent_compression(leaf, ei, 0);
7751 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
7752 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
7754 ptr = btrfs_file_extent_inline_start(ei);
7755 write_extent_buffer(leaf, symname, ptr, name_len);
7756 btrfs_mark_buffer_dirty(leaf);
7757 btrfs_free_path(path);
7759 inode->i_op = &btrfs_symlink_inode_operations;
7760 inode->i_mapping->a_ops = &btrfs_symlink_aops;
7761 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7762 inode_set_bytes(inode, name_len);
7763 btrfs_i_size_write(inode, name_len - 1);
7764 err = btrfs_update_inode(trans, root, inode);
7770 d_instantiate(dentry, inode);
7771 btrfs_end_transaction(trans, root);
7773 inode_dec_link_count(inode);
7776 btrfs_btree_balance_dirty(root);
7780 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
7781 u64 start, u64 num_bytes, u64 min_size,
7782 loff_t actual_len, u64 *alloc_hint,
7783 struct btrfs_trans_handle *trans)
7785 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
7786 struct extent_map *em;
7787 struct btrfs_root *root = BTRFS_I(inode)->root;
7788 struct btrfs_key ins;
7789 u64 cur_offset = start;
7792 bool own_trans = true;
7796 while (num_bytes > 0) {
7798 trans = btrfs_start_transaction(root, 3);
7799 if (IS_ERR(trans)) {
7800 ret = PTR_ERR(trans);
7805 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
7806 0, *alloc_hint, &ins, 1);
7809 btrfs_end_transaction(trans, root);
7813 ret = insert_reserved_file_extent(trans, inode,
7814 cur_offset, ins.objectid,
7815 ins.offset, ins.offset,
7816 ins.offset, 0, 0, 0,
7817 BTRFS_FILE_EXTENT_PREALLOC);
7819 btrfs_abort_transaction(trans, root, ret);
7821 btrfs_end_transaction(trans, root);
7824 btrfs_drop_extent_cache(inode, cur_offset,
7825 cur_offset + ins.offset -1, 0);
7827 em = alloc_extent_map();
7829 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
7830 &BTRFS_I(inode)->runtime_flags);
7834 em->start = cur_offset;
7835 em->orig_start = cur_offset;
7836 em->len = ins.offset;
7837 em->block_start = ins.objectid;
7838 em->block_len = ins.offset;
7839 em->orig_block_len = ins.offset;
7840 em->bdev = root->fs_info->fs_devices->latest_bdev;
7841 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7842 em->generation = trans->transid;
7845 write_lock(&em_tree->lock);
7846 ret = add_extent_mapping(em_tree, em);
7848 list_move(&em->list,
7849 &em_tree->modified_extents);
7850 write_unlock(&em_tree->lock);
7853 btrfs_drop_extent_cache(inode, cur_offset,
7854 cur_offset + ins.offset - 1,
7857 free_extent_map(em);
7859 num_bytes -= ins.offset;
7860 cur_offset += ins.offset;
7861 *alloc_hint = ins.objectid + ins.offset;
7863 inode_inc_iversion(inode);
7864 inode->i_ctime = CURRENT_TIME;
7865 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
7866 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
7867 (actual_len > inode->i_size) &&
7868 (cur_offset > inode->i_size)) {
7869 if (cur_offset > actual_len)
7870 i_size = actual_len;
7872 i_size = cur_offset;
7873 i_size_write(inode, i_size);
7874 btrfs_ordered_update_i_size(inode, i_size, NULL);
7877 ret = btrfs_update_inode(trans, root, inode);
7880 btrfs_abort_transaction(trans, root, ret);
7882 btrfs_end_transaction(trans, root);
7887 btrfs_end_transaction(trans, root);
7892 int btrfs_prealloc_file_range(struct inode *inode, int mode,
7893 u64 start, u64 num_bytes, u64 min_size,
7894 loff_t actual_len, u64 *alloc_hint)
7896 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7897 min_size, actual_len, alloc_hint,
7901 int btrfs_prealloc_file_range_trans(struct inode *inode,
7902 struct btrfs_trans_handle *trans, int mode,
7903 u64 start, u64 num_bytes, u64 min_size,
7904 loff_t actual_len, u64 *alloc_hint)
7906 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7907 min_size, actual_len, alloc_hint, trans);
7910 static int btrfs_set_page_dirty(struct page *page)
7912 return __set_page_dirty_nobuffers(page);
7915 static int btrfs_permission(struct inode *inode, int mask)
7917 struct btrfs_root *root = BTRFS_I(inode)->root;
7918 umode_t mode = inode->i_mode;
7920 if (mask & MAY_WRITE &&
7921 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
7922 if (btrfs_root_readonly(root))
7924 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
7927 return generic_permission(inode, mask);
7930 static const struct inode_operations btrfs_dir_inode_operations = {
7931 .getattr = btrfs_getattr,
7932 .lookup = btrfs_lookup,
7933 .create = btrfs_create,
7934 .unlink = btrfs_unlink,
7936 .mkdir = btrfs_mkdir,
7937 .rmdir = btrfs_rmdir,
7938 .rename = btrfs_rename,
7939 .symlink = btrfs_symlink,
7940 .setattr = btrfs_setattr,
7941 .mknod = btrfs_mknod,
7942 .setxattr = btrfs_setxattr,
7943 .getxattr = btrfs_getxattr,
7944 .listxattr = btrfs_listxattr,
7945 .removexattr = btrfs_removexattr,
7946 .permission = btrfs_permission,
7947 .get_acl = btrfs_get_acl,
7949 static const struct inode_operations btrfs_dir_ro_inode_operations = {
7950 .lookup = btrfs_lookup,
7951 .permission = btrfs_permission,
7952 .get_acl = btrfs_get_acl,
7955 static const struct file_operations btrfs_dir_file_operations = {
7956 .llseek = generic_file_llseek,
7957 .read = generic_read_dir,
7958 .readdir = btrfs_real_readdir,
7959 .unlocked_ioctl = btrfs_ioctl,
7960 #ifdef CONFIG_COMPAT
7961 .compat_ioctl = btrfs_ioctl,
7963 .release = btrfs_release_file,
7964 .fsync = btrfs_sync_file,
7967 static struct extent_io_ops btrfs_extent_io_ops = {
7968 .fill_delalloc = run_delalloc_range,
7969 .submit_bio_hook = btrfs_submit_bio_hook,
7970 .merge_bio_hook = btrfs_merge_bio_hook,
7971 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
7972 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
7973 .writepage_start_hook = btrfs_writepage_start_hook,
7974 .set_bit_hook = btrfs_set_bit_hook,
7975 .clear_bit_hook = btrfs_clear_bit_hook,
7976 .merge_extent_hook = btrfs_merge_extent_hook,
7977 .split_extent_hook = btrfs_split_extent_hook,
7981 * btrfs doesn't support the bmap operation because swapfiles
7982 * use bmap to make a mapping of extents in the file. They assume
7983 * these extents won't change over the life of the file and they
7984 * use the bmap result to do IO directly to the drive.
7986 * the btrfs bmap call would return logical addresses that aren't
7987 * suitable for IO and they also will change frequently as COW
7988 * operations happen. So, swapfile + btrfs == corruption.
7990 * For now we're avoiding this by dropping bmap.
7992 static const struct address_space_operations btrfs_aops = {
7993 .readpage = btrfs_readpage,
7994 .writepage = btrfs_writepage,
7995 .writepages = btrfs_writepages,
7996 .readpages = btrfs_readpages,
7997 .direct_IO = btrfs_direct_IO,
7998 .invalidatepage = btrfs_invalidatepage,
7999 .releasepage = btrfs_releasepage,
8000 .set_page_dirty = btrfs_set_page_dirty,
8001 .error_remove_page = generic_error_remove_page,
8004 static const struct address_space_operations btrfs_symlink_aops = {
8005 .readpage = btrfs_readpage,
8006 .writepage = btrfs_writepage,
8007 .invalidatepage = btrfs_invalidatepage,
8008 .releasepage = btrfs_releasepage,
8011 static const struct inode_operations btrfs_file_inode_operations = {
8012 .getattr = btrfs_getattr,
8013 .setattr = btrfs_setattr,
8014 .setxattr = btrfs_setxattr,
8015 .getxattr = btrfs_getxattr,
8016 .listxattr = btrfs_listxattr,
8017 .removexattr = btrfs_removexattr,
8018 .permission = btrfs_permission,
8019 .fiemap = btrfs_fiemap,
8020 .get_acl = btrfs_get_acl,
8021 .update_time = btrfs_update_time,
8023 static const struct inode_operations btrfs_special_inode_operations = {
8024 .getattr = btrfs_getattr,
8025 .setattr = btrfs_setattr,
8026 .permission = btrfs_permission,
8027 .setxattr = btrfs_setxattr,
8028 .getxattr = btrfs_getxattr,
8029 .listxattr = btrfs_listxattr,
8030 .removexattr = btrfs_removexattr,
8031 .get_acl = btrfs_get_acl,
8032 .update_time = btrfs_update_time,
8034 static const struct inode_operations btrfs_symlink_inode_operations = {
8035 .readlink = generic_readlink,
8036 .follow_link = page_follow_link_light,
8037 .put_link = page_put_link,
8038 .getattr = btrfs_getattr,
8039 .setattr = btrfs_setattr,
8040 .permission = btrfs_permission,
8041 .setxattr = btrfs_setxattr,
8042 .getxattr = btrfs_getxattr,
8043 .listxattr = btrfs_listxattr,
8044 .removexattr = btrfs_removexattr,
8045 .get_acl = btrfs_get_acl,
8046 .update_time = btrfs_update_time,
8049 const struct dentry_operations btrfs_dentry_operations = {
8050 .d_delete = btrfs_dentry_delete,
8051 .d_release = btrfs_dentry_release,