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/btrfs.h>
43 #include <linux/blkdev.h>
47 #include "transaction.h"
48 #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"
60 struct btrfs_iget_args {
62 struct btrfs_root *root;
65 static const struct inode_operations btrfs_dir_inode_operations;
66 static const struct inode_operations btrfs_symlink_inode_operations;
67 static const struct inode_operations btrfs_dir_ro_inode_operations;
68 static const struct inode_operations btrfs_special_inode_operations;
69 static const struct inode_operations btrfs_file_inode_operations;
70 static const struct address_space_operations btrfs_aops;
71 static const struct address_space_operations btrfs_symlink_aops;
72 static const struct file_operations btrfs_dir_file_operations;
73 static struct extent_io_ops btrfs_extent_io_ops;
75 static struct kmem_cache *btrfs_inode_cachep;
76 static struct kmem_cache *btrfs_delalloc_work_cachep;
77 struct kmem_cache *btrfs_trans_handle_cachep;
78 struct kmem_cache *btrfs_transaction_cachep;
79 struct kmem_cache *btrfs_path_cachep;
80 struct kmem_cache *btrfs_free_space_cachep;
83 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
84 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
85 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
86 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
87 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
88 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
89 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
90 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
93 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
94 static int btrfs_truncate(struct inode *inode);
95 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
96 static noinline int cow_file_range(struct inode *inode,
97 struct page *locked_page,
98 u64 start, u64 end, int *page_started,
99 unsigned long *nr_written, int unlock);
100 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
101 u64 len, u64 orig_start,
102 u64 block_start, u64 block_len,
103 u64 orig_block_len, u64 ram_bytes,
106 static int btrfs_dirty_inode(struct inode *inode);
108 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
109 struct inode *inode, struct inode *dir,
110 const struct qstr *qstr)
114 err = btrfs_init_acl(trans, inode, dir);
116 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
121 * this does all the hard work for inserting an inline extent into
122 * the btree. The caller should have done a btrfs_drop_extents so that
123 * no overlapping inline items exist in the btree
125 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
126 struct btrfs_root *root, struct inode *inode,
127 u64 start, size_t size, size_t compressed_size,
129 struct page **compressed_pages)
131 struct btrfs_key key;
132 struct btrfs_path *path;
133 struct extent_buffer *leaf;
134 struct page *page = NULL;
137 struct btrfs_file_extent_item *ei;
140 size_t cur_size = size;
142 unsigned long offset;
144 if (compressed_size && compressed_pages)
145 cur_size = compressed_size;
147 path = btrfs_alloc_path();
151 path->leave_spinning = 1;
153 key.objectid = btrfs_ino(inode);
155 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
156 datasize = btrfs_file_extent_calc_inline_size(cur_size);
158 inode_add_bytes(inode, size);
159 ret = btrfs_insert_empty_item(trans, root, path, &key,
165 leaf = path->nodes[0];
166 ei = btrfs_item_ptr(leaf, path->slots[0],
167 struct btrfs_file_extent_item);
168 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
169 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
170 btrfs_set_file_extent_encryption(leaf, ei, 0);
171 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
172 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
173 ptr = btrfs_file_extent_inline_start(ei);
175 if (compress_type != BTRFS_COMPRESS_NONE) {
178 while (compressed_size > 0) {
179 cpage = compressed_pages[i];
180 cur_size = min_t(unsigned long, compressed_size,
183 kaddr = kmap_atomic(cpage);
184 write_extent_buffer(leaf, kaddr, ptr, cur_size);
185 kunmap_atomic(kaddr);
189 compressed_size -= cur_size;
191 btrfs_set_file_extent_compression(leaf, ei,
194 page = find_get_page(inode->i_mapping,
195 start >> PAGE_CACHE_SHIFT);
196 btrfs_set_file_extent_compression(leaf, ei, 0);
197 kaddr = kmap_atomic(page);
198 offset = start & (PAGE_CACHE_SIZE - 1);
199 write_extent_buffer(leaf, kaddr + offset, ptr, size);
200 kunmap_atomic(kaddr);
201 page_cache_release(page);
203 btrfs_mark_buffer_dirty(leaf);
204 btrfs_free_path(path);
207 * we're an inline extent, so nobody can
208 * extend the file past i_size without locking
209 * a page we already have locked.
211 * We must do any isize and inode updates
212 * before we unlock the pages. Otherwise we
213 * could end up racing with unlink.
215 BTRFS_I(inode)->disk_i_size = inode->i_size;
216 ret = btrfs_update_inode(trans, root, inode);
220 btrfs_free_path(path);
226 * conditionally insert an inline extent into the file. This
227 * does the checks required to make sure the data is small enough
228 * to fit as an inline extent.
230 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
231 struct btrfs_root *root,
232 struct inode *inode, u64 start, u64 end,
233 size_t compressed_size, int compress_type,
234 struct page **compressed_pages)
236 u64 isize = i_size_read(inode);
237 u64 actual_end = min(end + 1, isize);
238 u64 inline_len = actual_end - start;
239 u64 aligned_end = ALIGN(end, root->sectorsize);
240 u64 data_len = inline_len;
244 data_len = compressed_size;
247 actual_end >= PAGE_CACHE_SIZE ||
248 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
250 (actual_end & (root->sectorsize - 1)) == 0) ||
252 data_len > root->fs_info->max_inline) {
256 ret = btrfs_drop_extents(trans, root, inode, start, aligned_end, 1);
260 if (isize > actual_end)
261 inline_len = min_t(u64, isize, actual_end);
262 ret = insert_inline_extent(trans, root, inode, start,
263 inline_len, compressed_size,
264 compress_type, compressed_pages);
265 if (ret && ret != -ENOSPC) {
266 btrfs_abort_transaction(trans, root, ret);
268 } else if (ret == -ENOSPC) {
272 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
273 btrfs_delalloc_release_metadata(inode, end + 1 - start);
274 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
278 struct async_extent {
283 unsigned long nr_pages;
285 struct list_head list;
290 struct btrfs_root *root;
291 struct page *locked_page;
294 struct list_head extents;
295 struct btrfs_work work;
298 static noinline int add_async_extent(struct async_cow *cow,
299 u64 start, u64 ram_size,
302 unsigned long nr_pages,
305 struct async_extent *async_extent;
307 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
308 BUG_ON(!async_extent); /* -ENOMEM */
309 async_extent->start = start;
310 async_extent->ram_size = ram_size;
311 async_extent->compressed_size = compressed_size;
312 async_extent->pages = pages;
313 async_extent->nr_pages = nr_pages;
314 async_extent->compress_type = compress_type;
315 list_add_tail(&async_extent->list, &cow->extents);
320 * we create compressed extents in two phases. The first
321 * phase compresses a range of pages that have already been
322 * locked (both pages and state bits are locked).
324 * This is done inside an ordered work queue, and the compression
325 * is spread across many cpus. The actual IO submission is step
326 * two, and the ordered work queue takes care of making sure that
327 * happens in the same order things were put onto the queue by
328 * writepages and friends.
330 * If this code finds it can't get good compression, it puts an
331 * entry onto the work queue to write the uncompressed bytes. This
332 * makes sure that both compressed inodes and uncompressed inodes
333 * are written in the same order that the flusher thread sent them
336 static noinline int compress_file_range(struct inode *inode,
337 struct page *locked_page,
339 struct async_cow *async_cow,
342 struct btrfs_root *root = BTRFS_I(inode)->root;
343 struct btrfs_trans_handle *trans;
345 u64 blocksize = root->sectorsize;
347 u64 isize = i_size_read(inode);
349 struct page **pages = NULL;
350 unsigned long nr_pages;
351 unsigned long nr_pages_ret = 0;
352 unsigned long total_compressed = 0;
353 unsigned long total_in = 0;
354 unsigned long max_compressed = 128 * 1024;
355 unsigned long max_uncompressed = 128 * 1024;
358 int compress_type = root->fs_info->compress_type;
361 /* if this is a small write inside eof, kick off a defrag */
362 if ((end - start + 1) < 16 * 1024 &&
363 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
364 btrfs_add_inode_defrag(NULL, inode);
366 actual_end = min_t(u64, isize, end + 1);
369 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
370 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
373 * we don't want to send crud past the end of i_size through
374 * compression, that's just a waste of CPU time. So, if the
375 * end of the file is before the start of our current
376 * requested range of bytes, we bail out to the uncompressed
377 * cleanup code that can deal with all of this.
379 * It isn't really the fastest way to fix things, but this is a
380 * very uncommon corner.
382 if (actual_end <= start)
383 goto cleanup_and_bail_uncompressed;
385 total_compressed = actual_end - start;
387 /* we want to make sure that amount of ram required to uncompress
388 * an extent is reasonable, so we limit the total size in ram
389 * of a compressed extent to 128k. This is a crucial number
390 * because it also controls how easily we can spread reads across
391 * cpus for decompression.
393 * We also want to make sure the amount of IO required to do
394 * a random read is reasonably small, so we limit the size of
395 * a compressed extent to 128k.
397 total_compressed = min(total_compressed, max_uncompressed);
398 num_bytes = ALIGN(end - start + 1, blocksize);
399 num_bytes = max(blocksize, num_bytes);
404 * we do compression for mount -o compress and when the
405 * inode has not been flagged as nocompress. This flag can
406 * change at any time if we discover bad compression ratios.
408 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
409 (btrfs_test_opt(root, COMPRESS) ||
410 (BTRFS_I(inode)->force_compress) ||
411 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
413 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
415 /* just bail out to the uncompressed code */
419 if (BTRFS_I(inode)->force_compress)
420 compress_type = BTRFS_I(inode)->force_compress;
423 * we need to call clear_page_dirty_for_io on each
424 * page in the range. Otherwise applications with the file
425 * mmap'd can wander in and change the page contents while
426 * we are compressing them.
428 * If the compression fails for any reason, we set the pages
429 * dirty again later on.
431 extent_range_clear_dirty_for_io(inode, start, end);
433 ret = btrfs_compress_pages(compress_type,
434 inode->i_mapping, start,
435 total_compressed, pages,
436 nr_pages, &nr_pages_ret,
442 unsigned long offset = total_compressed &
443 (PAGE_CACHE_SIZE - 1);
444 struct page *page = pages[nr_pages_ret - 1];
447 /* zero the tail end of the last page, we might be
448 * sending it down to disk
451 kaddr = kmap_atomic(page);
452 memset(kaddr + offset, 0,
453 PAGE_CACHE_SIZE - offset);
454 kunmap_atomic(kaddr);
461 trans = btrfs_join_transaction(root);
463 ret = PTR_ERR(trans);
465 goto cleanup_and_out;
467 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
469 /* lets try to make an inline extent */
470 if (ret || total_in < (actual_end - start)) {
471 /* we didn't compress the entire range, try
472 * to make an uncompressed inline extent.
474 ret = cow_file_range_inline(trans, root, inode,
475 start, end, 0, 0, NULL);
477 /* try making a compressed inline extent */
478 ret = cow_file_range_inline(trans, root, inode,
481 compress_type, pages);
485 * inline extent creation worked or returned error,
486 * we don't need to create any more async work items.
487 * Unlock and free up our temp pages.
489 extent_clear_unlock_delalloc(inode,
490 &BTRFS_I(inode)->io_tree,
492 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
493 EXTENT_CLEAR_DELALLOC |
494 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
496 btrfs_end_transaction(trans, root);
499 btrfs_end_transaction(trans, root);
504 * we aren't doing an inline extent round the compressed size
505 * up to a block size boundary so the allocator does sane
508 total_compressed = ALIGN(total_compressed, blocksize);
511 * one last check to make sure the compression is really a
512 * win, compare the page count read with the blocks on disk
514 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
515 if (total_compressed >= total_in) {
518 num_bytes = total_in;
521 if (!will_compress && pages) {
523 * the compression code ran but failed to make things smaller,
524 * free any pages it allocated and our page pointer array
526 for (i = 0; i < nr_pages_ret; i++) {
527 WARN_ON(pages[i]->mapping);
528 page_cache_release(pages[i]);
532 total_compressed = 0;
535 /* flag the file so we don't compress in the future */
536 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
537 !(BTRFS_I(inode)->force_compress)) {
538 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
544 /* the async work queues will take care of doing actual
545 * allocation on disk for these compressed pages,
546 * and will submit them to the elevator.
548 add_async_extent(async_cow, start, num_bytes,
549 total_compressed, pages, nr_pages_ret,
552 if (start + num_bytes < end) {
559 cleanup_and_bail_uncompressed:
561 * No compression, but we still need to write the pages in
562 * the file we've been given so far. redirty the locked
563 * page if it corresponds to our extent and set things up
564 * for the async work queue to run cow_file_range to do
565 * the normal delalloc dance
567 if (page_offset(locked_page) >= start &&
568 page_offset(locked_page) <= end) {
569 __set_page_dirty_nobuffers(locked_page);
570 /* unlocked later on in the async handlers */
573 extent_range_redirty_for_io(inode, start, end);
574 add_async_extent(async_cow, start, end - start + 1,
575 0, NULL, 0, BTRFS_COMPRESS_NONE);
583 for (i = 0; i < nr_pages_ret; i++) {
584 WARN_ON(pages[i]->mapping);
585 page_cache_release(pages[i]);
592 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
594 EXTENT_CLEAR_UNLOCK_PAGE |
596 EXTENT_CLEAR_DELALLOC |
597 EXTENT_SET_WRITEBACK |
598 EXTENT_END_WRITEBACK);
599 if (!trans || IS_ERR(trans))
600 btrfs_error(root->fs_info, ret, "Failed to join transaction");
602 btrfs_abort_transaction(trans, root, ret);
607 * phase two of compressed writeback. This is the ordered portion
608 * of the code, which only gets called in the order the work was
609 * queued. We walk all the async extents created by compress_file_range
610 * and send them down to the disk.
612 static noinline int submit_compressed_extents(struct inode *inode,
613 struct async_cow *async_cow)
615 struct async_extent *async_extent;
617 struct btrfs_trans_handle *trans;
618 struct btrfs_key ins;
619 struct extent_map *em;
620 struct btrfs_root *root = BTRFS_I(inode)->root;
621 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
622 struct extent_io_tree *io_tree;
625 if (list_empty(&async_cow->extents))
629 while (!list_empty(&async_cow->extents)) {
630 async_extent = list_entry(async_cow->extents.next,
631 struct async_extent, list);
632 list_del(&async_extent->list);
634 io_tree = &BTRFS_I(inode)->io_tree;
637 /* did the compression code fall back to uncompressed IO? */
638 if (!async_extent->pages) {
639 int page_started = 0;
640 unsigned long nr_written = 0;
642 lock_extent(io_tree, async_extent->start,
643 async_extent->start +
644 async_extent->ram_size - 1);
646 /* allocate blocks */
647 ret = cow_file_range(inode, async_cow->locked_page,
649 async_extent->start +
650 async_extent->ram_size - 1,
651 &page_started, &nr_written, 0);
656 * if page_started, cow_file_range inserted an
657 * inline extent and took care of all the unlocking
658 * and IO for us. Otherwise, we need to submit
659 * all those pages down to the drive.
661 if (!page_started && !ret)
662 extent_write_locked_range(io_tree,
663 inode, async_extent->start,
664 async_extent->start +
665 async_extent->ram_size - 1,
669 unlock_page(async_cow->locked_page);
675 lock_extent(io_tree, async_extent->start,
676 async_extent->start + async_extent->ram_size - 1);
678 trans = btrfs_join_transaction(root);
680 ret = PTR_ERR(trans);
682 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
683 ret = btrfs_reserve_extent(trans, root,
684 async_extent->compressed_size,
685 async_extent->compressed_size,
686 0, alloc_hint, &ins, 1);
687 if (ret && ret != -ENOSPC)
688 btrfs_abort_transaction(trans, root, ret);
689 btrfs_end_transaction(trans, root);
695 for (i = 0; i < async_extent->nr_pages; i++) {
696 WARN_ON(async_extent->pages[i]->mapping);
697 page_cache_release(async_extent->pages[i]);
699 kfree(async_extent->pages);
700 async_extent->nr_pages = 0;
701 async_extent->pages = NULL;
709 * here we're doing allocation and writeback of the
712 btrfs_drop_extent_cache(inode, async_extent->start,
713 async_extent->start +
714 async_extent->ram_size - 1, 0);
716 em = alloc_extent_map();
719 goto out_free_reserve;
721 em->start = async_extent->start;
722 em->len = async_extent->ram_size;
723 em->orig_start = em->start;
724 em->mod_start = em->start;
725 em->mod_len = em->len;
727 em->block_start = ins.objectid;
728 em->block_len = ins.offset;
729 em->orig_block_len = ins.offset;
730 em->ram_bytes = async_extent->ram_size;
731 em->bdev = root->fs_info->fs_devices->latest_bdev;
732 em->compress_type = async_extent->compress_type;
733 set_bit(EXTENT_FLAG_PINNED, &em->flags);
734 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
738 write_lock(&em_tree->lock);
739 ret = add_extent_mapping(em_tree, em, 1);
740 write_unlock(&em_tree->lock);
741 if (ret != -EEXIST) {
745 btrfs_drop_extent_cache(inode, async_extent->start,
746 async_extent->start +
747 async_extent->ram_size - 1, 0);
751 goto out_free_reserve;
753 ret = btrfs_add_ordered_extent_compress(inode,
756 async_extent->ram_size,
758 BTRFS_ORDERED_COMPRESSED,
759 async_extent->compress_type);
761 goto out_free_reserve;
764 * clear dirty, set writeback and unlock the pages.
766 extent_clear_unlock_delalloc(inode,
767 &BTRFS_I(inode)->io_tree,
769 async_extent->start +
770 async_extent->ram_size - 1,
771 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
772 EXTENT_CLEAR_UNLOCK |
773 EXTENT_CLEAR_DELALLOC |
774 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
776 ret = btrfs_submit_compressed_write(inode,
778 async_extent->ram_size,
780 ins.offset, async_extent->pages,
781 async_extent->nr_pages);
782 alloc_hint = ins.objectid + ins.offset;
792 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
794 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
796 async_extent->start +
797 async_extent->ram_size - 1,
798 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
799 EXTENT_CLEAR_UNLOCK |
800 EXTENT_CLEAR_DELALLOC |
802 EXTENT_SET_WRITEBACK |
803 EXTENT_END_WRITEBACK);
808 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
811 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
812 struct extent_map *em;
815 read_lock(&em_tree->lock);
816 em = search_extent_mapping(em_tree, start, num_bytes);
819 * if block start isn't an actual block number then find the
820 * first block in this inode and use that as a hint. If that
821 * block is also bogus then just don't worry about it.
823 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
825 em = search_extent_mapping(em_tree, 0, 0);
826 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
827 alloc_hint = em->block_start;
831 alloc_hint = em->block_start;
835 read_unlock(&em_tree->lock);
841 * when extent_io.c finds a delayed allocation range in the file,
842 * the call backs end up in this code. The basic idea is to
843 * allocate extents on disk for the range, and create ordered data structs
844 * in ram to track those extents.
846 * locked_page is the page that writepage had locked already. We use
847 * it to make sure we don't do extra locks or unlocks.
849 * *page_started is set to one if we unlock locked_page and do everything
850 * required to start IO on it. It may be clean and already done with
853 static noinline int __cow_file_range(struct btrfs_trans_handle *trans,
855 struct btrfs_root *root,
856 struct page *locked_page,
857 u64 start, u64 end, int *page_started,
858 unsigned long *nr_written,
863 unsigned long ram_size;
866 u64 blocksize = root->sectorsize;
867 struct btrfs_key ins;
868 struct extent_map *em;
869 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
872 BUG_ON(btrfs_is_free_space_inode(inode));
874 num_bytes = ALIGN(end - start + 1, blocksize);
875 num_bytes = max(blocksize, num_bytes);
876 disk_num_bytes = num_bytes;
878 /* if this is a small write inside eof, kick off defrag */
879 if (num_bytes < 64 * 1024 &&
880 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
881 btrfs_add_inode_defrag(trans, inode);
884 /* lets try to make an inline extent */
885 ret = cow_file_range_inline(trans, root, inode,
886 start, end, 0, 0, NULL);
888 extent_clear_unlock_delalloc(inode,
889 &BTRFS_I(inode)->io_tree,
891 EXTENT_CLEAR_UNLOCK_PAGE |
892 EXTENT_CLEAR_UNLOCK |
893 EXTENT_CLEAR_DELALLOC |
895 EXTENT_SET_WRITEBACK |
896 EXTENT_END_WRITEBACK);
898 *nr_written = *nr_written +
899 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
902 } else if (ret < 0) {
903 btrfs_abort_transaction(trans, root, ret);
908 BUG_ON(disk_num_bytes >
909 btrfs_super_total_bytes(root->fs_info->super_copy));
911 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
912 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
914 while (disk_num_bytes > 0) {
917 cur_alloc_size = disk_num_bytes;
918 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
919 root->sectorsize, 0, alloc_hint,
922 btrfs_abort_transaction(trans, root, ret);
926 em = alloc_extent_map();
932 em->orig_start = em->start;
933 ram_size = ins.offset;
934 em->len = ins.offset;
935 em->mod_start = em->start;
936 em->mod_len = em->len;
938 em->block_start = ins.objectid;
939 em->block_len = ins.offset;
940 em->orig_block_len = ins.offset;
941 em->ram_bytes = ram_size;
942 em->bdev = root->fs_info->fs_devices->latest_bdev;
943 set_bit(EXTENT_FLAG_PINNED, &em->flags);
947 write_lock(&em_tree->lock);
948 ret = add_extent_mapping(em_tree, em, 1);
949 write_unlock(&em_tree->lock);
950 if (ret != -EEXIST) {
954 btrfs_drop_extent_cache(inode, start,
955 start + ram_size - 1, 0);
960 cur_alloc_size = ins.offset;
961 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
962 ram_size, cur_alloc_size, 0);
966 if (root->root_key.objectid ==
967 BTRFS_DATA_RELOC_TREE_OBJECTID) {
968 ret = btrfs_reloc_clone_csums(inode, start,
971 btrfs_abort_transaction(trans, root, ret);
976 if (disk_num_bytes < cur_alloc_size)
979 /* we're not doing compressed IO, don't unlock the first
980 * page (which the caller expects to stay locked), don't
981 * clear any dirty bits and don't set any writeback bits
983 * Do set the Private2 bit so we know this page was properly
984 * setup for writepage
986 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
987 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
990 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
991 start, start + ram_size - 1,
993 disk_num_bytes -= cur_alloc_size;
994 num_bytes -= cur_alloc_size;
995 alloc_hint = ins.objectid + ins.offset;
996 start += cur_alloc_size;
1002 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
1004 extent_clear_unlock_delalloc(inode,
1005 &BTRFS_I(inode)->io_tree,
1006 start, end, locked_page,
1007 EXTENT_CLEAR_UNLOCK_PAGE |
1008 EXTENT_CLEAR_UNLOCK |
1009 EXTENT_CLEAR_DELALLOC |
1010 EXTENT_CLEAR_DIRTY |
1011 EXTENT_SET_WRITEBACK |
1012 EXTENT_END_WRITEBACK);
1017 static noinline int cow_file_range(struct inode *inode,
1018 struct page *locked_page,
1019 u64 start, u64 end, int *page_started,
1020 unsigned long *nr_written,
1023 struct btrfs_trans_handle *trans;
1024 struct btrfs_root *root = BTRFS_I(inode)->root;
1027 trans = btrfs_join_transaction(root);
1028 if (IS_ERR(trans)) {
1029 extent_clear_unlock_delalloc(inode,
1030 &BTRFS_I(inode)->io_tree,
1031 start, end, locked_page,
1032 EXTENT_CLEAR_UNLOCK_PAGE |
1033 EXTENT_CLEAR_UNLOCK |
1034 EXTENT_CLEAR_DELALLOC |
1035 EXTENT_CLEAR_DIRTY |
1036 EXTENT_SET_WRITEBACK |
1037 EXTENT_END_WRITEBACK);
1038 return PTR_ERR(trans);
1040 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1042 ret = __cow_file_range(trans, inode, root, locked_page, start, end,
1043 page_started, nr_written, unlock);
1045 btrfs_end_transaction(trans, root);
1051 * work queue call back to started compression on a file and pages
1053 static noinline void async_cow_start(struct btrfs_work *work)
1055 struct async_cow *async_cow;
1057 async_cow = container_of(work, struct async_cow, work);
1059 compress_file_range(async_cow->inode, async_cow->locked_page,
1060 async_cow->start, async_cow->end, async_cow,
1062 if (num_added == 0) {
1063 btrfs_add_delayed_iput(async_cow->inode);
1064 async_cow->inode = NULL;
1069 * work queue call back to submit previously compressed pages
1071 static noinline void async_cow_submit(struct btrfs_work *work)
1073 struct async_cow *async_cow;
1074 struct btrfs_root *root;
1075 unsigned long nr_pages;
1077 async_cow = container_of(work, struct async_cow, work);
1079 root = async_cow->root;
1080 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1083 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1085 waitqueue_active(&root->fs_info->async_submit_wait))
1086 wake_up(&root->fs_info->async_submit_wait);
1088 if (async_cow->inode)
1089 submit_compressed_extents(async_cow->inode, async_cow);
1092 static noinline void async_cow_free(struct btrfs_work *work)
1094 struct async_cow *async_cow;
1095 async_cow = container_of(work, struct async_cow, work);
1096 if (async_cow->inode)
1097 btrfs_add_delayed_iput(async_cow->inode);
1101 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1102 u64 start, u64 end, int *page_started,
1103 unsigned long *nr_written)
1105 struct async_cow *async_cow;
1106 struct btrfs_root *root = BTRFS_I(inode)->root;
1107 unsigned long nr_pages;
1109 int limit = 10 * 1024 * 1024;
1111 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1112 1, 0, NULL, GFP_NOFS);
1113 while (start < end) {
1114 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1115 BUG_ON(!async_cow); /* -ENOMEM */
1116 async_cow->inode = igrab(inode);
1117 async_cow->root = root;
1118 async_cow->locked_page = locked_page;
1119 async_cow->start = start;
1121 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1124 cur_end = min(end, start + 512 * 1024 - 1);
1126 async_cow->end = cur_end;
1127 INIT_LIST_HEAD(&async_cow->extents);
1129 async_cow->work.func = async_cow_start;
1130 async_cow->work.ordered_func = async_cow_submit;
1131 async_cow->work.ordered_free = async_cow_free;
1132 async_cow->work.flags = 0;
1134 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1136 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1138 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1141 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1142 wait_event(root->fs_info->async_submit_wait,
1143 (atomic_read(&root->fs_info->async_delalloc_pages) <
1147 while (atomic_read(&root->fs_info->async_submit_draining) &&
1148 atomic_read(&root->fs_info->async_delalloc_pages)) {
1149 wait_event(root->fs_info->async_submit_wait,
1150 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1154 *nr_written += nr_pages;
1155 start = cur_end + 1;
1161 static noinline int csum_exist_in_range(struct btrfs_root *root,
1162 u64 bytenr, u64 num_bytes)
1165 struct btrfs_ordered_sum *sums;
1168 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1169 bytenr + num_bytes - 1, &list, 0);
1170 if (ret == 0 && list_empty(&list))
1173 while (!list_empty(&list)) {
1174 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1175 list_del(&sums->list);
1182 * when nowcow writeback call back. This checks for snapshots or COW copies
1183 * of the extents that exist in the file, and COWs the file as required.
1185 * If no cow copies or snapshots exist, we write directly to the existing
1188 static noinline int run_delalloc_nocow(struct inode *inode,
1189 struct page *locked_page,
1190 u64 start, u64 end, int *page_started, int force,
1191 unsigned long *nr_written)
1193 struct btrfs_root *root = BTRFS_I(inode)->root;
1194 struct btrfs_trans_handle *trans;
1195 struct extent_buffer *leaf;
1196 struct btrfs_path *path;
1197 struct btrfs_file_extent_item *fi;
1198 struct btrfs_key found_key;
1213 u64 ino = btrfs_ino(inode);
1215 path = btrfs_alloc_path();
1217 extent_clear_unlock_delalloc(inode,
1218 &BTRFS_I(inode)->io_tree,
1219 start, end, locked_page,
1220 EXTENT_CLEAR_UNLOCK_PAGE |
1221 EXTENT_CLEAR_UNLOCK |
1222 EXTENT_CLEAR_DELALLOC |
1223 EXTENT_CLEAR_DIRTY |
1224 EXTENT_SET_WRITEBACK |
1225 EXTENT_END_WRITEBACK);
1229 nolock = btrfs_is_free_space_inode(inode);
1232 trans = btrfs_join_transaction_nolock(root);
1234 trans = btrfs_join_transaction(root);
1236 if (IS_ERR(trans)) {
1237 extent_clear_unlock_delalloc(inode,
1238 &BTRFS_I(inode)->io_tree,
1239 start, end, locked_page,
1240 EXTENT_CLEAR_UNLOCK_PAGE |
1241 EXTENT_CLEAR_UNLOCK |
1242 EXTENT_CLEAR_DELALLOC |
1243 EXTENT_CLEAR_DIRTY |
1244 EXTENT_SET_WRITEBACK |
1245 EXTENT_END_WRITEBACK);
1246 btrfs_free_path(path);
1247 return PTR_ERR(trans);
1250 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1252 cow_start = (u64)-1;
1255 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1258 btrfs_abort_transaction(trans, root, ret);
1261 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1262 leaf = path->nodes[0];
1263 btrfs_item_key_to_cpu(leaf, &found_key,
1264 path->slots[0] - 1);
1265 if (found_key.objectid == ino &&
1266 found_key.type == BTRFS_EXTENT_DATA_KEY)
1271 leaf = path->nodes[0];
1272 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1273 ret = btrfs_next_leaf(root, path);
1275 btrfs_abort_transaction(trans, root, ret);
1280 leaf = path->nodes[0];
1286 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1288 if (found_key.objectid > ino ||
1289 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1290 found_key.offset > end)
1293 if (found_key.offset > cur_offset) {
1294 extent_end = found_key.offset;
1299 fi = btrfs_item_ptr(leaf, path->slots[0],
1300 struct btrfs_file_extent_item);
1301 extent_type = btrfs_file_extent_type(leaf, fi);
1303 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1304 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1305 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1306 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1307 extent_offset = btrfs_file_extent_offset(leaf, fi);
1308 extent_end = found_key.offset +
1309 btrfs_file_extent_num_bytes(leaf, fi);
1311 btrfs_file_extent_disk_num_bytes(leaf, fi);
1312 if (extent_end <= start) {
1316 if (disk_bytenr == 0)
1318 if (btrfs_file_extent_compression(leaf, fi) ||
1319 btrfs_file_extent_encryption(leaf, fi) ||
1320 btrfs_file_extent_other_encoding(leaf, fi))
1322 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1324 if (btrfs_extent_readonly(root, disk_bytenr))
1326 if (btrfs_cross_ref_exist(trans, root, ino,
1328 extent_offset, disk_bytenr))
1330 disk_bytenr += extent_offset;
1331 disk_bytenr += cur_offset - found_key.offset;
1332 num_bytes = min(end + 1, extent_end) - cur_offset;
1334 * force cow if csum exists in the range.
1335 * this ensure that csum for a given extent are
1336 * either valid or do not exist.
1338 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1341 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1342 extent_end = found_key.offset +
1343 btrfs_file_extent_inline_len(leaf, fi);
1344 extent_end = ALIGN(extent_end, root->sectorsize);
1349 if (extent_end <= start) {
1354 if (cow_start == (u64)-1)
1355 cow_start = cur_offset;
1356 cur_offset = extent_end;
1357 if (cur_offset > end)
1363 btrfs_release_path(path);
1364 if (cow_start != (u64)-1) {
1365 ret = __cow_file_range(trans, inode, root, locked_page,
1366 cow_start, found_key.offset - 1,
1367 page_started, nr_written, 1);
1369 btrfs_abort_transaction(trans, root, ret);
1372 cow_start = (u64)-1;
1375 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1376 struct extent_map *em;
1377 struct extent_map_tree *em_tree;
1378 em_tree = &BTRFS_I(inode)->extent_tree;
1379 em = alloc_extent_map();
1380 BUG_ON(!em); /* -ENOMEM */
1381 em->start = cur_offset;
1382 em->orig_start = found_key.offset - extent_offset;
1383 em->len = num_bytes;
1384 em->block_len = num_bytes;
1385 em->block_start = disk_bytenr;
1386 em->orig_block_len = disk_num_bytes;
1387 em->ram_bytes = ram_bytes;
1388 em->bdev = root->fs_info->fs_devices->latest_bdev;
1389 em->mod_start = em->start;
1390 em->mod_len = em->len;
1391 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1392 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1393 em->generation = -1;
1395 write_lock(&em_tree->lock);
1396 ret = add_extent_mapping(em_tree, em, 1);
1397 write_unlock(&em_tree->lock);
1398 if (ret != -EEXIST) {
1399 free_extent_map(em);
1402 btrfs_drop_extent_cache(inode, em->start,
1403 em->start + em->len - 1, 0);
1405 type = BTRFS_ORDERED_PREALLOC;
1407 type = BTRFS_ORDERED_NOCOW;
1410 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1411 num_bytes, num_bytes, type);
1412 BUG_ON(ret); /* -ENOMEM */
1414 if (root->root_key.objectid ==
1415 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1416 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1419 btrfs_abort_transaction(trans, root, ret);
1424 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1425 cur_offset, cur_offset + num_bytes - 1,
1426 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1427 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1428 EXTENT_SET_PRIVATE2);
1429 cur_offset = extent_end;
1430 if (cur_offset > end)
1433 btrfs_release_path(path);
1435 if (cur_offset <= end && cow_start == (u64)-1) {
1436 cow_start = cur_offset;
1440 if (cow_start != (u64)-1) {
1441 ret = __cow_file_range(trans, inode, root, locked_page,
1443 page_started, nr_written, 1);
1445 btrfs_abort_transaction(trans, root, ret);
1451 err = btrfs_end_transaction(trans, root);
1455 if (ret && cur_offset < end)
1456 extent_clear_unlock_delalloc(inode,
1457 &BTRFS_I(inode)->io_tree,
1458 cur_offset, end, locked_page,
1459 EXTENT_CLEAR_UNLOCK_PAGE |
1460 EXTENT_CLEAR_UNLOCK |
1461 EXTENT_CLEAR_DELALLOC |
1462 EXTENT_CLEAR_DIRTY |
1463 EXTENT_SET_WRITEBACK |
1464 EXTENT_END_WRITEBACK);
1466 btrfs_free_path(path);
1471 * extent_io.c call back to do delayed allocation processing
1473 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1474 u64 start, u64 end, int *page_started,
1475 unsigned long *nr_written)
1478 struct btrfs_root *root = BTRFS_I(inode)->root;
1480 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1481 ret = run_delalloc_nocow(inode, locked_page, start, end,
1482 page_started, 1, nr_written);
1483 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1484 ret = run_delalloc_nocow(inode, locked_page, start, end,
1485 page_started, 0, nr_written);
1486 } else if (!btrfs_test_opt(root, COMPRESS) &&
1487 !(BTRFS_I(inode)->force_compress) &&
1488 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1489 ret = cow_file_range(inode, locked_page, start, end,
1490 page_started, nr_written, 1);
1492 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1493 &BTRFS_I(inode)->runtime_flags);
1494 ret = cow_file_range_async(inode, locked_page, start, end,
1495 page_started, nr_written);
1500 static void btrfs_split_extent_hook(struct inode *inode,
1501 struct extent_state *orig, u64 split)
1503 /* not delalloc, ignore it */
1504 if (!(orig->state & EXTENT_DELALLOC))
1507 spin_lock(&BTRFS_I(inode)->lock);
1508 BTRFS_I(inode)->outstanding_extents++;
1509 spin_unlock(&BTRFS_I(inode)->lock);
1513 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1514 * extents so we can keep track of new extents that are just merged onto old
1515 * extents, such as when we are doing sequential writes, so we can properly
1516 * account for the metadata space we'll need.
1518 static void btrfs_merge_extent_hook(struct inode *inode,
1519 struct extent_state *new,
1520 struct extent_state *other)
1522 /* not delalloc, ignore it */
1523 if (!(other->state & EXTENT_DELALLOC))
1526 spin_lock(&BTRFS_I(inode)->lock);
1527 BTRFS_I(inode)->outstanding_extents--;
1528 spin_unlock(&BTRFS_I(inode)->lock);
1532 * extent_io.c set_bit_hook, used to track delayed allocation
1533 * bytes in this file, and to maintain the list of inodes that
1534 * have pending delalloc work to be done.
1536 static void btrfs_set_bit_hook(struct inode *inode,
1537 struct extent_state *state, unsigned long *bits)
1541 * set_bit and clear bit hooks normally require _irqsave/restore
1542 * but in this case, we are only testing for the DELALLOC
1543 * bit, which is only set or cleared with irqs on
1545 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1546 struct btrfs_root *root = BTRFS_I(inode)->root;
1547 u64 len = state->end + 1 - state->start;
1548 bool do_list = !btrfs_is_free_space_inode(inode);
1550 if (*bits & EXTENT_FIRST_DELALLOC) {
1551 *bits &= ~EXTENT_FIRST_DELALLOC;
1553 spin_lock(&BTRFS_I(inode)->lock);
1554 BTRFS_I(inode)->outstanding_extents++;
1555 spin_unlock(&BTRFS_I(inode)->lock);
1558 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1559 root->fs_info->delalloc_batch);
1560 spin_lock(&BTRFS_I(inode)->lock);
1561 BTRFS_I(inode)->delalloc_bytes += len;
1562 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1563 &BTRFS_I(inode)->runtime_flags)) {
1564 spin_lock(&root->fs_info->delalloc_lock);
1565 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1566 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1567 &root->fs_info->delalloc_inodes);
1568 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1569 &BTRFS_I(inode)->runtime_flags);
1571 spin_unlock(&root->fs_info->delalloc_lock);
1573 spin_unlock(&BTRFS_I(inode)->lock);
1578 * extent_io.c clear_bit_hook, see set_bit_hook for why
1580 static void btrfs_clear_bit_hook(struct inode *inode,
1581 struct extent_state *state,
1582 unsigned long *bits)
1585 * set_bit and clear bit hooks normally require _irqsave/restore
1586 * but in this case, we are only testing for the DELALLOC
1587 * bit, which is only set or cleared with irqs on
1589 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1590 struct btrfs_root *root = BTRFS_I(inode)->root;
1591 u64 len = state->end + 1 - state->start;
1592 bool do_list = !btrfs_is_free_space_inode(inode);
1594 if (*bits & EXTENT_FIRST_DELALLOC) {
1595 *bits &= ~EXTENT_FIRST_DELALLOC;
1596 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1597 spin_lock(&BTRFS_I(inode)->lock);
1598 BTRFS_I(inode)->outstanding_extents--;
1599 spin_unlock(&BTRFS_I(inode)->lock);
1602 if (*bits & EXTENT_DO_ACCOUNTING)
1603 btrfs_delalloc_release_metadata(inode, len);
1605 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1607 btrfs_free_reserved_data_space(inode, len);
1609 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1610 root->fs_info->delalloc_batch);
1611 spin_lock(&BTRFS_I(inode)->lock);
1612 BTRFS_I(inode)->delalloc_bytes -= len;
1613 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1614 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1615 &BTRFS_I(inode)->runtime_flags)) {
1616 spin_lock(&root->fs_info->delalloc_lock);
1617 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1618 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1619 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1620 &BTRFS_I(inode)->runtime_flags);
1622 spin_unlock(&root->fs_info->delalloc_lock);
1624 spin_unlock(&BTRFS_I(inode)->lock);
1629 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1630 * we don't create bios that span stripes or chunks
1632 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1633 size_t size, struct bio *bio,
1634 unsigned long bio_flags)
1636 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1637 u64 logical = (u64)bio->bi_sector << 9;
1642 if (bio_flags & EXTENT_BIO_COMPRESSED)
1645 length = bio->bi_size;
1646 map_length = length;
1647 ret = btrfs_map_block(root->fs_info, rw, logical,
1648 &map_length, NULL, 0);
1649 /* Will always return 0 with map_multi == NULL */
1651 if (map_length < length + size)
1657 * in order to insert checksums into the metadata in large chunks,
1658 * we wait until bio submission time. All the pages in the bio are
1659 * checksummed and sums are attached onto the ordered extent record.
1661 * At IO completion time the cums attached on the ordered extent record
1662 * are inserted into the btree
1664 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1665 struct bio *bio, int mirror_num,
1666 unsigned long bio_flags,
1669 struct btrfs_root *root = BTRFS_I(inode)->root;
1672 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1673 BUG_ON(ret); /* -ENOMEM */
1678 * in order to insert checksums into the metadata in large chunks,
1679 * we wait until bio submission time. All the pages in the bio are
1680 * checksummed and sums are attached onto the ordered extent record.
1682 * At IO completion time the cums attached on the ordered extent record
1683 * are inserted into the btree
1685 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1686 int mirror_num, unsigned long bio_flags,
1689 struct btrfs_root *root = BTRFS_I(inode)->root;
1692 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1694 bio_endio(bio, ret);
1699 * extent_io.c submission hook. This does the right thing for csum calculation
1700 * on write, or reading the csums from the tree before a read
1702 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1703 int mirror_num, unsigned long bio_flags,
1706 struct btrfs_root *root = BTRFS_I(inode)->root;
1710 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1712 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1714 if (btrfs_is_free_space_inode(inode))
1717 if (!(rw & REQ_WRITE)) {
1718 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1722 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1723 ret = btrfs_submit_compressed_read(inode, bio,
1727 } else if (!skip_sum) {
1728 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1733 } else if (async && !skip_sum) {
1734 /* csum items have already been cloned */
1735 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1737 /* we're doing a write, do the async checksumming */
1738 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1739 inode, rw, bio, mirror_num,
1740 bio_flags, bio_offset,
1741 __btrfs_submit_bio_start,
1742 __btrfs_submit_bio_done);
1744 } else if (!skip_sum) {
1745 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1751 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1755 bio_endio(bio, ret);
1760 * given a list of ordered sums record them in the inode. This happens
1761 * at IO completion time based on sums calculated at bio submission time.
1763 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1764 struct inode *inode, u64 file_offset,
1765 struct list_head *list)
1767 struct btrfs_ordered_sum *sum;
1769 list_for_each_entry(sum, list, list) {
1770 trans->adding_csums = 1;
1771 btrfs_csum_file_blocks(trans,
1772 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1773 trans->adding_csums = 0;
1778 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1779 struct extent_state **cached_state)
1781 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1782 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1783 cached_state, GFP_NOFS);
1786 /* see btrfs_writepage_start_hook for details on why this is required */
1787 struct btrfs_writepage_fixup {
1789 struct btrfs_work work;
1792 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1794 struct btrfs_writepage_fixup *fixup;
1795 struct btrfs_ordered_extent *ordered;
1796 struct extent_state *cached_state = NULL;
1798 struct inode *inode;
1803 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1807 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1808 ClearPageChecked(page);
1812 inode = page->mapping->host;
1813 page_start = page_offset(page);
1814 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1816 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1819 /* already ordered? We're done */
1820 if (PagePrivate2(page))
1823 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1825 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1826 page_end, &cached_state, GFP_NOFS);
1828 btrfs_start_ordered_extent(inode, ordered, 1);
1829 btrfs_put_ordered_extent(ordered);
1833 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1835 mapping_set_error(page->mapping, ret);
1836 end_extent_writepage(page, ret, page_start, page_end);
1837 ClearPageChecked(page);
1841 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1842 ClearPageChecked(page);
1843 set_page_dirty(page);
1845 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1846 &cached_state, GFP_NOFS);
1849 page_cache_release(page);
1854 * There are a few paths in the higher layers of the kernel that directly
1855 * set the page dirty bit without asking the filesystem if it is a
1856 * good idea. This causes problems because we want to make sure COW
1857 * properly happens and the data=ordered rules are followed.
1859 * In our case any range that doesn't have the ORDERED bit set
1860 * hasn't been properly setup for IO. We kick off an async process
1861 * to fix it up. The async helper will wait for ordered extents, set
1862 * the delalloc bit and make it safe to write the page.
1864 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1866 struct inode *inode = page->mapping->host;
1867 struct btrfs_writepage_fixup *fixup;
1868 struct btrfs_root *root = BTRFS_I(inode)->root;
1870 /* this page is properly in the ordered list */
1871 if (TestClearPagePrivate2(page))
1874 if (PageChecked(page))
1877 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1881 SetPageChecked(page);
1882 page_cache_get(page);
1883 fixup->work.func = btrfs_writepage_fixup_worker;
1885 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1889 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1890 struct inode *inode, u64 file_pos,
1891 u64 disk_bytenr, u64 disk_num_bytes,
1892 u64 num_bytes, u64 ram_bytes,
1893 u8 compression, u8 encryption,
1894 u16 other_encoding, int extent_type)
1896 struct btrfs_root *root = BTRFS_I(inode)->root;
1897 struct btrfs_file_extent_item *fi;
1898 struct btrfs_path *path;
1899 struct extent_buffer *leaf;
1900 struct btrfs_key ins;
1903 path = btrfs_alloc_path();
1907 path->leave_spinning = 1;
1910 * we may be replacing one extent in the tree with another.
1911 * The new extent is pinned in the extent map, and we don't want
1912 * to drop it from the cache until it is completely in the btree.
1914 * So, tell btrfs_drop_extents to leave this extent in the cache.
1915 * the caller is expected to unpin it and allow it to be merged
1918 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1919 file_pos + num_bytes, 0);
1923 ins.objectid = btrfs_ino(inode);
1924 ins.offset = file_pos;
1925 ins.type = BTRFS_EXTENT_DATA_KEY;
1926 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1929 leaf = path->nodes[0];
1930 fi = btrfs_item_ptr(leaf, path->slots[0],
1931 struct btrfs_file_extent_item);
1932 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1933 btrfs_set_file_extent_type(leaf, fi, extent_type);
1934 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1935 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1936 btrfs_set_file_extent_offset(leaf, fi, 0);
1937 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1938 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1939 btrfs_set_file_extent_compression(leaf, fi, compression);
1940 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1941 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1943 btrfs_mark_buffer_dirty(leaf);
1944 btrfs_release_path(path);
1946 inode_add_bytes(inode, num_bytes);
1948 ins.objectid = disk_bytenr;
1949 ins.offset = disk_num_bytes;
1950 ins.type = BTRFS_EXTENT_ITEM_KEY;
1951 ret = btrfs_alloc_reserved_file_extent(trans, root,
1952 root->root_key.objectid,
1953 btrfs_ino(inode), file_pos, &ins);
1955 btrfs_free_path(path);
1960 /* snapshot-aware defrag */
1961 struct sa_defrag_extent_backref {
1962 struct rb_node node;
1963 struct old_sa_defrag_extent *old;
1972 struct old_sa_defrag_extent {
1973 struct list_head list;
1974 struct new_sa_defrag_extent *new;
1983 struct new_sa_defrag_extent {
1984 struct rb_root root;
1985 struct list_head head;
1986 struct btrfs_path *path;
1987 struct inode *inode;
1995 static int backref_comp(struct sa_defrag_extent_backref *b1,
1996 struct sa_defrag_extent_backref *b2)
1998 if (b1->root_id < b2->root_id)
2000 else if (b1->root_id > b2->root_id)
2003 if (b1->inum < b2->inum)
2005 else if (b1->inum > b2->inum)
2008 if (b1->file_pos < b2->file_pos)
2010 else if (b1->file_pos > b2->file_pos)
2014 * [------------------------------] ===> (a range of space)
2015 * |<--->| |<---->| =============> (fs/file tree A)
2016 * |<---------------------------->| ===> (fs/file tree B)
2018 * A range of space can refer to two file extents in one tree while
2019 * refer to only one file extent in another tree.
2021 * So we may process a disk offset more than one time(two extents in A)
2022 * and locate at the same extent(one extent in B), then insert two same
2023 * backrefs(both refer to the extent in B).
2028 static void backref_insert(struct rb_root *root,
2029 struct sa_defrag_extent_backref *backref)
2031 struct rb_node **p = &root->rb_node;
2032 struct rb_node *parent = NULL;
2033 struct sa_defrag_extent_backref *entry;
2038 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2040 ret = backref_comp(backref, entry);
2044 p = &(*p)->rb_right;
2047 rb_link_node(&backref->node, parent, p);
2048 rb_insert_color(&backref->node, root);
2052 * Note the backref might has changed, and in this case we just return 0.
2054 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2057 struct btrfs_file_extent_item *extent;
2058 struct btrfs_fs_info *fs_info;
2059 struct old_sa_defrag_extent *old = ctx;
2060 struct new_sa_defrag_extent *new = old->new;
2061 struct btrfs_path *path = new->path;
2062 struct btrfs_key key;
2063 struct btrfs_root *root;
2064 struct sa_defrag_extent_backref *backref;
2065 struct extent_buffer *leaf;
2066 struct inode *inode = new->inode;
2072 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2073 inum == btrfs_ino(inode))
2076 key.objectid = root_id;
2077 key.type = BTRFS_ROOT_ITEM_KEY;
2078 key.offset = (u64)-1;
2080 fs_info = BTRFS_I(inode)->root->fs_info;
2081 root = btrfs_read_fs_root_no_name(fs_info, &key);
2083 if (PTR_ERR(root) == -ENOENT)
2086 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2087 inum, offset, root_id);
2088 return PTR_ERR(root);
2091 key.objectid = inum;
2092 key.type = BTRFS_EXTENT_DATA_KEY;
2093 if (offset > (u64)-1 << 32)
2096 key.offset = offset;
2098 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2107 leaf = path->nodes[0];
2108 slot = path->slots[0];
2110 if (slot >= btrfs_header_nritems(leaf)) {
2111 ret = btrfs_next_leaf(root, path);
2114 } else if (ret > 0) {
2123 btrfs_item_key_to_cpu(leaf, &key, slot);
2125 if (key.objectid > inum)
2128 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2131 extent = btrfs_item_ptr(leaf, slot,
2132 struct btrfs_file_extent_item);
2134 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2137 extent_offset = btrfs_file_extent_offset(leaf, extent);
2138 if (key.offset - extent_offset != offset)
2141 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2142 if (extent_offset >= old->extent_offset + old->offset +
2143 old->len || extent_offset + num_bytes <=
2144 old->extent_offset + old->offset)
2150 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2156 backref->root_id = root_id;
2157 backref->inum = inum;
2158 backref->file_pos = offset + extent_offset;
2159 backref->num_bytes = num_bytes;
2160 backref->extent_offset = extent_offset;
2161 backref->generation = btrfs_file_extent_generation(leaf, extent);
2163 backref_insert(&new->root, backref);
2166 btrfs_release_path(path);
2171 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2172 struct new_sa_defrag_extent *new)
2174 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2175 struct old_sa_defrag_extent *old, *tmp;
2180 list_for_each_entry_safe(old, tmp, &new->head, list) {
2181 ret = iterate_inodes_from_logical(old->bytenr, fs_info,
2182 path, record_one_backref,
2184 BUG_ON(ret < 0 && ret != -ENOENT);
2186 /* no backref to be processed for this extent */
2188 list_del(&old->list);
2193 if (list_empty(&new->head))
2199 static int relink_is_mergable(struct extent_buffer *leaf,
2200 struct btrfs_file_extent_item *fi,
2203 if (btrfs_file_extent_disk_bytenr(leaf, fi) != disk_bytenr)
2206 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2209 if (btrfs_file_extent_compression(leaf, fi) ||
2210 btrfs_file_extent_encryption(leaf, fi) ||
2211 btrfs_file_extent_other_encoding(leaf, fi))
2218 * Note the backref might has changed, and in this case we just return 0.
2220 static noinline int relink_extent_backref(struct btrfs_path *path,
2221 struct sa_defrag_extent_backref *prev,
2222 struct sa_defrag_extent_backref *backref)
2224 struct btrfs_file_extent_item *extent;
2225 struct btrfs_file_extent_item *item;
2226 struct btrfs_ordered_extent *ordered;
2227 struct btrfs_trans_handle *trans;
2228 struct btrfs_fs_info *fs_info;
2229 struct btrfs_root *root;
2230 struct btrfs_key key;
2231 struct extent_buffer *leaf;
2232 struct old_sa_defrag_extent *old = backref->old;
2233 struct new_sa_defrag_extent *new = old->new;
2234 struct inode *src_inode = new->inode;
2235 struct inode *inode;
2236 struct extent_state *cached = NULL;
2245 if (prev && prev->root_id == backref->root_id &&
2246 prev->inum == backref->inum &&
2247 prev->file_pos + prev->num_bytes == backref->file_pos)
2250 /* step 1: get root */
2251 key.objectid = backref->root_id;
2252 key.type = BTRFS_ROOT_ITEM_KEY;
2253 key.offset = (u64)-1;
2255 fs_info = BTRFS_I(src_inode)->root->fs_info;
2256 index = srcu_read_lock(&fs_info->subvol_srcu);
2258 root = btrfs_read_fs_root_no_name(fs_info, &key);
2260 srcu_read_unlock(&fs_info->subvol_srcu, index);
2261 if (PTR_ERR(root) == -ENOENT)
2263 return PTR_ERR(root);
2265 if (btrfs_root_refs(&root->root_item) == 0) {
2266 srcu_read_unlock(&fs_info->subvol_srcu, index);
2267 /* parse ENOENT to 0 */
2271 /* step 2: get inode */
2272 key.objectid = backref->inum;
2273 key.type = BTRFS_INODE_ITEM_KEY;
2276 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2277 if (IS_ERR(inode)) {
2278 srcu_read_unlock(&fs_info->subvol_srcu, index);
2282 srcu_read_unlock(&fs_info->subvol_srcu, index);
2284 /* step 3: relink backref */
2285 lock_start = backref->file_pos;
2286 lock_end = backref->file_pos + backref->num_bytes - 1;
2287 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2290 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2292 btrfs_put_ordered_extent(ordered);
2296 trans = btrfs_join_transaction(root);
2297 if (IS_ERR(trans)) {
2298 ret = PTR_ERR(trans);
2302 key.objectid = backref->inum;
2303 key.type = BTRFS_EXTENT_DATA_KEY;
2304 key.offset = backref->file_pos;
2306 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2309 } else if (ret > 0) {
2314 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2315 struct btrfs_file_extent_item);
2317 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2318 backref->generation)
2321 btrfs_release_path(path);
2323 start = backref->file_pos;
2324 if (backref->extent_offset < old->extent_offset + old->offset)
2325 start += old->extent_offset + old->offset -
2326 backref->extent_offset;
2328 len = min(backref->extent_offset + backref->num_bytes,
2329 old->extent_offset + old->offset + old->len);
2330 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2332 ret = btrfs_drop_extents(trans, root, inode, start,
2337 key.objectid = btrfs_ino(inode);
2338 key.type = BTRFS_EXTENT_DATA_KEY;
2341 path->leave_spinning = 1;
2343 struct btrfs_file_extent_item *fi;
2345 struct btrfs_key found_key;
2347 ret = btrfs_search_slot(trans, root, &key, path, 1, 1);
2352 leaf = path->nodes[0];
2353 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2355 fi = btrfs_item_ptr(leaf, path->slots[0],
2356 struct btrfs_file_extent_item);
2357 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2359 if (relink_is_mergable(leaf, fi, new->bytenr) &&
2360 extent_len + found_key.offset == start) {
2361 btrfs_set_file_extent_num_bytes(leaf, fi,
2363 btrfs_mark_buffer_dirty(leaf);
2364 inode_add_bytes(inode, len);
2370 btrfs_release_path(path);
2375 ret = btrfs_insert_empty_item(trans, root, path, &key,
2378 btrfs_abort_transaction(trans, root, ret);
2382 leaf = path->nodes[0];
2383 item = btrfs_item_ptr(leaf, path->slots[0],
2384 struct btrfs_file_extent_item);
2385 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2386 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2387 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2388 btrfs_set_file_extent_num_bytes(leaf, item, len);
2389 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2390 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2391 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2392 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2393 btrfs_set_file_extent_encryption(leaf, item, 0);
2394 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2396 btrfs_mark_buffer_dirty(leaf);
2397 inode_add_bytes(inode, len);
2398 btrfs_release_path(path);
2400 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2402 backref->root_id, backref->inum,
2403 new->file_pos, 0); /* start - extent_offset */
2405 btrfs_abort_transaction(trans, root, ret);
2411 btrfs_release_path(path);
2412 path->leave_spinning = 0;
2413 btrfs_end_transaction(trans, root);
2415 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2421 static void relink_file_extents(struct new_sa_defrag_extent *new)
2423 struct btrfs_path *path;
2424 struct old_sa_defrag_extent *old, *tmp;
2425 struct sa_defrag_extent_backref *backref;
2426 struct sa_defrag_extent_backref *prev = NULL;
2427 struct inode *inode;
2428 struct btrfs_root *root;
2429 struct rb_node *node;
2433 root = BTRFS_I(inode)->root;
2435 path = btrfs_alloc_path();
2439 if (!record_extent_backrefs(path, new)) {
2440 btrfs_free_path(path);
2443 btrfs_release_path(path);
2446 node = rb_first(&new->root);
2449 rb_erase(node, &new->root);
2451 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2453 ret = relink_extent_backref(path, prev, backref);
2466 btrfs_free_path(path);
2468 list_for_each_entry_safe(old, tmp, &new->head, list) {
2469 list_del(&old->list);
2473 atomic_dec(&root->fs_info->defrag_running);
2474 wake_up(&root->fs_info->transaction_wait);
2479 static struct new_sa_defrag_extent *
2480 record_old_file_extents(struct inode *inode,
2481 struct btrfs_ordered_extent *ordered)
2483 struct btrfs_root *root = BTRFS_I(inode)->root;
2484 struct btrfs_path *path;
2485 struct btrfs_key key;
2486 struct old_sa_defrag_extent *old, *tmp;
2487 struct new_sa_defrag_extent *new;
2490 new = kmalloc(sizeof(*new), GFP_NOFS);
2495 new->file_pos = ordered->file_offset;
2496 new->len = ordered->len;
2497 new->bytenr = ordered->start;
2498 new->disk_len = ordered->disk_len;
2499 new->compress_type = ordered->compress_type;
2500 new->root = RB_ROOT;
2501 INIT_LIST_HEAD(&new->head);
2503 path = btrfs_alloc_path();
2507 key.objectid = btrfs_ino(inode);
2508 key.type = BTRFS_EXTENT_DATA_KEY;
2509 key.offset = new->file_pos;
2511 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2514 if (ret > 0 && path->slots[0] > 0)
2517 /* find out all the old extents for the file range */
2519 struct btrfs_file_extent_item *extent;
2520 struct extent_buffer *l;
2529 slot = path->slots[0];
2531 if (slot >= btrfs_header_nritems(l)) {
2532 ret = btrfs_next_leaf(root, path);
2540 btrfs_item_key_to_cpu(l, &key, slot);
2542 if (key.objectid != btrfs_ino(inode))
2544 if (key.type != BTRFS_EXTENT_DATA_KEY)
2546 if (key.offset >= new->file_pos + new->len)
2549 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2551 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2552 if (key.offset + num_bytes < new->file_pos)
2555 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2559 extent_offset = btrfs_file_extent_offset(l, extent);
2561 old = kmalloc(sizeof(*old), GFP_NOFS);
2565 offset = max(new->file_pos, key.offset);
2566 end = min(new->file_pos + new->len, key.offset + num_bytes);
2568 old->bytenr = disk_bytenr;
2569 old->extent_offset = extent_offset;
2570 old->offset = offset - key.offset;
2571 old->len = end - offset;
2574 list_add_tail(&old->list, &new->head);
2580 btrfs_free_path(path);
2581 atomic_inc(&root->fs_info->defrag_running);
2586 list_for_each_entry_safe(old, tmp, &new->head, list) {
2587 list_del(&old->list);
2591 btrfs_free_path(path);
2598 * helper function for btrfs_finish_ordered_io, this
2599 * just reads in some of the csum leaves to prime them into ram
2600 * before we start the transaction. It limits the amount of btree
2601 * reads required while inside the transaction.
2603 /* as ordered data IO finishes, this gets called so we can finish
2604 * an ordered extent if the range of bytes in the file it covers are
2607 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2609 struct inode *inode = ordered_extent->inode;
2610 struct btrfs_root *root = BTRFS_I(inode)->root;
2611 struct btrfs_trans_handle *trans = NULL;
2612 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2613 struct extent_state *cached_state = NULL;
2614 struct new_sa_defrag_extent *new = NULL;
2615 int compress_type = 0;
2619 nolock = btrfs_is_free_space_inode(inode);
2621 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2626 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2627 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2628 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2630 trans = btrfs_join_transaction_nolock(root);
2632 trans = btrfs_join_transaction(root);
2633 if (IS_ERR(trans)) {
2634 ret = PTR_ERR(trans);
2638 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2639 ret = btrfs_update_inode_fallback(trans, root, inode);
2640 if (ret) /* -ENOMEM or corruption */
2641 btrfs_abort_transaction(trans, root, ret);
2645 lock_extent_bits(io_tree, ordered_extent->file_offset,
2646 ordered_extent->file_offset + ordered_extent->len - 1,
2649 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2650 ordered_extent->file_offset + ordered_extent->len - 1,
2651 EXTENT_DEFRAG, 1, cached_state);
2653 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2654 if (last_snapshot >= BTRFS_I(inode)->generation)
2655 /* the inode is shared */
2656 new = record_old_file_extents(inode, ordered_extent);
2658 clear_extent_bit(io_tree, ordered_extent->file_offset,
2659 ordered_extent->file_offset + ordered_extent->len - 1,
2660 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2664 trans = btrfs_join_transaction_nolock(root);
2666 trans = btrfs_join_transaction(root);
2667 if (IS_ERR(trans)) {
2668 ret = PTR_ERR(trans);
2672 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2674 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2675 compress_type = ordered_extent->compress_type;
2676 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2677 BUG_ON(compress_type);
2678 ret = btrfs_mark_extent_written(trans, inode,
2679 ordered_extent->file_offset,
2680 ordered_extent->file_offset +
2681 ordered_extent->len);
2683 BUG_ON(root == root->fs_info->tree_root);
2684 ret = insert_reserved_file_extent(trans, inode,
2685 ordered_extent->file_offset,
2686 ordered_extent->start,
2687 ordered_extent->disk_len,
2688 ordered_extent->len,
2689 ordered_extent->len,
2690 compress_type, 0, 0,
2691 BTRFS_FILE_EXTENT_REG);
2693 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2694 ordered_extent->file_offset, ordered_extent->len,
2697 btrfs_abort_transaction(trans, root, ret);
2701 add_pending_csums(trans, inode, ordered_extent->file_offset,
2702 &ordered_extent->list);
2704 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2705 ret = btrfs_update_inode_fallback(trans, root, inode);
2706 if (ret) { /* -ENOMEM or corruption */
2707 btrfs_abort_transaction(trans, root, ret);
2712 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2713 ordered_extent->file_offset +
2714 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2716 if (root != root->fs_info->tree_root)
2717 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2719 btrfs_end_transaction(trans, root);
2722 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
2723 ordered_extent->file_offset +
2724 ordered_extent->len - 1, NULL, GFP_NOFS);
2727 * If the ordered extent had an IOERR or something else went
2728 * wrong we need to return the space for this ordered extent
2729 * back to the allocator.
2731 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2732 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2733 btrfs_free_reserved_extent(root, ordered_extent->start,
2734 ordered_extent->disk_len);
2739 * This needs to be done to make sure anybody waiting knows we are done
2740 * updating everything for this ordered extent.
2742 btrfs_remove_ordered_extent(inode, ordered_extent);
2744 /* for snapshot-aware defrag */
2746 relink_file_extents(new);
2749 btrfs_put_ordered_extent(ordered_extent);
2750 /* once for the tree */
2751 btrfs_put_ordered_extent(ordered_extent);
2756 static void finish_ordered_fn(struct btrfs_work *work)
2758 struct btrfs_ordered_extent *ordered_extent;
2759 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2760 btrfs_finish_ordered_io(ordered_extent);
2763 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2764 struct extent_state *state, int uptodate)
2766 struct inode *inode = page->mapping->host;
2767 struct btrfs_root *root = BTRFS_I(inode)->root;
2768 struct btrfs_ordered_extent *ordered_extent = NULL;
2769 struct btrfs_workers *workers;
2771 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2773 ClearPagePrivate2(page);
2774 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2775 end - start + 1, uptodate))
2778 ordered_extent->work.func = finish_ordered_fn;
2779 ordered_extent->work.flags = 0;
2781 if (btrfs_is_free_space_inode(inode))
2782 workers = &root->fs_info->endio_freespace_worker;
2784 workers = &root->fs_info->endio_write_workers;
2785 btrfs_queue_worker(workers, &ordered_extent->work);
2791 * when reads are done, we need to check csums to verify the data is correct
2792 * if there's a match, we allow the bio to finish. If not, the code in
2793 * extent_io.c will try to find good copies for us.
2795 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
2796 struct extent_state *state, int mirror)
2798 size_t offset = start - page_offset(page);
2799 struct inode *inode = page->mapping->host;
2800 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2802 u64 private = ~(u32)0;
2804 struct btrfs_root *root = BTRFS_I(inode)->root;
2806 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2807 DEFAULT_RATELIMIT_BURST);
2809 if (PageChecked(page)) {
2810 ClearPageChecked(page);
2814 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2817 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2818 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2819 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2824 if (state && state->start == start) {
2825 private = state->private;
2828 ret = get_state_private(io_tree, start, &private);
2830 kaddr = kmap_atomic(page);
2834 csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
2835 btrfs_csum_final(csum, (char *)&csum);
2836 if (csum != private)
2839 kunmap_atomic(kaddr);
2844 if (__ratelimit(&_rs))
2845 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u private %llu",
2846 (unsigned long long)btrfs_ino(page->mapping->host),
2847 (unsigned long long)start, csum,
2848 (unsigned long long)private);
2849 memset(kaddr + offset, 1, end - start + 1);
2850 flush_dcache_page(page);
2851 kunmap_atomic(kaddr);
2857 struct delayed_iput {
2858 struct list_head list;
2859 struct inode *inode;
2862 /* JDM: If this is fs-wide, why can't we add a pointer to
2863 * btrfs_inode instead and avoid the allocation? */
2864 void btrfs_add_delayed_iput(struct inode *inode)
2866 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2867 struct delayed_iput *delayed;
2869 if (atomic_add_unless(&inode->i_count, -1, 1))
2872 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2873 delayed->inode = inode;
2875 spin_lock(&fs_info->delayed_iput_lock);
2876 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2877 spin_unlock(&fs_info->delayed_iput_lock);
2880 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2883 struct btrfs_fs_info *fs_info = root->fs_info;
2884 struct delayed_iput *delayed;
2887 spin_lock(&fs_info->delayed_iput_lock);
2888 empty = list_empty(&fs_info->delayed_iputs);
2889 spin_unlock(&fs_info->delayed_iput_lock);
2893 spin_lock(&fs_info->delayed_iput_lock);
2894 list_splice_init(&fs_info->delayed_iputs, &list);
2895 spin_unlock(&fs_info->delayed_iput_lock);
2897 while (!list_empty(&list)) {
2898 delayed = list_entry(list.next, struct delayed_iput, list);
2899 list_del(&delayed->list);
2900 iput(delayed->inode);
2906 * This is called in transaction commit time. If there are no orphan
2907 * files in the subvolume, it removes orphan item and frees block_rsv
2910 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2911 struct btrfs_root *root)
2913 struct btrfs_block_rsv *block_rsv;
2916 if (atomic_read(&root->orphan_inodes) ||
2917 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2920 spin_lock(&root->orphan_lock);
2921 if (atomic_read(&root->orphan_inodes)) {
2922 spin_unlock(&root->orphan_lock);
2926 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2927 spin_unlock(&root->orphan_lock);
2931 block_rsv = root->orphan_block_rsv;
2932 root->orphan_block_rsv = NULL;
2933 spin_unlock(&root->orphan_lock);
2935 if (root->orphan_item_inserted &&
2936 btrfs_root_refs(&root->root_item) > 0) {
2937 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2938 root->root_key.objectid);
2940 root->orphan_item_inserted = 0;
2944 WARN_ON(block_rsv->size > 0);
2945 btrfs_free_block_rsv(root, block_rsv);
2950 * This creates an orphan entry for the given inode in case something goes
2951 * wrong in the middle of an unlink/truncate.
2953 * NOTE: caller of this function should reserve 5 units of metadata for
2956 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2958 struct btrfs_root *root = BTRFS_I(inode)->root;
2959 struct btrfs_block_rsv *block_rsv = NULL;
2964 if (!root->orphan_block_rsv) {
2965 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2970 spin_lock(&root->orphan_lock);
2971 if (!root->orphan_block_rsv) {
2972 root->orphan_block_rsv = block_rsv;
2973 } else if (block_rsv) {
2974 btrfs_free_block_rsv(root, block_rsv);
2978 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2979 &BTRFS_I(inode)->runtime_flags)) {
2982 * For proper ENOSPC handling, we should do orphan
2983 * cleanup when mounting. But this introduces backward
2984 * compatibility issue.
2986 if (!xchg(&root->orphan_item_inserted, 1))
2992 atomic_inc(&root->orphan_inodes);
2995 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2996 &BTRFS_I(inode)->runtime_flags))
2998 spin_unlock(&root->orphan_lock);
3000 /* grab metadata reservation from transaction handle */
3002 ret = btrfs_orphan_reserve_metadata(trans, inode);
3003 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3006 /* insert an orphan item to track this unlinked/truncated file */
3008 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3009 if (ret && ret != -EEXIST) {
3010 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3011 &BTRFS_I(inode)->runtime_flags);
3012 btrfs_abort_transaction(trans, root, ret);
3018 /* insert an orphan item to track subvolume contains orphan files */
3020 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3021 root->root_key.objectid);
3022 if (ret && ret != -EEXIST) {
3023 btrfs_abort_transaction(trans, root, ret);
3031 * We have done the truncate/delete so we can go ahead and remove the orphan
3032 * item for this particular inode.
3034 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3035 struct inode *inode)
3037 struct btrfs_root *root = BTRFS_I(inode)->root;
3038 int delete_item = 0;
3039 int release_rsv = 0;
3042 spin_lock(&root->orphan_lock);
3043 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3044 &BTRFS_I(inode)->runtime_flags))
3047 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3048 &BTRFS_I(inode)->runtime_flags))
3050 spin_unlock(&root->orphan_lock);
3052 if (trans && delete_item) {
3053 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3054 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3058 btrfs_orphan_release_metadata(inode);
3059 atomic_dec(&root->orphan_inodes);
3066 * this cleans up any orphans that may be left on the list from the last use
3069 int btrfs_orphan_cleanup(struct btrfs_root *root)
3071 struct btrfs_path *path;
3072 struct extent_buffer *leaf;
3073 struct btrfs_key key, found_key;
3074 struct btrfs_trans_handle *trans;
3075 struct inode *inode;
3076 u64 last_objectid = 0;
3077 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3079 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3082 path = btrfs_alloc_path();
3089 key.objectid = BTRFS_ORPHAN_OBJECTID;
3090 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3091 key.offset = (u64)-1;
3094 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3099 * if ret == 0 means we found what we were searching for, which
3100 * is weird, but possible, so only screw with path if we didn't
3101 * find the key and see if we have stuff that matches
3105 if (path->slots[0] == 0)
3110 /* pull out the item */
3111 leaf = path->nodes[0];
3112 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3114 /* make sure the item matches what we want */
3115 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3117 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3120 /* release the path since we're done with it */
3121 btrfs_release_path(path);
3124 * this is where we are basically btrfs_lookup, without the
3125 * crossing root thing. we store the inode number in the
3126 * offset of the orphan item.
3129 if (found_key.offset == last_objectid) {
3130 btrfs_err(root->fs_info,
3131 "Error removing orphan entry, stopping orphan cleanup");
3136 last_objectid = found_key.offset;
3138 found_key.objectid = found_key.offset;
3139 found_key.type = BTRFS_INODE_ITEM_KEY;
3140 found_key.offset = 0;
3141 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3142 ret = PTR_RET(inode);
3143 if (ret && ret != -ESTALE)
3146 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3147 struct btrfs_root *dead_root;
3148 struct btrfs_fs_info *fs_info = root->fs_info;
3149 int is_dead_root = 0;
3152 * this is an orphan in the tree root. Currently these
3153 * could come from 2 sources:
3154 * a) a snapshot deletion in progress
3155 * b) a free space cache inode
3156 * We need to distinguish those two, as the snapshot
3157 * orphan must not get deleted.
3158 * find_dead_roots already ran before us, so if this
3159 * is a snapshot deletion, we should find the root
3160 * in the dead_roots list
3162 spin_lock(&fs_info->trans_lock);
3163 list_for_each_entry(dead_root, &fs_info->dead_roots,
3165 if (dead_root->root_key.objectid ==
3166 found_key.objectid) {
3171 spin_unlock(&fs_info->trans_lock);
3173 /* prevent this orphan from being found again */
3174 key.offset = found_key.objectid - 1;
3179 * Inode is already gone but the orphan item is still there,
3180 * kill the orphan item.
3182 if (ret == -ESTALE) {
3183 trans = btrfs_start_transaction(root, 1);
3184 if (IS_ERR(trans)) {
3185 ret = PTR_ERR(trans);
3188 btrfs_debug(root->fs_info, "auto deleting %Lu",
3189 found_key.objectid);
3190 ret = btrfs_del_orphan_item(trans, root,
3191 found_key.objectid);
3192 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3193 btrfs_end_transaction(trans, root);
3198 * add this inode to the orphan list so btrfs_orphan_del does
3199 * the proper thing when we hit it
3201 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3202 &BTRFS_I(inode)->runtime_flags);
3203 atomic_inc(&root->orphan_inodes);
3205 /* if we have links, this was a truncate, lets do that */
3206 if (inode->i_nlink) {
3207 if (!S_ISREG(inode->i_mode)) {
3214 /* 1 for the orphan item deletion. */
3215 trans = btrfs_start_transaction(root, 1);
3216 if (IS_ERR(trans)) {
3217 ret = PTR_ERR(trans);
3220 ret = btrfs_orphan_add(trans, inode);
3221 btrfs_end_transaction(trans, root);
3225 ret = btrfs_truncate(inode);
3227 btrfs_orphan_del(NULL, inode);
3232 /* this will do delete_inode and everything for us */
3237 /* release the path since we're done with it */
3238 btrfs_release_path(path);
3240 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3242 if (root->orphan_block_rsv)
3243 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3246 if (root->orphan_block_rsv || root->orphan_item_inserted) {
3247 trans = btrfs_join_transaction(root);
3249 btrfs_end_transaction(trans, root);
3253 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3255 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3259 btrfs_crit(root->fs_info,
3260 "could not do orphan cleanup %d", ret);
3261 btrfs_free_path(path);
3266 * very simple check to peek ahead in the leaf looking for xattrs. If we
3267 * don't find any xattrs, we know there can't be any acls.
3269 * slot is the slot the inode is in, objectid is the objectid of the inode
3271 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3272 int slot, u64 objectid)
3274 u32 nritems = btrfs_header_nritems(leaf);
3275 struct btrfs_key found_key;
3279 while (slot < nritems) {
3280 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3282 /* we found a different objectid, there must not be acls */
3283 if (found_key.objectid != objectid)
3286 /* we found an xattr, assume we've got an acl */
3287 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
3291 * we found a key greater than an xattr key, there can't
3292 * be any acls later on
3294 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3301 * it goes inode, inode backrefs, xattrs, extents,
3302 * so if there are a ton of hard links to an inode there can
3303 * be a lot of backrefs. Don't waste time searching too hard,
3304 * this is just an optimization
3309 /* we hit the end of the leaf before we found an xattr or
3310 * something larger than an xattr. We have to assume the inode
3317 * read an inode from the btree into the in-memory inode
3319 static void btrfs_read_locked_inode(struct inode *inode)
3321 struct btrfs_path *path;
3322 struct extent_buffer *leaf;
3323 struct btrfs_inode_item *inode_item;
3324 struct btrfs_timespec *tspec;
3325 struct btrfs_root *root = BTRFS_I(inode)->root;
3326 struct btrfs_key location;
3330 bool filled = false;
3332 ret = btrfs_fill_inode(inode, &rdev);
3336 path = btrfs_alloc_path();
3340 path->leave_spinning = 1;
3341 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3343 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3347 leaf = path->nodes[0];
3352 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3353 struct btrfs_inode_item);
3354 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3355 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3356 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3357 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3358 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3360 tspec = btrfs_inode_atime(inode_item);
3361 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3362 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3364 tspec = btrfs_inode_mtime(inode_item);
3365 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3366 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3368 tspec = btrfs_inode_ctime(inode_item);
3369 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3370 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3372 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3373 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3374 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3377 * If we were modified in the current generation and evicted from memory
3378 * and then re-read we need to do a full sync since we don't have any
3379 * idea about which extents were modified before we were evicted from
3382 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3383 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3384 &BTRFS_I(inode)->runtime_flags);
3386 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3387 inode->i_generation = BTRFS_I(inode)->generation;
3389 rdev = btrfs_inode_rdev(leaf, inode_item);
3391 BTRFS_I(inode)->index_cnt = (u64)-1;
3392 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3395 * try to precache a NULL acl entry for files that don't have
3396 * any xattrs or acls
3398 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3401 cache_no_acl(inode);
3403 btrfs_free_path(path);
3405 switch (inode->i_mode & S_IFMT) {
3407 inode->i_mapping->a_ops = &btrfs_aops;
3408 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3409 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3410 inode->i_fop = &btrfs_file_operations;
3411 inode->i_op = &btrfs_file_inode_operations;
3414 inode->i_fop = &btrfs_dir_file_operations;
3415 if (root == root->fs_info->tree_root)
3416 inode->i_op = &btrfs_dir_ro_inode_operations;
3418 inode->i_op = &btrfs_dir_inode_operations;
3421 inode->i_op = &btrfs_symlink_inode_operations;
3422 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3423 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3426 inode->i_op = &btrfs_special_inode_operations;
3427 init_special_inode(inode, inode->i_mode, rdev);
3431 btrfs_update_iflags(inode);
3435 btrfs_free_path(path);
3436 make_bad_inode(inode);
3440 * given a leaf and an inode, copy the inode fields into the leaf
3442 static void fill_inode_item(struct btrfs_trans_handle *trans,
3443 struct extent_buffer *leaf,
3444 struct btrfs_inode_item *item,
3445 struct inode *inode)
3447 struct btrfs_map_token token;
3449 btrfs_init_map_token(&token);
3451 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3452 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3453 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3455 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3456 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3458 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3459 inode->i_atime.tv_sec, &token);
3460 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3461 inode->i_atime.tv_nsec, &token);
3463 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3464 inode->i_mtime.tv_sec, &token);
3465 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3466 inode->i_mtime.tv_nsec, &token);
3468 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3469 inode->i_ctime.tv_sec, &token);
3470 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3471 inode->i_ctime.tv_nsec, &token);
3473 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3475 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3477 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3478 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3479 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3480 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3481 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3485 * copy everything in the in-memory inode into the btree.
3487 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3488 struct btrfs_root *root, struct inode *inode)
3490 struct btrfs_inode_item *inode_item;
3491 struct btrfs_path *path;
3492 struct extent_buffer *leaf;
3495 path = btrfs_alloc_path();
3499 path->leave_spinning = 1;
3500 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3508 btrfs_unlock_up_safe(path, 1);
3509 leaf = path->nodes[0];
3510 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3511 struct btrfs_inode_item);
3513 fill_inode_item(trans, leaf, inode_item, inode);
3514 btrfs_mark_buffer_dirty(leaf);
3515 btrfs_set_inode_last_trans(trans, inode);
3518 btrfs_free_path(path);
3523 * copy everything in the in-memory inode into the btree.
3525 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3526 struct btrfs_root *root, struct inode *inode)
3531 * If the inode is a free space inode, we can deadlock during commit
3532 * if we put it into the delayed code.
3534 * The data relocation inode should also be directly updated
3537 if (!btrfs_is_free_space_inode(inode)
3538 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3539 btrfs_update_root_times(trans, root);
3541 ret = btrfs_delayed_update_inode(trans, root, inode);
3543 btrfs_set_inode_last_trans(trans, inode);
3547 return btrfs_update_inode_item(trans, root, inode);
3550 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3551 struct btrfs_root *root,
3552 struct inode *inode)
3556 ret = btrfs_update_inode(trans, root, inode);
3558 return btrfs_update_inode_item(trans, root, inode);
3563 * unlink helper that gets used here in inode.c and in the tree logging
3564 * recovery code. It remove a link in a directory with a given name, and
3565 * also drops the back refs in the inode to the directory
3567 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3568 struct btrfs_root *root,
3569 struct inode *dir, struct inode *inode,
3570 const char *name, int name_len)
3572 struct btrfs_path *path;
3574 struct extent_buffer *leaf;
3575 struct btrfs_dir_item *di;
3576 struct btrfs_key key;
3578 u64 ino = btrfs_ino(inode);
3579 u64 dir_ino = btrfs_ino(dir);
3581 path = btrfs_alloc_path();
3587 path->leave_spinning = 1;
3588 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3589 name, name_len, -1);
3598 leaf = path->nodes[0];
3599 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3600 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3603 btrfs_release_path(path);
3605 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3608 btrfs_info(root->fs_info,
3609 "failed to delete reference to %.*s, inode %llu parent %llu",
3611 (unsigned long long)ino, (unsigned long long)dir_ino);
3612 btrfs_abort_transaction(trans, root, ret);
3616 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3618 btrfs_abort_transaction(trans, root, ret);
3622 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3624 if (ret != 0 && ret != -ENOENT) {
3625 btrfs_abort_transaction(trans, root, ret);
3629 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3634 btrfs_abort_transaction(trans, root, ret);
3636 btrfs_free_path(path);
3640 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3641 inode_inc_iversion(inode);
3642 inode_inc_iversion(dir);
3643 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3644 ret = btrfs_update_inode(trans, root, dir);
3649 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3650 struct btrfs_root *root,
3651 struct inode *dir, struct inode *inode,
3652 const char *name, int name_len)
3655 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3657 btrfs_drop_nlink(inode);
3658 ret = btrfs_update_inode(trans, root, inode);
3664 /* helper to check if there is any shared block in the path */
3665 static int check_path_shared(struct btrfs_root *root,
3666 struct btrfs_path *path)
3668 struct extent_buffer *eb;
3672 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
3675 if (!path->nodes[level])
3677 eb = path->nodes[level];
3678 if (!btrfs_block_can_be_shared(root, eb))
3680 ret = btrfs_lookup_extent_info(NULL, root, eb->start, level, 1,
3689 * helper to start transaction for unlink and rmdir.
3691 * unlink and rmdir are special in btrfs, they do not always free space.
3692 * so in enospc case, we should make sure they will free space before
3693 * allowing them to use the global metadata reservation.
3695 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
3696 struct dentry *dentry)
3698 struct btrfs_trans_handle *trans;
3699 struct btrfs_root *root = BTRFS_I(dir)->root;
3700 struct btrfs_path *path;
3701 struct btrfs_dir_item *di;
3702 struct inode *inode = dentry->d_inode;
3707 u64 ino = btrfs_ino(inode);
3708 u64 dir_ino = btrfs_ino(dir);
3711 * 1 for the possible orphan item
3712 * 1 for the dir item
3713 * 1 for the dir index
3714 * 1 for the inode ref
3717 trans = btrfs_start_transaction(root, 5);
3718 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3721 if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
3722 return ERR_PTR(-ENOSPC);
3724 /* check if there is someone else holds reference */
3725 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
3726 return ERR_PTR(-ENOSPC);
3728 if (atomic_read(&inode->i_count) > 2)
3729 return ERR_PTR(-ENOSPC);
3731 if (xchg(&root->fs_info->enospc_unlink, 1))
3732 return ERR_PTR(-ENOSPC);
3734 path = btrfs_alloc_path();
3736 root->fs_info->enospc_unlink = 0;
3737 return ERR_PTR(-ENOMEM);
3740 /* 1 for the orphan item */
3741 trans = btrfs_start_transaction(root, 1);
3742 if (IS_ERR(trans)) {
3743 btrfs_free_path(path);
3744 root->fs_info->enospc_unlink = 0;
3748 path->skip_locking = 1;
3749 path->search_commit_root = 1;
3751 ret = btrfs_lookup_inode(trans, root, path,
3752 &BTRFS_I(dir)->location, 0);
3758 if (check_path_shared(root, path))
3763 btrfs_release_path(path);
3765 ret = btrfs_lookup_inode(trans, root, path,
3766 &BTRFS_I(inode)->location, 0);
3772 if (check_path_shared(root, path))
3777 btrfs_release_path(path);
3779 if (ret == 0 && S_ISREG(inode->i_mode)) {
3780 ret = btrfs_lookup_file_extent(trans, root, path,
3786 BUG_ON(ret == 0); /* Corruption */
3787 if (check_path_shared(root, path))
3789 btrfs_release_path(path);
3797 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3798 dentry->d_name.name, dentry->d_name.len, 0);
3804 if (check_path_shared(root, path))
3810 btrfs_release_path(path);
3812 ret = btrfs_get_inode_ref_index(trans, root, path, dentry->d_name.name,
3813 dentry->d_name.len, ino, dir_ino, 0,
3820 if (check_path_shared(root, path))
3823 btrfs_release_path(path);
3826 * This is a commit root search, if we can lookup inode item and other
3827 * relative items in the commit root, it means the transaction of
3828 * dir/file creation has been committed, and the dir index item that we
3829 * delay to insert has also been inserted into the commit root. So
3830 * we needn't worry about the delayed insertion of the dir index item
3833 di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
3834 dentry->d_name.name, dentry->d_name.len, 0);
3839 BUG_ON(ret == -ENOENT);
3840 if (check_path_shared(root, path))
3845 btrfs_free_path(path);
3846 /* Migrate the orphan reservation over */
3848 err = btrfs_block_rsv_migrate(trans->block_rsv,
3849 &root->fs_info->global_block_rsv,
3850 trans->bytes_reserved);
3853 btrfs_end_transaction(trans, root);
3854 root->fs_info->enospc_unlink = 0;
3855 return ERR_PTR(err);
3858 trans->block_rsv = &root->fs_info->global_block_rsv;
3862 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
3863 struct btrfs_root *root)
3865 if (trans->block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL) {
3866 btrfs_block_rsv_release(root, trans->block_rsv,
3867 trans->bytes_reserved);
3868 trans->block_rsv = &root->fs_info->trans_block_rsv;
3869 BUG_ON(!root->fs_info->enospc_unlink);
3870 root->fs_info->enospc_unlink = 0;
3872 btrfs_end_transaction(trans, root);
3875 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3877 struct btrfs_root *root = BTRFS_I(dir)->root;
3878 struct btrfs_trans_handle *trans;
3879 struct inode *inode = dentry->d_inode;
3882 trans = __unlink_start_trans(dir, dentry);
3884 return PTR_ERR(trans);
3886 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3888 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3889 dentry->d_name.name, dentry->d_name.len);
3893 if (inode->i_nlink == 0) {
3894 ret = btrfs_orphan_add(trans, inode);
3900 __unlink_end_trans(trans, root);
3901 btrfs_btree_balance_dirty(root);
3905 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3906 struct btrfs_root *root,
3907 struct inode *dir, u64 objectid,
3908 const char *name, int name_len)
3910 struct btrfs_path *path;
3911 struct extent_buffer *leaf;
3912 struct btrfs_dir_item *di;
3913 struct btrfs_key key;
3916 u64 dir_ino = btrfs_ino(dir);
3918 path = btrfs_alloc_path();
3922 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3923 name, name_len, -1);
3924 if (IS_ERR_OR_NULL(di)) {
3932 leaf = path->nodes[0];
3933 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3934 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3935 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3937 btrfs_abort_transaction(trans, root, ret);
3940 btrfs_release_path(path);
3942 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3943 objectid, root->root_key.objectid,
3944 dir_ino, &index, name, name_len);
3946 if (ret != -ENOENT) {
3947 btrfs_abort_transaction(trans, root, ret);
3950 di = btrfs_search_dir_index_item(root, path, dir_ino,
3952 if (IS_ERR_OR_NULL(di)) {
3957 btrfs_abort_transaction(trans, root, ret);
3961 leaf = path->nodes[0];
3962 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3963 btrfs_release_path(path);
3966 btrfs_release_path(path);
3968 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3970 btrfs_abort_transaction(trans, root, ret);
3974 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3975 inode_inc_iversion(dir);
3976 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3977 ret = btrfs_update_inode_fallback(trans, root, dir);
3979 btrfs_abort_transaction(trans, root, ret);
3981 btrfs_free_path(path);
3985 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3987 struct inode *inode = dentry->d_inode;
3989 struct btrfs_root *root = BTRFS_I(dir)->root;
3990 struct btrfs_trans_handle *trans;
3992 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3994 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3997 trans = __unlink_start_trans(dir, dentry);
3999 return PTR_ERR(trans);
4001 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4002 err = btrfs_unlink_subvol(trans, root, dir,
4003 BTRFS_I(inode)->location.objectid,
4004 dentry->d_name.name,
4005 dentry->d_name.len);
4009 err = btrfs_orphan_add(trans, inode);
4013 /* now the directory is empty */
4014 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
4015 dentry->d_name.name, dentry->d_name.len);
4017 btrfs_i_size_write(inode, 0);
4019 __unlink_end_trans(trans, root);
4020 btrfs_btree_balance_dirty(root);
4026 * this can truncate away extent items, csum items and directory items.
4027 * It starts at a high offset and removes keys until it can't find
4028 * any higher than new_size
4030 * csum items that cross the new i_size are truncated to the new size
4033 * min_type is the minimum key type to truncate down to. If set to 0, this
4034 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4036 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4037 struct btrfs_root *root,
4038 struct inode *inode,
4039 u64 new_size, u32 min_type)
4041 struct btrfs_path *path;
4042 struct extent_buffer *leaf;
4043 struct btrfs_file_extent_item *fi;
4044 struct btrfs_key key;
4045 struct btrfs_key found_key;
4046 u64 extent_start = 0;
4047 u64 extent_num_bytes = 0;
4048 u64 extent_offset = 0;
4050 u32 found_type = (u8)-1;
4053 int pending_del_nr = 0;
4054 int pending_del_slot = 0;
4055 int extent_type = -1;
4058 u64 ino = btrfs_ino(inode);
4060 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4062 path = btrfs_alloc_path();
4068 * We want to drop from the next block forward in case this new size is
4069 * not block aligned since we will be keeping the last block of the
4070 * extent just the way it is.
4072 if (root->ref_cows || root == root->fs_info->tree_root)
4073 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4074 root->sectorsize), (u64)-1, 0);
4077 * This function is also used to drop the items in the log tree before
4078 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4079 * it is used to drop the loged items. So we shouldn't kill the delayed
4082 if (min_type == 0 && root == BTRFS_I(inode)->root)
4083 btrfs_kill_delayed_inode_items(inode);
4086 key.offset = (u64)-1;
4090 path->leave_spinning = 1;
4091 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4098 /* there are no items in the tree for us to truncate, we're
4101 if (path->slots[0] == 0)
4108 leaf = path->nodes[0];
4109 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4110 found_type = btrfs_key_type(&found_key);
4112 if (found_key.objectid != ino)
4115 if (found_type < min_type)
4118 item_end = found_key.offset;
4119 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4120 fi = btrfs_item_ptr(leaf, path->slots[0],
4121 struct btrfs_file_extent_item);
4122 extent_type = btrfs_file_extent_type(leaf, fi);
4123 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4125 btrfs_file_extent_num_bytes(leaf, fi);
4126 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4127 item_end += btrfs_file_extent_inline_len(leaf,
4132 if (found_type > min_type) {
4135 if (item_end < new_size)
4137 if (found_key.offset >= new_size)
4143 /* FIXME, shrink the extent if the ref count is only 1 */
4144 if (found_type != BTRFS_EXTENT_DATA_KEY)
4147 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4149 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4151 u64 orig_num_bytes =
4152 btrfs_file_extent_num_bytes(leaf, fi);
4153 extent_num_bytes = ALIGN(new_size -
4156 btrfs_set_file_extent_num_bytes(leaf, fi,
4158 num_dec = (orig_num_bytes -
4160 if (root->ref_cows && extent_start != 0)
4161 inode_sub_bytes(inode, num_dec);
4162 btrfs_mark_buffer_dirty(leaf);
4165 btrfs_file_extent_disk_num_bytes(leaf,
4167 extent_offset = found_key.offset -
4168 btrfs_file_extent_offset(leaf, fi);
4170 /* FIXME blocksize != 4096 */
4171 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4172 if (extent_start != 0) {
4175 inode_sub_bytes(inode, num_dec);
4178 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4180 * we can't truncate inline items that have had
4184 btrfs_file_extent_compression(leaf, fi) == 0 &&
4185 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4186 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4187 u32 size = new_size - found_key.offset;
4189 if (root->ref_cows) {
4190 inode_sub_bytes(inode, item_end + 1 -
4194 btrfs_file_extent_calc_inline_size(size);
4195 btrfs_truncate_item(root, path, size, 1);
4196 } else if (root->ref_cows) {
4197 inode_sub_bytes(inode, item_end + 1 -
4203 if (!pending_del_nr) {
4204 /* no pending yet, add ourselves */
4205 pending_del_slot = path->slots[0];
4207 } else if (pending_del_nr &&
4208 path->slots[0] + 1 == pending_del_slot) {
4209 /* hop on the pending chunk */
4211 pending_del_slot = path->slots[0];
4218 if (found_extent && (root->ref_cows ||
4219 root == root->fs_info->tree_root)) {
4220 btrfs_set_path_blocking(path);
4221 ret = btrfs_free_extent(trans, root, extent_start,
4222 extent_num_bytes, 0,
4223 btrfs_header_owner(leaf),
4224 ino, extent_offset, 0);
4228 if (found_type == BTRFS_INODE_ITEM_KEY)
4231 if (path->slots[0] == 0 ||
4232 path->slots[0] != pending_del_slot) {
4233 if (pending_del_nr) {
4234 ret = btrfs_del_items(trans, root, path,
4238 btrfs_abort_transaction(trans,
4244 btrfs_release_path(path);
4251 if (pending_del_nr) {
4252 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4255 btrfs_abort_transaction(trans, root, ret);
4258 btrfs_free_path(path);
4263 * btrfs_truncate_page - read, zero a chunk and write a page
4264 * @inode - inode that we're zeroing
4265 * @from - the offset to start zeroing
4266 * @len - the length to zero, 0 to zero the entire range respective to the
4268 * @front - zero up to the offset instead of from the offset on
4270 * This will find the page for the "from" offset and cow the page and zero the
4271 * part we want to zero. This is used with truncate and hole punching.
4273 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4276 struct address_space *mapping = inode->i_mapping;
4277 struct btrfs_root *root = BTRFS_I(inode)->root;
4278 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4279 struct btrfs_ordered_extent *ordered;
4280 struct extent_state *cached_state = NULL;
4282 u32 blocksize = root->sectorsize;
4283 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4284 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4286 gfp_t mask = btrfs_alloc_write_mask(mapping);
4291 if ((offset & (blocksize - 1)) == 0 &&
4292 (!len || ((len & (blocksize - 1)) == 0)))
4294 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4299 page = find_or_create_page(mapping, index, mask);
4301 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4306 page_start = page_offset(page);
4307 page_end = page_start + PAGE_CACHE_SIZE - 1;
4309 if (!PageUptodate(page)) {
4310 ret = btrfs_readpage(NULL, page);
4312 if (page->mapping != mapping) {
4314 page_cache_release(page);
4317 if (!PageUptodate(page)) {
4322 wait_on_page_writeback(page);
4324 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4325 set_page_extent_mapped(page);
4327 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4329 unlock_extent_cached(io_tree, page_start, page_end,
4330 &cached_state, GFP_NOFS);
4332 page_cache_release(page);
4333 btrfs_start_ordered_extent(inode, ordered, 1);
4334 btrfs_put_ordered_extent(ordered);
4338 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4339 EXTENT_DIRTY | EXTENT_DELALLOC |
4340 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4341 0, 0, &cached_state, GFP_NOFS);
4343 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4346 unlock_extent_cached(io_tree, page_start, page_end,
4347 &cached_state, GFP_NOFS);
4351 if (offset != PAGE_CACHE_SIZE) {
4353 len = PAGE_CACHE_SIZE - offset;
4356 memset(kaddr, 0, offset);
4358 memset(kaddr + offset, 0, len);
4359 flush_dcache_page(page);
4362 ClearPageChecked(page);
4363 set_page_dirty(page);
4364 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4369 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4371 page_cache_release(page);
4377 * This function puts in dummy file extents for the area we're creating a hole
4378 * for. So if we are truncating this file to a larger size we need to insert
4379 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4380 * the range between oldsize and size
4382 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4384 struct btrfs_trans_handle *trans;
4385 struct btrfs_root *root = BTRFS_I(inode)->root;
4386 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4387 struct extent_map *em = NULL;
4388 struct extent_state *cached_state = NULL;
4389 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4390 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4391 u64 block_end = ALIGN(size, root->sectorsize);
4397 if (size <= hole_start)
4401 struct btrfs_ordered_extent *ordered;
4402 btrfs_wait_ordered_range(inode, hole_start,
4403 block_end - hole_start);
4404 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4406 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
4409 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4410 &cached_state, GFP_NOFS);
4411 btrfs_put_ordered_extent(ordered);
4414 cur_offset = hole_start;
4416 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4417 block_end - cur_offset, 0);
4423 last_byte = min(extent_map_end(em), block_end);
4424 last_byte = ALIGN(last_byte , root->sectorsize);
4425 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4426 struct extent_map *hole_em;
4427 hole_size = last_byte - cur_offset;
4429 trans = btrfs_start_transaction(root, 3);
4430 if (IS_ERR(trans)) {
4431 err = PTR_ERR(trans);
4435 err = btrfs_drop_extents(trans, root, inode,
4437 cur_offset + hole_size, 1);
4439 btrfs_abort_transaction(trans, root, err);
4440 btrfs_end_transaction(trans, root);
4444 err = btrfs_insert_file_extent(trans, root,
4445 btrfs_ino(inode), cur_offset, 0,
4446 0, hole_size, 0, hole_size,
4449 btrfs_abort_transaction(trans, root, err);
4450 btrfs_end_transaction(trans, root);
4454 btrfs_drop_extent_cache(inode, cur_offset,
4455 cur_offset + hole_size - 1, 0);
4456 hole_em = alloc_extent_map();
4458 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4459 &BTRFS_I(inode)->runtime_flags);
4462 hole_em->start = cur_offset;
4463 hole_em->len = hole_size;
4464 hole_em->orig_start = cur_offset;
4466 hole_em->block_start = EXTENT_MAP_HOLE;
4467 hole_em->block_len = 0;
4468 hole_em->orig_block_len = 0;
4469 hole_em->ram_bytes = hole_size;
4470 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4471 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4472 hole_em->generation = trans->transid;
4475 write_lock(&em_tree->lock);
4476 err = add_extent_mapping(em_tree, hole_em, 1);
4477 write_unlock(&em_tree->lock);
4480 btrfs_drop_extent_cache(inode, cur_offset,
4484 free_extent_map(hole_em);
4486 btrfs_update_inode(trans, root, inode);
4487 btrfs_end_transaction(trans, root);
4489 free_extent_map(em);
4491 cur_offset = last_byte;
4492 if (cur_offset >= block_end)
4496 free_extent_map(em);
4497 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4502 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4504 struct btrfs_root *root = BTRFS_I(inode)->root;
4505 struct btrfs_trans_handle *trans;
4506 loff_t oldsize = i_size_read(inode);
4507 loff_t newsize = attr->ia_size;
4508 int mask = attr->ia_valid;
4511 if (newsize == oldsize)
4515 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4516 * special case where we need to update the times despite not having
4517 * these flags set. For all other operations the VFS set these flags
4518 * explicitly if it wants a timestamp update.
4520 if (newsize != oldsize && (!(mask & (ATTR_CTIME | ATTR_MTIME))))
4521 inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb);
4523 if (newsize > oldsize) {
4524 truncate_pagecache(inode, oldsize, newsize);
4525 ret = btrfs_cont_expand(inode, oldsize, newsize);
4529 trans = btrfs_start_transaction(root, 1);
4531 return PTR_ERR(trans);
4533 i_size_write(inode, newsize);
4534 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4535 ret = btrfs_update_inode(trans, root, inode);
4536 btrfs_end_transaction(trans, root);
4540 * We're truncating a file that used to have good data down to
4541 * zero. Make sure it gets into the ordered flush list so that
4542 * any new writes get down to disk quickly.
4545 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4546 &BTRFS_I(inode)->runtime_flags);
4549 * 1 for the orphan item we're going to add
4550 * 1 for the orphan item deletion.
4552 trans = btrfs_start_transaction(root, 2);
4554 return PTR_ERR(trans);
4557 * We need to do this in case we fail at _any_ point during the
4558 * actual truncate. Once we do the truncate_setsize we could
4559 * invalidate pages which forces any outstanding ordered io to
4560 * be instantly completed which will give us extents that need
4561 * to be truncated. If we fail to get an orphan inode down we
4562 * could have left over extents that were never meant to live,
4563 * so we need to garuntee from this point on that everything
4564 * will be consistent.
4566 ret = btrfs_orphan_add(trans, inode);
4567 btrfs_end_transaction(trans, root);
4571 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4572 truncate_setsize(inode, newsize);
4574 /* Disable nonlocked read DIO to avoid the end less truncate */
4575 btrfs_inode_block_unlocked_dio(inode);
4576 inode_dio_wait(inode);
4577 btrfs_inode_resume_unlocked_dio(inode);
4579 ret = btrfs_truncate(inode);
4580 if (ret && inode->i_nlink)
4581 btrfs_orphan_del(NULL, inode);
4587 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4589 struct inode *inode = dentry->d_inode;
4590 struct btrfs_root *root = BTRFS_I(inode)->root;
4593 if (btrfs_root_readonly(root))
4596 err = inode_change_ok(inode, attr);
4600 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4601 err = btrfs_setsize(inode, attr);
4606 if (attr->ia_valid) {
4607 setattr_copy(inode, attr);
4608 inode_inc_iversion(inode);
4609 err = btrfs_dirty_inode(inode);
4611 if (!err && attr->ia_valid & ATTR_MODE)
4612 err = btrfs_acl_chmod(inode);
4618 void btrfs_evict_inode(struct inode *inode)
4620 struct btrfs_trans_handle *trans;
4621 struct btrfs_root *root = BTRFS_I(inode)->root;
4622 struct btrfs_block_rsv *rsv, *global_rsv;
4623 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4626 trace_btrfs_inode_evict(inode);
4628 truncate_inode_pages(&inode->i_data, 0);
4629 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
4630 btrfs_is_free_space_inode(inode)))
4633 if (is_bad_inode(inode)) {
4634 btrfs_orphan_del(NULL, inode);
4637 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4638 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4640 if (root->fs_info->log_root_recovering) {
4641 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4642 &BTRFS_I(inode)->runtime_flags));
4646 if (inode->i_nlink > 0) {
4647 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
4651 ret = btrfs_commit_inode_delayed_inode(inode);
4653 btrfs_orphan_del(NULL, inode);
4657 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4659 btrfs_orphan_del(NULL, inode);
4662 rsv->size = min_size;
4664 global_rsv = &root->fs_info->global_block_rsv;
4666 btrfs_i_size_write(inode, 0);
4669 * This is a bit simpler than btrfs_truncate since we've already
4670 * reserved our space for our orphan item in the unlink, so we just
4671 * need to reserve some slack space in case we add bytes and update
4672 * inode item when doing the truncate.
4675 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4676 BTRFS_RESERVE_FLUSH_LIMIT);
4679 * Try and steal from the global reserve since we will
4680 * likely not use this space anyway, we want to try as
4681 * hard as possible to get this to work.
4684 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4687 btrfs_warn(root->fs_info,
4688 "Could not get space for a delete, will truncate on mount %d",
4690 btrfs_orphan_del(NULL, inode);
4691 btrfs_free_block_rsv(root, rsv);
4695 trans = btrfs_join_transaction(root);
4696 if (IS_ERR(trans)) {
4697 btrfs_orphan_del(NULL, inode);
4698 btrfs_free_block_rsv(root, rsv);
4702 trans->block_rsv = rsv;
4704 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4708 trans->block_rsv = &root->fs_info->trans_block_rsv;
4709 btrfs_end_transaction(trans, root);
4711 btrfs_btree_balance_dirty(root);
4714 btrfs_free_block_rsv(root, rsv);
4717 trans->block_rsv = root->orphan_block_rsv;
4718 ret = btrfs_orphan_del(trans, inode);
4722 trans->block_rsv = &root->fs_info->trans_block_rsv;
4723 if (!(root == root->fs_info->tree_root ||
4724 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4725 btrfs_return_ino(root, btrfs_ino(inode));
4727 btrfs_end_transaction(trans, root);
4728 btrfs_btree_balance_dirty(root);
4730 btrfs_remove_delayed_node(inode);
4736 * this returns the key found in the dir entry in the location pointer.
4737 * If no dir entries were found, location->objectid is 0.
4739 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4740 struct btrfs_key *location)
4742 const char *name = dentry->d_name.name;
4743 int namelen = dentry->d_name.len;
4744 struct btrfs_dir_item *di;
4745 struct btrfs_path *path;
4746 struct btrfs_root *root = BTRFS_I(dir)->root;
4749 path = btrfs_alloc_path();
4753 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4758 if (IS_ERR_OR_NULL(di))
4761 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4763 btrfs_free_path(path);
4766 location->objectid = 0;
4771 * when we hit a tree root in a directory, the btrfs part of the inode
4772 * needs to be changed to reflect the root directory of the tree root. This
4773 * is kind of like crossing a mount point.
4775 static int fixup_tree_root_location(struct btrfs_root *root,
4777 struct dentry *dentry,
4778 struct btrfs_key *location,
4779 struct btrfs_root **sub_root)
4781 struct btrfs_path *path;
4782 struct btrfs_root *new_root;
4783 struct btrfs_root_ref *ref;
4784 struct extent_buffer *leaf;
4788 path = btrfs_alloc_path();
4795 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
4796 BTRFS_I(dir)->root->root_key.objectid,
4797 location->objectid);
4804 leaf = path->nodes[0];
4805 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4806 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4807 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4810 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4811 (unsigned long)(ref + 1),
4812 dentry->d_name.len);
4816 btrfs_release_path(path);
4818 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4819 if (IS_ERR(new_root)) {
4820 err = PTR_ERR(new_root);
4824 if (btrfs_root_refs(&new_root->root_item) == 0) {
4829 *sub_root = new_root;
4830 location->objectid = btrfs_root_dirid(&new_root->root_item);
4831 location->type = BTRFS_INODE_ITEM_KEY;
4832 location->offset = 0;
4835 btrfs_free_path(path);
4839 static void inode_tree_add(struct inode *inode)
4841 struct btrfs_root *root = BTRFS_I(inode)->root;
4842 struct btrfs_inode *entry;
4844 struct rb_node *parent;
4845 u64 ino = btrfs_ino(inode);
4847 p = &root->inode_tree.rb_node;
4850 if (inode_unhashed(inode))
4853 spin_lock(&root->inode_lock);
4856 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4858 if (ino < btrfs_ino(&entry->vfs_inode))
4859 p = &parent->rb_left;
4860 else if (ino > btrfs_ino(&entry->vfs_inode))
4861 p = &parent->rb_right;
4863 WARN_ON(!(entry->vfs_inode.i_state &
4864 (I_WILL_FREE | I_FREEING)));
4865 rb_erase(parent, &root->inode_tree);
4866 RB_CLEAR_NODE(parent);
4867 spin_unlock(&root->inode_lock);
4871 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
4872 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4873 spin_unlock(&root->inode_lock);
4876 static void inode_tree_del(struct inode *inode)
4878 struct btrfs_root *root = BTRFS_I(inode)->root;
4881 spin_lock(&root->inode_lock);
4882 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4883 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4884 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4885 empty = RB_EMPTY_ROOT(&root->inode_tree);
4887 spin_unlock(&root->inode_lock);
4890 * Free space cache has inodes in the tree root, but the tree root has a
4891 * root_refs of 0, so this could end up dropping the tree root as a
4892 * snapshot, so we need the extra !root->fs_info->tree_root check to
4893 * make sure we don't drop it.
4895 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4896 root != root->fs_info->tree_root) {
4897 synchronize_srcu(&root->fs_info->subvol_srcu);
4898 spin_lock(&root->inode_lock);
4899 empty = RB_EMPTY_ROOT(&root->inode_tree);
4900 spin_unlock(&root->inode_lock);
4902 btrfs_add_dead_root(root);
4906 void btrfs_invalidate_inodes(struct btrfs_root *root)
4908 struct rb_node *node;
4909 struct rb_node *prev;
4910 struct btrfs_inode *entry;
4911 struct inode *inode;
4914 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4916 spin_lock(&root->inode_lock);
4918 node = root->inode_tree.rb_node;
4922 entry = rb_entry(node, struct btrfs_inode, rb_node);
4924 if (objectid < btrfs_ino(&entry->vfs_inode))
4925 node = node->rb_left;
4926 else if (objectid > btrfs_ino(&entry->vfs_inode))
4927 node = node->rb_right;
4933 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4934 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4938 prev = rb_next(prev);
4942 entry = rb_entry(node, struct btrfs_inode, rb_node);
4943 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4944 inode = igrab(&entry->vfs_inode);
4946 spin_unlock(&root->inode_lock);
4947 if (atomic_read(&inode->i_count) > 1)
4948 d_prune_aliases(inode);
4950 * btrfs_drop_inode will have it removed from
4951 * the inode cache when its usage count
4956 spin_lock(&root->inode_lock);
4960 if (cond_resched_lock(&root->inode_lock))
4963 node = rb_next(node);
4965 spin_unlock(&root->inode_lock);
4968 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4970 struct btrfs_iget_args *args = p;
4971 inode->i_ino = args->ino;
4972 BTRFS_I(inode)->root = args->root;
4976 static int btrfs_find_actor(struct inode *inode, void *opaque)
4978 struct btrfs_iget_args *args = opaque;
4979 return args->ino == btrfs_ino(inode) &&
4980 args->root == BTRFS_I(inode)->root;
4983 static struct inode *btrfs_iget_locked(struct super_block *s,
4985 struct btrfs_root *root)
4987 struct inode *inode;
4988 struct btrfs_iget_args args;
4989 args.ino = objectid;
4992 inode = iget5_locked(s, objectid, btrfs_find_actor,
4993 btrfs_init_locked_inode,
4998 /* Get an inode object given its location and corresponding root.
4999 * Returns in *is_new if the inode was read from disk
5001 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5002 struct btrfs_root *root, int *new)
5004 struct inode *inode;
5006 inode = btrfs_iget_locked(s, location->objectid, root);
5008 return ERR_PTR(-ENOMEM);
5010 if (inode->i_state & I_NEW) {
5011 BTRFS_I(inode)->root = root;
5012 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
5013 btrfs_read_locked_inode(inode);
5014 if (!is_bad_inode(inode)) {
5015 inode_tree_add(inode);
5016 unlock_new_inode(inode);
5020 unlock_new_inode(inode);
5022 inode = ERR_PTR(-ESTALE);
5029 static struct inode *new_simple_dir(struct super_block *s,
5030 struct btrfs_key *key,
5031 struct btrfs_root *root)
5033 struct inode *inode = new_inode(s);
5036 return ERR_PTR(-ENOMEM);
5038 BTRFS_I(inode)->root = root;
5039 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5040 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5042 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5043 inode->i_op = &btrfs_dir_ro_inode_operations;
5044 inode->i_fop = &simple_dir_operations;
5045 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5046 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5051 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5053 struct inode *inode;
5054 struct btrfs_root *root = BTRFS_I(dir)->root;
5055 struct btrfs_root *sub_root = root;
5056 struct btrfs_key location;
5060 if (dentry->d_name.len > BTRFS_NAME_LEN)
5061 return ERR_PTR(-ENAMETOOLONG);
5063 ret = btrfs_inode_by_name(dir, dentry, &location);
5065 return ERR_PTR(ret);
5067 if (location.objectid == 0)
5070 if (location.type == BTRFS_INODE_ITEM_KEY) {
5071 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5075 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5077 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5078 ret = fixup_tree_root_location(root, dir, dentry,
5079 &location, &sub_root);
5082 inode = ERR_PTR(ret);
5084 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5086 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5088 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5090 if (!IS_ERR(inode) && root != sub_root) {
5091 down_read(&root->fs_info->cleanup_work_sem);
5092 if (!(inode->i_sb->s_flags & MS_RDONLY))
5093 ret = btrfs_orphan_cleanup(sub_root);
5094 up_read(&root->fs_info->cleanup_work_sem);
5096 inode = ERR_PTR(ret);
5102 static int btrfs_dentry_delete(const struct dentry *dentry)
5104 struct btrfs_root *root;
5105 struct inode *inode = dentry->d_inode;
5107 if (!inode && !IS_ROOT(dentry))
5108 inode = dentry->d_parent->d_inode;
5111 root = BTRFS_I(inode)->root;
5112 if (btrfs_root_refs(&root->root_item) == 0)
5115 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5121 static void btrfs_dentry_release(struct dentry *dentry)
5123 if (dentry->d_fsdata)
5124 kfree(dentry->d_fsdata);
5127 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5132 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
5136 unsigned char btrfs_filetype_table[] = {
5137 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5140 static int btrfs_real_readdir(struct file *filp, void *dirent,
5143 struct inode *inode = file_inode(filp);
5144 struct btrfs_root *root = BTRFS_I(inode)->root;
5145 struct btrfs_item *item;
5146 struct btrfs_dir_item *di;
5147 struct btrfs_key key;
5148 struct btrfs_key found_key;
5149 struct btrfs_path *path;
5150 struct list_head ins_list;
5151 struct list_head del_list;
5153 struct extent_buffer *leaf;
5155 unsigned char d_type;
5160 int key_type = BTRFS_DIR_INDEX_KEY;
5164 int is_curr = 0; /* filp->f_pos points to the current index? */
5166 /* FIXME, use a real flag for deciding about the key type */
5167 if (root->fs_info->tree_root == root)
5168 key_type = BTRFS_DIR_ITEM_KEY;
5170 /* special case for "." */
5171 if (filp->f_pos == 0) {
5172 over = filldir(dirent, ".", 1,
5173 filp->f_pos, btrfs_ino(inode), DT_DIR);
5178 /* special case for .., just use the back ref */
5179 if (filp->f_pos == 1) {
5180 u64 pino = parent_ino(filp->f_path.dentry);
5181 over = filldir(dirent, "..", 2,
5182 filp->f_pos, pino, DT_DIR);
5187 path = btrfs_alloc_path();
5193 if (key_type == BTRFS_DIR_INDEX_KEY) {
5194 INIT_LIST_HEAD(&ins_list);
5195 INIT_LIST_HEAD(&del_list);
5196 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5199 btrfs_set_key_type(&key, key_type);
5200 key.offset = filp->f_pos;
5201 key.objectid = btrfs_ino(inode);
5203 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5208 leaf = path->nodes[0];
5209 slot = path->slots[0];
5210 if (slot >= btrfs_header_nritems(leaf)) {
5211 ret = btrfs_next_leaf(root, path);
5219 item = btrfs_item_nr(leaf, slot);
5220 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5222 if (found_key.objectid != key.objectid)
5224 if (btrfs_key_type(&found_key) != key_type)
5226 if (found_key.offset < filp->f_pos)
5228 if (key_type == BTRFS_DIR_INDEX_KEY &&
5229 btrfs_should_delete_dir_index(&del_list,
5233 filp->f_pos = found_key.offset;
5236 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5238 di_total = btrfs_item_size(leaf, item);
5240 while (di_cur < di_total) {
5241 struct btrfs_key location;
5243 if (verify_dir_item(root, leaf, di))
5246 name_len = btrfs_dir_name_len(leaf, di);
5247 if (name_len <= sizeof(tmp_name)) {
5248 name_ptr = tmp_name;
5250 name_ptr = kmalloc(name_len, GFP_NOFS);
5256 read_extent_buffer(leaf, name_ptr,
5257 (unsigned long)(di + 1), name_len);
5259 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5260 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5263 /* is this a reference to our own snapshot? If so
5266 * In contrast to old kernels, we insert the snapshot's
5267 * dir item and dir index after it has been created, so
5268 * we won't find a reference to our own snapshot. We
5269 * still keep the following code for backward
5272 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5273 location.objectid == root->root_key.objectid) {
5277 over = filldir(dirent, name_ptr, name_len,
5278 found_key.offset, location.objectid,
5282 if (name_ptr != tmp_name)
5287 di_len = btrfs_dir_name_len(leaf, di) +
5288 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5290 di = (struct btrfs_dir_item *)((char *)di + di_len);
5296 if (key_type == BTRFS_DIR_INDEX_KEY) {
5299 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
5305 /* Reached end of directory/root. Bump pos past the last item. */
5306 if (key_type == BTRFS_DIR_INDEX_KEY)
5308 * 32-bit glibc will use getdents64, but then strtol -
5309 * so the last number we can serve is this.
5311 filp->f_pos = 0x7fffffff;
5317 if (key_type == BTRFS_DIR_INDEX_KEY)
5318 btrfs_put_delayed_items(&ins_list, &del_list);
5319 btrfs_free_path(path);
5323 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5325 struct btrfs_root *root = BTRFS_I(inode)->root;
5326 struct btrfs_trans_handle *trans;
5328 bool nolock = false;
5330 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5333 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5336 if (wbc->sync_mode == WB_SYNC_ALL) {
5338 trans = btrfs_join_transaction_nolock(root);
5340 trans = btrfs_join_transaction(root);
5342 return PTR_ERR(trans);
5343 ret = btrfs_commit_transaction(trans, root);
5349 * This is somewhat expensive, updating the tree every time the
5350 * inode changes. But, it is most likely to find the inode in cache.
5351 * FIXME, needs more benchmarking...there are no reasons other than performance
5352 * to keep or drop this code.
5354 static int btrfs_dirty_inode(struct inode *inode)
5356 struct btrfs_root *root = BTRFS_I(inode)->root;
5357 struct btrfs_trans_handle *trans;
5360 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5363 trans = btrfs_join_transaction(root);
5365 return PTR_ERR(trans);
5367 ret = btrfs_update_inode(trans, root, inode);
5368 if (ret && ret == -ENOSPC) {
5369 /* whoops, lets try again with the full transaction */
5370 btrfs_end_transaction(trans, root);
5371 trans = btrfs_start_transaction(root, 1);
5373 return PTR_ERR(trans);
5375 ret = btrfs_update_inode(trans, root, inode);
5377 btrfs_end_transaction(trans, root);
5378 if (BTRFS_I(inode)->delayed_node)
5379 btrfs_balance_delayed_items(root);
5385 * This is a copy of file_update_time. We need this so we can return error on
5386 * ENOSPC for updating the inode in the case of file write and mmap writes.
5388 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5391 struct btrfs_root *root = BTRFS_I(inode)->root;
5393 if (btrfs_root_readonly(root))
5396 if (flags & S_VERSION)
5397 inode_inc_iversion(inode);
5398 if (flags & S_CTIME)
5399 inode->i_ctime = *now;
5400 if (flags & S_MTIME)
5401 inode->i_mtime = *now;
5402 if (flags & S_ATIME)
5403 inode->i_atime = *now;
5404 return btrfs_dirty_inode(inode);
5408 * find the highest existing sequence number in a directory
5409 * and then set the in-memory index_cnt variable to reflect
5410 * free sequence numbers
5412 static int btrfs_set_inode_index_count(struct inode *inode)
5414 struct btrfs_root *root = BTRFS_I(inode)->root;
5415 struct btrfs_key key, found_key;
5416 struct btrfs_path *path;
5417 struct extent_buffer *leaf;
5420 key.objectid = btrfs_ino(inode);
5421 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5422 key.offset = (u64)-1;
5424 path = btrfs_alloc_path();
5428 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5431 /* FIXME: we should be able to handle this */
5437 * MAGIC NUMBER EXPLANATION:
5438 * since we search a directory based on f_pos we have to start at 2
5439 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5440 * else has to start at 2
5442 if (path->slots[0] == 0) {
5443 BTRFS_I(inode)->index_cnt = 2;
5449 leaf = path->nodes[0];
5450 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5452 if (found_key.objectid != btrfs_ino(inode) ||
5453 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5454 BTRFS_I(inode)->index_cnt = 2;
5458 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5460 btrfs_free_path(path);
5465 * helper to find a free sequence number in a given directory. This current
5466 * code is very simple, later versions will do smarter things in the btree
5468 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5472 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5473 ret = btrfs_inode_delayed_dir_index_count(dir);
5475 ret = btrfs_set_inode_index_count(dir);
5481 *index = BTRFS_I(dir)->index_cnt;
5482 BTRFS_I(dir)->index_cnt++;
5487 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5488 struct btrfs_root *root,
5490 const char *name, int name_len,
5491 u64 ref_objectid, u64 objectid,
5492 umode_t mode, u64 *index)
5494 struct inode *inode;
5495 struct btrfs_inode_item *inode_item;
5496 struct btrfs_key *location;
5497 struct btrfs_path *path;
5498 struct btrfs_inode_ref *ref;
5499 struct btrfs_key key[2];
5505 path = btrfs_alloc_path();
5507 return ERR_PTR(-ENOMEM);
5509 inode = new_inode(root->fs_info->sb);
5511 btrfs_free_path(path);
5512 return ERR_PTR(-ENOMEM);
5516 * we have to initialize this early, so we can reclaim the inode
5517 * number if we fail afterwards in this function.
5519 inode->i_ino = objectid;
5522 trace_btrfs_inode_request(dir);
5524 ret = btrfs_set_inode_index(dir, index);
5526 btrfs_free_path(path);
5528 return ERR_PTR(ret);
5532 * index_cnt is ignored for everything but a dir,
5533 * btrfs_get_inode_index_count has an explanation for the magic
5536 BTRFS_I(inode)->index_cnt = 2;
5537 BTRFS_I(inode)->root = root;
5538 BTRFS_I(inode)->generation = trans->transid;
5539 inode->i_generation = BTRFS_I(inode)->generation;
5542 * We could have gotten an inode number from somebody who was fsynced
5543 * and then removed in this same transaction, so let's just set full
5544 * sync since it will be a full sync anyway and this will blow away the
5545 * old info in the log.
5547 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5554 key[0].objectid = objectid;
5555 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5559 * Start new inodes with an inode_ref. This is slightly more
5560 * efficient for small numbers of hard links since they will
5561 * be packed into one item. Extended refs will kick in if we
5562 * add more hard links than can fit in the ref item.
5564 key[1].objectid = objectid;
5565 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5566 key[1].offset = ref_objectid;
5568 sizes[0] = sizeof(struct btrfs_inode_item);
5569 sizes[1] = name_len + sizeof(*ref);
5571 path->leave_spinning = 1;
5572 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
5576 inode_init_owner(inode, dir, mode);
5577 inode_set_bytes(inode, 0);
5578 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5579 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5580 struct btrfs_inode_item);
5581 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5582 sizeof(*inode_item));
5583 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5585 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5586 struct btrfs_inode_ref);
5587 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5588 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5589 ptr = (unsigned long)(ref + 1);
5590 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5592 btrfs_mark_buffer_dirty(path->nodes[0]);
5593 btrfs_free_path(path);
5595 location = &BTRFS_I(inode)->location;
5596 location->objectid = objectid;
5597 location->offset = 0;
5598 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5600 btrfs_inherit_iflags(inode, dir);
5602 if (S_ISREG(mode)) {
5603 if (btrfs_test_opt(root, NODATASUM))
5604 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5605 if (btrfs_test_opt(root, NODATACOW))
5606 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5607 BTRFS_INODE_NODATASUM;
5610 insert_inode_hash(inode);
5611 inode_tree_add(inode);
5613 trace_btrfs_inode_new(inode);
5614 btrfs_set_inode_last_trans(trans, inode);
5616 btrfs_update_root_times(trans, root);
5621 BTRFS_I(dir)->index_cnt--;
5622 btrfs_free_path(path);
5624 return ERR_PTR(ret);
5627 static inline u8 btrfs_inode_type(struct inode *inode)
5629 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5633 * utility function to add 'inode' into 'parent_inode' with
5634 * a give name and a given sequence number.
5635 * if 'add_backref' is true, also insert a backref from the
5636 * inode to the parent directory.
5638 int btrfs_add_link(struct btrfs_trans_handle *trans,
5639 struct inode *parent_inode, struct inode *inode,
5640 const char *name, int name_len, int add_backref, u64 index)
5643 struct btrfs_key key;
5644 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5645 u64 ino = btrfs_ino(inode);
5646 u64 parent_ino = btrfs_ino(parent_inode);
5648 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5649 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5652 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5656 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5657 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5658 key.objectid, root->root_key.objectid,
5659 parent_ino, index, name, name_len);
5660 } else if (add_backref) {
5661 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5665 /* Nothing to clean up yet */
5669 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5671 btrfs_inode_type(inode), index);
5672 if (ret == -EEXIST || ret == -EOVERFLOW)
5675 btrfs_abort_transaction(trans, root, ret);
5679 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5681 inode_inc_iversion(parent_inode);
5682 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5683 ret = btrfs_update_inode(trans, root, parent_inode);
5685 btrfs_abort_transaction(trans, root, ret);
5689 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5692 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5693 key.objectid, root->root_key.objectid,
5694 parent_ino, &local_index, name, name_len);
5696 } else if (add_backref) {
5700 err = btrfs_del_inode_ref(trans, root, name, name_len,
5701 ino, parent_ino, &local_index);
5706 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5707 struct inode *dir, struct dentry *dentry,
5708 struct inode *inode, int backref, u64 index)
5710 int err = btrfs_add_link(trans, dir, inode,
5711 dentry->d_name.name, dentry->d_name.len,
5718 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5719 umode_t mode, dev_t rdev)
5721 struct btrfs_trans_handle *trans;
5722 struct btrfs_root *root = BTRFS_I(dir)->root;
5723 struct inode *inode = NULL;
5729 if (!new_valid_dev(rdev))
5733 * 2 for inode item and ref
5735 * 1 for xattr if selinux is on
5737 trans = btrfs_start_transaction(root, 5);
5739 return PTR_ERR(trans);
5741 err = btrfs_find_free_ino(root, &objectid);
5745 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5746 dentry->d_name.len, btrfs_ino(dir), objectid,
5748 if (IS_ERR(inode)) {
5749 err = PTR_ERR(inode);
5753 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5760 * If the active LSM wants to access the inode during
5761 * d_instantiate it needs these. Smack checks to see
5762 * if the filesystem supports xattrs by looking at the
5766 inode->i_op = &btrfs_special_inode_operations;
5767 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5771 init_special_inode(inode, inode->i_mode, rdev);
5772 btrfs_update_inode(trans, root, inode);
5773 d_instantiate(dentry, inode);
5776 btrfs_end_transaction(trans, root);
5777 btrfs_btree_balance_dirty(root);
5779 inode_dec_link_count(inode);
5785 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5786 umode_t mode, bool excl)
5788 struct btrfs_trans_handle *trans;
5789 struct btrfs_root *root = BTRFS_I(dir)->root;
5790 struct inode *inode = NULL;
5791 int drop_inode_on_err = 0;
5797 * 2 for inode item and ref
5799 * 1 for xattr if selinux is on
5801 trans = btrfs_start_transaction(root, 5);
5803 return PTR_ERR(trans);
5805 err = btrfs_find_free_ino(root, &objectid);
5809 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5810 dentry->d_name.len, btrfs_ino(dir), objectid,
5812 if (IS_ERR(inode)) {
5813 err = PTR_ERR(inode);
5816 drop_inode_on_err = 1;
5818 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5822 err = btrfs_update_inode(trans, root, inode);
5827 * If the active LSM wants to access the inode during
5828 * d_instantiate it needs these. Smack checks to see
5829 * if the filesystem supports xattrs by looking at the
5832 inode->i_fop = &btrfs_file_operations;
5833 inode->i_op = &btrfs_file_inode_operations;
5835 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5839 inode->i_mapping->a_ops = &btrfs_aops;
5840 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5841 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5842 d_instantiate(dentry, inode);
5845 btrfs_end_transaction(trans, root);
5846 if (err && drop_inode_on_err) {
5847 inode_dec_link_count(inode);
5850 btrfs_btree_balance_dirty(root);
5854 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5855 struct dentry *dentry)
5857 struct btrfs_trans_handle *trans;
5858 struct btrfs_root *root = BTRFS_I(dir)->root;
5859 struct inode *inode = old_dentry->d_inode;
5864 /* do not allow sys_link's with other subvols of the same device */
5865 if (root->objectid != BTRFS_I(inode)->root->objectid)
5868 if (inode->i_nlink >= BTRFS_LINK_MAX)
5871 err = btrfs_set_inode_index(dir, &index);
5876 * 2 items for inode and inode ref
5877 * 2 items for dir items
5878 * 1 item for parent inode
5880 trans = btrfs_start_transaction(root, 5);
5881 if (IS_ERR(trans)) {
5882 err = PTR_ERR(trans);
5886 btrfs_inc_nlink(inode);
5887 inode_inc_iversion(inode);
5888 inode->i_ctime = CURRENT_TIME;
5890 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5892 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5897 struct dentry *parent = dentry->d_parent;
5898 err = btrfs_update_inode(trans, root, inode);
5901 d_instantiate(dentry, inode);
5902 btrfs_log_new_name(trans, inode, NULL, parent);
5905 btrfs_end_transaction(trans, root);
5908 inode_dec_link_count(inode);
5911 btrfs_btree_balance_dirty(root);
5915 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5917 struct inode *inode = NULL;
5918 struct btrfs_trans_handle *trans;
5919 struct btrfs_root *root = BTRFS_I(dir)->root;
5921 int drop_on_err = 0;
5926 * 2 items for inode and ref
5927 * 2 items for dir items
5928 * 1 for xattr if selinux is on
5930 trans = btrfs_start_transaction(root, 5);
5932 return PTR_ERR(trans);
5934 err = btrfs_find_free_ino(root, &objectid);
5938 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5939 dentry->d_name.len, btrfs_ino(dir), objectid,
5940 S_IFDIR | mode, &index);
5941 if (IS_ERR(inode)) {
5942 err = PTR_ERR(inode);
5948 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5952 inode->i_op = &btrfs_dir_inode_operations;
5953 inode->i_fop = &btrfs_dir_file_operations;
5955 btrfs_i_size_write(inode, 0);
5956 err = btrfs_update_inode(trans, root, inode);
5960 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5961 dentry->d_name.len, 0, index);
5965 d_instantiate(dentry, inode);
5969 btrfs_end_transaction(trans, root);
5972 btrfs_btree_balance_dirty(root);
5976 /* helper for btfs_get_extent. Given an existing extent in the tree,
5977 * and an extent that you want to insert, deal with overlap and insert
5978 * the new extent into the tree.
5980 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5981 struct extent_map *existing,
5982 struct extent_map *em,
5983 u64 map_start, u64 map_len)
5987 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5988 start_diff = map_start - em->start;
5989 em->start = map_start;
5991 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5992 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5993 em->block_start += start_diff;
5994 em->block_len -= start_diff;
5996 return add_extent_mapping(em_tree, em, 0);
5999 static noinline int uncompress_inline(struct btrfs_path *path,
6000 struct inode *inode, struct page *page,
6001 size_t pg_offset, u64 extent_offset,
6002 struct btrfs_file_extent_item *item)
6005 struct extent_buffer *leaf = path->nodes[0];
6008 unsigned long inline_size;
6012 WARN_ON(pg_offset != 0);
6013 compress_type = btrfs_file_extent_compression(leaf, item);
6014 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6015 inline_size = btrfs_file_extent_inline_item_len(leaf,
6016 btrfs_item_nr(leaf, path->slots[0]));
6017 tmp = kmalloc(inline_size, GFP_NOFS);
6020 ptr = btrfs_file_extent_inline_start(item);
6022 read_extent_buffer(leaf, tmp, ptr, inline_size);
6024 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6025 ret = btrfs_decompress(compress_type, tmp, page,
6026 extent_offset, inline_size, max_size);
6028 char *kaddr = kmap_atomic(page);
6029 unsigned long copy_size = min_t(u64,
6030 PAGE_CACHE_SIZE - pg_offset,
6031 max_size - extent_offset);
6032 memset(kaddr + pg_offset, 0, copy_size);
6033 kunmap_atomic(kaddr);
6040 * a bit scary, this does extent mapping from logical file offset to the disk.
6041 * the ugly parts come from merging extents from the disk with the in-ram
6042 * representation. This gets more complex because of the data=ordered code,
6043 * where the in-ram extents might be locked pending data=ordered completion.
6045 * This also copies inline extents directly into the page.
6048 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6049 size_t pg_offset, u64 start, u64 len,
6055 u64 extent_start = 0;
6057 u64 objectid = btrfs_ino(inode);
6059 struct btrfs_path *path = NULL;
6060 struct btrfs_root *root = BTRFS_I(inode)->root;
6061 struct btrfs_file_extent_item *item;
6062 struct extent_buffer *leaf;
6063 struct btrfs_key found_key;
6064 struct extent_map *em = NULL;
6065 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6066 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6067 struct btrfs_trans_handle *trans = NULL;
6071 read_lock(&em_tree->lock);
6072 em = lookup_extent_mapping(em_tree, start, len);
6074 em->bdev = root->fs_info->fs_devices->latest_bdev;
6075 read_unlock(&em_tree->lock);
6078 if (em->start > start || em->start + em->len <= start)
6079 free_extent_map(em);
6080 else if (em->block_start == EXTENT_MAP_INLINE && page)
6081 free_extent_map(em);
6085 em = alloc_extent_map();
6090 em->bdev = root->fs_info->fs_devices->latest_bdev;
6091 em->start = EXTENT_MAP_HOLE;
6092 em->orig_start = EXTENT_MAP_HOLE;
6094 em->block_len = (u64)-1;
6097 path = btrfs_alloc_path();
6103 * Chances are we'll be called again, so go ahead and do
6109 ret = btrfs_lookup_file_extent(trans, root, path,
6110 objectid, start, trans != NULL);
6117 if (path->slots[0] == 0)
6122 leaf = path->nodes[0];
6123 item = btrfs_item_ptr(leaf, path->slots[0],
6124 struct btrfs_file_extent_item);
6125 /* are we inside the extent that was found? */
6126 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6127 found_type = btrfs_key_type(&found_key);
6128 if (found_key.objectid != objectid ||
6129 found_type != BTRFS_EXTENT_DATA_KEY) {
6133 found_type = btrfs_file_extent_type(leaf, item);
6134 extent_start = found_key.offset;
6135 compress_type = btrfs_file_extent_compression(leaf, item);
6136 if (found_type == BTRFS_FILE_EXTENT_REG ||
6137 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6138 extent_end = extent_start +
6139 btrfs_file_extent_num_bytes(leaf, item);
6140 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6142 size = btrfs_file_extent_inline_len(leaf, item);
6143 extent_end = ALIGN(extent_start + size, root->sectorsize);
6146 if (start >= extent_end) {
6148 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6149 ret = btrfs_next_leaf(root, path);
6156 leaf = path->nodes[0];
6158 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6159 if (found_key.objectid != objectid ||
6160 found_key.type != BTRFS_EXTENT_DATA_KEY)
6162 if (start + len <= found_key.offset)
6165 em->orig_start = start;
6166 em->len = found_key.offset - start;
6170 em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
6171 if (found_type == BTRFS_FILE_EXTENT_REG ||
6172 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6173 em->start = extent_start;
6174 em->len = extent_end - extent_start;
6175 em->orig_start = extent_start -
6176 btrfs_file_extent_offset(leaf, item);
6177 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6179 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6181 em->block_start = EXTENT_MAP_HOLE;
6184 if (compress_type != BTRFS_COMPRESS_NONE) {
6185 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6186 em->compress_type = compress_type;
6187 em->block_start = bytenr;
6188 em->block_len = em->orig_block_len;
6190 bytenr += btrfs_file_extent_offset(leaf, item);
6191 em->block_start = bytenr;
6192 em->block_len = em->len;
6193 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6194 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6197 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6201 size_t extent_offset;
6204 em->block_start = EXTENT_MAP_INLINE;
6205 if (!page || create) {
6206 em->start = extent_start;
6207 em->len = extent_end - extent_start;
6211 size = btrfs_file_extent_inline_len(leaf, item);
6212 extent_offset = page_offset(page) + pg_offset - extent_start;
6213 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6214 size - extent_offset);
6215 em->start = extent_start + extent_offset;
6216 em->len = ALIGN(copy_size, root->sectorsize);
6217 em->orig_block_len = em->len;
6218 em->orig_start = em->start;
6219 if (compress_type) {
6220 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6221 em->compress_type = compress_type;
6223 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6224 if (create == 0 && !PageUptodate(page)) {
6225 if (btrfs_file_extent_compression(leaf, item) !=
6226 BTRFS_COMPRESS_NONE) {
6227 ret = uncompress_inline(path, inode, page,
6229 extent_offset, item);
6230 BUG_ON(ret); /* -ENOMEM */
6233 read_extent_buffer(leaf, map + pg_offset, ptr,
6235 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6236 memset(map + pg_offset + copy_size, 0,
6237 PAGE_CACHE_SIZE - pg_offset -
6242 flush_dcache_page(page);
6243 } else if (create && PageUptodate(page)) {
6247 free_extent_map(em);
6250 btrfs_release_path(path);
6251 trans = btrfs_join_transaction(root);
6254 return ERR_CAST(trans);
6258 write_extent_buffer(leaf, map + pg_offset, ptr,
6261 btrfs_mark_buffer_dirty(leaf);
6263 set_extent_uptodate(io_tree, em->start,
6264 extent_map_end(em) - 1, NULL, GFP_NOFS);
6267 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6271 em->orig_start = start;
6274 em->block_start = EXTENT_MAP_HOLE;
6275 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6277 btrfs_release_path(path);
6278 if (em->start > start || extent_map_end(em) <= start) {
6279 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6280 (unsigned long long)em->start,
6281 (unsigned long long)em->len,
6282 (unsigned long long)start,
6283 (unsigned long long)len);
6289 write_lock(&em_tree->lock);
6290 ret = add_extent_mapping(em_tree, em, 0);
6291 /* it is possible that someone inserted the extent into the tree
6292 * while we had the lock dropped. It is also possible that
6293 * an overlapping map exists in the tree
6295 if (ret == -EEXIST) {
6296 struct extent_map *existing;
6300 existing = lookup_extent_mapping(em_tree, start, len);
6301 if (existing && (existing->start > start ||
6302 existing->start + existing->len <= start)) {
6303 free_extent_map(existing);
6307 existing = lookup_extent_mapping(em_tree, em->start,
6310 err = merge_extent_mapping(em_tree, existing,
6313 free_extent_map(existing);
6315 free_extent_map(em);
6320 free_extent_map(em);
6324 free_extent_map(em);
6329 write_unlock(&em_tree->lock);
6333 trace_btrfs_get_extent(root, em);
6336 btrfs_free_path(path);
6338 ret = btrfs_end_transaction(trans, root);
6343 free_extent_map(em);
6344 return ERR_PTR(err);
6346 BUG_ON(!em); /* Error is always set */
6350 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6351 size_t pg_offset, u64 start, u64 len,
6354 struct extent_map *em;
6355 struct extent_map *hole_em = NULL;
6356 u64 range_start = start;
6362 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6369 * - a pre-alloc extent,
6370 * there might actually be delalloc bytes behind it.
6372 if (em->block_start != EXTENT_MAP_HOLE &&
6373 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6379 /* check to see if we've wrapped (len == -1 or similar) */
6388 /* ok, we didn't find anything, lets look for delalloc */
6389 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6390 end, len, EXTENT_DELALLOC, 1);
6391 found_end = range_start + found;
6392 if (found_end < range_start)
6393 found_end = (u64)-1;
6396 * we didn't find anything useful, return
6397 * the original results from get_extent()
6399 if (range_start > end || found_end <= start) {
6405 /* adjust the range_start to make sure it doesn't
6406 * go backwards from the start they passed in
6408 range_start = max(start,range_start);
6409 found = found_end - range_start;
6412 u64 hole_start = start;
6415 em = alloc_extent_map();
6421 * when btrfs_get_extent can't find anything it
6422 * returns one huge hole
6424 * make sure what it found really fits our range, and
6425 * adjust to make sure it is based on the start from
6429 u64 calc_end = extent_map_end(hole_em);
6431 if (calc_end <= start || (hole_em->start > end)) {
6432 free_extent_map(hole_em);
6435 hole_start = max(hole_em->start, start);
6436 hole_len = calc_end - hole_start;
6440 if (hole_em && range_start > hole_start) {
6441 /* our hole starts before our delalloc, so we
6442 * have to return just the parts of the hole
6443 * that go until the delalloc starts
6445 em->len = min(hole_len,
6446 range_start - hole_start);
6447 em->start = hole_start;
6448 em->orig_start = hole_start;
6450 * don't adjust block start at all,
6451 * it is fixed at EXTENT_MAP_HOLE
6453 em->block_start = hole_em->block_start;
6454 em->block_len = hole_len;
6455 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6456 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6458 em->start = range_start;
6460 em->orig_start = range_start;
6461 em->block_start = EXTENT_MAP_DELALLOC;
6462 em->block_len = found;
6464 } else if (hole_em) {
6469 free_extent_map(hole_em);
6471 free_extent_map(em);
6472 return ERR_PTR(err);
6477 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6480 struct btrfs_root *root = BTRFS_I(inode)->root;
6481 struct btrfs_trans_handle *trans;
6482 struct extent_map *em;
6483 struct btrfs_key ins;
6487 trans = btrfs_join_transaction(root);
6489 return ERR_CAST(trans);
6491 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
6493 alloc_hint = get_extent_allocation_hint(inode, start, len);
6494 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
6495 alloc_hint, &ins, 1);
6501 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6502 ins.offset, ins.offset, ins.offset, 0);
6506 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6507 ins.offset, ins.offset, 0);
6509 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6513 btrfs_end_transaction(trans, root);
6518 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6519 * block must be cow'd
6521 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
6522 struct inode *inode, u64 offset, u64 *len,
6523 u64 *orig_start, u64 *orig_block_len,
6526 struct btrfs_path *path;
6528 struct extent_buffer *leaf;
6529 struct btrfs_root *root = BTRFS_I(inode)->root;
6530 struct btrfs_file_extent_item *fi;
6531 struct btrfs_key key;
6539 path = btrfs_alloc_path();
6543 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
6548 slot = path->slots[0];
6551 /* can't find the item, must cow */
6558 leaf = path->nodes[0];
6559 btrfs_item_key_to_cpu(leaf, &key, slot);
6560 if (key.objectid != btrfs_ino(inode) ||
6561 key.type != BTRFS_EXTENT_DATA_KEY) {
6562 /* not our file or wrong item type, must cow */
6566 if (key.offset > offset) {
6567 /* Wrong offset, must cow */
6571 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6572 found_type = btrfs_file_extent_type(leaf, fi);
6573 if (found_type != BTRFS_FILE_EXTENT_REG &&
6574 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6575 /* not a regular extent, must cow */
6578 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6579 backref_offset = btrfs_file_extent_offset(leaf, fi);
6581 *orig_start = key.offset - backref_offset;
6582 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6583 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6585 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6586 if (extent_end < offset + *len) {
6587 /* extent doesn't include our full range, must cow */
6591 if (btrfs_extent_readonly(root, disk_bytenr))
6595 * look for other files referencing this extent, if we
6596 * find any we must cow
6598 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6599 key.offset - backref_offset, disk_bytenr))
6603 * adjust disk_bytenr and num_bytes to cover just the bytes
6604 * in this extent we are about to write. If there
6605 * are any csums in that range we have to cow in order
6606 * to keep the csums correct
6608 disk_bytenr += backref_offset;
6609 disk_bytenr += offset - key.offset;
6610 num_bytes = min(offset + *len, extent_end) - offset;
6611 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6614 * all of the above have passed, it is safe to overwrite this extent
6620 btrfs_free_path(path);
6624 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6625 struct extent_state **cached_state, int writing)
6627 struct btrfs_ordered_extent *ordered;
6631 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6634 * We're concerned with the entire range that we're going to be
6635 * doing DIO to, so we need to make sure theres no ordered
6636 * extents in this range.
6638 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6639 lockend - lockstart + 1);
6642 * We need to make sure there are no buffered pages in this
6643 * range either, we could have raced between the invalidate in
6644 * generic_file_direct_write and locking the extent. The
6645 * invalidate needs to happen so that reads after a write do not
6648 if (!ordered && (!writing ||
6649 !test_range_bit(&BTRFS_I(inode)->io_tree,
6650 lockstart, lockend, EXTENT_UPTODATE, 0,
6654 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6655 cached_state, GFP_NOFS);
6658 btrfs_start_ordered_extent(inode, ordered, 1);
6659 btrfs_put_ordered_extent(ordered);
6661 /* Screw you mmap */
6662 ret = filemap_write_and_wait_range(inode->i_mapping,
6669 * If we found a page that couldn't be invalidated just
6670 * fall back to buffered.
6672 ret = invalidate_inode_pages2_range(inode->i_mapping,
6673 lockstart >> PAGE_CACHE_SHIFT,
6674 lockend >> PAGE_CACHE_SHIFT);
6685 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6686 u64 len, u64 orig_start,
6687 u64 block_start, u64 block_len,
6688 u64 orig_block_len, u64 ram_bytes,
6691 struct extent_map_tree *em_tree;
6692 struct extent_map *em;
6693 struct btrfs_root *root = BTRFS_I(inode)->root;
6696 em_tree = &BTRFS_I(inode)->extent_tree;
6697 em = alloc_extent_map();
6699 return ERR_PTR(-ENOMEM);
6702 em->orig_start = orig_start;
6703 em->mod_start = start;
6706 em->block_len = block_len;
6707 em->block_start = block_start;
6708 em->bdev = root->fs_info->fs_devices->latest_bdev;
6709 em->orig_block_len = orig_block_len;
6710 em->ram_bytes = ram_bytes;
6711 em->generation = -1;
6712 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6713 if (type == BTRFS_ORDERED_PREALLOC)
6714 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6717 btrfs_drop_extent_cache(inode, em->start,
6718 em->start + em->len - 1, 0);
6719 write_lock(&em_tree->lock);
6720 ret = add_extent_mapping(em_tree, em, 1);
6721 write_unlock(&em_tree->lock);
6722 } while (ret == -EEXIST);
6725 free_extent_map(em);
6726 return ERR_PTR(ret);
6733 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6734 struct buffer_head *bh_result, int create)
6736 struct extent_map *em;
6737 struct btrfs_root *root = BTRFS_I(inode)->root;
6738 struct extent_state *cached_state = NULL;
6739 u64 start = iblock << inode->i_blkbits;
6740 u64 lockstart, lockend;
6741 u64 len = bh_result->b_size;
6742 struct btrfs_trans_handle *trans;
6743 int unlock_bits = EXTENT_LOCKED;
6747 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6749 len = min_t(u64, len, root->sectorsize);
6752 lockend = start + len - 1;
6755 * If this errors out it's because we couldn't invalidate pagecache for
6756 * this range and we need to fallback to buffered.
6758 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6761 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6768 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6769 * io. INLINE is special, and we could probably kludge it in here, but
6770 * it's still buffered so for safety lets just fall back to the generic
6773 * For COMPRESSED we _have_ to read the entire extent in so we can
6774 * decompress it, so there will be buffering required no matter what we
6775 * do, so go ahead and fallback to buffered.
6777 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6778 * to buffered IO. Don't blame me, this is the price we pay for using
6781 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6782 em->block_start == EXTENT_MAP_INLINE) {
6783 free_extent_map(em);
6788 /* Just a good old fashioned hole, return */
6789 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6790 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6791 free_extent_map(em);
6796 * We don't allocate a new extent in the following cases
6798 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6800 * 2) The extent is marked as PREALLOC. We're good to go here and can
6801 * just use the extent.
6805 len = min(len, em->len - (start - em->start));
6806 lockstart = start + len;
6810 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6811 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6812 em->block_start != EXTENT_MAP_HOLE)) {
6815 u64 block_start, orig_start, orig_block_len, ram_bytes;
6817 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6818 type = BTRFS_ORDERED_PREALLOC;
6820 type = BTRFS_ORDERED_NOCOW;
6821 len = min(len, em->len - (start - em->start));
6822 block_start = em->block_start + (start - em->start);
6825 * we're not going to log anything, but we do need
6826 * to make sure the current transaction stays open
6827 * while we look for nocow cross refs
6829 trans = btrfs_join_transaction(root);
6833 if (can_nocow_odirect(trans, inode, start, &len, &orig_start,
6834 &orig_block_len, &ram_bytes) == 1) {
6835 if (type == BTRFS_ORDERED_PREALLOC) {
6836 free_extent_map(em);
6837 em = create_pinned_em(inode, start, len,
6843 btrfs_end_transaction(trans, root);
6848 ret = btrfs_add_ordered_extent_dio(inode, start,
6849 block_start, len, len, type);
6850 btrfs_end_transaction(trans, root);
6852 free_extent_map(em);
6857 btrfs_end_transaction(trans, root);
6861 * this will cow the extent, reset the len in case we changed
6864 len = bh_result->b_size;
6865 free_extent_map(em);
6866 em = btrfs_new_extent_direct(inode, start, len);
6871 len = min(len, em->len - (start - em->start));
6873 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6875 bh_result->b_size = len;
6876 bh_result->b_bdev = em->bdev;
6877 set_buffer_mapped(bh_result);
6879 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6880 set_buffer_new(bh_result);
6883 * Need to update the i_size under the extent lock so buffered
6884 * readers will get the updated i_size when we unlock.
6886 if (start + len > i_size_read(inode))
6887 i_size_write(inode, start + len);
6889 spin_lock(&BTRFS_I(inode)->lock);
6890 BTRFS_I(inode)->outstanding_extents++;
6891 spin_unlock(&BTRFS_I(inode)->lock);
6893 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6894 lockstart + len - 1, EXTENT_DELALLOC, NULL,
6895 &cached_state, GFP_NOFS);
6900 * In the case of write we need to clear and unlock the entire range,
6901 * in the case of read we need to unlock only the end area that we
6902 * aren't using if there is any left over space.
6904 if (lockstart < lockend) {
6905 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6906 lockend, unlock_bits, 1, 0,
6907 &cached_state, GFP_NOFS);
6909 free_extent_state(cached_state);
6912 free_extent_map(em);
6917 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6918 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6922 struct btrfs_dio_private {
6923 struct inode *inode;
6929 /* number of bios pending for this dio */
6930 atomic_t pending_bios;
6935 struct bio *orig_bio;
6938 static void btrfs_endio_direct_read(struct bio *bio, int err)
6940 struct btrfs_dio_private *dip = bio->bi_private;
6941 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6942 struct bio_vec *bvec = bio->bi_io_vec;
6943 struct inode *inode = dip->inode;
6944 struct btrfs_root *root = BTRFS_I(inode)->root;
6947 start = dip->logical_offset;
6949 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6950 struct page *page = bvec->bv_page;
6953 u64 private = ~(u32)0;
6954 unsigned long flags;
6956 if (get_state_private(&BTRFS_I(inode)->io_tree,
6959 local_irq_save(flags);
6960 kaddr = kmap_atomic(page);
6961 csum = btrfs_csum_data(kaddr + bvec->bv_offset,
6962 csum, bvec->bv_len);
6963 btrfs_csum_final(csum, (char *)&csum);
6964 kunmap_atomic(kaddr);
6965 local_irq_restore(flags);
6967 flush_dcache_page(bvec->bv_page);
6968 if (csum != private) {
6970 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u private %u",
6971 (unsigned long long)btrfs_ino(inode),
6972 (unsigned long long)start,
6973 csum, (unsigned)private);
6978 start += bvec->bv_len;
6980 } while (bvec <= bvec_end);
6982 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6983 dip->logical_offset + dip->bytes - 1);
6984 bio->bi_private = dip->private;
6988 /* If we had a csum failure make sure to clear the uptodate flag */
6990 clear_bit(BIO_UPTODATE, &bio->bi_flags);
6991 dio_end_io(bio, err);
6994 static void btrfs_endio_direct_write(struct bio *bio, int err)
6996 struct btrfs_dio_private *dip = bio->bi_private;
6997 struct inode *inode = dip->inode;
6998 struct btrfs_root *root = BTRFS_I(inode)->root;
6999 struct btrfs_ordered_extent *ordered = NULL;
7000 u64 ordered_offset = dip->logical_offset;
7001 u64 ordered_bytes = dip->bytes;
7007 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7009 ordered_bytes, !err);
7013 ordered->work.func = finish_ordered_fn;
7014 ordered->work.flags = 0;
7015 btrfs_queue_worker(&root->fs_info->endio_write_workers,
7019 * our bio might span multiple ordered extents. If we haven't
7020 * completed the accounting for the whole dio, go back and try again
7022 if (ordered_offset < dip->logical_offset + dip->bytes) {
7023 ordered_bytes = dip->logical_offset + dip->bytes -
7029 bio->bi_private = dip->private;
7033 /* If we had an error make sure to clear the uptodate flag */
7035 clear_bit(BIO_UPTODATE, &bio->bi_flags);
7036 dio_end_io(bio, err);
7039 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7040 struct bio *bio, int mirror_num,
7041 unsigned long bio_flags, u64 offset)
7044 struct btrfs_root *root = BTRFS_I(inode)->root;
7045 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7046 BUG_ON(ret); /* -ENOMEM */
7050 static void btrfs_end_dio_bio(struct bio *bio, int err)
7052 struct btrfs_dio_private *dip = bio->bi_private;
7055 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
7056 "sector %#Lx len %u err no %d\n",
7057 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
7058 (unsigned long long)bio->bi_sector, bio->bi_size, err);
7062 * before atomic variable goto zero, we must make sure
7063 * dip->errors is perceived to be set.
7065 smp_mb__before_atomic_dec();
7068 /* if there are more bios still pending for this dio, just exit */
7069 if (!atomic_dec_and_test(&dip->pending_bios))
7073 bio_io_error(dip->orig_bio);
7075 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
7076 bio_endio(dip->orig_bio, 0);
7082 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7083 u64 first_sector, gfp_t gfp_flags)
7085 int nr_vecs = bio_get_nr_vecs(bdev);
7086 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7089 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7090 int rw, u64 file_offset, int skip_sum,
7093 int write = rw & REQ_WRITE;
7094 struct btrfs_root *root = BTRFS_I(inode)->root;
7098 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7103 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
7111 if (write && async_submit) {
7112 ret = btrfs_wq_submit_bio(root->fs_info,
7113 inode, rw, bio, 0, 0,
7115 __btrfs_submit_bio_start_direct_io,
7116 __btrfs_submit_bio_done);
7120 * If we aren't doing async submit, calculate the csum of the
7123 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7126 } else if (!skip_sum) {
7127 ret = btrfs_lookup_bio_sums_dio(root, inode, bio, file_offset);
7133 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7139 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7142 struct inode *inode = dip->inode;
7143 struct btrfs_root *root = BTRFS_I(inode)->root;
7145 struct bio *orig_bio = dip->orig_bio;
7146 struct bio_vec *bvec = orig_bio->bi_io_vec;
7147 u64 start_sector = orig_bio->bi_sector;
7148 u64 file_offset = dip->logical_offset;
7153 int async_submit = 0;
7155 map_length = orig_bio->bi_size;
7156 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7157 &map_length, NULL, 0);
7162 if (map_length >= orig_bio->bi_size) {
7167 /* async crcs make it difficult to collect full stripe writes. */
7168 if (btrfs_get_alloc_profile(root, 1) &
7169 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7174 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7177 bio->bi_private = dip;
7178 bio->bi_end_io = btrfs_end_dio_bio;
7179 atomic_inc(&dip->pending_bios);
7181 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7182 if (unlikely(map_length < submit_len + bvec->bv_len ||
7183 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7184 bvec->bv_offset) < bvec->bv_len)) {
7186 * inc the count before we submit the bio so
7187 * we know the end IO handler won't happen before
7188 * we inc the count. Otherwise, the dip might get freed
7189 * before we're done setting it up
7191 atomic_inc(&dip->pending_bios);
7192 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7193 file_offset, skip_sum,
7197 atomic_dec(&dip->pending_bios);
7201 start_sector += submit_len >> 9;
7202 file_offset += submit_len;
7207 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7208 start_sector, GFP_NOFS);
7211 bio->bi_private = dip;
7212 bio->bi_end_io = btrfs_end_dio_bio;
7214 map_length = orig_bio->bi_size;
7215 ret = btrfs_map_block(root->fs_info, rw,
7217 &map_length, NULL, 0);
7223 submit_len += bvec->bv_len;
7230 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7239 * before atomic variable goto zero, we must
7240 * make sure dip->errors is perceived to be set.
7242 smp_mb__before_atomic_dec();
7243 if (atomic_dec_and_test(&dip->pending_bios))
7244 bio_io_error(dip->orig_bio);
7246 /* bio_end_io() will handle error, so we needn't return it */
7250 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
7253 struct btrfs_root *root = BTRFS_I(inode)->root;
7254 struct btrfs_dio_private *dip;
7255 struct bio_vec *bvec = bio->bi_io_vec;
7257 int write = rw & REQ_WRITE;
7260 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7262 dip = kmalloc(sizeof(*dip), GFP_NOFS);
7268 dip->private = bio->bi_private;
7270 dip->logical_offset = file_offset;
7274 dip->bytes += bvec->bv_len;
7276 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
7278 dip->disk_bytenr = (u64)bio->bi_sector << 9;
7279 bio->bi_private = dip;
7281 dip->orig_bio = bio;
7282 atomic_set(&dip->pending_bios, 0);
7285 bio->bi_end_io = btrfs_endio_direct_write;
7287 bio->bi_end_io = btrfs_endio_direct_read;
7289 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7294 * If this is a write, we need to clean up the reserved space and kill
7295 * the ordered extent.
7298 struct btrfs_ordered_extent *ordered;
7299 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7300 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7301 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7302 btrfs_free_reserved_extent(root, ordered->start,
7304 btrfs_put_ordered_extent(ordered);
7305 btrfs_put_ordered_extent(ordered);
7307 bio_endio(bio, ret);
7310 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7311 const struct iovec *iov, loff_t offset,
7312 unsigned long nr_segs)
7318 unsigned blocksize_mask = root->sectorsize - 1;
7319 ssize_t retval = -EINVAL;
7320 loff_t end = offset;
7322 if (offset & blocksize_mask)
7325 /* Check the memory alignment. Blocks cannot straddle pages */
7326 for (seg = 0; seg < nr_segs; seg++) {
7327 addr = (unsigned long)iov[seg].iov_base;
7328 size = iov[seg].iov_len;
7330 if ((addr & blocksize_mask) || (size & blocksize_mask))
7333 /* If this is a write we don't need to check anymore */
7338 * Check to make sure we don't have duplicate iov_base's in this
7339 * iovec, if so return EINVAL, otherwise we'll get csum errors
7340 * when reading back.
7342 for (i = seg + 1; i < nr_segs; i++) {
7343 if (iov[seg].iov_base == iov[i].iov_base)
7352 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7353 const struct iovec *iov, loff_t offset,
7354 unsigned long nr_segs)
7356 struct file *file = iocb->ki_filp;
7357 struct inode *inode = file->f_mapping->host;
7361 bool relock = false;
7364 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7368 atomic_inc(&inode->i_dio_count);
7369 smp_mb__after_atomic_inc();
7372 count = iov_length(iov, nr_segs);
7374 * If the write DIO is beyond the EOF, we need update
7375 * the isize, but it is protected by i_mutex. So we can
7376 * not unlock the i_mutex at this case.
7378 if (offset + count <= inode->i_size) {
7379 mutex_unlock(&inode->i_mutex);
7382 ret = btrfs_delalloc_reserve_space(inode, count);
7385 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7386 &BTRFS_I(inode)->runtime_flags))) {
7387 inode_dio_done(inode);
7388 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7392 ret = __blockdev_direct_IO(rw, iocb, inode,
7393 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7394 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7395 btrfs_submit_direct, flags);
7397 if (ret < 0 && ret != -EIOCBQUEUED)
7398 btrfs_delalloc_release_space(inode, count);
7399 else if (ret >= 0 && (size_t)ret < count)
7400 btrfs_delalloc_release_space(inode,
7401 count - (size_t)ret);
7403 btrfs_delalloc_release_metadata(inode, 0);
7407 inode_dio_done(inode);
7409 mutex_lock(&inode->i_mutex);
7414 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7416 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7417 __u64 start, __u64 len)
7421 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7425 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7428 int btrfs_readpage(struct file *file, struct page *page)
7430 struct extent_io_tree *tree;
7431 tree = &BTRFS_I(page->mapping->host)->io_tree;
7432 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7435 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7437 struct extent_io_tree *tree;
7440 if (current->flags & PF_MEMALLOC) {
7441 redirty_page_for_writepage(wbc, page);
7445 tree = &BTRFS_I(page->mapping->host)->io_tree;
7446 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7449 static int btrfs_writepages(struct address_space *mapping,
7450 struct writeback_control *wbc)
7452 struct extent_io_tree *tree;
7454 tree = &BTRFS_I(mapping->host)->io_tree;
7455 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7459 btrfs_readpages(struct file *file, struct address_space *mapping,
7460 struct list_head *pages, unsigned nr_pages)
7462 struct extent_io_tree *tree;
7463 tree = &BTRFS_I(mapping->host)->io_tree;
7464 return extent_readpages(tree, mapping, pages, nr_pages,
7467 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7469 struct extent_io_tree *tree;
7470 struct extent_map_tree *map;
7473 tree = &BTRFS_I(page->mapping->host)->io_tree;
7474 map = &BTRFS_I(page->mapping->host)->extent_tree;
7475 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7477 ClearPagePrivate(page);
7478 set_page_private(page, 0);
7479 page_cache_release(page);
7484 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7486 if (PageWriteback(page) || PageDirty(page))
7488 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7491 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
7493 struct inode *inode = page->mapping->host;
7494 struct extent_io_tree *tree;
7495 struct btrfs_ordered_extent *ordered;
7496 struct extent_state *cached_state = NULL;
7497 u64 page_start = page_offset(page);
7498 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7501 * we have the page locked, so new writeback can't start,
7502 * and the dirty bit won't be cleared while we are here.
7504 * Wait for IO on this page so that we can safely clear
7505 * the PagePrivate2 bit and do ordered accounting
7507 wait_on_page_writeback(page);
7509 tree = &BTRFS_I(inode)->io_tree;
7511 btrfs_releasepage(page, GFP_NOFS);
7514 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7515 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
7518 * IO on this page will never be started, so we need
7519 * to account for any ordered extents now
7521 clear_extent_bit(tree, page_start, page_end,
7522 EXTENT_DIRTY | EXTENT_DELALLOC |
7523 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7524 EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS);
7526 * whoever cleared the private bit is responsible
7527 * for the finish_ordered_io
7529 if (TestClearPagePrivate2(page) &&
7530 btrfs_dec_test_ordered_pending(inode, &ordered, page_start,
7531 PAGE_CACHE_SIZE, 1)) {
7532 btrfs_finish_ordered_io(ordered);
7534 btrfs_put_ordered_extent(ordered);
7535 cached_state = NULL;
7536 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7538 clear_extent_bit(tree, page_start, page_end,
7539 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
7540 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
7541 &cached_state, GFP_NOFS);
7542 __btrfs_releasepage(page, GFP_NOFS);
7544 ClearPageChecked(page);
7545 if (PagePrivate(page)) {
7546 ClearPagePrivate(page);
7547 set_page_private(page, 0);
7548 page_cache_release(page);
7553 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7554 * called from a page fault handler when a page is first dirtied. Hence we must
7555 * be careful to check for EOF conditions here. We set the page up correctly
7556 * for a written page which means we get ENOSPC checking when writing into
7557 * holes and correct delalloc and unwritten extent mapping on filesystems that
7558 * support these features.
7560 * We are not allowed to take the i_mutex here so we have to play games to
7561 * protect against truncate races as the page could now be beyond EOF. Because
7562 * vmtruncate() writes the inode size before removing pages, once we have the
7563 * page lock we can determine safely if the page is beyond EOF. If it is not
7564 * beyond EOF, then the page is guaranteed safe against truncation until we
7567 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7569 struct page *page = vmf->page;
7570 struct inode *inode = file_inode(vma->vm_file);
7571 struct btrfs_root *root = BTRFS_I(inode)->root;
7572 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7573 struct btrfs_ordered_extent *ordered;
7574 struct extent_state *cached_state = NULL;
7576 unsigned long zero_start;
7583 sb_start_pagefault(inode->i_sb);
7584 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7586 ret = file_update_time(vma->vm_file);
7592 else /* -ENOSPC, -EIO, etc */
7593 ret = VM_FAULT_SIGBUS;
7599 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7602 size = i_size_read(inode);
7603 page_start = page_offset(page);
7604 page_end = page_start + PAGE_CACHE_SIZE - 1;
7606 if ((page->mapping != inode->i_mapping) ||
7607 (page_start >= size)) {
7608 /* page got truncated out from underneath us */
7611 wait_on_page_writeback(page);
7613 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7614 set_page_extent_mapped(page);
7617 * we can't set the delalloc bits if there are pending ordered
7618 * extents. Drop our locks and wait for them to finish
7620 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7622 unlock_extent_cached(io_tree, page_start, page_end,
7623 &cached_state, GFP_NOFS);
7625 btrfs_start_ordered_extent(inode, ordered, 1);
7626 btrfs_put_ordered_extent(ordered);
7631 * XXX - page_mkwrite gets called every time the page is dirtied, even
7632 * if it was already dirty, so for space accounting reasons we need to
7633 * clear any delalloc bits for the range we are fixing to save. There
7634 * is probably a better way to do this, but for now keep consistent with
7635 * prepare_pages in the normal write path.
7637 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7638 EXTENT_DIRTY | EXTENT_DELALLOC |
7639 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7640 0, 0, &cached_state, GFP_NOFS);
7642 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7645 unlock_extent_cached(io_tree, page_start, page_end,
7646 &cached_state, GFP_NOFS);
7647 ret = VM_FAULT_SIGBUS;
7652 /* page is wholly or partially inside EOF */
7653 if (page_start + PAGE_CACHE_SIZE > size)
7654 zero_start = size & ~PAGE_CACHE_MASK;
7656 zero_start = PAGE_CACHE_SIZE;
7658 if (zero_start != PAGE_CACHE_SIZE) {
7660 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7661 flush_dcache_page(page);
7664 ClearPageChecked(page);
7665 set_page_dirty(page);
7666 SetPageUptodate(page);
7668 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7669 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7670 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7672 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7676 sb_end_pagefault(inode->i_sb);
7677 return VM_FAULT_LOCKED;
7681 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7683 sb_end_pagefault(inode->i_sb);
7687 static int btrfs_truncate(struct inode *inode)
7689 struct btrfs_root *root = BTRFS_I(inode)->root;
7690 struct btrfs_block_rsv *rsv;
7693 struct btrfs_trans_handle *trans;
7694 u64 mask = root->sectorsize - 1;
7695 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7697 ret = btrfs_truncate_page(inode, inode->i_size, 0, 0);
7701 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
7702 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
7705 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7706 * 3 things going on here
7708 * 1) We need to reserve space for our orphan item and the space to
7709 * delete our orphan item. Lord knows we don't want to have a dangling
7710 * orphan item because we didn't reserve space to remove it.
7712 * 2) We need to reserve space to update our inode.
7714 * 3) We need to have something to cache all the space that is going to
7715 * be free'd up by the truncate operation, but also have some slack
7716 * space reserved in case it uses space during the truncate (thank you
7717 * very much snapshotting).
7719 * And we need these to all be seperate. The fact is we can use alot of
7720 * space doing the truncate, and we have no earthly idea how much space
7721 * we will use, so we need the truncate reservation to be seperate so it
7722 * doesn't end up using space reserved for updating the inode or
7723 * removing the orphan item. We also need to be able to stop the
7724 * transaction and start a new one, which means we need to be able to
7725 * update the inode several times, and we have no idea of knowing how
7726 * many times that will be, so we can't just reserve 1 item for the
7727 * entirety of the opration, so that has to be done seperately as well.
7728 * Then there is the orphan item, which does indeed need to be held on
7729 * to for the whole operation, and we need nobody to touch this reserved
7730 * space except the orphan code.
7732 * So that leaves us with
7734 * 1) root->orphan_block_rsv - for the orphan deletion.
7735 * 2) rsv - for the truncate reservation, which we will steal from the
7736 * transaction reservation.
7737 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7738 * updating the inode.
7740 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7743 rsv->size = min_size;
7747 * 1 for the truncate slack space
7748 * 1 for updating the inode.
7750 trans = btrfs_start_transaction(root, 2);
7751 if (IS_ERR(trans)) {
7752 err = PTR_ERR(trans);
7756 /* Migrate the slack space for the truncate to our reserve */
7757 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7762 * setattr is responsible for setting the ordered_data_close flag,
7763 * but that is only tested during the last file release. That
7764 * could happen well after the next commit, leaving a great big
7765 * window where new writes may get lost if someone chooses to write
7766 * to this file after truncating to zero
7768 * The inode doesn't have any dirty data here, and so if we commit
7769 * this is a noop. If someone immediately starts writing to the inode
7770 * it is very likely we'll catch some of their writes in this
7771 * transaction, and the commit will find this file on the ordered
7772 * data list with good things to send down.
7774 * This is a best effort solution, there is still a window where
7775 * using truncate to replace the contents of the file will
7776 * end up with a zero length file after a crash.
7778 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7779 &BTRFS_I(inode)->runtime_flags))
7780 btrfs_add_ordered_operation(trans, root, inode);
7783 * So if we truncate and then write and fsync we normally would just
7784 * write the extents that changed, which is a problem if we need to
7785 * first truncate that entire inode. So set this flag so we write out
7786 * all of the extents in the inode to the sync log so we're completely
7789 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7790 trans->block_rsv = rsv;
7793 ret = btrfs_truncate_inode_items(trans, root, inode,
7795 BTRFS_EXTENT_DATA_KEY);
7796 if (ret != -ENOSPC) {
7801 trans->block_rsv = &root->fs_info->trans_block_rsv;
7802 ret = btrfs_update_inode(trans, root, inode);
7808 btrfs_end_transaction(trans, root);
7809 btrfs_btree_balance_dirty(root);
7811 trans = btrfs_start_transaction(root, 2);
7812 if (IS_ERR(trans)) {
7813 ret = err = PTR_ERR(trans);
7818 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7820 BUG_ON(ret); /* shouldn't happen */
7821 trans->block_rsv = rsv;
7824 if (ret == 0 && inode->i_nlink > 0) {
7825 trans->block_rsv = root->orphan_block_rsv;
7826 ret = btrfs_orphan_del(trans, inode);
7832 trans->block_rsv = &root->fs_info->trans_block_rsv;
7833 ret = btrfs_update_inode(trans, root, inode);
7837 ret = btrfs_end_transaction(trans, root);
7838 btrfs_btree_balance_dirty(root);
7842 btrfs_free_block_rsv(root, rsv);
7851 * create a new subvolume directory/inode (helper for the ioctl).
7853 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7854 struct btrfs_root *new_root, u64 new_dirid)
7856 struct inode *inode;
7860 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7861 new_dirid, new_dirid,
7862 S_IFDIR | (~current_umask() & S_IRWXUGO),
7865 return PTR_ERR(inode);
7866 inode->i_op = &btrfs_dir_inode_operations;
7867 inode->i_fop = &btrfs_dir_file_operations;
7869 set_nlink(inode, 1);
7870 btrfs_i_size_write(inode, 0);
7872 err = btrfs_update_inode(trans, new_root, inode);
7878 struct inode *btrfs_alloc_inode(struct super_block *sb)
7880 struct btrfs_inode *ei;
7881 struct inode *inode;
7883 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7890 ei->last_sub_trans = 0;
7891 ei->logged_trans = 0;
7892 ei->delalloc_bytes = 0;
7893 ei->disk_i_size = 0;
7896 ei->index_cnt = (u64)-1;
7897 ei->last_unlink_trans = 0;
7898 ei->last_log_commit = 0;
7900 spin_lock_init(&ei->lock);
7901 ei->outstanding_extents = 0;
7902 ei->reserved_extents = 0;
7904 ei->runtime_flags = 0;
7905 ei->force_compress = BTRFS_COMPRESS_NONE;
7907 ei->delayed_node = NULL;
7909 inode = &ei->vfs_inode;
7910 extent_map_tree_init(&ei->extent_tree);
7911 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7912 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7913 ei->io_tree.track_uptodate = 1;
7914 ei->io_failure_tree.track_uptodate = 1;
7915 atomic_set(&ei->sync_writers, 0);
7916 mutex_init(&ei->log_mutex);
7917 mutex_init(&ei->delalloc_mutex);
7918 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7919 INIT_LIST_HEAD(&ei->delalloc_inodes);
7920 INIT_LIST_HEAD(&ei->ordered_operations);
7921 RB_CLEAR_NODE(&ei->rb_node);
7926 static void btrfs_i_callback(struct rcu_head *head)
7928 struct inode *inode = container_of(head, struct inode, i_rcu);
7929 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7932 void btrfs_destroy_inode(struct inode *inode)
7934 struct btrfs_ordered_extent *ordered;
7935 struct btrfs_root *root = BTRFS_I(inode)->root;
7937 WARN_ON(!hlist_empty(&inode->i_dentry));
7938 WARN_ON(inode->i_data.nrpages);
7939 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7940 WARN_ON(BTRFS_I(inode)->reserved_extents);
7941 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7942 WARN_ON(BTRFS_I(inode)->csum_bytes);
7945 * This can happen where we create an inode, but somebody else also
7946 * created the same inode and we need to destroy the one we already
7953 * Make sure we're properly removed from the ordered operation
7957 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7958 spin_lock(&root->fs_info->ordered_extent_lock);
7959 list_del_init(&BTRFS_I(inode)->ordered_operations);
7960 spin_unlock(&root->fs_info->ordered_extent_lock);
7963 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7964 &BTRFS_I(inode)->runtime_flags)) {
7965 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
7966 (unsigned long long)btrfs_ino(inode));
7967 atomic_dec(&root->orphan_inodes);
7971 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7975 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
7976 (unsigned long long)ordered->file_offset,
7977 (unsigned long long)ordered->len);
7978 btrfs_remove_ordered_extent(inode, ordered);
7979 btrfs_put_ordered_extent(ordered);
7980 btrfs_put_ordered_extent(ordered);
7983 inode_tree_del(inode);
7984 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7986 call_rcu(&inode->i_rcu, btrfs_i_callback);
7989 int btrfs_drop_inode(struct inode *inode)
7991 struct btrfs_root *root = BTRFS_I(inode)->root;
7993 /* the snap/subvol tree is on deleting */
7994 if (btrfs_root_refs(&root->root_item) == 0 &&
7995 root != root->fs_info->tree_root)
7998 return generic_drop_inode(inode);
8001 static void init_once(void *foo)
8003 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8005 inode_init_once(&ei->vfs_inode);
8008 void btrfs_destroy_cachep(void)
8011 * Make sure all delayed rcu free inodes are flushed before we
8015 if (btrfs_inode_cachep)
8016 kmem_cache_destroy(btrfs_inode_cachep);
8017 if (btrfs_trans_handle_cachep)
8018 kmem_cache_destroy(btrfs_trans_handle_cachep);
8019 if (btrfs_transaction_cachep)
8020 kmem_cache_destroy(btrfs_transaction_cachep);
8021 if (btrfs_path_cachep)
8022 kmem_cache_destroy(btrfs_path_cachep);
8023 if (btrfs_free_space_cachep)
8024 kmem_cache_destroy(btrfs_free_space_cachep);
8025 if (btrfs_delalloc_work_cachep)
8026 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8029 int btrfs_init_cachep(void)
8031 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8032 sizeof(struct btrfs_inode), 0,
8033 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8034 if (!btrfs_inode_cachep)
8037 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8038 sizeof(struct btrfs_trans_handle), 0,
8039 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8040 if (!btrfs_trans_handle_cachep)
8043 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8044 sizeof(struct btrfs_transaction), 0,
8045 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8046 if (!btrfs_transaction_cachep)
8049 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8050 sizeof(struct btrfs_path), 0,
8051 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8052 if (!btrfs_path_cachep)
8055 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8056 sizeof(struct btrfs_free_space), 0,
8057 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8058 if (!btrfs_free_space_cachep)
8061 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8062 sizeof(struct btrfs_delalloc_work), 0,
8063 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8065 if (!btrfs_delalloc_work_cachep)
8070 btrfs_destroy_cachep();
8074 static int btrfs_getattr(struct vfsmount *mnt,
8075 struct dentry *dentry, struct kstat *stat)
8078 struct inode *inode = dentry->d_inode;
8079 u32 blocksize = inode->i_sb->s_blocksize;
8081 generic_fillattr(inode, stat);
8082 stat->dev = BTRFS_I(inode)->root->anon_dev;
8083 stat->blksize = PAGE_CACHE_SIZE;
8085 spin_lock(&BTRFS_I(inode)->lock);
8086 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8087 spin_unlock(&BTRFS_I(inode)->lock);
8088 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8089 ALIGN(delalloc_bytes, blocksize)) >> 9;
8093 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8094 struct inode *new_dir, struct dentry *new_dentry)
8096 struct btrfs_trans_handle *trans;
8097 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8098 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8099 struct inode *new_inode = new_dentry->d_inode;
8100 struct inode *old_inode = old_dentry->d_inode;
8101 struct timespec ctime = CURRENT_TIME;
8105 u64 old_ino = btrfs_ino(old_inode);
8107 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8110 /* we only allow rename subvolume link between subvolumes */
8111 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8114 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8115 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8118 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8119 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8123 /* check for collisions, even if the name isn't there */
8124 ret = btrfs_check_dir_item_collision(root, new_dir->i_ino,
8125 new_dentry->d_name.name,
8126 new_dentry->d_name.len);
8129 if (ret == -EEXIST) {
8131 * eexist without a new_inode */
8137 /* maybe -EOVERFLOW */
8144 * we're using rename to replace one file with another.
8145 * and the replacement file is large. Start IO on it now so
8146 * we don't add too much work to the end of the transaction
8148 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8149 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8150 filemap_flush(old_inode->i_mapping);
8152 /* close the racy window with snapshot create/destroy ioctl */
8153 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8154 down_read(&root->fs_info->subvol_sem);
8156 * We want to reserve the absolute worst case amount of items. So if
8157 * both inodes are subvols and we need to unlink them then that would
8158 * require 4 item modifications, but if they are both normal inodes it
8159 * would require 5 item modifications, so we'll assume their normal
8160 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8161 * should cover the worst case number of items we'll modify.
8163 trans = btrfs_start_transaction(root, 11);
8164 if (IS_ERR(trans)) {
8165 ret = PTR_ERR(trans);
8170 btrfs_record_root_in_trans(trans, dest);
8172 ret = btrfs_set_inode_index(new_dir, &index);
8176 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8177 /* force full log commit if subvolume involved. */
8178 root->fs_info->last_trans_log_full_commit = trans->transid;
8180 ret = btrfs_insert_inode_ref(trans, dest,
8181 new_dentry->d_name.name,
8182 new_dentry->d_name.len,
8184 btrfs_ino(new_dir), index);
8188 * this is an ugly little race, but the rename is required
8189 * to make sure that if we crash, the inode is either at the
8190 * old name or the new one. pinning the log transaction lets
8191 * us make sure we don't allow a log commit to come in after
8192 * we unlink the name but before we add the new name back in.
8194 btrfs_pin_log_trans(root);
8197 * make sure the inode gets flushed if it is replacing
8200 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8201 btrfs_add_ordered_operation(trans, root, old_inode);
8203 inode_inc_iversion(old_dir);
8204 inode_inc_iversion(new_dir);
8205 inode_inc_iversion(old_inode);
8206 old_dir->i_ctime = old_dir->i_mtime = ctime;
8207 new_dir->i_ctime = new_dir->i_mtime = ctime;
8208 old_inode->i_ctime = ctime;
8210 if (old_dentry->d_parent != new_dentry->d_parent)
8211 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8213 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8214 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8215 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8216 old_dentry->d_name.name,
8217 old_dentry->d_name.len);
8219 ret = __btrfs_unlink_inode(trans, root, old_dir,
8220 old_dentry->d_inode,
8221 old_dentry->d_name.name,
8222 old_dentry->d_name.len);
8224 ret = btrfs_update_inode(trans, root, old_inode);
8227 btrfs_abort_transaction(trans, root, ret);
8232 inode_inc_iversion(new_inode);
8233 new_inode->i_ctime = CURRENT_TIME;
8234 if (unlikely(btrfs_ino(new_inode) ==
8235 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8236 root_objectid = BTRFS_I(new_inode)->location.objectid;
8237 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8239 new_dentry->d_name.name,
8240 new_dentry->d_name.len);
8241 BUG_ON(new_inode->i_nlink == 0);
8243 ret = btrfs_unlink_inode(trans, dest, new_dir,
8244 new_dentry->d_inode,
8245 new_dentry->d_name.name,
8246 new_dentry->d_name.len);
8248 if (!ret && new_inode->i_nlink == 0) {
8249 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8253 btrfs_abort_transaction(trans, root, ret);
8258 ret = btrfs_add_link(trans, new_dir, old_inode,
8259 new_dentry->d_name.name,
8260 new_dentry->d_name.len, 0, index);
8262 btrfs_abort_transaction(trans, root, ret);
8266 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8267 struct dentry *parent = new_dentry->d_parent;
8268 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8269 btrfs_end_log_trans(root);
8272 btrfs_end_transaction(trans, root);
8274 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8275 up_read(&root->fs_info->subvol_sem);
8280 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8282 struct btrfs_delalloc_work *delalloc_work;
8284 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8286 if (delalloc_work->wait)
8287 btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1);
8289 filemap_flush(delalloc_work->inode->i_mapping);
8291 if (delalloc_work->delay_iput)
8292 btrfs_add_delayed_iput(delalloc_work->inode);
8294 iput(delalloc_work->inode);
8295 complete(&delalloc_work->completion);
8298 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8299 int wait, int delay_iput)
8301 struct btrfs_delalloc_work *work;
8303 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8307 init_completion(&work->completion);
8308 INIT_LIST_HEAD(&work->list);
8309 work->inode = inode;
8311 work->delay_iput = delay_iput;
8312 work->work.func = btrfs_run_delalloc_work;
8317 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8319 wait_for_completion(&work->completion);
8320 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8324 * some fairly slow code that needs optimization. This walks the list
8325 * of all the inodes with pending delalloc and forces them to disk.
8327 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8329 struct btrfs_inode *binode;
8330 struct inode *inode;
8331 struct btrfs_delalloc_work *work, *next;
8332 struct list_head works;
8333 struct list_head splice;
8336 if (root->fs_info->sb->s_flags & MS_RDONLY)
8339 INIT_LIST_HEAD(&works);
8340 INIT_LIST_HEAD(&splice);
8342 spin_lock(&root->fs_info->delalloc_lock);
8343 list_splice_init(&root->fs_info->delalloc_inodes, &splice);
8344 while (!list_empty(&splice)) {
8345 binode = list_entry(splice.next, struct btrfs_inode,
8348 list_del_init(&binode->delalloc_inodes);
8350 inode = igrab(&binode->vfs_inode);
8352 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
8353 &binode->runtime_flags);
8357 list_add_tail(&binode->delalloc_inodes,
8358 &root->fs_info->delalloc_inodes);
8359 spin_unlock(&root->fs_info->delalloc_lock);
8361 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8362 if (unlikely(!work)) {
8366 list_add_tail(&work->list, &works);
8367 btrfs_queue_worker(&root->fs_info->flush_workers,
8371 spin_lock(&root->fs_info->delalloc_lock);
8373 spin_unlock(&root->fs_info->delalloc_lock);
8375 list_for_each_entry_safe(work, next, &works, list) {
8376 list_del_init(&work->list);
8377 btrfs_wait_and_free_delalloc_work(work);
8380 /* the filemap_flush will queue IO into the worker threads, but
8381 * we have to make sure the IO is actually started and that
8382 * ordered extents get created before we return
8384 atomic_inc(&root->fs_info->async_submit_draining);
8385 while (atomic_read(&root->fs_info->nr_async_submits) ||
8386 atomic_read(&root->fs_info->async_delalloc_pages)) {
8387 wait_event(root->fs_info->async_submit_wait,
8388 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8389 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8391 atomic_dec(&root->fs_info->async_submit_draining);
8394 list_for_each_entry_safe(work, next, &works, list) {
8395 list_del_init(&work->list);
8396 btrfs_wait_and_free_delalloc_work(work);
8399 if (!list_empty_careful(&splice)) {
8400 spin_lock(&root->fs_info->delalloc_lock);
8401 list_splice_tail(&splice, &root->fs_info->delalloc_inodes);
8402 spin_unlock(&root->fs_info->delalloc_lock);
8407 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8408 const char *symname)
8410 struct btrfs_trans_handle *trans;
8411 struct btrfs_root *root = BTRFS_I(dir)->root;
8412 struct btrfs_path *path;
8413 struct btrfs_key key;
8414 struct inode *inode = NULL;
8422 struct btrfs_file_extent_item *ei;
8423 struct extent_buffer *leaf;
8425 name_len = strlen(symname) + 1;
8426 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8427 return -ENAMETOOLONG;
8430 * 2 items for inode item and ref
8431 * 2 items for dir items
8432 * 1 item for xattr if selinux is on
8434 trans = btrfs_start_transaction(root, 5);
8436 return PTR_ERR(trans);
8438 err = btrfs_find_free_ino(root, &objectid);
8442 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8443 dentry->d_name.len, btrfs_ino(dir), objectid,
8444 S_IFLNK|S_IRWXUGO, &index);
8445 if (IS_ERR(inode)) {
8446 err = PTR_ERR(inode);
8450 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8457 * If the active LSM wants to access the inode during
8458 * d_instantiate it needs these. Smack checks to see
8459 * if the filesystem supports xattrs by looking at the
8462 inode->i_fop = &btrfs_file_operations;
8463 inode->i_op = &btrfs_file_inode_operations;
8465 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8469 inode->i_mapping->a_ops = &btrfs_aops;
8470 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8471 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8476 path = btrfs_alloc_path();
8482 key.objectid = btrfs_ino(inode);
8484 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8485 datasize = btrfs_file_extent_calc_inline_size(name_len);
8486 err = btrfs_insert_empty_item(trans, root, path, &key,
8490 btrfs_free_path(path);
8493 leaf = path->nodes[0];
8494 ei = btrfs_item_ptr(leaf, path->slots[0],
8495 struct btrfs_file_extent_item);
8496 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8497 btrfs_set_file_extent_type(leaf, ei,
8498 BTRFS_FILE_EXTENT_INLINE);
8499 btrfs_set_file_extent_encryption(leaf, ei, 0);
8500 btrfs_set_file_extent_compression(leaf, ei, 0);
8501 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8502 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8504 ptr = btrfs_file_extent_inline_start(ei);
8505 write_extent_buffer(leaf, symname, ptr, name_len);
8506 btrfs_mark_buffer_dirty(leaf);
8507 btrfs_free_path(path);
8509 inode->i_op = &btrfs_symlink_inode_operations;
8510 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8511 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8512 inode_set_bytes(inode, name_len);
8513 btrfs_i_size_write(inode, name_len - 1);
8514 err = btrfs_update_inode(trans, root, inode);
8520 d_instantiate(dentry, inode);
8521 btrfs_end_transaction(trans, root);
8523 inode_dec_link_count(inode);
8526 btrfs_btree_balance_dirty(root);
8530 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8531 u64 start, u64 num_bytes, u64 min_size,
8532 loff_t actual_len, u64 *alloc_hint,
8533 struct btrfs_trans_handle *trans)
8535 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8536 struct extent_map *em;
8537 struct btrfs_root *root = BTRFS_I(inode)->root;
8538 struct btrfs_key ins;
8539 u64 cur_offset = start;
8543 bool own_trans = true;
8547 while (num_bytes > 0) {
8549 trans = btrfs_start_transaction(root, 3);
8550 if (IS_ERR(trans)) {
8551 ret = PTR_ERR(trans);
8556 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8557 cur_bytes = max(cur_bytes, min_size);
8558 ret = btrfs_reserve_extent(trans, root, cur_bytes,
8559 min_size, 0, *alloc_hint, &ins, 1);
8562 btrfs_end_transaction(trans, root);
8566 ret = insert_reserved_file_extent(trans, inode,
8567 cur_offset, ins.objectid,
8568 ins.offset, ins.offset,
8569 ins.offset, 0, 0, 0,
8570 BTRFS_FILE_EXTENT_PREALLOC);
8572 btrfs_abort_transaction(trans, root, ret);
8574 btrfs_end_transaction(trans, root);
8577 btrfs_drop_extent_cache(inode, cur_offset,
8578 cur_offset + ins.offset -1, 0);
8580 em = alloc_extent_map();
8582 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8583 &BTRFS_I(inode)->runtime_flags);
8587 em->start = cur_offset;
8588 em->orig_start = cur_offset;
8589 em->len = ins.offset;
8590 em->block_start = ins.objectid;
8591 em->block_len = ins.offset;
8592 em->orig_block_len = ins.offset;
8593 em->ram_bytes = ins.offset;
8594 em->bdev = root->fs_info->fs_devices->latest_bdev;
8595 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8596 em->generation = trans->transid;
8599 write_lock(&em_tree->lock);
8600 ret = add_extent_mapping(em_tree, em, 1);
8601 write_unlock(&em_tree->lock);
8604 btrfs_drop_extent_cache(inode, cur_offset,
8605 cur_offset + ins.offset - 1,
8608 free_extent_map(em);
8610 num_bytes -= ins.offset;
8611 cur_offset += ins.offset;
8612 *alloc_hint = ins.objectid + ins.offset;
8614 inode_inc_iversion(inode);
8615 inode->i_ctime = CURRENT_TIME;
8616 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8617 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8618 (actual_len > inode->i_size) &&
8619 (cur_offset > inode->i_size)) {
8620 if (cur_offset > actual_len)
8621 i_size = actual_len;
8623 i_size = cur_offset;
8624 i_size_write(inode, i_size);
8625 btrfs_ordered_update_i_size(inode, i_size, NULL);
8628 ret = btrfs_update_inode(trans, root, inode);
8631 btrfs_abort_transaction(trans, root, ret);
8633 btrfs_end_transaction(trans, root);
8638 btrfs_end_transaction(trans, root);
8643 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8644 u64 start, u64 num_bytes, u64 min_size,
8645 loff_t actual_len, u64 *alloc_hint)
8647 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8648 min_size, actual_len, alloc_hint,
8652 int btrfs_prealloc_file_range_trans(struct inode *inode,
8653 struct btrfs_trans_handle *trans, int mode,
8654 u64 start, u64 num_bytes, u64 min_size,
8655 loff_t actual_len, u64 *alloc_hint)
8657 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8658 min_size, actual_len, alloc_hint, trans);
8661 static int btrfs_set_page_dirty(struct page *page)
8663 return __set_page_dirty_nobuffers(page);
8666 static int btrfs_permission(struct inode *inode, int mask)
8668 struct btrfs_root *root = BTRFS_I(inode)->root;
8669 umode_t mode = inode->i_mode;
8671 if (mask & MAY_WRITE &&
8672 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8673 if (btrfs_root_readonly(root))
8675 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8678 return generic_permission(inode, mask);
8681 static const struct inode_operations btrfs_dir_inode_operations = {
8682 .getattr = btrfs_getattr,
8683 .lookup = btrfs_lookup,
8684 .create = btrfs_create,
8685 .unlink = btrfs_unlink,
8687 .mkdir = btrfs_mkdir,
8688 .rmdir = btrfs_rmdir,
8689 .rename = btrfs_rename,
8690 .symlink = btrfs_symlink,
8691 .setattr = btrfs_setattr,
8692 .mknod = btrfs_mknod,
8693 .setxattr = btrfs_setxattr,
8694 .getxattr = btrfs_getxattr,
8695 .listxattr = btrfs_listxattr,
8696 .removexattr = btrfs_removexattr,
8697 .permission = btrfs_permission,
8698 .get_acl = btrfs_get_acl,
8700 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8701 .lookup = btrfs_lookup,
8702 .permission = btrfs_permission,
8703 .get_acl = btrfs_get_acl,
8706 static const struct file_operations btrfs_dir_file_operations = {
8707 .llseek = generic_file_llseek,
8708 .read = generic_read_dir,
8709 .readdir = btrfs_real_readdir,
8710 .unlocked_ioctl = btrfs_ioctl,
8711 #ifdef CONFIG_COMPAT
8712 .compat_ioctl = btrfs_ioctl,
8714 .release = btrfs_release_file,
8715 .fsync = btrfs_sync_file,
8718 static struct extent_io_ops btrfs_extent_io_ops = {
8719 .fill_delalloc = run_delalloc_range,
8720 .submit_bio_hook = btrfs_submit_bio_hook,
8721 .merge_bio_hook = btrfs_merge_bio_hook,
8722 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8723 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8724 .writepage_start_hook = btrfs_writepage_start_hook,
8725 .set_bit_hook = btrfs_set_bit_hook,
8726 .clear_bit_hook = btrfs_clear_bit_hook,
8727 .merge_extent_hook = btrfs_merge_extent_hook,
8728 .split_extent_hook = btrfs_split_extent_hook,
8732 * btrfs doesn't support the bmap operation because swapfiles
8733 * use bmap to make a mapping of extents in the file. They assume
8734 * these extents won't change over the life of the file and they
8735 * use the bmap result to do IO directly to the drive.
8737 * the btrfs bmap call would return logical addresses that aren't
8738 * suitable for IO and they also will change frequently as COW
8739 * operations happen. So, swapfile + btrfs == corruption.
8741 * For now we're avoiding this by dropping bmap.
8743 static const struct address_space_operations btrfs_aops = {
8744 .readpage = btrfs_readpage,
8745 .writepage = btrfs_writepage,
8746 .writepages = btrfs_writepages,
8747 .readpages = btrfs_readpages,
8748 .direct_IO = btrfs_direct_IO,
8749 .invalidatepage = btrfs_invalidatepage,
8750 .releasepage = btrfs_releasepage,
8751 .set_page_dirty = btrfs_set_page_dirty,
8752 .error_remove_page = generic_error_remove_page,
8755 static const struct address_space_operations btrfs_symlink_aops = {
8756 .readpage = btrfs_readpage,
8757 .writepage = btrfs_writepage,
8758 .invalidatepage = btrfs_invalidatepage,
8759 .releasepage = btrfs_releasepage,
8762 static const struct inode_operations btrfs_file_inode_operations = {
8763 .getattr = btrfs_getattr,
8764 .setattr = btrfs_setattr,
8765 .setxattr = btrfs_setxattr,
8766 .getxattr = btrfs_getxattr,
8767 .listxattr = btrfs_listxattr,
8768 .removexattr = btrfs_removexattr,
8769 .permission = btrfs_permission,
8770 .fiemap = btrfs_fiemap,
8771 .get_acl = btrfs_get_acl,
8772 .update_time = btrfs_update_time,
8774 static const struct inode_operations btrfs_special_inode_operations = {
8775 .getattr = btrfs_getattr,
8776 .setattr = btrfs_setattr,
8777 .permission = btrfs_permission,
8778 .setxattr = btrfs_setxattr,
8779 .getxattr = btrfs_getxattr,
8780 .listxattr = btrfs_listxattr,
8781 .removexattr = btrfs_removexattr,
8782 .get_acl = btrfs_get_acl,
8783 .update_time = btrfs_update_time,
8785 static const struct inode_operations btrfs_symlink_inode_operations = {
8786 .readlink = generic_readlink,
8787 .follow_link = page_follow_link_light,
8788 .put_link = page_put_link,
8789 .getattr = btrfs_getattr,
8790 .setattr = btrfs_setattr,
8791 .permission = btrfs_permission,
8792 .setxattr = btrfs_setxattr,
8793 .getxattr = btrfs_getxattr,
8794 .listxattr = btrfs_listxattr,
8795 .removexattr = btrfs_removexattr,
8796 .get_acl = btrfs_get_acl,
8797 .update_time = btrfs_update_time,
8800 const struct dentry_operations btrfs_dentry_operations = {
8801 .d_delete = btrfs_dentry_delete,
8802 .d_release = btrfs_dentry_release,