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/aio.h>
36 #include <linux/bit_spinlock.h>
37 #include <linux/xattr.h>
38 #include <linux/posix_acl.h>
39 #include <linux/falloc.h>
40 #include <linux/slab.h>
41 #include <linux/ratelimit.h>
42 #include <linux/mount.h>
43 #include <linux/btrfs.h>
44 #include <linux/blkdev.h>
45 #include <linux/posix_acl_xattr.h>
48 #include "transaction.h"
49 #include "btrfs_inode.h"
50 #include "print-tree.h"
51 #include "ordered-data.h"
55 #include "compression.h"
57 #include "free-space-cache.h"
58 #include "inode-map.h"
62 struct btrfs_iget_args {
64 struct btrfs_root *root;
67 static const struct inode_operations btrfs_dir_inode_operations;
68 static const struct inode_operations btrfs_symlink_inode_operations;
69 static const struct inode_operations btrfs_dir_ro_inode_operations;
70 static const struct inode_operations btrfs_special_inode_operations;
71 static const struct inode_operations btrfs_file_inode_operations;
72 static const struct address_space_operations btrfs_aops;
73 static const struct address_space_operations btrfs_symlink_aops;
74 static const struct file_operations btrfs_dir_file_operations;
75 static struct extent_io_ops btrfs_extent_io_ops;
77 static struct kmem_cache *btrfs_inode_cachep;
78 static struct kmem_cache *btrfs_delalloc_work_cachep;
79 struct kmem_cache *btrfs_trans_handle_cachep;
80 struct kmem_cache *btrfs_transaction_cachep;
81 struct kmem_cache *btrfs_path_cachep;
82 struct kmem_cache *btrfs_free_space_cachep;
85 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
86 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
87 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
88 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
89 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
90 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
91 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
92 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
95 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
96 static int btrfs_truncate(struct inode *inode);
97 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
98 static noinline int cow_file_range(struct inode *inode,
99 struct page *locked_page,
100 u64 start, u64 end, int *page_started,
101 unsigned long *nr_written, int unlock);
102 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
103 u64 len, u64 orig_start,
104 u64 block_start, u64 block_len,
105 u64 orig_block_len, u64 ram_bytes,
108 static int btrfs_dirty_inode(struct inode *inode);
110 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
111 struct inode *inode, struct inode *dir,
112 const struct qstr *qstr)
116 err = btrfs_init_acl(trans, inode, dir);
118 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
123 * this does all the hard work for inserting an inline extent into
124 * the btree. The caller should have done a btrfs_drop_extents so that
125 * no overlapping inline items exist in the btree
127 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
128 struct btrfs_path *path, int extent_inserted,
129 struct btrfs_root *root, struct inode *inode,
130 u64 start, size_t size, size_t compressed_size,
132 struct page **compressed_pages)
134 struct extent_buffer *leaf;
135 struct page *page = NULL;
138 struct btrfs_file_extent_item *ei;
141 size_t cur_size = size;
142 unsigned long offset;
144 if (compressed_size && compressed_pages)
145 cur_size = compressed_size;
147 inode_add_bytes(inode, size);
149 if (!extent_inserted) {
150 struct btrfs_key key;
153 key.objectid = btrfs_ino(inode);
155 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
157 datasize = btrfs_file_extent_calc_inline_size(cur_size);
158 path->leave_spinning = 1;
159 ret = btrfs_insert_empty_item(trans, root, path, &key,
166 leaf = path->nodes[0];
167 ei = btrfs_item_ptr(leaf, path->slots[0],
168 struct btrfs_file_extent_item);
169 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
170 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
171 btrfs_set_file_extent_encryption(leaf, ei, 0);
172 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
173 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
174 ptr = btrfs_file_extent_inline_start(ei);
176 if (compress_type != BTRFS_COMPRESS_NONE) {
179 while (compressed_size > 0) {
180 cpage = compressed_pages[i];
181 cur_size = min_t(unsigned long, compressed_size,
184 kaddr = kmap_atomic(cpage);
185 write_extent_buffer(leaf, kaddr, ptr, cur_size);
186 kunmap_atomic(kaddr);
190 compressed_size -= cur_size;
192 btrfs_set_file_extent_compression(leaf, ei,
195 page = find_get_page(inode->i_mapping,
196 start >> PAGE_CACHE_SHIFT);
197 btrfs_set_file_extent_compression(leaf, ei, 0);
198 kaddr = kmap_atomic(page);
199 offset = start & (PAGE_CACHE_SIZE - 1);
200 write_extent_buffer(leaf, kaddr + offset, ptr, size);
201 kunmap_atomic(kaddr);
202 page_cache_release(page);
204 btrfs_mark_buffer_dirty(leaf);
205 btrfs_release_path(path);
208 * we're an inline extent, so nobody can
209 * extend the file past i_size without locking
210 * a page we already have locked.
212 * We must do any isize and inode updates
213 * before we unlock the pages. Otherwise we
214 * could end up racing with unlink.
216 BTRFS_I(inode)->disk_i_size = inode->i_size;
217 ret = btrfs_update_inode(trans, root, inode);
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_root *root,
231 struct inode *inode, u64 start,
232 u64 end, size_t compressed_size,
234 struct page **compressed_pages)
236 struct btrfs_trans_handle *trans;
237 u64 isize = i_size_read(inode);
238 u64 actual_end = min(end + 1, isize);
239 u64 inline_len = actual_end - start;
240 u64 aligned_end = ALIGN(end, root->sectorsize);
241 u64 data_len = inline_len;
243 struct btrfs_path *path;
244 int extent_inserted = 0;
245 u32 extent_item_size;
248 data_len = compressed_size;
251 actual_end >= PAGE_CACHE_SIZE ||
252 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
254 (actual_end & (root->sectorsize - 1)) == 0) ||
256 data_len > root->fs_info->max_inline) {
260 path = btrfs_alloc_path();
264 trans = btrfs_join_transaction(root);
266 btrfs_free_path(path);
267 return PTR_ERR(trans);
269 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
271 if (compressed_size && compressed_pages)
272 extent_item_size = btrfs_file_extent_calc_inline_size(
275 extent_item_size = btrfs_file_extent_calc_inline_size(
278 ret = __btrfs_drop_extents(trans, root, inode, path,
279 start, aligned_end, NULL,
280 1, 1, extent_item_size, &extent_inserted);
282 btrfs_abort_transaction(trans, root, ret);
286 if (isize > actual_end)
287 inline_len = min_t(u64, isize, actual_end);
288 ret = insert_inline_extent(trans, path, extent_inserted,
290 inline_len, compressed_size,
291 compress_type, compressed_pages);
292 if (ret && ret != -ENOSPC) {
293 btrfs_abort_transaction(trans, root, ret);
295 } else if (ret == -ENOSPC) {
300 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
301 btrfs_delalloc_release_metadata(inode, end + 1 - start);
302 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
304 btrfs_free_path(path);
305 btrfs_end_transaction(trans, root);
309 struct async_extent {
314 unsigned long nr_pages;
316 struct list_head list;
321 struct btrfs_root *root;
322 struct page *locked_page;
325 struct list_head extents;
326 struct btrfs_work work;
329 static noinline int add_async_extent(struct async_cow *cow,
330 u64 start, u64 ram_size,
333 unsigned long nr_pages,
336 struct async_extent *async_extent;
338 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
339 BUG_ON(!async_extent); /* -ENOMEM */
340 async_extent->start = start;
341 async_extent->ram_size = ram_size;
342 async_extent->compressed_size = compressed_size;
343 async_extent->pages = pages;
344 async_extent->nr_pages = nr_pages;
345 async_extent->compress_type = compress_type;
346 list_add_tail(&async_extent->list, &cow->extents);
351 * we create compressed extents in two phases. The first
352 * phase compresses a range of pages that have already been
353 * locked (both pages and state bits are locked).
355 * This is done inside an ordered work queue, and the compression
356 * is spread across many cpus. The actual IO submission is step
357 * two, and the ordered work queue takes care of making sure that
358 * happens in the same order things were put onto the queue by
359 * writepages and friends.
361 * If this code finds it can't get good compression, it puts an
362 * entry onto the work queue to write the uncompressed bytes. This
363 * makes sure that both compressed inodes and uncompressed inodes
364 * are written in the same order that the flusher thread sent them
367 static noinline int compress_file_range(struct inode *inode,
368 struct page *locked_page,
370 struct async_cow *async_cow,
373 struct btrfs_root *root = BTRFS_I(inode)->root;
375 u64 blocksize = root->sectorsize;
377 u64 isize = i_size_read(inode);
379 struct page **pages = NULL;
380 unsigned long nr_pages;
381 unsigned long nr_pages_ret = 0;
382 unsigned long total_compressed = 0;
383 unsigned long total_in = 0;
384 unsigned long max_compressed = 128 * 1024;
385 unsigned long max_uncompressed = 128 * 1024;
388 int compress_type = root->fs_info->compress_type;
391 /* if this is a small write inside eof, kick off a defrag */
392 if ((end - start + 1) < 16 * 1024 &&
393 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
394 btrfs_add_inode_defrag(NULL, inode);
396 actual_end = min_t(u64, isize, end + 1);
399 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
400 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
403 * we don't want to send crud past the end of i_size through
404 * compression, that's just a waste of CPU time. So, if the
405 * end of the file is before the start of our current
406 * requested range of bytes, we bail out to the uncompressed
407 * cleanup code that can deal with all of this.
409 * It isn't really the fastest way to fix things, but this is a
410 * very uncommon corner.
412 if (actual_end <= start)
413 goto cleanup_and_bail_uncompressed;
415 total_compressed = actual_end - start;
417 /* we want to make sure that amount of ram required to uncompress
418 * an extent is reasonable, so we limit the total size in ram
419 * of a compressed extent to 128k. This is a crucial number
420 * because it also controls how easily we can spread reads across
421 * cpus for decompression.
423 * We also want to make sure the amount of IO required to do
424 * a random read is reasonably small, so we limit the size of
425 * a compressed extent to 128k.
427 total_compressed = min(total_compressed, max_uncompressed);
428 num_bytes = ALIGN(end - start + 1, blocksize);
429 num_bytes = max(blocksize, num_bytes);
434 * we do compression for mount -o compress and when the
435 * inode has not been flagged as nocompress. This flag can
436 * change at any time if we discover bad compression ratios.
438 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
439 (btrfs_test_opt(root, COMPRESS) ||
440 (BTRFS_I(inode)->force_compress) ||
441 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
443 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
445 /* just bail out to the uncompressed code */
449 if (BTRFS_I(inode)->force_compress)
450 compress_type = BTRFS_I(inode)->force_compress;
453 * we need to call clear_page_dirty_for_io on each
454 * page in the range. Otherwise applications with the file
455 * mmap'd can wander in and change the page contents while
456 * we are compressing them.
458 * If the compression fails for any reason, we set the pages
459 * dirty again later on.
461 extent_range_clear_dirty_for_io(inode, start, end);
463 ret = btrfs_compress_pages(compress_type,
464 inode->i_mapping, start,
465 total_compressed, pages,
466 nr_pages, &nr_pages_ret,
472 unsigned long offset = total_compressed &
473 (PAGE_CACHE_SIZE - 1);
474 struct page *page = pages[nr_pages_ret - 1];
477 /* zero the tail end of the last page, we might be
478 * sending it down to disk
481 kaddr = kmap_atomic(page);
482 memset(kaddr + offset, 0,
483 PAGE_CACHE_SIZE - offset);
484 kunmap_atomic(kaddr);
491 /* lets try to make an inline extent */
492 if (ret || total_in < (actual_end - start)) {
493 /* we didn't compress the entire range, try
494 * to make an uncompressed inline extent.
496 ret = cow_file_range_inline(root, inode, start, end,
499 /* try making a compressed inline extent */
500 ret = cow_file_range_inline(root, inode, start, end,
502 compress_type, pages);
505 unsigned long clear_flags = EXTENT_DELALLOC |
507 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
510 * inline extent creation worked or returned error,
511 * we don't need to create any more async work items.
512 * Unlock and free up our temp pages.
514 extent_clear_unlock_delalloc(inode, start, end, NULL,
515 clear_flags, PAGE_UNLOCK |
525 * we aren't doing an inline extent round the compressed size
526 * up to a block size boundary so the allocator does sane
529 total_compressed = ALIGN(total_compressed, blocksize);
532 * one last check to make sure the compression is really a
533 * win, compare the page count read with the blocks on disk
535 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
536 if (total_compressed >= total_in) {
539 num_bytes = total_in;
542 if (!will_compress && pages) {
544 * the compression code ran but failed to make things smaller,
545 * free any pages it allocated and our page pointer array
547 for (i = 0; i < nr_pages_ret; i++) {
548 WARN_ON(pages[i]->mapping);
549 page_cache_release(pages[i]);
553 total_compressed = 0;
556 /* flag the file so we don't compress in the future */
557 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
558 !(BTRFS_I(inode)->force_compress)) {
559 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
565 /* the async work queues will take care of doing actual
566 * allocation on disk for these compressed pages,
567 * and will submit them to the elevator.
569 add_async_extent(async_cow, start, num_bytes,
570 total_compressed, pages, nr_pages_ret,
573 if (start + num_bytes < end) {
580 cleanup_and_bail_uncompressed:
582 * No compression, but we still need to write the pages in
583 * the file we've been given so far. redirty the locked
584 * page if it corresponds to our extent and set things up
585 * for the async work queue to run cow_file_range to do
586 * the normal delalloc dance
588 if (page_offset(locked_page) >= start &&
589 page_offset(locked_page) <= end) {
590 __set_page_dirty_nobuffers(locked_page);
591 /* unlocked later on in the async handlers */
594 extent_range_redirty_for_io(inode, start, end);
595 add_async_extent(async_cow, start, end - start + 1,
596 0, NULL, 0, BTRFS_COMPRESS_NONE);
604 for (i = 0; i < nr_pages_ret; i++) {
605 WARN_ON(pages[i]->mapping);
606 page_cache_release(pages[i]);
614 * phase two of compressed writeback. This is the ordered portion
615 * of the code, which only gets called in the order the work was
616 * queued. We walk all the async extents created by compress_file_range
617 * and send them down to the disk.
619 static noinline int submit_compressed_extents(struct inode *inode,
620 struct async_cow *async_cow)
622 struct async_extent *async_extent;
624 struct btrfs_key ins;
625 struct extent_map *em;
626 struct btrfs_root *root = BTRFS_I(inode)->root;
627 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
628 struct extent_io_tree *io_tree;
631 if (list_empty(&async_cow->extents))
635 while (!list_empty(&async_cow->extents)) {
636 async_extent = list_entry(async_cow->extents.next,
637 struct async_extent, list);
638 list_del(&async_extent->list);
640 io_tree = &BTRFS_I(inode)->io_tree;
643 /* did the compression code fall back to uncompressed IO? */
644 if (!async_extent->pages) {
645 int page_started = 0;
646 unsigned long nr_written = 0;
648 lock_extent(io_tree, async_extent->start,
649 async_extent->start +
650 async_extent->ram_size - 1);
652 /* allocate blocks */
653 ret = cow_file_range(inode, async_cow->locked_page,
655 async_extent->start +
656 async_extent->ram_size - 1,
657 &page_started, &nr_written, 0);
662 * if page_started, cow_file_range inserted an
663 * inline extent and took care of all the unlocking
664 * and IO for us. Otherwise, we need to submit
665 * all those pages down to the drive.
667 if (!page_started && !ret)
668 extent_write_locked_range(io_tree,
669 inode, async_extent->start,
670 async_extent->start +
671 async_extent->ram_size - 1,
675 unlock_page(async_cow->locked_page);
681 lock_extent(io_tree, async_extent->start,
682 async_extent->start + async_extent->ram_size - 1);
684 ret = btrfs_reserve_extent(root,
685 async_extent->compressed_size,
686 async_extent->compressed_size,
687 0, alloc_hint, &ins, 1);
691 for (i = 0; i < async_extent->nr_pages; i++) {
692 WARN_ON(async_extent->pages[i]->mapping);
693 page_cache_release(async_extent->pages[i]);
695 kfree(async_extent->pages);
696 async_extent->nr_pages = 0;
697 async_extent->pages = NULL;
699 if (ret == -ENOSPC) {
700 unlock_extent(io_tree, async_extent->start,
701 async_extent->start +
702 async_extent->ram_size - 1);
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, async_extent->start,
767 async_extent->start +
768 async_extent->ram_size - 1,
769 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
770 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
772 ret = btrfs_submit_compressed_write(inode,
774 async_extent->ram_size,
776 ins.offset, async_extent->pages,
777 async_extent->nr_pages);
778 alloc_hint = ins.objectid + ins.offset;
788 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
790 extent_clear_unlock_delalloc(inode, async_extent->start,
791 async_extent->start +
792 async_extent->ram_size - 1,
793 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
794 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
795 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
796 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
801 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
804 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
805 struct extent_map *em;
808 read_lock(&em_tree->lock);
809 em = search_extent_mapping(em_tree, start, num_bytes);
812 * if block start isn't an actual block number then find the
813 * first block in this inode and use that as a hint. If that
814 * block is also bogus then just don't worry about it.
816 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
818 em = search_extent_mapping(em_tree, 0, 0);
819 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
820 alloc_hint = em->block_start;
824 alloc_hint = em->block_start;
828 read_unlock(&em_tree->lock);
834 * when extent_io.c finds a delayed allocation range in the file,
835 * the call backs end up in this code. The basic idea is to
836 * allocate extents on disk for the range, and create ordered data structs
837 * in ram to track those extents.
839 * locked_page is the page that writepage had locked already. We use
840 * it to make sure we don't do extra locks or unlocks.
842 * *page_started is set to one if we unlock locked_page and do everything
843 * required to start IO on it. It may be clean and already done with
846 static noinline int cow_file_range(struct inode *inode,
847 struct page *locked_page,
848 u64 start, u64 end, int *page_started,
849 unsigned long *nr_written,
852 struct btrfs_root *root = BTRFS_I(inode)->root;
855 unsigned long ram_size;
858 u64 blocksize = root->sectorsize;
859 struct btrfs_key ins;
860 struct extent_map *em;
861 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
864 if (btrfs_is_free_space_inode(inode)) {
869 num_bytes = ALIGN(end - start + 1, blocksize);
870 num_bytes = max(blocksize, num_bytes);
871 disk_num_bytes = num_bytes;
873 /* if this is a small write inside eof, kick off defrag */
874 if (num_bytes < 64 * 1024 &&
875 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
876 btrfs_add_inode_defrag(NULL, inode);
879 /* lets try to make an inline extent */
880 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
883 extent_clear_unlock_delalloc(inode, start, end, NULL,
884 EXTENT_LOCKED | EXTENT_DELALLOC |
885 EXTENT_DEFRAG, PAGE_UNLOCK |
886 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
889 *nr_written = *nr_written +
890 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
893 } else if (ret < 0) {
898 BUG_ON(disk_num_bytes >
899 btrfs_super_total_bytes(root->fs_info->super_copy));
901 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
902 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
904 while (disk_num_bytes > 0) {
907 cur_alloc_size = disk_num_bytes;
908 ret = btrfs_reserve_extent(root, cur_alloc_size,
909 root->sectorsize, 0, alloc_hint,
914 em = alloc_extent_map();
920 em->orig_start = em->start;
921 ram_size = ins.offset;
922 em->len = ins.offset;
923 em->mod_start = em->start;
924 em->mod_len = em->len;
926 em->block_start = ins.objectid;
927 em->block_len = ins.offset;
928 em->orig_block_len = ins.offset;
929 em->ram_bytes = ram_size;
930 em->bdev = root->fs_info->fs_devices->latest_bdev;
931 set_bit(EXTENT_FLAG_PINNED, &em->flags);
935 write_lock(&em_tree->lock);
936 ret = add_extent_mapping(em_tree, em, 1);
937 write_unlock(&em_tree->lock);
938 if (ret != -EEXIST) {
942 btrfs_drop_extent_cache(inode, start,
943 start + ram_size - 1, 0);
948 cur_alloc_size = ins.offset;
949 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
950 ram_size, cur_alloc_size, 0);
954 if (root->root_key.objectid ==
955 BTRFS_DATA_RELOC_TREE_OBJECTID) {
956 ret = btrfs_reloc_clone_csums(inode, start,
962 if (disk_num_bytes < cur_alloc_size)
965 /* we're not doing compressed IO, don't unlock the first
966 * page (which the caller expects to stay locked), don't
967 * clear any dirty bits and don't set any writeback bits
969 * Do set the Private2 bit so we know this page was properly
970 * setup for writepage
972 op = unlock ? PAGE_UNLOCK : 0;
973 op |= PAGE_SET_PRIVATE2;
975 extent_clear_unlock_delalloc(inode, start,
976 start + ram_size - 1, locked_page,
977 EXTENT_LOCKED | EXTENT_DELALLOC,
979 disk_num_bytes -= cur_alloc_size;
980 num_bytes -= cur_alloc_size;
981 alloc_hint = ins.objectid + ins.offset;
982 start += cur_alloc_size;
988 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
990 extent_clear_unlock_delalloc(inode, start, end, locked_page,
991 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
992 EXTENT_DELALLOC | EXTENT_DEFRAG,
993 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
994 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
999 * work queue call back to started compression on a file and pages
1001 static noinline void async_cow_start(struct btrfs_work *work)
1003 struct async_cow *async_cow;
1005 async_cow = container_of(work, struct async_cow, work);
1007 compress_file_range(async_cow->inode, async_cow->locked_page,
1008 async_cow->start, async_cow->end, async_cow,
1010 if (num_added == 0) {
1011 btrfs_add_delayed_iput(async_cow->inode);
1012 async_cow->inode = NULL;
1017 * work queue call back to submit previously compressed pages
1019 static noinline void async_cow_submit(struct btrfs_work *work)
1021 struct async_cow *async_cow;
1022 struct btrfs_root *root;
1023 unsigned long nr_pages;
1025 async_cow = container_of(work, struct async_cow, work);
1027 root = async_cow->root;
1028 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1031 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1033 waitqueue_active(&root->fs_info->async_submit_wait))
1034 wake_up(&root->fs_info->async_submit_wait);
1036 if (async_cow->inode)
1037 submit_compressed_extents(async_cow->inode, async_cow);
1040 static noinline void async_cow_free(struct btrfs_work *work)
1042 struct async_cow *async_cow;
1043 async_cow = container_of(work, struct async_cow, work);
1044 if (async_cow->inode)
1045 btrfs_add_delayed_iput(async_cow->inode);
1049 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1050 u64 start, u64 end, int *page_started,
1051 unsigned long *nr_written)
1053 struct async_cow *async_cow;
1054 struct btrfs_root *root = BTRFS_I(inode)->root;
1055 unsigned long nr_pages;
1057 int limit = 10 * 1024 * 1024;
1059 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1060 1, 0, NULL, GFP_NOFS);
1061 while (start < end) {
1062 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1063 BUG_ON(!async_cow); /* -ENOMEM */
1064 async_cow->inode = igrab(inode);
1065 async_cow->root = root;
1066 async_cow->locked_page = locked_page;
1067 async_cow->start = start;
1069 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1072 cur_end = min(end, start + 512 * 1024 - 1);
1074 async_cow->end = cur_end;
1075 INIT_LIST_HEAD(&async_cow->extents);
1077 async_cow->work.func = async_cow_start;
1078 async_cow->work.ordered_func = async_cow_submit;
1079 async_cow->work.ordered_free = async_cow_free;
1080 async_cow->work.flags = 0;
1082 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1084 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1086 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1089 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1090 wait_event(root->fs_info->async_submit_wait,
1091 (atomic_read(&root->fs_info->async_delalloc_pages) <
1095 while (atomic_read(&root->fs_info->async_submit_draining) &&
1096 atomic_read(&root->fs_info->async_delalloc_pages)) {
1097 wait_event(root->fs_info->async_submit_wait,
1098 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1102 *nr_written += nr_pages;
1103 start = cur_end + 1;
1109 static noinline int csum_exist_in_range(struct btrfs_root *root,
1110 u64 bytenr, u64 num_bytes)
1113 struct btrfs_ordered_sum *sums;
1116 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1117 bytenr + num_bytes - 1, &list, 0);
1118 if (ret == 0 && list_empty(&list))
1121 while (!list_empty(&list)) {
1122 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1123 list_del(&sums->list);
1130 * when nowcow writeback call back. This checks for snapshots or COW copies
1131 * of the extents that exist in the file, and COWs the file as required.
1133 * If no cow copies or snapshots exist, we write directly to the existing
1136 static noinline int run_delalloc_nocow(struct inode *inode,
1137 struct page *locked_page,
1138 u64 start, u64 end, int *page_started, int force,
1139 unsigned long *nr_written)
1141 struct btrfs_root *root = BTRFS_I(inode)->root;
1142 struct btrfs_trans_handle *trans;
1143 struct extent_buffer *leaf;
1144 struct btrfs_path *path;
1145 struct btrfs_file_extent_item *fi;
1146 struct btrfs_key found_key;
1161 u64 ino = btrfs_ino(inode);
1163 path = btrfs_alloc_path();
1165 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1166 EXTENT_LOCKED | EXTENT_DELALLOC |
1167 EXTENT_DO_ACCOUNTING |
1168 EXTENT_DEFRAG, PAGE_UNLOCK |
1170 PAGE_SET_WRITEBACK |
1171 PAGE_END_WRITEBACK);
1175 nolock = btrfs_is_free_space_inode(inode);
1178 trans = btrfs_join_transaction_nolock(root);
1180 trans = btrfs_join_transaction(root);
1182 if (IS_ERR(trans)) {
1183 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1184 EXTENT_LOCKED | EXTENT_DELALLOC |
1185 EXTENT_DO_ACCOUNTING |
1186 EXTENT_DEFRAG, PAGE_UNLOCK |
1188 PAGE_SET_WRITEBACK |
1189 PAGE_END_WRITEBACK);
1190 btrfs_free_path(path);
1191 return PTR_ERR(trans);
1194 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1196 cow_start = (u64)-1;
1199 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1203 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1204 leaf = path->nodes[0];
1205 btrfs_item_key_to_cpu(leaf, &found_key,
1206 path->slots[0] - 1);
1207 if (found_key.objectid == ino &&
1208 found_key.type == BTRFS_EXTENT_DATA_KEY)
1213 leaf = path->nodes[0];
1214 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1215 ret = btrfs_next_leaf(root, path);
1220 leaf = path->nodes[0];
1226 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1228 if (found_key.objectid > ino ||
1229 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1230 found_key.offset > end)
1233 if (found_key.offset > cur_offset) {
1234 extent_end = found_key.offset;
1239 fi = btrfs_item_ptr(leaf, path->slots[0],
1240 struct btrfs_file_extent_item);
1241 extent_type = btrfs_file_extent_type(leaf, fi);
1243 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1244 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1245 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1246 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1247 extent_offset = btrfs_file_extent_offset(leaf, fi);
1248 extent_end = found_key.offset +
1249 btrfs_file_extent_num_bytes(leaf, fi);
1251 btrfs_file_extent_disk_num_bytes(leaf, fi);
1252 if (extent_end <= start) {
1256 if (disk_bytenr == 0)
1258 if (btrfs_file_extent_compression(leaf, fi) ||
1259 btrfs_file_extent_encryption(leaf, fi) ||
1260 btrfs_file_extent_other_encoding(leaf, fi))
1262 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1264 if (btrfs_extent_readonly(root, disk_bytenr))
1266 if (btrfs_cross_ref_exist(trans, root, ino,
1268 extent_offset, disk_bytenr))
1270 disk_bytenr += extent_offset;
1271 disk_bytenr += cur_offset - found_key.offset;
1272 num_bytes = min(end + 1, extent_end) - cur_offset;
1274 * force cow if csum exists in the range.
1275 * this ensure that csum for a given extent are
1276 * either valid or do not exist.
1278 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1281 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1282 extent_end = found_key.offset +
1283 btrfs_file_extent_inline_len(leaf, fi);
1284 extent_end = ALIGN(extent_end, root->sectorsize);
1289 if (extent_end <= start) {
1294 if (cow_start == (u64)-1)
1295 cow_start = cur_offset;
1296 cur_offset = extent_end;
1297 if (cur_offset > end)
1303 btrfs_release_path(path);
1304 if (cow_start != (u64)-1) {
1305 ret = cow_file_range(inode, locked_page,
1306 cow_start, found_key.offset - 1,
1307 page_started, nr_written, 1);
1310 cow_start = (u64)-1;
1313 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1314 struct extent_map *em;
1315 struct extent_map_tree *em_tree;
1316 em_tree = &BTRFS_I(inode)->extent_tree;
1317 em = alloc_extent_map();
1318 BUG_ON(!em); /* -ENOMEM */
1319 em->start = cur_offset;
1320 em->orig_start = found_key.offset - extent_offset;
1321 em->len = num_bytes;
1322 em->block_len = num_bytes;
1323 em->block_start = disk_bytenr;
1324 em->orig_block_len = disk_num_bytes;
1325 em->ram_bytes = ram_bytes;
1326 em->bdev = root->fs_info->fs_devices->latest_bdev;
1327 em->mod_start = em->start;
1328 em->mod_len = em->len;
1329 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1330 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1331 em->generation = -1;
1333 write_lock(&em_tree->lock);
1334 ret = add_extent_mapping(em_tree, em, 1);
1335 write_unlock(&em_tree->lock);
1336 if (ret != -EEXIST) {
1337 free_extent_map(em);
1340 btrfs_drop_extent_cache(inode, em->start,
1341 em->start + em->len - 1, 0);
1343 type = BTRFS_ORDERED_PREALLOC;
1345 type = BTRFS_ORDERED_NOCOW;
1348 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1349 num_bytes, num_bytes, type);
1350 BUG_ON(ret); /* -ENOMEM */
1352 if (root->root_key.objectid ==
1353 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1354 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1360 extent_clear_unlock_delalloc(inode, cur_offset,
1361 cur_offset + num_bytes - 1,
1362 locked_page, EXTENT_LOCKED |
1363 EXTENT_DELALLOC, PAGE_UNLOCK |
1365 cur_offset = extent_end;
1366 if (cur_offset > end)
1369 btrfs_release_path(path);
1371 if (cur_offset <= end && cow_start == (u64)-1) {
1372 cow_start = cur_offset;
1376 if (cow_start != (u64)-1) {
1377 ret = cow_file_range(inode, locked_page, cow_start, end,
1378 page_started, nr_written, 1);
1384 err = btrfs_end_transaction(trans, root);
1388 if (ret && cur_offset < end)
1389 extent_clear_unlock_delalloc(inode, cur_offset, end,
1390 locked_page, EXTENT_LOCKED |
1391 EXTENT_DELALLOC | EXTENT_DEFRAG |
1392 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1394 PAGE_SET_WRITEBACK |
1395 PAGE_END_WRITEBACK);
1396 btrfs_free_path(path);
1401 * extent_io.c call back to do delayed allocation processing
1403 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1404 u64 start, u64 end, int *page_started,
1405 unsigned long *nr_written)
1408 struct btrfs_root *root = BTRFS_I(inode)->root;
1410 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1411 ret = run_delalloc_nocow(inode, locked_page, start, end,
1412 page_started, 1, nr_written);
1413 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1414 ret = run_delalloc_nocow(inode, locked_page, start, end,
1415 page_started, 0, nr_written);
1416 } else if (!btrfs_test_opt(root, COMPRESS) &&
1417 !(BTRFS_I(inode)->force_compress) &&
1418 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1419 ret = cow_file_range(inode, locked_page, start, end,
1420 page_started, nr_written, 1);
1422 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1423 &BTRFS_I(inode)->runtime_flags);
1424 ret = cow_file_range_async(inode, locked_page, start, end,
1425 page_started, nr_written);
1430 static void btrfs_split_extent_hook(struct inode *inode,
1431 struct extent_state *orig, u64 split)
1433 /* not delalloc, ignore it */
1434 if (!(orig->state & EXTENT_DELALLOC))
1437 spin_lock(&BTRFS_I(inode)->lock);
1438 BTRFS_I(inode)->outstanding_extents++;
1439 spin_unlock(&BTRFS_I(inode)->lock);
1443 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1444 * extents so we can keep track of new extents that are just merged onto old
1445 * extents, such as when we are doing sequential writes, so we can properly
1446 * account for the metadata space we'll need.
1448 static void btrfs_merge_extent_hook(struct inode *inode,
1449 struct extent_state *new,
1450 struct extent_state *other)
1452 /* not delalloc, ignore it */
1453 if (!(other->state & EXTENT_DELALLOC))
1456 spin_lock(&BTRFS_I(inode)->lock);
1457 BTRFS_I(inode)->outstanding_extents--;
1458 spin_unlock(&BTRFS_I(inode)->lock);
1461 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1462 struct inode *inode)
1464 spin_lock(&root->delalloc_lock);
1465 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1466 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1467 &root->delalloc_inodes);
1468 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1469 &BTRFS_I(inode)->runtime_flags);
1470 root->nr_delalloc_inodes++;
1471 if (root->nr_delalloc_inodes == 1) {
1472 spin_lock(&root->fs_info->delalloc_root_lock);
1473 BUG_ON(!list_empty(&root->delalloc_root));
1474 list_add_tail(&root->delalloc_root,
1475 &root->fs_info->delalloc_roots);
1476 spin_unlock(&root->fs_info->delalloc_root_lock);
1479 spin_unlock(&root->delalloc_lock);
1482 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1483 struct inode *inode)
1485 spin_lock(&root->delalloc_lock);
1486 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1487 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1488 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1489 &BTRFS_I(inode)->runtime_flags);
1490 root->nr_delalloc_inodes--;
1491 if (!root->nr_delalloc_inodes) {
1492 spin_lock(&root->fs_info->delalloc_root_lock);
1493 BUG_ON(list_empty(&root->delalloc_root));
1494 list_del_init(&root->delalloc_root);
1495 spin_unlock(&root->fs_info->delalloc_root_lock);
1498 spin_unlock(&root->delalloc_lock);
1502 * extent_io.c set_bit_hook, used to track delayed allocation
1503 * bytes in this file, and to maintain the list of inodes that
1504 * have pending delalloc work to be done.
1506 static void btrfs_set_bit_hook(struct inode *inode,
1507 struct extent_state *state, unsigned long *bits)
1511 * set_bit and clear bit hooks normally require _irqsave/restore
1512 * but in this case, we are only testing for the DELALLOC
1513 * bit, which is only set or cleared with irqs on
1515 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1516 struct btrfs_root *root = BTRFS_I(inode)->root;
1517 u64 len = state->end + 1 - state->start;
1518 bool do_list = !btrfs_is_free_space_inode(inode);
1520 if (*bits & EXTENT_FIRST_DELALLOC) {
1521 *bits &= ~EXTENT_FIRST_DELALLOC;
1523 spin_lock(&BTRFS_I(inode)->lock);
1524 BTRFS_I(inode)->outstanding_extents++;
1525 spin_unlock(&BTRFS_I(inode)->lock);
1528 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1529 root->fs_info->delalloc_batch);
1530 spin_lock(&BTRFS_I(inode)->lock);
1531 BTRFS_I(inode)->delalloc_bytes += len;
1532 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1533 &BTRFS_I(inode)->runtime_flags))
1534 btrfs_add_delalloc_inodes(root, inode);
1535 spin_unlock(&BTRFS_I(inode)->lock);
1540 * extent_io.c clear_bit_hook, see set_bit_hook for why
1542 static void btrfs_clear_bit_hook(struct inode *inode,
1543 struct extent_state *state,
1544 unsigned long *bits)
1547 * set_bit and clear bit hooks normally require _irqsave/restore
1548 * but in this case, we are only testing for the DELALLOC
1549 * bit, which is only set or cleared with irqs on
1551 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1552 struct btrfs_root *root = BTRFS_I(inode)->root;
1553 u64 len = state->end + 1 - state->start;
1554 bool do_list = !btrfs_is_free_space_inode(inode);
1556 if (*bits & EXTENT_FIRST_DELALLOC) {
1557 *bits &= ~EXTENT_FIRST_DELALLOC;
1558 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1559 spin_lock(&BTRFS_I(inode)->lock);
1560 BTRFS_I(inode)->outstanding_extents--;
1561 spin_unlock(&BTRFS_I(inode)->lock);
1565 * We don't reserve metadata space for space cache inodes so we
1566 * don't need to call dellalloc_release_metadata if there is an
1569 if (*bits & EXTENT_DO_ACCOUNTING &&
1570 root != root->fs_info->tree_root)
1571 btrfs_delalloc_release_metadata(inode, len);
1573 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1574 && do_list && !(state->state & EXTENT_NORESERVE))
1575 btrfs_free_reserved_data_space(inode, len);
1577 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1578 root->fs_info->delalloc_batch);
1579 spin_lock(&BTRFS_I(inode)->lock);
1580 BTRFS_I(inode)->delalloc_bytes -= len;
1581 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1582 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1583 &BTRFS_I(inode)->runtime_flags))
1584 btrfs_del_delalloc_inode(root, inode);
1585 spin_unlock(&BTRFS_I(inode)->lock);
1590 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1591 * we don't create bios that span stripes or chunks
1593 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1594 size_t size, struct bio *bio,
1595 unsigned long bio_flags)
1597 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1598 u64 logical = (u64)bio->bi_sector << 9;
1603 if (bio_flags & EXTENT_BIO_COMPRESSED)
1606 length = bio->bi_size;
1607 map_length = length;
1608 ret = btrfs_map_block(root->fs_info, rw, logical,
1609 &map_length, NULL, 0);
1610 /* Will always return 0 with map_multi == NULL */
1612 if (map_length < length + size)
1618 * in order to insert checksums into the metadata in large chunks,
1619 * we wait until bio submission time. All the pages in the bio are
1620 * checksummed and sums are attached onto the ordered extent record.
1622 * At IO completion time the cums attached on the ordered extent record
1623 * are inserted into the btree
1625 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1626 struct bio *bio, int mirror_num,
1627 unsigned long bio_flags,
1630 struct btrfs_root *root = BTRFS_I(inode)->root;
1633 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1634 BUG_ON(ret); /* -ENOMEM */
1639 * in order to insert checksums into the metadata in large chunks,
1640 * we wait until bio submission time. All the pages in the bio are
1641 * checksummed and sums are attached onto the ordered extent record.
1643 * At IO completion time the cums attached on the ordered extent record
1644 * are inserted into the btree
1646 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1647 int mirror_num, unsigned long bio_flags,
1650 struct btrfs_root *root = BTRFS_I(inode)->root;
1653 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1655 bio_endio(bio, ret);
1660 * extent_io.c submission hook. This does the right thing for csum calculation
1661 * on write, or reading the csums from the tree before a read
1663 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1664 int mirror_num, unsigned long bio_flags,
1667 struct btrfs_root *root = BTRFS_I(inode)->root;
1671 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1673 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1675 if (btrfs_is_free_space_inode(inode))
1678 if (!(rw & REQ_WRITE)) {
1679 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1683 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1684 ret = btrfs_submit_compressed_read(inode, bio,
1688 } else if (!skip_sum) {
1689 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1694 } else if (async && !skip_sum) {
1695 /* csum items have already been cloned */
1696 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1698 /* we're doing a write, do the async checksumming */
1699 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1700 inode, rw, bio, mirror_num,
1701 bio_flags, bio_offset,
1702 __btrfs_submit_bio_start,
1703 __btrfs_submit_bio_done);
1705 } else if (!skip_sum) {
1706 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1712 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1716 bio_endio(bio, ret);
1721 * given a list of ordered sums record them in the inode. This happens
1722 * at IO completion time based on sums calculated at bio submission time.
1724 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1725 struct inode *inode, u64 file_offset,
1726 struct list_head *list)
1728 struct btrfs_ordered_sum *sum;
1730 list_for_each_entry(sum, list, list) {
1731 trans->adding_csums = 1;
1732 btrfs_csum_file_blocks(trans,
1733 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1734 trans->adding_csums = 0;
1739 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1740 struct extent_state **cached_state)
1742 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1743 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1744 cached_state, GFP_NOFS);
1747 /* see btrfs_writepage_start_hook for details on why this is required */
1748 struct btrfs_writepage_fixup {
1750 struct btrfs_work work;
1753 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1755 struct btrfs_writepage_fixup *fixup;
1756 struct btrfs_ordered_extent *ordered;
1757 struct extent_state *cached_state = NULL;
1759 struct inode *inode;
1764 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1768 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1769 ClearPageChecked(page);
1773 inode = page->mapping->host;
1774 page_start = page_offset(page);
1775 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1777 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1780 /* already ordered? We're done */
1781 if (PagePrivate2(page))
1784 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1786 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1787 page_end, &cached_state, GFP_NOFS);
1789 btrfs_start_ordered_extent(inode, ordered, 1);
1790 btrfs_put_ordered_extent(ordered);
1794 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1796 mapping_set_error(page->mapping, ret);
1797 end_extent_writepage(page, ret, page_start, page_end);
1798 ClearPageChecked(page);
1802 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1803 ClearPageChecked(page);
1804 set_page_dirty(page);
1806 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1807 &cached_state, GFP_NOFS);
1810 page_cache_release(page);
1815 * There are a few paths in the higher layers of the kernel that directly
1816 * set the page dirty bit without asking the filesystem if it is a
1817 * good idea. This causes problems because we want to make sure COW
1818 * properly happens and the data=ordered rules are followed.
1820 * In our case any range that doesn't have the ORDERED bit set
1821 * hasn't been properly setup for IO. We kick off an async process
1822 * to fix it up. The async helper will wait for ordered extents, set
1823 * the delalloc bit and make it safe to write the page.
1825 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1827 struct inode *inode = page->mapping->host;
1828 struct btrfs_writepage_fixup *fixup;
1829 struct btrfs_root *root = BTRFS_I(inode)->root;
1831 /* this page is properly in the ordered list */
1832 if (TestClearPagePrivate2(page))
1835 if (PageChecked(page))
1838 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1842 SetPageChecked(page);
1843 page_cache_get(page);
1844 fixup->work.func = btrfs_writepage_fixup_worker;
1846 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1850 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1851 struct inode *inode, u64 file_pos,
1852 u64 disk_bytenr, u64 disk_num_bytes,
1853 u64 num_bytes, u64 ram_bytes,
1854 u8 compression, u8 encryption,
1855 u16 other_encoding, int extent_type)
1857 struct btrfs_root *root = BTRFS_I(inode)->root;
1858 struct btrfs_file_extent_item *fi;
1859 struct btrfs_path *path;
1860 struct extent_buffer *leaf;
1861 struct btrfs_key ins;
1862 int extent_inserted = 0;
1865 path = btrfs_alloc_path();
1870 * we may be replacing one extent in the tree with another.
1871 * The new extent is pinned in the extent map, and we don't want
1872 * to drop it from the cache until it is completely in the btree.
1874 * So, tell btrfs_drop_extents to leave this extent in the cache.
1875 * the caller is expected to unpin it and allow it to be merged
1878 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
1879 file_pos + num_bytes, NULL, 0,
1880 1, sizeof(*fi), &extent_inserted);
1884 if (!extent_inserted) {
1885 ins.objectid = btrfs_ino(inode);
1886 ins.offset = file_pos;
1887 ins.type = BTRFS_EXTENT_DATA_KEY;
1889 path->leave_spinning = 1;
1890 ret = btrfs_insert_empty_item(trans, root, path, &ins,
1895 leaf = path->nodes[0];
1896 fi = btrfs_item_ptr(leaf, path->slots[0],
1897 struct btrfs_file_extent_item);
1898 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1899 btrfs_set_file_extent_type(leaf, fi, extent_type);
1900 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1901 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1902 btrfs_set_file_extent_offset(leaf, fi, 0);
1903 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1904 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1905 btrfs_set_file_extent_compression(leaf, fi, compression);
1906 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1907 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1909 btrfs_mark_buffer_dirty(leaf);
1910 btrfs_release_path(path);
1912 inode_add_bytes(inode, num_bytes);
1914 ins.objectid = disk_bytenr;
1915 ins.offset = disk_num_bytes;
1916 ins.type = BTRFS_EXTENT_ITEM_KEY;
1917 ret = btrfs_alloc_reserved_file_extent(trans, root,
1918 root->root_key.objectid,
1919 btrfs_ino(inode), file_pos, &ins);
1921 btrfs_free_path(path);
1926 /* snapshot-aware defrag */
1927 struct sa_defrag_extent_backref {
1928 struct rb_node node;
1929 struct old_sa_defrag_extent *old;
1938 struct old_sa_defrag_extent {
1939 struct list_head list;
1940 struct new_sa_defrag_extent *new;
1949 struct new_sa_defrag_extent {
1950 struct rb_root root;
1951 struct list_head head;
1952 struct btrfs_path *path;
1953 struct inode *inode;
1961 static int backref_comp(struct sa_defrag_extent_backref *b1,
1962 struct sa_defrag_extent_backref *b2)
1964 if (b1->root_id < b2->root_id)
1966 else if (b1->root_id > b2->root_id)
1969 if (b1->inum < b2->inum)
1971 else if (b1->inum > b2->inum)
1974 if (b1->file_pos < b2->file_pos)
1976 else if (b1->file_pos > b2->file_pos)
1980 * [------------------------------] ===> (a range of space)
1981 * |<--->| |<---->| =============> (fs/file tree A)
1982 * |<---------------------------->| ===> (fs/file tree B)
1984 * A range of space can refer to two file extents in one tree while
1985 * refer to only one file extent in another tree.
1987 * So we may process a disk offset more than one time(two extents in A)
1988 * and locate at the same extent(one extent in B), then insert two same
1989 * backrefs(both refer to the extent in B).
1994 static void backref_insert(struct rb_root *root,
1995 struct sa_defrag_extent_backref *backref)
1997 struct rb_node **p = &root->rb_node;
1998 struct rb_node *parent = NULL;
1999 struct sa_defrag_extent_backref *entry;
2004 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2006 ret = backref_comp(backref, entry);
2010 p = &(*p)->rb_right;
2013 rb_link_node(&backref->node, parent, p);
2014 rb_insert_color(&backref->node, root);
2018 * Note the backref might has changed, and in this case we just return 0.
2020 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2023 struct btrfs_file_extent_item *extent;
2024 struct btrfs_fs_info *fs_info;
2025 struct old_sa_defrag_extent *old = ctx;
2026 struct new_sa_defrag_extent *new = old->new;
2027 struct btrfs_path *path = new->path;
2028 struct btrfs_key key;
2029 struct btrfs_root *root;
2030 struct sa_defrag_extent_backref *backref;
2031 struct extent_buffer *leaf;
2032 struct inode *inode = new->inode;
2038 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2039 inum == btrfs_ino(inode))
2042 key.objectid = root_id;
2043 key.type = BTRFS_ROOT_ITEM_KEY;
2044 key.offset = (u64)-1;
2046 fs_info = BTRFS_I(inode)->root->fs_info;
2047 root = btrfs_read_fs_root_no_name(fs_info, &key);
2049 if (PTR_ERR(root) == -ENOENT)
2052 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2053 inum, offset, root_id);
2054 return PTR_ERR(root);
2057 key.objectid = inum;
2058 key.type = BTRFS_EXTENT_DATA_KEY;
2059 if (offset > (u64)-1 << 32)
2062 key.offset = offset;
2064 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2065 if (WARN_ON(ret < 0))
2072 leaf = path->nodes[0];
2073 slot = path->slots[0];
2075 if (slot >= btrfs_header_nritems(leaf)) {
2076 ret = btrfs_next_leaf(root, path);
2079 } else if (ret > 0) {
2088 btrfs_item_key_to_cpu(leaf, &key, slot);
2090 if (key.objectid > inum)
2093 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2096 extent = btrfs_item_ptr(leaf, slot,
2097 struct btrfs_file_extent_item);
2099 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2103 * 'offset' refers to the exact key.offset,
2104 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2105 * (key.offset - extent_offset).
2107 if (key.offset != offset)
2110 extent_offset = btrfs_file_extent_offset(leaf, extent);
2111 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2113 if (extent_offset >= old->extent_offset + old->offset +
2114 old->len || extent_offset + num_bytes <=
2115 old->extent_offset + old->offset)
2120 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2126 backref->root_id = root_id;
2127 backref->inum = inum;
2128 backref->file_pos = offset;
2129 backref->num_bytes = num_bytes;
2130 backref->extent_offset = extent_offset;
2131 backref->generation = btrfs_file_extent_generation(leaf, extent);
2133 backref_insert(&new->root, backref);
2136 btrfs_release_path(path);
2141 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2142 struct new_sa_defrag_extent *new)
2144 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2145 struct old_sa_defrag_extent *old, *tmp;
2150 list_for_each_entry_safe(old, tmp, &new->head, list) {
2151 ret = iterate_inodes_from_logical(old->bytenr +
2152 old->extent_offset, fs_info,
2153 path, record_one_backref,
2155 if (ret < 0 && ret != -ENOENT)
2158 /* no backref to be processed for this extent */
2160 list_del(&old->list);
2165 if (list_empty(&new->head))
2171 static int relink_is_mergable(struct extent_buffer *leaf,
2172 struct btrfs_file_extent_item *fi,
2173 struct new_sa_defrag_extent *new)
2175 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2178 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2181 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2184 if (btrfs_file_extent_encryption(leaf, fi) ||
2185 btrfs_file_extent_other_encoding(leaf, fi))
2192 * Note the backref might has changed, and in this case we just return 0.
2194 static noinline int relink_extent_backref(struct btrfs_path *path,
2195 struct sa_defrag_extent_backref *prev,
2196 struct sa_defrag_extent_backref *backref)
2198 struct btrfs_file_extent_item *extent;
2199 struct btrfs_file_extent_item *item;
2200 struct btrfs_ordered_extent *ordered;
2201 struct btrfs_trans_handle *trans;
2202 struct btrfs_fs_info *fs_info;
2203 struct btrfs_root *root;
2204 struct btrfs_key key;
2205 struct extent_buffer *leaf;
2206 struct old_sa_defrag_extent *old = backref->old;
2207 struct new_sa_defrag_extent *new = old->new;
2208 struct inode *src_inode = new->inode;
2209 struct inode *inode;
2210 struct extent_state *cached = NULL;
2219 if (prev && prev->root_id == backref->root_id &&
2220 prev->inum == backref->inum &&
2221 prev->file_pos + prev->num_bytes == backref->file_pos)
2224 /* step 1: get root */
2225 key.objectid = backref->root_id;
2226 key.type = BTRFS_ROOT_ITEM_KEY;
2227 key.offset = (u64)-1;
2229 fs_info = BTRFS_I(src_inode)->root->fs_info;
2230 index = srcu_read_lock(&fs_info->subvol_srcu);
2232 root = btrfs_read_fs_root_no_name(fs_info, &key);
2234 srcu_read_unlock(&fs_info->subvol_srcu, index);
2235 if (PTR_ERR(root) == -ENOENT)
2237 return PTR_ERR(root);
2240 /* step 2: get inode */
2241 key.objectid = backref->inum;
2242 key.type = BTRFS_INODE_ITEM_KEY;
2245 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2246 if (IS_ERR(inode)) {
2247 srcu_read_unlock(&fs_info->subvol_srcu, index);
2251 srcu_read_unlock(&fs_info->subvol_srcu, index);
2253 /* step 3: relink backref */
2254 lock_start = backref->file_pos;
2255 lock_end = backref->file_pos + backref->num_bytes - 1;
2256 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2259 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2261 btrfs_put_ordered_extent(ordered);
2265 trans = btrfs_join_transaction(root);
2266 if (IS_ERR(trans)) {
2267 ret = PTR_ERR(trans);
2271 key.objectid = backref->inum;
2272 key.type = BTRFS_EXTENT_DATA_KEY;
2273 key.offset = backref->file_pos;
2275 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2278 } else if (ret > 0) {
2283 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2284 struct btrfs_file_extent_item);
2286 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2287 backref->generation)
2290 btrfs_release_path(path);
2292 start = backref->file_pos;
2293 if (backref->extent_offset < old->extent_offset + old->offset)
2294 start += old->extent_offset + old->offset -
2295 backref->extent_offset;
2297 len = min(backref->extent_offset + backref->num_bytes,
2298 old->extent_offset + old->offset + old->len);
2299 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2301 ret = btrfs_drop_extents(trans, root, inode, start,
2306 key.objectid = btrfs_ino(inode);
2307 key.type = BTRFS_EXTENT_DATA_KEY;
2310 path->leave_spinning = 1;
2312 struct btrfs_file_extent_item *fi;
2314 struct btrfs_key found_key;
2316 ret = btrfs_search_slot(trans, root, &key, path, 1, 1);
2321 leaf = path->nodes[0];
2322 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2324 fi = btrfs_item_ptr(leaf, path->slots[0],
2325 struct btrfs_file_extent_item);
2326 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2328 if (extent_len + found_key.offset == start &&
2329 relink_is_mergable(leaf, fi, new)) {
2330 btrfs_set_file_extent_num_bytes(leaf, fi,
2332 btrfs_mark_buffer_dirty(leaf);
2333 inode_add_bytes(inode, len);
2339 btrfs_release_path(path);
2344 ret = btrfs_insert_empty_item(trans, root, path, &key,
2347 btrfs_abort_transaction(trans, root, ret);
2351 leaf = path->nodes[0];
2352 item = btrfs_item_ptr(leaf, path->slots[0],
2353 struct btrfs_file_extent_item);
2354 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2355 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2356 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2357 btrfs_set_file_extent_num_bytes(leaf, item, len);
2358 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2359 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2360 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2361 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2362 btrfs_set_file_extent_encryption(leaf, item, 0);
2363 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2365 btrfs_mark_buffer_dirty(leaf);
2366 inode_add_bytes(inode, len);
2367 btrfs_release_path(path);
2369 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2371 backref->root_id, backref->inum,
2372 new->file_pos, 0); /* start - extent_offset */
2374 btrfs_abort_transaction(trans, root, ret);
2380 btrfs_release_path(path);
2381 path->leave_spinning = 0;
2382 btrfs_end_transaction(trans, root);
2384 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2390 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2392 struct old_sa_defrag_extent *old, *tmp;
2397 list_for_each_entry_safe(old, tmp, &new->head, list) {
2398 list_del(&old->list);
2404 static void relink_file_extents(struct new_sa_defrag_extent *new)
2406 struct btrfs_path *path;
2407 struct sa_defrag_extent_backref *backref;
2408 struct sa_defrag_extent_backref *prev = NULL;
2409 struct inode *inode;
2410 struct btrfs_root *root;
2411 struct rb_node *node;
2415 root = BTRFS_I(inode)->root;
2417 path = btrfs_alloc_path();
2421 if (!record_extent_backrefs(path, new)) {
2422 btrfs_free_path(path);
2425 btrfs_release_path(path);
2428 node = rb_first(&new->root);
2431 rb_erase(node, &new->root);
2433 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2435 ret = relink_extent_backref(path, prev, backref);
2448 btrfs_free_path(path);
2450 free_sa_defrag_extent(new);
2452 atomic_dec(&root->fs_info->defrag_running);
2453 wake_up(&root->fs_info->transaction_wait);
2456 static struct new_sa_defrag_extent *
2457 record_old_file_extents(struct inode *inode,
2458 struct btrfs_ordered_extent *ordered)
2460 struct btrfs_root *root = BTRFS_I(inode)->root;
2461 struct btrfs_path *path;
2462 struct btrfs_key key;
2463 struct old_sa_defrag_extent *old;
2464 struct new_sa_defrag_extent *new;
2467 new = kmalloc(sizeof(*new), GFP_NOFS);
2472 new->file_pos = ordered->file_offset;
2473 new->len = ordered->len;
2474 new->bytenr = ordered->start;
2475 new->disk_len = ordered->disk_len;
2476 new->compress_type = ordered->compress_type;
2477 new->root = RB_ROOT;
2478 INIT_LIST_HEAD(&new->head);
2480 path = btrfs_alloc_path();
2484 key.objectid = btrfs_ino(inode);
2485 key.type = BTRFS_EXTENT_DATA_KEY;
2486 key.offset = new->file_pos;
2488 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2491 if (ret > 0 && path->slots[0] > 0)
2494 /* find out all the old extents for the file range */
2496 struct btrfs_file_extent_item *extent;
2497 struct extent_buffer *l;
2506 slot = path->slots[0];
2508 if (slot >= btrfs_header_nritems(l)) {
2509 ret = btrfs_next_leaf(root, path);
2517 btrfs_item_key_to_cpu(l, &key, slot);
2519 if (key.objectid != btrfs_ino(inode))
2521 if (key.type != BTRFS_EXTENT_DATA_KEY)
2523 if (key.offset >= new->file_pos + new->len)
2526 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2528 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2529 if (key.offset + num_bytes < new->file_pos)
2532 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2536 extent_offset = btrfs_file_extent_offset(l, extent);
2538 old = kmalloc(sizeof(*old), GFP_NOFS);
2542 offset = max(new->file_pos, key.offset);
2543 end = min(new->file_pos + new->len, key.offset + num_bytes);
2545 old->bytenr = disk_bytenr;
2546 old->extent_offset = extent_offset;
2547 old->offset = offset - key.offset;
2548 old->len = end - offset;
2551 list_add_tail(&old->list, &new->head);
2557 btrfs_free_path(path);
2558 atomic_inc(&root->fs_info->defrag_running);
2563 btrfs_free_path(path);
2565 free_sa_defrag_extent(new);
2569 /* as ordered data IO finishes, this gets called so we can finish
2570 * an ordered extent if the range of bytes in the file it covers are
2573 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2575 struct inode *inode = ordered_extent->inode;
2576 struct btrfs_root *root = BTRFS_I(inode)->root;
2577 struct btrfs_trans_handle *trans = NULL;
2578 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2579 struct extent_state *cached_state = NULL;
2580 struct new_sa_defrag_extent *new = NULL;
2581 int compress_type = 0;
2583 u64 logical_len = ordered_extent->len;
2585 bool truncated = false;
2587 nolock = btrfs_is_free_space_inode(inode);
2589 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2594 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2596 logical_len = ordered_extent->truncated_len;
2597 /* Truncated the entire extent, don't bother adding */
2602 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2603 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2604 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2606 trans = btrfs_join_transaction_nolock(root);
2608 trans = btrfs_join_transaction(root);
2609 if (IS_ERR(trans)) {
2610 ret = PTR_ERR(trans);
2614 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2615 ret = btrfs_update_inode_fallback(trans, root, inode);
2616 if (ret) /* -ENOMEM or corruption */
2617 btrfs_abort_transaction(trans, root, ret);
2621 lock_extent_bits(io_tree, ordered_extent->file_offset,
2622 ordered_extent->file_offset + ordered_extent->len - 1,
2625 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2626 ordered_extent->file_offset + ordered_extent->len - 1,
2627 EXTENT_DEFRAG, 1, cached_state);
2629 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2630 if (last_snapshot >= BTRFS_I(inode)->generation)
2631 /* the inode is shared */
2632 new = record_old_file_extents(inode, ordered_extent);
2634 clear_extent_bit(io_tree, ordered_extent->file_offset,
2635 ordered_extent->file_offset + ordered_extent->len - 1,
2636 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2640 trans = btrfs_join_transaction_nolock(root);
2642 trans = btrfs_join_transaction(root);
2643 if (IS_ERR(trans)) {
2644 ret = PTR_ERR(trans);
2648 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2650 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2651 compress_type = ordered_extent->compress_type;
2652 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2653 BUG_ON(compress_type);
2654 ret = btrfs_mark_extent_written(trans, inode,
2655 ordered_extent->file_offset,
2656 ordered_extent->file_offset +
2659 BUG_ON(root == root->fs_info->tree_root);
2660 ret = insert_reserved_file_extent(trans, inode,
2661 ordered_extent->file_offset,
2662 ordered_extent->start,
2663 ordered_extent->disk_len,
2664 logical_len, logical_len,
2665 compress_type, 0, 0,
2666 BTRFS_FILE_EXTENT_REG);
2668 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2669 ordered_extent->file_offset, ordered_extent->len,
2672 btrfs_abort_transaction(trans, root, ret);
2676 add_pending_csums(trans, inode, ordered_extent->file_offset,
2677 &ordered_extent->list);
2679 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2680 ret = btrfs_update_inode_fallback(trans, root, inode);
2681 if (ret) { /* -ENOMEM or corruption */
2682 btrfs_abort_transaction(trans, root, ret);
2687 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2688 ordered_extent->file_offset +
2689 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2691 if (root != root->fs_info->tree_root)
2692 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2694 btrfs_end_transaction(trans, root);
2696 if (ret || truncated) {
2700 start = ordered_extent->file_offset + logical_len;
2702 start = ordered_extent->file_offset;
2703 end = ordered_extent->file_offset + ordered_extent->len - 1;
2704 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2706 /* Drop the cache for the part of the extent we didn't write. */
2707 btrfs_drop_extent_cache(inode, start, end, 0);
2710 * If the ordered extent had an IOERR or something else went
2711 * wrong we need to return the space for this ordered extent
2712 * back to the allocator. We only free the extent in the
2713 * truncated case if we didn't write out the extent at all.
2715 if ((ret || !logical_len) &&
2716 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2717 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2718 btrfs_free_reserved_extent(root, ordered_extent->start,
2719 ordered_extent->disk_len);
2724 * This needs to be done to make sure anybody waiting knows we are done
2725 * updating everything for this ordered extent.
2727 btrfs_remove_ordered_extent(inode, ordered_extent);
2729 /* for snapshot-aware defrag */
2732 free_sa_defrag_extent(new);
2733 atomic_dec(&root->fs_info->defrag_running);
2735 relink_file_extents(new);
2740 btrfs_put_ordered_extent(ordered_extent);
2741 /* once for the tree */
2742 btrfs_put_ordered_extent(ordered_extent);
2747 static void finish_ordered_fn(struct btrfs_work *work)
2749 struct btrfs_ordered_extent *ordered_extent;
2750 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2751 btrfs_finish_ordered_io(ordered_extent);
2754 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2755 struct extent_state *state, int uptodate)
2757 struct inode *inode = page->mapping->host;
2758 struct btrfs_root *root = BTRFS_I(inode)->root;
2759 struct btrfs_ordered_extent *ordered_extent = NULL;
2760 struct btrfs_workers *workers;
2762 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2764 ClearPagePrivate2(page);
2765 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2766 end - start + 1, uptodate))
2769 ordered_extent->work.func = finish_ordered_fn;
2770 ordered_extent->work.flags = 0;
2772 if (btrfs_is_free_space_inode(inode))
2773 workers = &root->fs_info->endio_freespace_worker;
2775 workers = &root->fs_info->endio_write_workers;
2776 btrfs_queue_worker(workers, &ordered_extent->work);
2782 * when reads are done, we need to check csums to verify the data is correct
2783 * if there's a match, we allow the bio to finish. If not, the code in
2784 * extent_io.c will try to find good copies for us.
2786 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2787 u64 phy_offset, struct page *page,
2788 u64 start, u64 end, int mirror)
2790 size_t offset = start - page_offset(page);
2791 struct inode *inode = page->mapping->host;
2792 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2794 struct btrfs_root *root = BTRFS_I(inode)->root;
2797 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2798 DEFAULT_RATELIMIT_BURST);
2800 if (PageChecked(page)) {
2801 ClearPageChecked(page);
2805 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2808 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2809 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2810 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2815 phy_offset >>= inode->i_sb->s_blocksize_bits;
2816 csum_expected = *(((u32 *)io_bio->csum) + phy_offset);
2818 kaddr = kmap_atomic(page);
2819 csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
2820 btrfs_csum_final(csum, (char *)&csum);
2821 if (csum != csum_expected)
2824 kunmap_atomic(kaddr);
2829 if (__ratelimit(&_rs))
2830 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
2831 btrfs_ino(page->mapping->host), start, csum, csum_expected);
2832 memset(kaddr + offset, 1, end - start + 1);
2833 flush_dcache_page(page);
2834 kunmap_atomic(kaddr);
2835 if (csum_expected == 0)
2840 struct delayed_iput {
2841 struct list_head list;
2842 struct inode *inode;
2845 /* JDM: If this is fs-wide, why can't we add a pointer to
2846 * btrfs_inode instead and avoid the allocation? */
2847 void btrfs_add_delayed_iput(struct inode *inode)
2849 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2850 struct delayed_iput *delayed;
2852 if (atomic_add_unless(&inode->i_count, -1, 1))
2855 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2856 delayed->inode = inode;
2858 spin_lock(&fs_info->delayed_iput_lock);
2859 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2860 spin_unlock(&fs_info->delayed_iput_lock);
2863 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2866 struct btrfs_fs_info *fs_info = root->fs_info;
2867 struct delayed_iput *delayed;
2870 spin_lock(&fs_info->delayed_iput_lock);
2871 empty = list_empty(&fs_info->delayed_iputs);
2872 spin_unlock(&fs_info->delayed_iput_lock);
2876 spin_lock(&fs_info->delayed_iput_lock);
2877 list_splice_init(&fs_info->delayed_iputs, &list);
2878 spin_unlock(&fs_info->delayed_iput_lock);
2880 while (!list_empty(&list)) {
2881 delayed = list_entry(list.next, struct delayed_iput, list);
2882 list_del(&delayed->list);
2883 iput(delayed->inode);
2889 * This is called in transaction commit time. If there are no orphan
2890 * files in the subvolume, it removes orphan item and frees block_rsv
2893 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2894 struct btrfs_root *root)
2896 struct btrfs_block_rsv *block_rsv;
2899 if (atomic_read(&root->orphan_inodes) ||
2900 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2903 spin_lock(&root->orphan_lock);
2904 if (atomic_read(&root->orphan_inodes)) {
2905 spin_unlock(&root->orphan_lock);
2909 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2910 spin_unlock(&root->orphan_lock);
2914 block_rsv = root->orphan_block_rsv;
2915 root->orphan_block_rsv = NULL;
2916 spin_unlock(&root->orphan_lock);
2918 if (root->orphan_item_inserted &&
2919 btrfs_root_refs(&root->root_item) > 0) {
2920 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2921 root->root_key.objectid);
2923 btrfs_abort_transaction(trans, root, ret);
2925 root->orphan_item_inserted = 0;
2929 WARN_ON(block_rsv->size > 0);
2930 btrfs_free_block_rsv(root, block_rsv);
2935 * This creates an orphan entry for the given inode in case something goes
2936 * wrong in the middle of an unlink/truncate.
2938 * NOTE: caller of this function should reserve 5 units of metadata for
2941 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2943 struct btrfs_root *root = BTRFS_I(inode)->root;
2944 struct btrfs_block_rsv *block_rsv = NULL;
2949 if (!root->orphan_block_rsv) {
2950 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2955 spin_lock(&root->orphan_lock);
2956 if (!root->orphan_block_rsv) {
2957 root->orphan_block_rsv = block_rsv;
2958 } else if (block_rsv) {
2959 btrfs_free_block_rsv(root, block_rsv);
2963 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2964 &BTRFS_I(inode)->runtime_flags)) {
2967 * For proper ENOSPC handling, we should do orphan
2968 * cleanup when mounting. But this introduces backward
2969 * compatibility issue.
2971 if (!xchg(&root->orphan_item_inserted, 1))
2977 atomic_inc(&root->orphan_inodes);
2980 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2981 &BTRFS_I(inode)->runtime_flags))
2983 spin_unlock(&root->orphan_lock);
2985 /* grab metadata reservation from transaction handle */
2987 ret = btrfs_orphan_reserve_metadata(trans, inode);
2988 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
2991 /* insert an orphan item to track this unlinked/truncated file */
2993 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2995 atomic_dec(&root->orphan_inodes);
2997 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2998 &BTRFS_I(inode)->runtime_flags);
2999 btrfs_orphan_release_metadata(inode);
3001 if (ret != -EEXIST) {
3002 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3003 &BTRFS_I(inode)->runtime_flags);
3004 btrfs_abort_transaction(trans, root, ret);
3011 /* insert an orphan item to track subvolume contains orphan files */
3013 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3014 root->root_key.objectid);
3015 if (ret && ret != -EEXIST) {
3016 btrfs_abort_transaction(trans, root, ret);
3024 * We have done the truncate/delete so we can go ahead and remove the orphan
3025 * item for this particular inode.
3027 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3028 struct inode *inode)
3030 struct btrfs_root *root = BTRFS_I(inode)->root;
3031 int delete_item = 0;
3032 int release_rsv = 0;
3035 spin_lock(&root->orphan_lock);
3036 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3037 &BTRFS_I(inode)->runtime_flags))
3040 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3041 &BTRFS_I(inode)->runtime_flags))
3043 spin_unlock(&root->orphan_lock);
3046 atomic_dec(&root->orphan_inodes);
3048 ret = btrfs_del_orphan_item(trans, root,
3053 btrfs_orphan_release_metadata(inode);
3059 * this cleans up any orphans that may be left on the list from the last use
3062 int btrfs_orphan_cleanup(struct btrfs_root *root)
3064 struct btrfs_path *path;
3065 struct extent_buffer *leaf;
3066 struct btrfs_key key, found_key;
3067 struct btrfs_trans_handle *trans;
3068 struct inode *inode;
3069 u64 last_objectid = 0;
3070 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3072 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3075 path = btrfs_alloc_path();
3082 key.objectid = BTRFS_ORPHAN_OBJECTID;
3083 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3084 key.offset = (u64)-1;
3087 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3092 * if ret == 0 means we found what we were searching for, which
3093 * is weird, but possible, so only screw with path if we didn't
3094 * find the key and see if we have stuff that matches
3098 if (path->slots[0] == 0)
3103 /* pull out the item */
3104 leaf = path->nodes[0];
3105 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3107 /* make sure the item matches what we want */
3108 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3110 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3113 /* release the path since we're done with it */
3114 btrfs_release_path(path);
3117 * this is where we are basically btrfs_lookup, without the
3118 * crossing root thing. we store the inode number in the
3119 * offset of the orphan item.
3122 if (found_key.offset == last_objectid) {
3123 btrfs_err(root->fs_info,
3124 "Error removing orphan entry, stopping orphan cleanup");
3129 last_objectid = found_key.offset;
3131 found_key.objectid = found_key.offset;
3132 found_key.type = BTRFS_INODE_ITEM_KEY;
3133 found_key.offset = 0;
3134 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3135 ret = PTR_ERR_OR_ZERO(inode);
3136 if (ret && ret != -ESTALE)
3139 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3140 struct btrfs_root *dead_root;
3141 struct btrfs_fs_info *fs_info = root->fs_info;
3142 int is_dead_root = 0;
3145 * this is an orphan in the tree root. Currently these
3146 * could come from 2 sources:
3147 * a) a snapshot deletion in progress
3148 * b) a free space cache inode
3149 * We need to distinguish those two, as the snapshot
3150 * orphan must not get deleted.
3151 * find_dead_roots already ran before us, so if this
3152 * is a snapshot deletion, we should find the root
3153 * in the dead_roots list
3155 spin_lock(&fs_info->trans_lock);
3156 list_for_each_entry(dead_root, &fs_info->dead_roots,
3158 if (dead_root->root_key.objectid ==
3159 found_key.objectid) {
3164 spin_unlock(&fs_info->trans_lock);
3166 /* prevent this orphan from being found again */
3167 key.offset = found_key.objectid - 1;
3172 * Inode is already gone but the orphan item is still there,
3173 * kill the orphan item.
3175 if (ret == -ESTALE) {
3176 trans = btrfs_start_transaction(root, 1);
3177 if (IS_ERR(trans)) {
3178 ret = PTR_ERR(trans);
3181 btrfs_debug(root->fs_info, "auto deleting %Lu",
3182 found_key.objectid);
3183 ret = btrfs_del_orphan_item(trans, root,
3184 found_key.objectid);
3185 btrfs_end_transaction(trans, root);
3192 * add this inode to the orphan list so btrfs_orphan_del does
3193 * the proper thing when we hit it
3195 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3196 &BTRFS_I(inode)->runtime_flags);
3197 atomic_inc(&root->orphan_inodes);
3199 /* if we have links, this was a truncate, lets do that */
3200 if (inode->i_nlink) {
3201 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3207 /* 1 for the orphan item deletion. */
3208 trans = btrfs_start_transaction(root, 1);
3209 if (IS_ERR(trans)) {
3211 ret = PTR_ERR(trans);
3214 ret = btrfs_orphan_add(trans, inode);
3215 btrfs_end_transaction(trans, root);
3221 ret = btrfs_truncate(inode);
3223 btrfs_orphan_del(NULL, inode);
3228 /* this will do delete_inode and everything for us */
3233 /* release the path since we're done with it */
3234 btrfs_release_path(path);
3236 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3238 if (root->orphan_block_rsv)
3239 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3242 if (root->orphan_block_rsv || root->orphan_item_inserted) {
3243 trans = btrfs_join_transaction(root);
3245 btrfs_end_transaction(trans, root);
3249 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3251 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3255 btrfs_crit(root->fs_info,
3256 "could not do orphan cleanup %d", ret);
3257 btrfs_free_path(path);
3262 * very simple check to peek ahead in the leaf looking for xattrs. If we
3263 * don't find any xattrs, we know there can't be any acls.
3265 * slot is the slot the inode is in, objectid is the objectid of the inode
3267 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3268 int slot, u64 objectid)
3270 u32 nritems = btrfs_header_nritems(leaf);
3271 struct btrfs_key found_key;
3272 static u64 xattr_access = 0;
3273 static u64 xattr_default = 0;
3276 if (!xattr_access) {
3277 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3278 strlen(POSIX_ACL_XATTR_ACCESS));
3279 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3280 strlen(POSIX_ACL_XATTR_DEFAULT));
3284 while (slot < nritems) {
3285 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3287 /* we found a different objectid, there must not be acls */
3288 if (found_key.objectid != objectid)
3291 /* we found an xattr, assume we've got an acl */
3292 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3293 if (found_key.offset == xattr_access ||
3294 found_key.offset == xattr_default)
3299 * we found a key greater than an xattr key, there can't
3300 * be any acls later on
3302 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3309 * it goes inode, inode backrefs, xattrs, extents,
3310 * so if there are a ton of hard links to an inode there can
3311 * be a lot of backrefs. Don't waste time searching too hard,
3312 * this is just an optimization
3317 /* we hit the end of the leaf before we found an xattr or
3318 * something larger than an xattr. We have to assume the inode
3325 * read an inode from the btree into the in-memory inode
3327 static void btrfs_read_locked_inode(struct inode *inode)
3329 struct btrfs_path *path;
3330 struct extent_buffer *leaf;
3331 struct btrfs_inode_item *inode_item;
3332 struct btrfs_timespec *tspec;
3333 struct btrfs_root *root = BTRFS_I(inode)->root;
3334 struct btrfs_key location;
3339 bool filled = false;
3341 ret = btrfs_fill_inode(inode, &rdev);
3345 path = btrfs_alloc_path();
3349 path->leave_spinning = 1;
3350 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3352 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3356 leaf = path->nodes[0];
3361 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3362 struct btrfs_inode_item);
3363 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3364 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3365 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3366 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3367 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3369 tspec = btrfs_inode_atime(inode_item);
3370 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3371 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3373 tspec = btrfs_inode_mtime(inode_item);
3374 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3375 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3377 tspec = btrfs_inode_ctime(inode_item);
3378 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3379 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3381 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3382 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3383 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3386 * If we were modified in the current generation and evicted from memory
3387 * and then re-read we need to do a full sync since we don't have any
3388 * idea about which extents were modified before we were evicted from
3391 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3392 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3393 &BTRFS_I(inode)->runtime_flags);
3395 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3396 inode->i_generation = BTRFS_I(inode)->generation;
3398 rdev = btrfs_inode_rdev(leaf, inode_item);
3400 BTRFS_I(inode)->index_cnt = (u64)-1;
3401 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3405 if (inode->i_nlink != 1 ||
3406 path->slots[0] >= btrfs_header_nritems(leaf))
3409 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3410 if (location.objectid != btrfs_ino(inode))
3413 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3414 if (location.type == BTRFS_INODE_REF_KEY) {
3415 struct btrfs_inode_ref *ref;
3417 ref = (struct btrfs_inode_ref *)ptr;
3418 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3419 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3420 struct btrfs_inode_extref *extref;
3422 extref = (struct btrfs_inode_extref *)ptr;
3423 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3428 * try to precache a NULL acl entry for files that don't have
3429 * any xattrs or acls
3431 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3434 cache_no_acl(inode);
3436 btrfs_free_path(path);
3438 switch (inode->i_mode & S_IFMT) {
3440 inode->i_mapping->a_ops = &btrfs_aops;
3441 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3442 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3443 inode->i_fop = &btrfs_file_operations;
3444 inode->i_op = &btrfs_file_inode_operations;
3447 inode->i_fop = &btrfs_dir_file_operations;
3448 if (root == root->fs_info->tree_root)
3449 inode->i_op = &btrfs_dir_ro_inode_operations;
3451 inode->i_op = &btrfs_dir_inode_operations;
3454 inode->i_op = &btrfs_symlink_inode_operations;
3455 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3456 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3459 inode->i_op = &btrfs_special_inode_operations;
3460 init_special_inode(inode, inode->i_mode, rdev);
3464 btrfs_update_iflags(inode);
3468 btrfs_free_path(path);
3469 make_bad_inode(inode);
3473 * given a leaf and an inode, copy the inode fields into the leaf
3475 static void fill_inode_item(struct btrfs_trans_handle *trans,
3476 struct extent_buffer *leaf,
3477 struct btrfs_inode_item *item,
3478 struct inode *inode)
3480 struct btrfs_map_token token;
3482 btrfs_init_map_token(&token);
3484 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3485 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3486 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3488 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3489 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3491 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3492 inode->i_atime.tv_sec, &token);
3493 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3494 inode->i_atime.tv_nsec, &token);
3496 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3497 inode->i_mtime.tv_sec, &token);
3498 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3499 inode->i_mtime.tv_nsec, &token);
3501 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3502 inode->i_ctime.tv_sec, &token);
3503 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3504 inode->i_ctime.tv_nsec, &token);
3506 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3508 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3510 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3511 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3512 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3513 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3514 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3518 * copy everything in the in-memory inode into the btree.
3520 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3521 struct btrfs_root *root, struct inode *inode)
3523 struct btrfs_inode_item *inode_item;
3524 struct btrfs_path *path;
3525 struct extent_buffer *leaf;
3528 path = btrfs_alloc_path();
3532 path->leave_spinning = 1;
3533 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3541 leaf = path->nodes[0];
3542 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3543 struct btrfs_inode_item);
3545 fill_inode_item(trans, leaf, inode_item, inode);
3546 btrfs_mark_buffer_dirty(leaf);
3547 btrfs_set_inode_last_trans(trans, inode);
3550 btrfs_free_path(path);
3555 * copy everything in the in-memory inode into the btree.
3557 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3558 struct btrfs_root *root, struct inode *inode)
3563 * If the inode is a free space inode, we can deadlock during commit
3564 * if we put it into the delayed code.
3566 * The data relocation inode should also be directly updated
3569 if (!btrfs_is_free_space_inode(inode)
3570 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3571 btrfs_update_root_times(trans, root);
3573 ret = btrfs_delayed_update_inode(trans, root, inode);
3575 btrfs_set_inode_last_trans(trans, inode);
3579 return btrfs_update_inode_item(trans, root, inode);
3582 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3583 struct btrfs_root *root,
3584 struct inode *inode)
3588 ret = btrfs_update_inode(trans, root, inode);
3590 return btrfs_update_inode_item(trans, root, inode);
3595 * unlink helper that gets used here in inode.c and in the tree logging
3596 * recovery code. It remove a link in a directory with a given name, and
3597 * also drops the back refs in the inode to the directory
3599 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3600 struct btrfs_root *root,
3601 struct inode *dir, struct inode *inode,
3602 const char *name, int name_len)
3604 struct btrfs_path *path;
3606 struct extent_buffer *leaf;
3607 struct btrfs_dir_item *di;
3608 struct btrfs_key key;
3610 u64 ino = btrfs_ino(inode);
3611 u64 dir_ino = btrfs_ino(dir);
3613 path = btrfs_alloc_path();
3619 path->leave_spinning = 1;
3620 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3621 name, name_len, -1);
3630 leaf = path->nodes[0];
3631 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3632 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3635 btrfs_release_path(path);
3638 * If we don't have dir index, we have to get it by looking up
3639 * the inode ref, since we get the inode ref, remove it directly,
3640 * it is unnecessary to do delayed deletion.
3642 * But if we have dir index, needn't search inode ref to get it.
3643 * Since the inode ref is close to the inode item, it is better
3644 * that we delay to delete it, and just do this deletion when
3645 * we update the inode item.
3647 if (BTRFS_I(inode)->dir_index) {
3648 ret = btrfs_delayed_delete_inode_ref(inode);
3650 index = BTRFS_I(inode)->dir_index;
3655 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3658 btrfs_info(root->fs_info,
3659 "failed to delete reference to %.*s, inode %llu parent %llu",
3660 name_len, name, ino, dir_ino);
3661 btrfs_abort_transaction(trans, root, ret);
3665 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3667 btrfs_abort_transaction(trans, root, ret);
3671 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3673 if (ret != 0 && ret != -ENOENT) {
3674 btrfs_abort_transaction(trans, root, ret);
3678 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3683 btrfs_abort_transaction(trans, root, ret);
3685 btrfs_free_path(path);
3689 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3690 inode_inc_iversion(inode);
3691 inode_inc_iversion(dir);
3692 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3693 ret = btrfs_update_inode(trans, root, dir);
3698 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3699 struct btrfs_root *root,
3700 struct inode *dir, struct inode *inode,
3701 const char *name, int name_len)
3704 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3707 ret = btrfs_update_inode(trans, root, inode);
3713 * helper to start transaction for unlink and rmdir.
3715 * unlink and rmdir are special in btrfs, they do not always free space, so
3716 * if we cannot make our reservations the normal way try and see if there is
3717 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3718 * allow the unlink to occur.
3720 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3722 struct btrfs_trans_handle *trans;
3723 struct btrfs_root *root = BTRFS_I(dir)->root;
3727 * 1 for the possible orphan item
3728 * 1 for the dir item
3729 * 1 for the dir index
3730 * 1 for the inode ref
3733 trans = btrfs_start_transaction(root, 5);
3734 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3737 if (PTR_ERR(trans) == -ENOSPC) {
3738 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3740 trans = btrfs_start_transaction(root, 0);
3743 ret = btrfs_cond_migrate_bytes(root->fs_info,
3744 &root->fs_info->trans_block_rsv,
3747 btrfs_end_transaction(trans, root);
3748 return ERR_PTR(ret);
3750 trans->block_rsv = &root->fs_info->trans_block_rsv;
3751 trans->bytes_reserved = num_bytes;
3756 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3758 struct btrfs_root *root = BTRFS_I(dir)->root;
3759 struct btrfs_trans_handle *trans;
3760 struct inode *inode = dentry->d_inode;
3763 trans = __unlink_start_trans(dir);
3765 return PTR_ERR(trans);
3767 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3769 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3770 dentry->d_name.name, dentry->d_name.len);
3774 if (inode->i_nlink == 0) {
3775 ret = btrfs_orphan_add(trans, inode);
3781 btrfs_end_transaction(trans, root);
3782 btrfs_btree_balance_dirty(root);
3786 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3787 struct btrfs_root *root,
3788 struct inode *dir, u64 objectid,
3789 const char *name, int name_len)
3791 struct btrfs_path *path;
3792 struct extent_buffer *leaf;
3793 struct btrfs_dir_item *di;
3794 struct btrfs_key key;
3797 u64 dir_ino = btrfs_ino(dir);
3799 path = btrfs_alloc_path();
3803 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3804 name, name_len, -1);
3805 if (IS_ERR_OR_NULL(di)) {
3813 leaf = path->nodes[0];
3814 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3815 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3816 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3818 btrfs_abort_transaction(trans, root, ret);
3821 btrfs_release_path(path);
3823 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3824 objectid, root->root_key.objectid,
3825 dir_ino, &index, name, name_len);
3827 if (ret != -ENOENT) {
3828 btrfs_abort_transaction(trans, root, ret);
3831 di = btrfs_search_dir_index_item(root, path, dir_ino,
3833 if (IS_ERR_OR_NULL(di)) {
3838 btrfs_abort_transaction(trans, root, ret);
3842 leaf = path->nodes[0];
3843 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3844 btrfs_release_path(path);
3847 btrfs_release_path(path);
3849 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3851 btrfs_abort_transaction(trans, root, ret);
3855 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3856 inode_inc_iversion(dir);
3857 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3858 ret = btrfs_update_inode_fallback(trans, root, dir);
3860 btrfs_abort_transaction(trans, root, ret);
3862 btrfs_free_path(path);
3866 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3868 struct inode *inode = dentry->d_inode;
3870 struct btrfs_root *root = BTRFS_I(dir)->root;
3871 struct btrfs_trans_handle *trans;
3873 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3875 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3878 trans = __unlink_start_trans(dir);
3880 return PTR_ERR(trans);
3882 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3883 err = btrfs_unlink_subvol(trans, root, dir,
3884 BTRFS_I(inode)->location.objectid,
3885 dentry->d_name.name,
3886 dentry->d_name.len);
3890 err = btrfs_orphan_add(trans, inode);
3894 /* now the directory is empty */
3895 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3896 dentry->d_name.name, dentry->d_name.len);
3898 btrfs_i_size_write(inode, 0);
3900 btrfs_end_transaction(trans, root);
3901 btrfs_btree_balance_dirty(root);
3907 * this can truncate away extent items, csum items and directory items.
3908 * It starts at a high offset and removes keys until it can't find
3909 * any higher than new_size
3911 * csum items that cross the new i_size are truncated to the new size
3914 * min_type is the minimum key type to truncate down to. If set to 0, this
3915 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3917 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3918 struct btrfs_root *root,
3919 struct inode *inode,
3920 u64 new_size, u32 min_type)
3922 struct btrfs_path *path;
3923 struct extent_buffer *leaf;
3924 struct btrfs_file_extent_item *fi;
3925 struct btrfs_key key;
3926 struct btrfs_key found_key;
3927 u64 extent_start = 0;
3928 u64 extent_num_bytes = 0;
3929 u64 extent_offset = 0;
3931 u64 last_size = (u64)-1;
3932 u32 found_type = (u8)-1;
3935 int pending_del_nr = 0;
3936 int pending_del_slot = 0;
3937 int extent_type = -1;
3940 u64 ino = btrfs_ino(inode);
3942 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3944 path = btrfs_alloc_path();
3950 * We want to drop from the next block forward in case this new size is
3951 * not block aligned since we will be keeping the last block of the
3952 * extent just the way it is.
3954 if (root->ref_cows || root == root->fs_info->tree_root)
3955 btrfs_drop_extent_cache(inode, ALIGN(new_size,
3956 root->sectorsize), (u64)-1, 0);
3959 * This function is also used to drop the items in the log tree before
3960 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3961 * it is used to drop the loged items. So we shouldn't kill the delayed
3964 if (min_type == 0 && root == BTRFS_I(inode)->root)
3965 btrfs_kill_delayed_inode_items(inode);
3968 key.offset = (u64)-1;
3972 path->leave_spinning = 1;
3973 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3980 /* there are no items in the tree for us to truncate, we're
3983 if (path->slots[0] == 0)
3990 leaf = path->nodes[0];
3991 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3992 found_type = btrfs_key_type(&found_key);
3994 if (found_key.objectid != ino)
3997 if (found_type < min_type)
4000 item_end = found_key.offset;
4001 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4002 fi = btrfs_item_ptr(leaf, path->slots[0],
4003 struct btrfs_file_extent_item);
4004 extent_type = btrfs_file_extent_type(leaf, fi);
4005 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4007 btrfs_file_extent_num_bytes(leaf, fi);
4008 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4009 item_end += btrfs_file_extent_inline_len(leaf,
4014 if (found_type > min_type) {
4017 if (item_end < new_size)
4019 if (found_key.offset >= new_size)
4025 /* FIXME, shrink the extent if the ref count is only 1 */
4026 if (found_type != BTRFS_EXTENT_DATA_KEY)
4030 last_size = found_key.offset;
4032 last_size = new_size;
4034 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4036 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4038 u64 orig_num_bytes =
4039 btrfs_file_extent_num_bytes(leaf, fi);
4040 extent_num_bytes = ALIGN(new_size -
4043 btrfs_set_file_extent_num_bytes(leaf, fi,
4045 num_dec = (orig_num_bytes -
4047 if (root->ref_cows && extent_start != 0)
4048 inode_sub_bytes(inode, num_dec);
4049 btrfs_mark_buffer_dirty(leaf);
4052 btrfs_file_extent_disk_num_bytes(leaf,
4054 extent_offset = found_key.offset -
4055 btrfs_file_extent_offset(leaf, fi);
4057 /* FIXME blocksize != 4096 */
4058 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4059 if (extent_start != 0) {
4062 inode_sub_bytes(inode, num_dec);
4065 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4067 * we can't truncate inline items that have had
4071 btrfs_file_extent_compression(leaf, fi) == 0 &&
4072 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4073 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4074 u32 size = new_size - found_key.offset;
4076 if (root->ref_cows) {
4077 inode_sub_bytes(inode, item_end + 1 -
4081 btrfs_file_extent_calc_inline_size(size);
4082 btrfs_truncate_item(root, path, size, 1);
4083 } else if (root->ref_cows) {
4084 inode_sub_bytes(inode, item_end + 1 -
4090 if (!pending_del_nr) {
4091 /* no pending yet, add ourselves */
4092 pending_del_slot = path->slots[0];
4094 } else if (pending_del_nr &&
4095 path->slots[0] + 1 == pending_del_slot) {
4096 /* hop on the pending chunk */
4098 pending_del_slot = path->slots[0];
4105 if (found_extent && (root->ref_cows ||
4106 root == root->fs_info->tree_root)) {
4107 btrfs_set_path_blocking(path);
4108 ret = btrfs_free_extent(trans, root, extent_start,
4109 extent_num_bytes, 0,
4110 btrfs_header_owner(leaf),
4111 ino, extent_offset, 0);
4115 if (found_type == BTRFS_INODE_ITEM_KEY)
4118 if (path->slots[0] == 0 ||
4119 path->slots[0] != pending_del_slot) {
4120 if (pending_del_nr) {
4121 ret = btrfs_del_items(trans, root, path,
4125 btrfs_abort_transaction(trans,
4131 btrfs_release_path(path);
4138 if (pending_del_nr) {
4139 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4142 btrfs_abort_transaction(trans, root, ret);
4145 if (last_size != (u64)-1)
4146 btrfs_ordered_update_i_size(inode, last_size, NULL);
4147 btrfs_free_path(path);
4152 * btrfs_truncate_page - read, zero a chunk and write a page
4153 * @inode - inode that we're zeroing
4154 * @from - the offset to start zeroing
4155 * @len - the length to zero, 0 to zero the entire range respective to the
4157 * @front - zero up to the offset instead of from the offset on
4159 * This will find the page for the "from" offset and cow the page and zero the
4160 * part we want to zero. This is used with truncate and hole punching.
4162 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4165 struct address_space *mapping = inode->i_mapping;
4166 struct btrfs_root *root = BTRFS_I(inode)->root;
4167 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4168 struct btrfs_ordered_extent *ordered;
4169 struct extent_state *cached_state = NULL;
4171 u32 blocksize = root->sectorsize;
4172 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4173 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4175 gfp_t mask = btrfs_alloc_write_mask(mapping);
4180 if ((offset & (blocksize - 1)) == 0 &&
4181 (!len || ((len & (blocksize - 1)) == 0)))
4183 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4188 page = find_or_create_page(mapping, index, mask);
4190 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4195 page_start = page_offset(page);
4196 page_end = page_start + PAGE_CACHE_SIZE - 1;
4198 if (!PageUptodate(page)) {
4199 ret = btrfs_readpage(NULL, page);
4201 if (page->mapping != mapping) {
4203 page_cache_release(page);
4206 if (!PageUptodate(page)) {
4211 wait_on_page_writeback(page);
4213 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4214 set_page_extent_mapped(page);
4216 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4218 unlock_extent_cached(io_tree, page_start, page_end,
4219 &cached_state, GFP_NOFS);
4221 page_cache_release(page);
4222 btrfs_start_ordered_extent(inode, ordered, 1);
4223 btrfs_put_ordered_extent(ordered);
4227 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4228 EXTENT_DIRTY | EXTENT_DELALLOC |
4229 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4230 0, 0, &cached_state, GFP_NOFS);
4232 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4235 unlock_extent_cached(io_tree, page_start, page_end,
4236 &cached_state, GFP_NOFS);
4240 if (offset != PAGE_CACHE_SIZE) {
4242 len = PAGE_CACHE_SIZE - offset;
4245 memset(kaddr, 0, offset);
4247 memset(kaddr + offset, 0, len);
4248 flush_dcache_page(page);
4251 ClearPageChecked(page);
4252 set_page_dirty(page);
4253 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4258 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4260 page_cache_release(page);
4265 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4266 u64 offset, u64 len)
4268 struct btrfs_trans_handle *trans;
4272 * Still need to make sure the inode looks like it's been updated so
4273 * that any holes get logged if we fsync.
4275 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4276 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4277 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4278 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4283 * 1 - for the one we're dropping
4284 * 1 - for the one we're adding
4285 * 1 - for updating the inode.
4287 trans = btrfs_start_transaction(root, 3);
4289 return PTR_ERR(trans);
4291 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4293 btrfs_abort_transaction(trans, root, ret);
4294 btrfs_end_transaction(trans, root);
4298 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4299 0, 0, len, 0, len, 0, 0, 0);
4301 btrfs_abort_transaction(trans, root, ret);
4303 btrfs_update_inode(trans, root, inode);
4304 btrfs_end_transaction(trans, root);
4309 * This function puts in dummy file extents for the area we're creating a hole
4310 * for. So if we are truncating this file to a larger size we need to insert
4311 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4312 * the range between oldsize and size
4314 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4316 struct btrfs_root *root = BTRFS_I(inode)->root;
4317 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4318 struct extent_map *em = NULL;
4319 struct extent_state *cached_state = NULL;
4320 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4321 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4322 u64 block_end = ALIGN(size, root->sectorsize);
4329 * If our size started in the middle of a page we need to zero out the
4330 * rest of the page before we expand the i_size, otherwise we could
4331 * expose stale data.
4333 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4337 if (size <= hole_start)
4341 struct btrfs_ordered_extent *ordered;
4343 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4345 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4346 block_end - hole_start);
4349 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4350 &cached_state, GFP_NOFS);
4351 btrfs_start_ordered_extent(inode, ordered, 1);
4352 btrfs_put_ordered_extent(ordered);
4355 cur_offset = hole_start;
4357 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4358 block_end - cur_offset, 0);
4364 last_byte = min(extent_map_end(em), block_end);
4365 last_byte = ALIGN(last_byte , root->sectorsize);
4366 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4367 struct extent_map *hole_em;
4368 hole_size = last_byte - cur_offset;
4370 err = maybe_insert_hole(root, inode, cur_offset,
4374 btrfs_drop_extent_cache(inode, cur_offset,
4375 cur_offset + hole_size - 1, 0);
4376 hole_em = alloc_extent_map();
4378 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4379 &BTRFS_I(inode)->runtime_flags);
4382 hole_em->start = cur_offset;
4383 hole_em->len = hole_size;
4384 hole_em->orig_start = cur_offset;
4386 hole_em->block_start = EXTENT_MAP_HOLE;
4387 hole_em->block_len = 0;
4388 hole_em->orig_block_len = 0;
4389 hole_em->ram_bytes = hole_size;
4390 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4391 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4392 hole_em->generation = root->fs_info->generation;
4395 write_lock(&em_tree->lock);
4396 err = add_extent_mapping(em_tree, hole_em, 1);
4397 write_unlock(&em_tree->lock);
4400 btrfs_drop_extent_cache(inode, cur_offset,
4404 free_extent_map(hole_em);
4407 free_extent_map(em);
4409 cur_offset = last_byte;
4410 if (cur_offset >= block_end)
4413 free_extent_map(em);
4414 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4419 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4421 struct btrfs_root *root = BTRFS_I(inode)->root;
4422 struct btrfs_trans_handle *trans;
4423 loff_t oldsize = i_size_read(inode);
4424 loff_t newsize = attr->ia_size;
4425 int mask = attr->ia_valid;
4429 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4430 * special case where we need to update the times despite not having
4431 * these flags set. For all other operations the VFS set these flags
4432 * explicitly if it wants a timestamp update.
4434 if (newsize != oldsize && (!(mask & (ATTR_CTIME | ATTR_MTIME))))
4435 inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb);
4437 if (newsize > oldsize) {
4438 truncate_pagecache(inode, newsize);
4439 ret = btrfs_cont_expand(inode, oldsize, newsize);
4443 trans = btrfs_start_transaction(root, 1);
4445 return PTR_ERR(trans);
4447 i_size_write(inode, newsize);
4448 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4449 ret = btrfs_update_inode(trans, root, inode);
4450 btrfs_end_transaction(trans, root);
4454 * We're truncating a file that used to have good data down to
4455 * zero. Make sure it gets into the ordered flush list so that
4456 * any new writes get down to disk quickly.
4459 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4460 &BTRFS_I(inode)->runtime_flags);
4463 * 1 for the orphan item we're going to add
4464 * 1 for the orphan item deletion.
4466 trans = btrfs_start_transaction(root, 2);
4468 return PTR_ERR(trans);
4471 * We need to do this in case we fail at _any_ point during the
4472 * actual truncate. Once we do the truncate_setsize we could
4473 * invalidate pages which forces any outstanding ordered io to
4474 * be instantly completed which will give us extents that need
4475 * to be truncated. If we fail to get an orphan inode down we
4476 * could have left over extents that were never meant to live,
4477 * so we need to garuntee from this point on that everything
4478 * will be consistent.
4480 ret = btrfs_orphan_add(trans, inode);
4481 btrfs_end_transaction(trans, root);
4485 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4486 truncate_setsize(inode, newsize);
4488 /* Disable nonlocked read DIO to avoid the end less truncate */
4489 btrfs_inode_block_unlocked_dio(inode);
4490 inode_dio_wait(inode);
4491 btrfs_inode_resume_unlocked_dio(inode);
4493 ret = btrfs_truncate(inode);
4494 if (ret && inode->i_nlink) {
4498 * failed to truncate, disk_i_size is only adjusted down
4499 * as we remove extents, so it should represent the true
4500 * size of the inode, so reset the in memory size and
4501 * delete our orphan entry.
4503 trans = btrfs_join_transaction(root);
4504 if (IS_ERR(trans)) {
4505 btrfs_orphan_del(NULL, inode);
4508 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4509 err = btrfs_orphan_del(trans, inode);
4511 btrfs_abort_transaction(trans, root, err);
4512 btrfs_end_transaction(trans, root);
4519 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4521 struct inode *inode = dentry->d_inode;
4522 struct btrfs_root *root = BTRFS_I(inode)->root;
4525 if (btrfs_root_readonly(root))
4528 err = inode_change_ok(inode, attr);
4532 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4533 err = btrfs_setsize(inode, attr);
4538 if (attr->ia_valid) {
4539 setattr_copy(inode, attr);
4540 inode_inc_iversion(inode);
4541 err = btrfs_dirty_inode(inode);
4543 if (!err && attr->ia_valid & ATTR_MODE)
4544 err = btrfs_acl_chmod(inode);
4551 * While truncating the inode pages during eviction, we get the VFS calling
4552 * btrfs_invalidatepage() against each page of the inode. This is slow because
4553 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4554 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4555 * extent_state structures over and over, wasting lots of time.
4557 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4558 * those expensive operations on a per page basis and do only the ordered io
4559 * finishing, while we release here the extent_map and extent_state structures,
4560 * without the excessive merging and splitting.
4562 static void evict_inode_truncate_pages(struct inode *inode)
4564 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4565 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4566 struct rb_node *node;
4568 ASSERT(inode->i_state & I_FREEING);
4569 truncate_inode_pages(&inode->i_data, 0);
4571 write_lock(&map_tree->lock);
4572 while (!RB_EMPTY_ROOT(&map_tree->map)) {
4573 struct extent_map *em;
4575 node = rb_first(&map_tree->map);
4576 em = rb_entry(node, struct extent_map, rb_node);
4577 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4578 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4579 remove_extent_mapping(map_tree, em);
4580 free_extent_map(em);
4582 write_unlock(&map_tree->lock);
4584 spin_lock(&io_tree->lock);
4585 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4586 struct extent_state *state;
4587 struct extent_state *cached_state = NULL;
4589 node = rb_first(&io_tree->state);
4590 state = rb_entry(node, struct extent_state, rb_node);
4591 atomic_inc(&state->refs);
4592 spin_unlock(&io_tree->lock);
4594 lock_extent_bits(io_tree, state->start, state->end,
4596 clear_extent_bit(io_tree, state->start, state->end,
4597 EXTENT_LOCKED | EXTENT_DIRTY |
4598 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
4599 EXTENT_DEFRAG, 1, 1,
4600 &cached_state, GFP_NOFS);
4601 free_extent_state(state);
4603 spin_lock(&io_tree->lock);
4605 spin_unlock(&io_tree->lock);
4608 void btrfs_evict_inode(struct inode *inode)
4610 struct btrfs_trans_handle *trans;
4611 struct btrfs_root *root = BTRFS_I(inode)->root;
4612 struct btrfs_block_rsv *rsv, *global_rsv;
4613 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4616 trace_btrfs_inode_evict(inode);
4618 evict_inode_truncate_pages(inode);
4620 if (inode->i_nlink &&
4621 ((btrfs_root_refs(&root->root_item) != 0 &&
4622 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4623 btrfs_is_free_space_inode(inode)))
4626 if (is_bad_inode(inode)) {
4627 btrfs_orphan_del(NULL, inode);
4630 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4631 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4633 if (root->fs_info->log_root_recovering) {
4634 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4635 &BTRFS_I(inode)->runtime_flags));
4639 if (inode->i_nlink > 0) {
4640 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4641 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4645 ret = btrfs_commit_inode_delayed_inode(inode);
4647 btrfs_orphan_del(NULL, inode);
4651 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4653 btrfs_orphan_del(NULL, inode);
4656 rsv->size = min_size;
4658 global_rsv = &root->fs_info->global_block_rsv;
4660 btrfs_i_size_write(inode, 0);
4663 * This is a bit simpler than btrfs_truncate since we've already
4664 * reserved our space for our orphan item in the unlink, so we just
4665 * need to reserve some slack space in case we add bytes and update
4666 * inode item when doing the truncate.
4669 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4670 BTRFS_RESERVE_FLUSH_LIMIT);
4673 * Try and steal from the global reserve since we will
4674 * likely not use this space anyway, we want to try as
4675 * hard as possible to get this to work.
4678 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4681 btrfs_warn(root->fs_info,
4682 "Could not get space for a delete, will truncate on mount %d",
4684 btrfs_orphan_del(NULL, inode);
4685 btrfs_free_block_rsv(root, rsv);
4689 trans = btrfs_join_transaction(root);
4690 if (IS_ERR(trans)) {
4691 btrfs_orphan_del(NULL, inode);
4692 btrfs_free_block_rsv(root, rsv);
4696 trans->block_rsv = rsv;
4698 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4702 trans->block_rsv = &root->fs_info->trans_block_rsv;
4703 btrfs_end_transaction(trans, root);
4705 btrfs_btree_balance_dirty(root);
4708 btrfs_free_block_rsv(root, rsv);
4711 * Errors here aren't a big deal, it just means we leave orphan items
4712 * in the tree. They will be cleaned up on the next mount.
4715 trans->block_rsv = root->orphan_block_rsv;
4716 btrfs_orphan_del(trans, inode);
4718 btrfs_orphan_del(NULL, inode);
4721 trans->block_rsv = &root->fs_info->trans_block_rsv;
4722 if (!(root == root->fs_info->tree_root ||
4723 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4724 btrfs_return_ino(root, btrfs_ino(inode));
4726 btrfs_end_transaction(trans, root);
4727 btrfs_btree_balance_dirty(root);
4729 btrfs_remove_delayed_node(inode);
4735 * this returns the key found in the dir entry in the location pointer.
4736 * If no dir entries were found, location->objectid is 0.
4738 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4739 struct btrfs_key *location)
4741 const char *name = dentry->d_name.name;
4742 int namelen = dentry->d_name.len;
4743 struct btrfs_dir_item *di;
4744 struct btrfs_path *path;
4745 struct btrfs_root *root = BTRFS_I(dir)->root;
4748 path = btrfs_alloc_path();
4752 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4757 if (IS_ERR_OR_NULL(di))
4760 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4762 btrfs_free_path(path);
4765 location->objectid = 0;
4770 * when we hit a tree root in a directory, the btrfs part of the inode
4771 * needs to be changed to reflect the root directory of the tree root. This
4772 * is kind of like crossing a mount point.
4774 static int fixup_tree_root_location(struct btrfs_root *root,
4776 struct dentry *dentry,
4777 struct btrfs_key *location,
4778 struct btrfs_root **sub_root)
4780 struct btrfs_path *path;
4781 struct btrfs_root *new_root;
4782 struct btrfs_root_ref *ref;
4783 struct extent_buffer *leaf;
4787 path = btrfs_alloc_path();
4794 ret = btrfs_find_item(root->fs_info->tree_root, path,
4795 BTRFS_I(dir)->root->root_key.objectid,
4796 location->objectid, BTRFS_ROOT_REF_KEY, NULL);
4803 leaf = path->nodes[0];
4804 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4805 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4806 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4809 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4810 (unsigned long)(ref + 1),
4811 dentry->d_name.len);
4815 btrfs_release_path(path);
4817 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4818 if (IS_ERR(new_root)) {
4819 err = PTR_ERR(new_root);
4823 *sub_root = new_root;
4824 location->objectid = btrfs_root_dirid(&new_root->root_item);
4825 location->type = BTRFS_INODE_ITEM_KEY;
4826 location->offset = 0;
4829 btrfs_free_path(path);
4833 static void inode_tree_add(struct inode *inode)
4835 struct btrfs_root *root = BTRFS_I(inode)->root;
4836 struct btrfs_inode *entry;
4838 struct rb_node *parent;
4839 struct rb_node *new = &BTRFS_I(inode)->rb_node;
4840 u64 ino = btrfs_ino(inode);
4842 if (inode_unhashed(inode))
4845 spin_lock(&root->inode_lock);
4846 p = &root->inode_tree.rb_node;
4849 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4851 if (ino < btrfs_ino(&entry->vfs_inode))
4852 p = &parent->rb_left;
4853 else if (ino > btrfs_ino(&entry->vfs_inode))
4854 p = &parent->rb_right;
4856 WARN_ON(!(entry->vfs_inode.i_state &
4857 (I_WILL_FREE | I_FREEING)));
4858 rb_replace_node(parent, new, &root->inode_tree);
4859 RB_CLEAR_NODE(parent);
4860 spin_unlock(&root->inode_lock);
4864 rb_link_node(new, parent, p);
4865 rb_insert_color(new, &root->inode_tree);
4866 spin_unlock(&root->inode_lock);
4869 static void inode_tree_del(struct inode *inode)
4871 struct btrfs_root *root = BTRFS_I(inode)->root;
4874 spin_lock(&root->inode_lock);
4875 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4876 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4877 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4878 empty = RB_EMPTY_ROOT(&root->inode_tree);
4880 spin_unlock(&root->inode_lock);
4882 if (empty && btrfs_root_refs(&root->root_item) == 0) {
4883 synchronize_srcu(&root->fs_info->subvol_srcu);
4884 spin_lock(&root->inode_lock);
4885 empty = RB_EMPTY_ROOT(&root->inode_tree);
4886 spin_unlock(&root->inode_lock);
4888 btrfs_add_dead_root(root);
4892 void btrfs_invalidate_inodes(struct btrfs_root *root)
4894 struct rb_node *node;
4895 struct rb_node *prev;
4896 struct btrfs_inode *entry;
4897 struct inode *inode;
4900 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4902 spin_lock(&root->inode_lock);
4904 node = root->inode_tree.rb_node;
4908 entry = rb_entry(node, struct btrfs_inode, rb_node);
4910 if (objectid < btrfs_ino(&entry->vfs_inode))
4911 node = node->rb_left;
4912 else if (objectid > btrfs_ino(&entry->vfs_inode))
4913 node = node->rb_right;
4919 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4920 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4924 prev = rb_next(prev);
4928 entry = rb_entry(node, struct btrfs_inode, rb_node);
4929 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4930 inode = igrab(&entry->vfs_inode);
4932 spin_unlock(&root->inode_lock);
4933 if (atomic_read(&inode->i_count) > 1)
4934 d_prune_aliases(inode);
4936 * btrfs_drop_inode will have it removed from
4937 * the inode cache when its usage count
4942 spin_lock(&root->inode_lock);
4946 if (cond_resched_lock(&root->inode_lock))
4949 node = rb_next(node);
4951 spin_unlock(&root->inode_lock);
4954 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4956 struct btrfs_iget_args *args = p;
4957 inode->i_ino = args->ino;
4958 BTRFS_I(inode)->root = args->root;
4962 static int btrfs_find_actor(struct inode *inode, void *opaque)
4964 struct btrfs_iget_args *args = opaque;
4965 return args->ino == btrfs_ino(inode) &&
4966 args->root == BTRFS_I(inode)->root;
4969 static struct inode *btrfs_iget_locked(struct super_block *s,
4971 struct btrfs_root *root)
4973 struct inode *inode;
4974 struct btrfs_iget_args args;
4975 unsigned long hashval = btrfs_inode_hash(objectid, root);
4977 args.ino = objectid;
4980 inode = iget5_locked(s, hashval, btrfs_find_actor,
4981 btrfs_init_locked_inode,
4986 /* Get an inode object given its location and corresponding root.
4987 * Returns in *is_new if the inode was read from disk
4989 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4990 struct btrfs_root *root, int *new)
4992 struct inode *inode;
4994 inode = btrfs_iget_locked(s, location->objectid, root);
4996 return ERR_PTR(-ENOMEM);
4998 if (inode->i_state & I_NEW) {
4999 BTRFS_I(inode)->root = root;
5000 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
5001 btrfs_read_locked_inode(inode);
5002 if (!is_bad_inode(inode)) {
5003 inode_tree_add(inode);
5004 unlock_new_inode(inode);
5008 unlock_new_inode(inode);
5010 inode = ERR_PTR(-ESTALE);
5017 static struct inode *new_simple_dir(struct super_block *s,
5018 struct btrfs_key *key,
5019 struct btrfs_root *root)
5021 struct inode *inode = new_inode(s);
5024 return ERR_PTR(-ENOMEM);
5026 BTRFS_I(inode)->root = root;
5027 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5028 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5030 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5031 inode->i_op = &btrfs_dir_ro_inode_operations;
5032 inode->i_fop = &simple_dir_operations;
5033 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5034 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5039 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5041 struct inode *inode;
5042 struct btrfs_root *root = BTRFS_I(dir)->root;
5043 struct btrfs_root *sub_root = root;
5044 struct btrfs_key location;
5048 if (dentry->d_name.len > BTRFS_NAME_LEN)
5049 return ERR_PTR(-ENAMETOOLONG);
5051 ret = btrfs_inode_by_name(dir, dentry, &location);
5053 return ERR_PTR(ret);
5055 if (location.objectid == 0)
5056 return ERR_PTR(-ENOENT);
5058 if (location.type == BTRFS_INODE_ITEM_KEY) {
5059 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5063 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5065 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5066 ret = fixup_tree_root_location(root, dir, dentry,
5067 &location, &sub_root);
5070 inode = ERR_PTR(ret);
5072 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5074 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5076 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5078 if (!IS_ERR(inode) && root != sub_root) {
5079 down_read(&root->fs_info->cleanup_work_sem);
5080 if (!(inode->i_sb->s_flags & MS_RDONLY))
5081 ret = btrfs_orphan_cleanup(sub_root);
5082 up_read(&root->fs_info->cleanup_work_sem);
5085 inode = ERR_PTR(ret);
5092 static int btrfs_dentry_delete(const struct dentry *dentry)
5094 struct btrfs_root *root;
5095 struct inode *inode = dentry->d_inode;
5097 if (!inode && !IS_ROOT(dentry))
5098 inode = dentry->d_parent->d_inode;
5101 root = BTRFS_I(inode)->root;
5102 if (btrfs_root_refs(&root->root_item) == 0)
5105 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5111 static void btrfs_dentry_release(struct dentry *dentry)
5113 if (dentry->d_fsdata)
5114 kfree(dentry->d_fsdata);
5117 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5120 struct inode *inode;
5122 inode = btrfs_lookup_dentry(dir, dentry);
5123 if (IS_ERR(inode)) {
5124 if (PTR_ERR(inode) == -ENOENT)
5127 return ERR_CAST(inode);
5130 return d_splice_alias(inode, dentry);
5133 unsigned char btrfs_filetype_table[] = {
5134 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5137 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5139 struct inode *inode = file_inode(file);
5140 struct btrfs_root *root = BTRFS_I(inode)->root;
5141 struct btrfs_item *item;
5142 struct btrfs_dir_item *di;
5143 struct btrfs_key key;
5144 struct btrfs_key found_key;
5145 struct btrfs_path *path;
5146 struct list_head ins_list;
5147 struct list_head del_list;
5149 struct extent_buffer *leaf;
5151 unsigned char d_type;
5156 int key_type = BTRFS_DIR_INDEX_KEY;
5160 int is_curr = 0; /* ctx->pos points to the current index? */
5162 /* FIXME, use a real flag for deciding about the key type */
5163 if (root->fs_info->tree_root == root)
5164 key_type = BTRFS_DIR_ITEM_KEY;
5166 if (!dir_emit_dots(file, ctx))
5169 path = btrfs_alloc_path();
5175 if (key_type == BTRFS_DIR_INDEX_KEY) {
5176 INIT_LIST_HEAD(&ins_list);
5177 INIT_LIST_HEAD(&del_list);
5178 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5181 btrfs_set_key_type(&key, key_type);
5182 key.offset = ctx->pos;
5183 key.objectid = btrfs_ino(inode);
5185 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5190 leaf = path->nodes[0];
5191 slot = path->slots[0];
5192 if (slot >= btrfs_header_nritems(leaf)) {
5193 ret = btrfs_next_leaf(root, path);
5201 item = btrfs_item_nr(slot);
5202 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5204 if (found_key.objectid != key.objectid)
5206 if (btrfs_key_type(&found_key) != key_type)
5208 if (found_key.offset < ctx->pos)
5210 if (key_type == BTRFS_DIR_INDEX_KEY &&
5211 btrfs_should_delete_dir_index(&del_list,
5215 ctx->pos = found_key.offset;
5218 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5220 di_total = btrfs_item_size(leaf, item);
5222 while (di_cur < di_total) {
5223 struct btrfs_key location;
5225 if (verify_dir_item(root, leaf, di))
5228 name_len = btrfs_dir_name_len(leaf, di);
5229 if (name_len <= sizeof(tmp_name)) {
5230 name_ptr = tmp_name;
5232 name_ptr = kmalloc(name_len, GFP_NOFS);
5238 read_extent_buffer(leaf, name_ptr,
5239 (unsigned long)(di + 1), name_len);
5241 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5242 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5245 /* is this a reference to our own snapshot? If so
5248 * In contrast to old kernels, we insert the snapshot's
5249 * dir item and dir index after it has been created, so
5250 * we won't find a reference to our own snapshot. We
5251 * still keep the following code for backward
5254 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5255 location.objectid == root->root_key.objectid) {
5259 over = !dir_emit(ctx, name_ptr, name_len,
5260 location.objectid, d_type);
5263 if (name_ptr != tmp_name)
5268 di_len = btrfs_dir_name_len(leaf, di) +
5269 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5271 di = (struct btrfs_dir_item *)((char *)di + di_len);
5277 if (key_type == BTRFS_DIR_INDEX_KEY) {
5280 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5285 /* Reached end of directory/root. Bump pos past the last item. */
5289 * Stop new entries from being returned after we return the last
5292 * New directory entries are assigned a strictly increasing
5293 * offset. This means that new entries created during readdir
5294 * are *guaranteed* to be seen in the future by that readdir.
5295 * This has broken buggy programs which operate on names as
5296 * they're returned by readdir. Until we re-use freed offsets
5297 * we have this hack to stop new entries from being returned
5298 * under the assumption that they'll never reach this huge
5301 * This is being careful not to overflow 32bit loff_t unless the
5302 * last entry requires it because doing so has broken 32bit apps
5305 if (key_type == BTRFS_DIR_INDEX_KEY) {
5306 if (ctx->pos >= INT_MAX)
5307 ctx->pos = LLONG_MAX;
5314 if (key_type == BTRFS_DIR_INDEX_KEY)
5315 btrfs_put_delayed_items(&ins_list, &del_list);
5316 btrfs_free_path(path);
5320 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5322 struct btrfs_root *root = BTRFS_I(inode)->root;
5323 struct btrfs_trans_handle *trans;
5325 bool nolock = false;
5327 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5330 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5333 if (wbc->sync_mode == WB_SYNC_ALL) {
5335 trans = btrfs_join_transaction_nolock(root);
5337 trans = btrfs_join_transaction(root);
5339 return PTR_ERR(trans);
5340 ret = btrfs_commit_transaction(trans, root);
5346 * This is somewhat expensive, updating the tree every time the
5347 * inode changes. But, it is most likely to find the inode in cache.
5348 * FIXME, needs more benchmarking...there are no reasons other than performance
5349 * to keep or drop this code.
5351 static int btrfs_dirty_inode(struct inode *inode)
5353 struct btrfs_root *root = BTRFS_I(inode)->root;
5354 struct btrfs_trans_handle *trans;
5357 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5360 trans = btrfs_join_transaction(root);
5362 return PTR_ERR(trans);
5364 ret = btrfs_update_inode(trans, root, inode);
5365 if (ret && ret == -ENOSPC) {
5366 /* whoops, lets try again with the full transaction */
5367 btrfs_end_transaction(trans, root);
5368 trans = btrfs_start_transaction(root, 1);
5370 return PTR_ERR(trans);
5372 ret = btrfs_update_inode(trans, root, inode);
5374 btrfs_end_transaction(trans, root);
5375 if (BTRFS_I(inode)->delayed_node)
5376 btrfs_balance_delayed_items(root);
5382 * This is a copy of file_update_time. We need this so we can return error on
5383 * ENOSPC for updating the inode in the case of file write and mmap writes.
5385 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5388 struct btrfs_root *root = BTRFS_I(inode)->root;
5390 if (btrfs_root_readonly(root))
5393 if (flags & S_VERSION)
5394 inode_inc_iversion(inode);
5395 if (flags & S_CTIME)
5396 inode->i_ctime = *now;
5397 if (flags & S_MTIME)
5398 inode->i_mtime = *now;
5399 if (flags & S_ATIME)
5400 inode->i_atime = *now;
5401 return btrfs_dirty_inode(inode);
5405 * find the highest existing sequence number in a directory
5406 * and then set the in-memory index_cnt variable to reflect
5407 * free sequence numbers
5409 static int btrfs_set_inode_index_count(struct inode *inode)
5411 struct btrfs_root *root = BTRFS_I(inode)->root;
5412 struct btrfs_key key, found_key;
5413 struct btrfs_path *path;
5414 struct extent_buffer *leaf;
5417 key.objectid = btrfs_ino(inode);
5418 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5419 key.offset = (u64)-1;
5421 path = btrfs_alloc_path();
5425 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5428 /* FIXME: we should be able to handle this */
5434 * MAGIC NUMBER EXPLANATION:
5435 * since we search a directory based on f_pos we have to start at 2
5436 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5437 * else has to start at 2
5439 if (path->slots[0] == 0) {
5440 BTRFS_I(inode)->index_cnt = 2;
5446 leaf = path->nodes[0];
5447 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5449 if (found_key.objectid != btrfs_ino(inode) ||
5450 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5451 BTRFS_I(inode)->index_cnt = 2;
5455 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5457 btrfs_free_path(path);
5462 * helper to find a free sequence number in a given directory. This current
5463 * code is very simple, later versions will do smarter things in the btree
5465 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5469 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5470 ret = btrfs_inode_delayed_dir_index_count(dir);
5472 ret = btrfs_set_inode_index_count(dir);
5478 *index = BTRFS_I(dir)->index_cnt;
5479 BTRFS_I(dir)->index_cnt++;
5484 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5485 struct btrfs_root *root,
5487 const char *name, int name_len,
5488 u64 ref_objectid, u64 objectid,
5489 umode_t mode, u64 *index)
5491 struct inode *inode;
5492 struct btrfs_inode_item *inode_item;
5493 struct btrfs_key *location;
5494 struct btrfs_path *path;
5495 struct btrfs_inode_ref *ref;
5496 struct btrfs_key key[2];
5501 path = btrfs_alloc_path();
5503 return ERR_PTR(-ENOMEM);
5505 inode = new_inode(root->fs_info->sb);
5507 btrfs_free_path(path);
5508 return ERR_PTR(-ENOMEM);
5512 * we have to initialize this early, so we can reclaim the inode
5513 * number if we fail afterwards in this function.
5515 inode->i_ino = objectid;
5518 trace_btrfs_inode_request(dir);
5520 ret = btrfs_set_inode_index(dir, index);
5522 btrfs_free_path(path);
5524 return ERR_PTR(ret);
5528 * index_cnt is ignored for everything but a dir,
5529 * btrfs_get_inode_index_count has an explanation for the magic
5532 BTRFS_I(inode)->index_cnt = 2;
5533 BTRFS_I(inode)->dir_index = *index;
5534 BTRFS_I(inode)->root = root;
5535 BTRFS_I(inode)->generation = trans->transid;
5536 inode->i_generation = BTRFS_I(inode)->generation;
5539 * We could have gotten an inode number from somebody who was fsynced
5540 * and then removed in this same transaction, so let's just set full
5541 * sync since it will be a full sync anyway and this will blow away the
5542 * old info in the log.
5544 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5546 key[0].objectid = objectid;
5547 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5551 * Start new inodes with an inode_ref. This is slightly more
5552 * efficient for small numbers of hard links since they will
5553 * be packed into one item. Extended refs will kick in if we
5554 * add more hard links than can fit in the ref item.
5556 key[1].objectid = objectid;
5557 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5558 key[1].offset = ref_objectid;
5560 sizes[0] = sizeof(struct btrfs_inode_item);
5561 sizes[1] = name_len + sizeof(*ref);
5563 path->leave_spinning = 1;
5564 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
5568 inode_init_owner(inode, dir, mode);
5569 inode_set_bytes(inode, 0);
5570 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5571 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5572 struct btrfs_inode_item);
5573 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5574 sizeof(*inode_item));
5575 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5577 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5578 struct btrfs_inode_ref);
5579 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5580 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5581 ptr = (unsigned long)(ref + 1);
5582 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5584 btrfs_mark_buffer_dirty(path->nodes[0]);
5585 btrfs_free_path(path);
5587 location = &BTRFS_I(inode)->location;
5588 location->objectid = objectid;
5589 location->offset = 0;
5590 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5592 btrfs_inherit_iflags(inode, dir);
5594 if (S_ISREG(mode)) {
5595 if (btrfs_test_opt(root, NODATASUM))
5596 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5597 if (btrfs_test_opt(root, NODATACOW))
5598 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5599 BTRFS_INODE_NODATASUM;
5602 btrfs_insert_inode_hash(inode);
5603 inode_tree_add(inode);
5605 trace_btrfs_inode_new(inode);
5606 btrfs_set_inode_last_trans(trans, inode);
5608 btrfs_update_root_times(trans, root);
5613 BTRFS_I(dir)->index_cnt--;
5614 btrfs_free_path(path);
5616 return ERR_PTR(ret);
5619 static inline u8 btrfs_inode_type(struct inode *inode)
5621 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5625 * utility function to add 'inode' into 'parent_inode' with
5626 * a give name and a given sequence number.
5627 * if 'add_backref' is true, also insert a backref from the
5628 * inode to the parent directory.
5630 int btrfs_add_link(struct btrfs_trans_handle *trans,
5631 struct inode *parent_inode, struct inode *inode,
5632 const char *name, int name_len, int add_backref, u64 index)
5635 struct btrfs_key key;
5636 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5637 u64 ino = btrfs_ino(inode);
5638 u64 parent_ino = btrfs_ino(parent_inode);
5640 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5641 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5644 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5648 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5649 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5650 key.objectid, root->root_key.objectid,
5651 parent_ino, index, name, name_len);
5652 } else if (add_backref) {
5653 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5657 /* Nothing to clean up yet */
5661 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5663 btrfs_inode_type(inode), index);
5664 if (ret == -EEXIST || ret == -EOVERFLOW)
5667 btrfs_abort_transaction(trans, root, ret);
5671 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5673 inode_inc_iversion(parent_inode);
5674 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5675 ret = btrfs_update_inode(trans, root, parent_inode);
5677 btrfs_abort_transaction(trans, root, ret);
5681 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5684 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5685 key.objectid, root->root_key.objectid,
5686 parent_ino, &local_index, name, name_len);
5688 } else if (add_backref) {
5692 err = btrfs_del_inode_ref(trans, root, name, name_len,
5693 ino, parent_ino, &local_index);
5698 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5699 struct inode *dir, struct dentry *dentry,
5700 struct inode *inode, int backref, u64 index)
5702 int err = btrfs_add_link(trans, dir, inode,
5703 dentry->d_name.name, dentry->d_name.len,
5710 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5711 umode_t mode, dev_t rdev)
5713 struct btrfs_trans_handle *trans;
5714 struct btrfs_root *root = BTRFS_I(dir)->root;
5715 struct inode *inode = NULL;
5721 if (!new_valid_dev(rdev))
5725 * 2 for inode item and ref
5727 * 1 for xattr if selinux is on
5729 trans = btrfs_start_transaction(root, 5);
5731 return PTR_ERR(trans);
5733 err = btrfs_find_free_ino(root, &objectid);
5737 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5738 dentry->d_name.len, btrfs_ino(dir), objectid,
5740 if (IS_ERR(inode)) {
5741 err = PTR_ERR(inode);
5745 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5752 * If the active LSM wants to access the inode during
5753 * d_instantiate it needs these. Smack checks to see
5754 * if the filesystem supports xattrs by looking at the
5758 inode->i_op = &btrfs_special_inode_operations;
5759 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5763 init_special_inode(inode, inode->i_mode, rdev);
5764 btrfs_update_inode(trans, root, inode);
5765 d_instantiate(dentry, inode);
5768 btrfs_end_transaction(trans, root);
5769 btrfs_btree_balance_dirty(root);
5771 inode_dec_link_count(inode);
5777 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5778 umode_t mode, bool excl)
5780 struct btrfs_trans_handle *trans;
5781 struct btrfs_root *root = BTRFS_I(dir)->root;
5782 struct inode *inode = NULL;
5783 int drop_inode_on_err = 0;
5789 * 2 for inode item and ref
5791 * 1 for xattr if selinux is on
5793 trans = btrfs_start_transaction(root, 5);
5795 return PTR_ERR(trans);
5797 err = btrfs_find_free_ino(root, &objectid);
5801 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5802 dentry->d_name.len, btrfs_ino(dir), objectid,
5804 if (IS_ERR(inode)) {
5805 err = PTR_ERR(inode);
5808 drop_inode_on_err = 1;
5810 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5814 err = btrfs_update_inode(trans, root, inode);
5819 * If the active LSM wants to access the inode during
5820 * d_instantiate it needs these. Smack checks to see
5821 * if the filesystem supports xattrs by looking at the
5824 inode->i_fop = &btrfs_file_operations;
5825 inode->i_op = &btrfs_file_inode_operations;
5827 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5831 inode->i_mapping->a_ops = &btrfs_aops;
5832 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5833 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5834 d_instantiate(dentry, inode);
5837 btrfs_end_transaction(trans, root);
5838 if (err && drop_inode_on_err) {
5839 inode_dec_link_count(inode);
5842 btrfs_btree_balance_dirty(root);
5846 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5847 struct dentry *dentry)
5849 struct btrfs_trans_handle *trans;
5850 struct btrfs_root *root = BTRFS_I(dir)->root;
5851 struct inode *inode = old_dentry->d_inode;
5856 /* do not allow sys_link's with other subvols of the same device */
5857 if (root->objectid != BTRFS_I(inode)->root->objectid)
5860 if (inode->i_nlink >= BTRFS_LINK_MAX)
5863 err = btrfs_set_inode_index(dir, &index);
5868 * 2 items for inode and inode ref
5869 * 2 items for dir items
5870 * 1 item for parent inode
5872 trans = btrfs_start_transaction(root, 5);
5873 if (IS_ERR(trans)) {
5874 err = PTR_ERR(trans);
5878 /* There are several dir indexes for this inode, clear the cache. */
5879 BTRFS_I(inode)->dir_index = 0ULL;
5881 inode_inc_iversion(inode);
5882 inode->i_ctime = CURRENT_TIME;
5884 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5886 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5891 struct dentry *parent = dentry->d_parent;
5892 err = btrfs_update_inode(trans, root, inode);
5895 d_instantiate(dentry, inode);
5896 btrfs_log_new_name(trans, inode, NULL, parent);
5899 btrfs_end_transaction(trans, root);
5902 inode_dec_link_count(inode);
5905 btrfs_btree_balance_dirty(root);
5909 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5911 struct inode *inode = NULL;
5912 struct btrfs_trans_handle *trans;
5913 struct btrfs_root *root = BTRFS_I(dir)->root;
5915 int drop_on_err = 0;
5920 * 2 items for inode and ref
5921 * 2 items for dir items
5922 * 1 for xattr if selinux is on
5924 trans = btrfs_start_transaction(root, 5);
5926 return PTR_ERR(trans);
5928 err = btrfs_find_free_ino(root, &objectid);
5932 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5933 dentry->d_name.len, btrfs_ino(dir), objectid,
5934 S_IFDIR | mode, &index);
5935 if (IS_ERR(inode)) {
5936 err = PTR_ERR(inode);
5942 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5946 inode->i_op = &btrfs_dir_inode_operations;
5947 inode->i_fop = &btrfs_dir_file_operations;
5949 btrfs_i_size_write(inode, 0);
5950 err = btrfs_update_inode(trans, root, inode);
5954 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5955 dentry->d_name.len, 0, index);
5959 d_instantiate(dentry, inode);
5963 btrfs_end_transaction(trans, root);
5966 btrfs_btree_balance_dirty(root);
5970 /* helper for btfs_get_extent. Given an existing extent in the tree,
5971 * and an extent that you want to insert, deal with overlap and insert
5972 * the new extent into the tree.
5974 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5975 struct extent_map *existing,
5976 struct extent_map *em,
5977 u64 map_start, u64 map_len)
5981 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5982 start_diff = map_start - em->start;
5983 em->start = map_start;
5985 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5986 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5987 em->block_start += start_diff;
5988 em->block_len -= start_diff;
5990 return add_extent_mapping(em_tree, em, 0);
5993 static noinline int uncompress_inline(struct btrfs_path *path,
5994 struct inode *inode, struct page *page,
5995 size_t pg_offset, u64 extent_offset,
5996 struct btrfs_file_extent_item *item)
5999 struct extent_buffer *leaf = path->nodes[0];
6002 unsigned long inline_size;
6006 WARN_ON(pg_offset != 0);
6007 compress_type = btrfs_file_extent_compression(leaf, item);
6008 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6009 inline_size = btrfs_file_extent_inline_item_len(leaf,
6010 btrfs_item_nr(path->slots[0]));
6011 tmp = kmalloc(inline_size, GFP_NOFS);
6014 ptr = btrfs_file_extent_inline_start(item);
6016 read_extent_buffer(leaf, tmp, ptr, inline_size);
6018 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6019 ret = btrfs_decompress(compress_type, tmp, page,
6020 extent_offset, inline_size, max_size);
6022 char *kaddr = kmap_atomic(page);
6023 unsigned long copy_size = min_t(u64,
6024 PAGE_CACHE_SIZE - pg_offset,
6025 max_size - extent_offset);
6026 memset(kaddr + pg_offset, 0, copy_size);
6027 kunmap_atomic(kaddr);
6034 * a bit scary, this does extent mapping from logical file offset to the disk.
6035 * the ugly parts come from merging extents from the disk with the in-ram
6036 * representation. This gets more complex because of the data=ordered code,
6037 * where the in-ram extents might be locked pending data=ordered completion.
6039 * This also copies inline extents directly into the page.
6042 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6043 size_t pg_offset, u64 start, u64 len,
6049 u64 extent_start = 0;
6051 u64 objectid = btrfs_ino(inode);
6053 struct btrfs_path *path = NULL;
6054 struct btrfs_root *root = BTRFS_I(inode)->root;
6055 struct btrfs_file_extent_item *item;
6056 struct extent_buffer *leaf;
6057 struct btrfs_key found_key;
6058 struct extent_map *em = NULL;
6059 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6060 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6061 struct btrfs_trans_handle *trans = NULL;
6065 read_lock(&em_tree->lock);
6066 em = lookup_extent_mapping(em_tree, start, len);
6068 em->bdev = root->fs_info->fs_devices->latest_bdev;
6069 read_unlock(&em_tree->lock);
6072 if (em->start > start || em->start + em->len <= start)
6073 free_extent_map(em);
6074 else if (em->block_start == EXTENT_MAP_INLINE && page)
6075 free_extent_map(em);
6079 em = alloc_extent_map();
6084 em->bdev = root->fs_info->fs_devices->latest_bdev;
6085 em->start = EXTENT_MAP_HOLE;
6086 em->orig_start = EXTENT_MAP_HOLE;
6088 em->block_len = (u64)-1;
6091 path = btrfs_alloc_path();
6097 * Chances are we'll be called again, so go ahead and do
6103 ret = btrfs_lookup_file_extent(trans, root, path,
6104 objectid, start, trans != NULL);
6111 if (path->slots[0] == 0)
6116 leaf = path->nodes[0];
6117 item = btrfs_item_ptr(leaf, path->slots[0],
6118 struct btrfs_file_extent_item);
6119 /* are we inside the extent that was found? */
6120 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6121 found_type = btrfs_key_type(&found_key);
6122 if (found_key.objectid != objectid ||
6123 found_type != BTRFS_EXTENT_DATA_KEY) {
6125 * If we backup past the first extent we want to move forward
6126 * and see if there is an extent in front of us, otherwise we'll
6127 * say there is a hole for our whole search range which can
6134 found_type = btrfs_file_extent_type(leaf, item);
6135 extent_start = found_key.offset;
6136 compress_type = btrfs_file_extent_compression(leaf, item);
6137 if (found_type == BTRFS_FILE_EXTENT_REG ||
6138 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6139 extent_end = extent_start +
6140 btrfs_file_extent_num_bytes(leaf, item);
6141 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6143 size = btrfs_file_extent_inline_len(leaf, item);
6144 extent_end = ALIGN(extent_start + size, root->sectorsize);
6147 if (start >= extent_end) {
6149 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6150 ret = btrfs_next_leaf(root, path);
6157 leaf = path->nodes[0];
6159 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6160 if (found_key.objectid != objectid ||
6161 found_key.type != BTRFS_EXTENT_DATA_KEY)
6163 if (start + len <= found_key.offset)
6166 em->orig_start = start;
6167 em->len = found_key.offset - start;
6171 em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
6172 if (found_type == BTRFS_FILE_EXTENT_REG ||
6173 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6174 em->start = extent_start;
6175 em->len = extent_end - extent_start;
6176 em->orig_start = extent_start -
6177 btrfs_file_extent_offset(leaf, item);
6178 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6180 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6182 em->block_start = EXTENT_MAP_HOLE;
6185 if (compress_type != BTRFS_COMPRESS_NONE) {
6186 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6187 em->compress_type = compress_type;
6188 em->block_start = bytenr;
6189 em->block_len = em->orig_block_len;
6191 bytenr += btrfs_file_extent_offset(leaf, item);
6192 em->block_start = bytenr;
6193 em->block_len = em->len;
6194 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6195 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6198 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6202 size_t extent_offset;
6205 em->block_start = EXTENT_MAP_INLINE;
6206 if (!page || create) {
6207 em->start = extent_start;
6208 em->len = extent_end - extent_start;
6212 size = btrfs_file_extent_inline_len(leaf, item);
6213 extent_offset = page_offset(page) + pg_offset - extent_start;
6214 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6215 size - extent_offset);
6216 em->start = extent_start + extent_offset;
6217 em->len = ALIGN(copy_size, root->sectorsize);
6218 em->orig_block_len = em->len;
6219 em->orig_start = em->start;
6220 if (compress_type) {
6221 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6222 em->compress_type = compress_type;
6224 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6225 if (create == 0 && !PageUptodate(page)) {
6226 if (btrfs_file_extent_compression(leaf, item) !=
6227 BTRFS_COMPRESS_NONE) {
6228 ret = uncompress_inline(path, inode, page,
6230 extent_offset, item);
6231 BUG_ON(ret); /* -ENOMEM */
6234 read_extent_buffer(leaf, map + pg_offset, ptr,
6236 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6237 memset(map + pg_offset + copy_size, 0,
6238 PAGE_CACHE_SIZE - pg_offset -
6243 flush_dcache_page(page);
6244 } else if (create && PageUptodate(page)) {
6248 free_extent_map(em);
6251 btrfs_release_path(path);
6252 trans = btrfs_join_transaction(root);
6255 return ERR_CAST(trans);
6259 write_extent_buffer(leaf, map + pg_offset, ptr,
6262 btrfs_mark_buffer_dirty(leaf);
6264 set_extent_uptodate(io_tree, em->start,
6265 extent_map_end(em) - 1, NULL, GFP_NOFS);
6268 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6272 em->orig_start = start;
6275 em->block_start = EXTENT_MAP_HOLE;
6276 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6278 btrfs_release_path(path);
6279 if (em->start > start || extent_map_end(em) <= start) {
6280 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6281 em->start, em->len, start, len);
6287 write_lock(&em_tree->lock);
6288 ret = add_extent_mapping(em_tree, em, 0);
6289 /* it is possible that someone inserted the extent into the tree
6290 * while we had the lock dropped. It is also possible that
6291 * an overlapping map exists in the tree
6293 if (ret == -EEXIST) {
6294 struct extent_map *existing;
6298 existing = lookup_extent_mapping(em_tree, start, len);
6299 if (existing && (existing->start > start ||
6300 existing->start + existing->len <= start)) {
6301 free_extent_map(existing);
6305 existing = lookup_extent_mapping(em_tree, em->start,
6308 err = merge_extent_mapping(em_tree, existing,
6311 free_extent_map(existing);
6313 free_extent_map(em);
6318 free_extent_map(em);
6322 free_extent_map(em);
6327 write_unlock(&em_tree->lock);
6330 trace_btrfs_get_extent(root, em);
6333 btrfs_free_path(path);
6335 ret = btrfs_end_transaction(trans, root);
6340 free_extent_map(em);
6341 return ERR_PTR(err);
6343 BUG_ON(!em); /* Error is always set */
6347 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6348 size_t pg_offset, u64 start, u64 len,
6351 struct extent_map *em;
6352 struct extent_map *hole_em = NULL;
6353 u64 range_start = start;
6359 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6366 * - a pre-alloc extent,
6367 * there might actually be delalloc bytes behind it.
6369 if (em->block_start != EXTENT_MAP_HOLE &&
6370 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6376 /* check to see if we've wrapped (len == -1 or similar) */
6385 /* ok, we didn't find anything, lets look for delalloc */
6386 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6387 end, len, EXTENT_DELALLOC, 1);
6388 found_end = range_start + found;
6389 if (found_end < range_start)
6390 found_end = (u64)-1;
6393 * we didn't find anything useful, return
6394 * the original results from get_extent()
6396 if (range_start > end || found_end <= start) {
6402 /* adjust the range_start to make sure it doesn't
6403 * go backwards from the start they passed in
6405 range_start = max(start, range_start);
6406 found = found_end - range_start;
6409 u64 hole_start = start;
6412 em = alloc_extent_map();
6418 * when btrfs_get_extent can't find anything it
6419 * returns one huge hole
6421 * make sure what it found really fits our range, and
6422 * adjust to make sure it is based on the start from
6426 u64 calc_end = extent_map_end(hole_em);
6428 if (calc_end <= start || (hole_em->start > end)) {
6429 free_extent_map(hole_em);
6432 hole_start = max(hole_em->start, start);
6433 hole_len = calc_end - hole_start;
6437 if (hole_em && range_start > hole_start) {
6438 /* our hole starts before our delalloc, so we
6439 * have to return just the parts of the hole
6440 * that go until the delalloc starts
6442 em->len = min(hole_len,
6443 range_start - hole_start);
6444 em->start = hole_start;
6445 em->orig_start = hole_start;
6447 * don't adjust block start at all,
6448 * it is fixed at EXTENT_MAP_HOLE
6450 em->block_start = hole_em->block_start;
6451 em->block_len = hole_len;
6452 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6453 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6455 em->start = range_start;
6457 em->orig_start = range_start;
6458 em->block_start = EXTENT_MAP_DELALLOC;
6459 em->block_len = found;
6461 } else if (hole_em) {
6466 free_extent_map(hole_em);
6468 free_extent_map(em);
6469 return ERR_PTR(err);
6474 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6477 struct btrfs_root *root = BTRFS_I(inode)->root;
6478 struct extent_map *em;
6479 struct btrfs_key ins;
6483 alloc_hint = get_extent_allocation_hint(inode, start, len);
6484 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
6485 alloc_hint, &ins, 1);
6487 return ERR_PTR(ret);
6489 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6490 ins.offset, ins.offset, ins.offset, 0);
6492 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6496 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6497 ins.offset, ins.offset, 0);
6499 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6500 free_extent_map(em);
6501 return ERR_PTR(ret);
6508 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6509 * block must be cow'd
6511 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6512 u64 *orig_start, u64 *orig_block_len,
6515 struct btrfs_trans_handle *trans;
6516 struct btrfs_path *path;
6518 struct extent_buffer *leaf;
6519 struct btrfs_root *root = BTRFS_I(inode)->root;
6520 struct btrfs_file_extent_item *fi;
6521 struct btrfs_key key;
6528 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6530 path = btrfs_alloc_path();
6534 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
6539 slot = path->slots[0];
6542 /* can't find the item, must cow */
6549 leaf = path->nodes[0];
6550 btrfs_item_key_to_cpu(leaf, &key, slot);
6551 if (key.objectid != btrfs_ino(inode) ||
6552 key.type != BTRFS_EXTENT_DATA_KEY) {
6553 /* not our file or wrong item type, must cow */
6557 if (key.offset > offset) {
6558 /* Wrong offset, must cow */
6562 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6563 found_type = btrfs_file_extent_type(leaf, fi);
6564 if (found_type != BTRFS_FILE_EXTENT_REG &&
6565 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6566 /* not a regular extent, must cow */
6570 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6573 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6574 if (extent_end <= offset)
6577 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6578 if (disk_bytenr == 0)
6581 if (btrfs_file_extent_compression(leaf, fi) ||
6582 btrfs_file_extent_encryption(leaf, fi) ||
6583 btrfs_file_extent_other_encoding(leaf, fi))
6586 backref_offset = btrfs_file_extent_offset(leaf, fi);
6589 *orig_start = key.offset - backref_offset;
6590 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6591 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6594 if (btrfs_extent_readonly(root, disk_bytenr))
6596 btrfs_release_path(path);
6599 * look for other files referencing this extent, if we
6600 * find any we must cow
6602 trans = btrfs_join_transaction(root);
6603 if (IS_ERR(trans)) {
6608 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6609 key.offset - backref_offset, disk_bytenr);
6610 btrfs_end_transaction(trans, root);
6617 * adjust disk_bytenr and num_bytes to cover just the bytes
6618 * in this extent we are about to write. If there
6619 * are any csums in that range we have to cow in order
6620 * to keep the csums correct
6622 disk_bytenr += backref_offset;
6623 disk_bytenr += offset - key.offset;
6624 num_bytes = min(offset + *len, extent_end) - offset;
6625 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6628 * all of the above have passed, it is safe to overwrite this extent
6634 btrfs_free_path(path);
6638 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6639 struct extent_state **cached_state, int writing)
6641 struct btrfs_ordered_extent *ordered;
6645 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6648 * We're concerned with the entire range that we're going to be
6649 * doing DIO to, so we need to make sure theres no ordered
6650 * extents in this range.
6652 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6653 lockend - lockstart + 1);
6656 * We need to make sure there are no buffered pages in this
6657 * range either, we could have raced between the invalidate in
6658 * generic_file_direct_write and locking the extent. The
6659 * invalidate needs to happen so that reads after a write do not
6662 if (!ordered && (!writing ||
6663 !test_range_bit(&BTRFS_I(inode)->io_tree,
6664 lockstart, lockend, EXTENT_UPTODATE, 0,
6668 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6669 cached_state, GFP_NOFS);
6672 btrfs_start_ordered_extent(inode, ordered, 1);
6673 btrfs_put_ordered_extent(ordered);
6675 /* Screw you mmap */
6676 ret = filemap_write_and_wait_range(inode->i_mapping,
6683 * If we found a page that couldn't be invalidated just
6684 * fall back to buffered.
6686 ret = invalidate_inode_pages2_range(inode->i_mapping,
6687 lockstart >> PAGE_CACHE_SHIFT,
6688 lockend >> PAGE_CACHE_SHIFT);
6699 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6700 u64 len, u64 orig_start,
6701 u64 block_start, u64 block_len,
6702 u64 orig_block_len, u64 ram_bytes,
6705 struct extent_map_tree *em_tree;
6706 struct extent_map *em;
6707 struct btrfs_root *root = BTRFS_I(inode)->root;
6710 em_tree = &BTRFS_I(inode)->extent_tree;
6711 em = alloc_extent_map();
6713 return ERR_PTR(-ENOMEM);
6716 em->orig_start = orig_start;
6717 em->mod_start = start;
6720 em->block_len = block_len;
6721 em->block_start = block_start;
6722 em->bdev = root->fs_info->fs_devices->latest_bdev;
6723 em->orig_block_len = orig_block_len;
6724 em->ram_bytes = ram_bytes;
6725 em->generation = -1;
6726 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6727 if (type == BTRFS_ORDERED_PREALLOC)
6728 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6731 btrfs_drop_extent_cache(inode, em->start,
6732 em->start + em->len - 1, 0);
6733 write_lock(&em_tree->lock);
6734 ret = add_extent_mapping(em_tree, em, 1);
6735 write_unlock(&em_tree->lock);
6736 } while (ret == -EEXIST);
6739 free_extent_map(em);
6740 return ERR_PTR(ret);
6747 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6748 struct buffer_head *bh_result, int create)
6750 struct extent_map *em;
6751 struct btrfs_root *root = BTRFS_I(inode)->root;
6752 struct extent_state *cached_state = NULL;
6753 u64 start = iblock << inode->i_blkbits;
6754 u64 lockstart, lockend;
6755 u64 len = bh_result->b_size;
6756 int unlock_bits = EXTENT_LOCKED;
6760 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6762 len = min_t(u64, len, root->sectorsize);
6765 lockend = start + len - 1;
6768 * If this errors out it's because we couldn't invalidate pagecache for
6769 * this range and we need to fallback to buffered.
6771 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6774 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6781 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6782 * io. INLINE is special, and we could probably kludge it in here, but
6783 * it's still buffered so for safety lets just fall back to the generic
6786 * For COMPRESSED we _have_ to read the entire extent in so we can
6787 * decompress it, so there will be buffering required no matter what we
6788 * do, so go ahead and fallback to buffered.
6790 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6791 * to buffered IO. Don't blame me, this is the price we pay for using
6794 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6795 em->block_start == EXTENT_MAP_INLINE) {
6796 free_extent_map(em);
6801 /* Just a good old fashioned hole, return */
6802 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6803 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6804 free_extent_map(em);
6809 * We don't allocate a new extent in the following cases
6811 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6813 * 2) The extent is marked as PREALLOC. We're good to go here and can
6814 * just use the extent.
6818 len = min(len, em->len - (start - em->start));
6819 lockstart = start + len;
6823 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6824 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6825 em->block_start != EXTENT_MAP_HOLE)) {
6828 u64 block_start, orig_start, orig_block_len, ram_bytes;
6830 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6831 type = BTRFS_ORDERED_PREALLOC;
6833 type = BTRFS_ORDERED_NOCOW;
6834 len = min(len, em->len - (start - em->start));
6835 block_start = em->block_start + (start - em->start);
6837 if (can_nocow_extent(inode, start, &len, &orig_start,
6838 &orig_block_len, &ram_bytes) == 1) {
6839 if (type == BTRFS_ORDERED_PREALLOC) {
6840 free_extent_map(em);
6841 em = create_pinned_em(inode, start, len,
6850 ret = btrfs_add_ordered_extent_dio(inode, start,
6851 block_start, len, len, type);
6853 free_extent_map(em);
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 static void btrfs_endio_direct_read(struct bio *bio, int err)
6924 struct btrfs_dio_private *dip = bio->bi_private;
6925 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6926 struct bio_vec *bvec = bio->bi_io_vec;
6927 struct inode *inode = dip->inode;
6928 struct btrfs_root *root = BTRFS_I(inode)->root;
6929 struct bio *dio_bio;
6930 u32 *csums = (u32 *)dip->csum;
6934 start = dip->logical_offset;
6936 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6937 struct page *page = bvec->bv_page;
6940 unsigned long flags;
6942 local_irq_save(flags);
6943 kaddr = kmap_atomic(page);
6944 csum = btrfs_csum_data(kaddr + bvec->bv_offset,
6945 csum, bvec->bv_len);
6946 btrfs_csum_final(csum, (char *)&csum);
6947 kunmap_atomic(kaddr);
6948 local_irq_restore(flags);
6950 flush_dcache_page(bvec->bv_page);
6951 if (csum != csums[index]) {
6952 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
6953 btrfs_ino(inode), start, csum,
6959 start += bvec->bv_len;
6962 } while (bvec <= bvec_end);
6964 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6965 dip->logical_offset + dip->bytes - 1);
6966 dio_bio = dip->dio_bio;
6970 /* If we had a csum failure make sure to clear the uptodate flag */
6972 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
6973 dio_end_io(dio_bio, err);
6977 static void btrfs_endio_direct_write(struct bio *bio, int err)
6979 struct btrfs_dio_private *dip = bio->bi_private;
6980 struct inode *inode = dip->inode;
6981 struct btrfs_root *root = BTRFS_I(inode)->root;
6982 struct btrfs_ordered_extent *ordered = NULL;
6983 u64 ordered_offset = dip->logical_offset;
6984 u64 ordered_bytes = dip->bytes;
6985 struct bio *dio_bio;
6991 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
6993 ordered_bytes, !err);
6997 ordered->work.func = finish_ordered_fn;
6998 ordered->work.flags = 0;
6999 btrfs_queue_worker(&root->fs_info->endio_write_workers,
7003 * our bio might span multiple ordered extents. If we haven't
7004 * completed the accounting for the whole dio, go back and try again
7006 if (ordered_offset < dip->logical_offset + dip->bytes) {
7007 ordered_bytes = dip->logical_offset + dip->bytes -
7013 dio_bio = dip->dio_bio;
7017 /* If we had an error make sure to clear the uptodate flag */
7019 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7020 dio_end_io(dio_bio, err);
7024 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7025 struct bio *bio, int mirror_num,
7026 unsigned long bio_flags, u64 offset)
7029 struct btrfs_root *root = BTRFS_I(inode)->root;
7030 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7031 BUG_ON(ret); /* -ENOMEM */
7035 static void btrfs_end_dio_bio(struct bio *bio, int err)
7037 struct btrfs_dio_private *dip = bio->bi_private;
7040 btrfs_err(BTRFS_I(dip->inode)->root->fs_info,
7041 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
7042 btrfs_ino(dip->inode), bio->bi_rw,
7043 (unsigned long long)bio->bi_sector, bio->bi_size, err);
7047 * before atomic variable goto zero, we must make sure
7048 * dip->errors is perceived to be set.
7050 smp_mb__before_atomic_dec();
7053 /* if there are more bios still pending for this dio, just exit */
7054 if (!atomic_dec_and_test(&dip->pending_bios))
7058 bio_io_error(dip->orig_bio);
7060 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
7061 bio_endio(dip->orig_bio, 0);
7067 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7068 u64 first_sector, gfp_t gfp_flags)
7070 int nr_vecs = bio_get_nr_vecs(bdev);
7071 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7074 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7075 int rw, u64 file_offset, int skip_sum,
7078 struct btrfs_dio_private *dip = bio->bi_private;
7079 int write = rw & REQ_WRITE;
7080 struct btrfs_root *root = BTRFS_I(inode)->root;
7084 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7089 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
7097 if (write && async_submit) {
7098 ret = btrfs_wq_submit_bio(root->fs_info,
7099 inode, rw, bio, 0, 0,
7101 __btrfs_submit_bio_start_direct_io,
7102 __btrfs_submit_bio_done);
7106 * If we aren't doing async submit, calculate the csum of the
7109 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7112 } else if (!skip_sum) {
7113 ret = btrfs_lookup_bio_sums_dio(root, inode, dip, bio,
7120 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7126 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7129 struct inode *inode = dip->inode;
7130 struct btrfs_root *root = BTRFS_I(inode)->root;
7132 struct bio *orig_bio = dip->orig_bio;
7133 struct bio_vec *bvec = orig_bio->bi_io_vec;
7134 u64 start_sector = orig_bio->bi_sector;
7135 u64 file_offset = dip->logical_offset;
7140 int async_submit = 0;
7142 map_length = orig_bio->bi_size;
7143 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7144 &map_length, NULL, 0);
7150 if (map_length >= orig_bio->bi_size) {
7155 /* async crcs make it difficult to collect full stripe writes. */
7156 if (btrfs_get_alloc_profile(root, 1) &
7157 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7162 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7165 bio->bi_private = dip;
7166 bio->bi_end_io = btrfs_end_dio_bio;
7167 atomic_inc(&dip->pending_bios);
7169 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7170 if (unlikely(map_length < submit_len + bvec->bv_len ||
7171 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7172 bvec->bv_offset) < bvec->bv_len)) {
7174 * inc the count before we submit the bio so
7175 * we know the end IO handler won't happen before
7176 * we inc the count. Otherwise, the dip might get freed
7177 * before we're done setting it up
7179 atomic_inc(&dip->pending_bios);
7180 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7181 file_offset, skip_sum,
7185 atomic_dec(&dip->pending_bios);
7189 start_sector += submit_len >> 9;
7190 file_offset += submit_len;
7195 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7196 start_sector, GFP_NOFS);
7199 bio->bi_private = dip;
7200 bio->bi_end_io = btrfs_end_dio_bio;
7202 map_length = orig_bio->bi_size;
7203 ret = btrfs_map_block(root->fs_info, rw,
7205 &map_length, NULL, 0);
7211 submit_len += bvec->bv_len;
7218 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7227 * before atomic variable goto zero, we must
7228 * make sure dip->errors is perceived to be set.
7230 smp_mb__before_atomic_dec();
7231 if (atomic_dec_and_test(&dip->pending_bios))
7232 bio_io_error(dip->orig_bio);
7234 /* bio_end_io() will handle error, so we needn't return it */
7238 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7239 struct inode *inode, loff_t file_offset)
7241 struct btrfs_root *root = BTRFS_I(inode)->root;
7242 struct btrfs_dio_private *dip;
7246 int write = rw & REQ_WRITE;
7250 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7252 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7258 if (!skip_sum && !write) {
7259 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
7260 sum_len = dio_bio->bi_size >> inode->i_sb->s_blocksize_bits;
7261 sum_len *= csum_size;
7266 dip = kmalloc(sizeof(*dip) + sum_len, GFP_NOFS);
7272 dip->private = dio_bio->bi_private;
7274 dip->logical_offset = file_offset;
7275 dip->bytes = dio_bio->bi_size;
7276 dip->disk_bytenr = (u64)dio_bio->bi_sector << 9;
7277 io_bio->bi_private = dip;
7279 dip->orig_bio = io_bio;
7280 dip->dio_bio = dio_bio;
7281 atomic_set(&dip->pending_bios, 0);
7284 io_bio->bi_end_io = btrfs_endio_direct_write;
7286 io_bio->bi_end_io = btrfs_endio_direct_read;
7288 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7297 * If this is a write, we need to clean up the reserved space and kill
7298 * the ordered extent.
7301 struct btrfs_ordered_extent *ordered;
7302 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7303 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7304 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7305 btrfs_free_reserved_extent(root, ordered->start,
7307 btrfs_put_ordered_extent(ordered);
7308 btrfs_put_ordered_extent(ordered);
7310 bio_endio(dio_bio, ret);
7313 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7314 const struct iovec *iov, loff_t offset,
7315 unsigned long nr_segs)
7321 unsigned blocksize_mask = root->sectorsize - 1;
7322 ssize_t retval = -EINVAL;
7323 loff_t end = offset;
7325 if (offset & blocksize_mask)
7328 /* Check the memory alignment. Blocks cannot straddle pages */
7329 for (seg = 0; seg < nr_segs; seg++) {
7330 addr = (unsigned long)iov[seg].iov_base;
7331 size = iov[seg].iov_len;
7333 if ((addr & blocksize_mask) || (size & blocksize_mask))
7336 /* If this is a write we don't need to check anymore */
7341 * Check to make sure we don't have duplicate iov_base's in this
7342 * iovec, if so return EINVAL, otherwise we'll get csum errors
7343 * when reading back.
7345 for (i = seg + 1; i < nr_segs; i++) {
7346 if (iov[seg].iov_base == iov[i].iov_base)
7355 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7356 const struct iovec *iov, loff_t offset,
7357 unsigned long nr_segs)
7359 struct file *file = iocb->ki_filp;
7360 struct inode *inode = file->f_mapping->host;
7364 bool relock = false;
7367 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7371 atomic_inc(&inode->i_dio_count);
7372 smp_mb__after_atomic_inc();
7375 * The generic stuff only does filemap_write_and_wait_range, which isn't
7376 * enough if we've written compressed pages to this area, so we need to
7377 * call btrfs_wait_ordered_range to make absolutely sure that any
7378 * outstanding dirty pages are on disk.
7380 count = iov_length(iov, nr_segs);
7381 ret = btrfs_wait_ordered_range(inode, offset, count);
7387 * If the write DIO is beyond the EOF, we need update
7388 * the isize, but it is protected by i_mutex. So we can
7389 * not unlock the i_mutex at this case.
7391 if (offset + count <= inode->i_size) {
7392 mutex_unlock(&inode->i_mutex);
7395 ret = btrfs_delalloc_reserve_space(inode, count);
7398 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7399 &BTRFS_I(inode)->runtime_flags))) {
7400 inode_dio_done(inode);
7401 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7405 ret = __blockdev_direct_IO(rw, iocb, inode,
7406 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7407 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7408 btrfs_submit_direct, flags);
7410 if (ret < 0 && ret != -EIOCBQUEUED)
7411 btrfs_delalloc_release_space(inode, count);
7412 else if (ret >= 0 && (size_t)ret < count)
7413 btrfs_delalloc_release_space(inode,
7414 count - (size_t)ret);
7416 btrfs_delalloc_release_metadata(inode, 0);
7420 inode_dio_done(inode);
7422 mutex_lock(&inode->i_mutex);
7427 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7429 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7430 __u64 start, __u64 len)
7434 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7438 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7441 int btrfs_readpage(struct file *file, struct page *page)
7443 struct extent_io_tree *tree;
7444 tree = &BTRFS_I(page->mapping->host)->io_tree;
7445 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7448 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7450 struct extent_io_tree *tree;
7453 if (current->flags & PF_MEMALLOC) {
7454 redirty_page_for_writepage(wbc, page);
7458 tree = &BTRFS_I(page->mapping->host)->io_tree;
7459 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7462 static int btrfs_writepages(struct address_space *mapping,
7463 struct writeback_control *wbc)
7465 struct extent_io_tree *tree;
7467 tree = &BTRFS_I(mapping->host)->io_tree;
7468 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7472 btrfs_readpages(struct file *file, struct address_space *mapping,
7473 struct list_head *pages, unsigned nr_pages)
7475 struct extent_io_tree *tree;
7476 tree = &BTRFS_I(mapping->host)->io_tree;
7477 return extent_readpages(tree, mapping, pages, nr_pages,
7480 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7482 struct extent_io_tree *tree;
7483 struct extent_map_tree *map;
7486 tree = &BTRFS_I(page->mapping->host)->io_tree;
7487 map = &BTRFS_I(page->mapping->host)->extent_tree;
7488 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7490 ClearPagePrivate(page);
7491 set_page_private(page, 0);
7492 page_cache_release(page);
7497 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7499 if (PageWriteback(page) || PageDirty(page))
7501 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7504 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
7505 unsigned int length)
7507 struct inode *inode = page->mapping->host;
7508 struct extent_io_tree *tree;
7509 struct btrfs_ordered_extent *ordered;
7510 struct extent_state *cached_state = NULL;
7511 u64 page_start = page_offset(page);
7512 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7513 int inode_evicting = inode->i_state & I_FREEING;
7516 * we have the page locked, so new writeback can't start,
7517 * and the dirty bit won't be cleared while we are here.
7519 * Wait for IO on this page so that we can safely clear
7520 * the PagePrivate2 bit and do ordered accounting
7522 wait_on_page_writeback(page);
7524 tree = &BTRFS_I(inode)->io_tree;
7526 btrfs_releasepage(page, GFP_NOFS);
7530 if (!inode_evicting)
7531 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7532 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7535 * IO on this page will never be started, so we need
7536 * to account for any ordered extents now
7538 if (!inode_evicting)
7539 clear_extent_bit(tree, page_start, page_end,
7540 EXTENT_DIRTY | EXTENT_DELALLOC |
7541 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7542 EXTENT_DEFRAG, 1, 0, &cached_state,
7545 * whoever cleared the private bit is responsible
7546 * for the finish_ordered_io
7548 if (TestClearPagePrivate2(page)) {
7549 struct btrfs_ordered_inode_tree *tree;
7552 tree = &BTRFS_I(inode)->ordered_tree;
7554 spin_lock_irq(&tree->lock);
7555 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
7556 new_len = page_start - ordered->file_offset;
7557 if (new_len < ordered->truncated_len)
7558 ordered->truncated_len = new_len;
7559 spin_unlock_irq(&tree->lock);
7561 if (btrfs_dec_test_ordered_pending(inode, &ordered,
7563 PAGE_CACHE_SIZE, 1))
7564 btrfs_finish_ordered_io(ordered);
7566 btrfs_put_ordered_extent(ordered);
7567 if (!inode_evicting) {
7568 cached_state = NULL;
7569 lock_extent_bits(tree, page_start, page_end, 0,
7574 if (!inode_evicting) {
7575 clear_extent_bit(tree, page_start, page_end,
7576 EXTENT_LOCKED | EXTENT_DIRTY |
7577 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
7578 EXTENT_DEFRAG, 1, 1,
7579 &cached_state, GFP_NOFS);
7581 __btrfs_releasepage(page, GFP_NOFS);
7584 ClearPageChecked(page);
7585 if (PagePrivate(page)) {
7586 ClearPagePrivate(page);
7587 set_page_private(page, 0);
7588 page_cache_release(page);
7593 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7594 * called from a page fault handler when a page is first dirtied. Hence we must
7595 * be careful to check for EOF conditions here. We set the page up correctly
7596 * for a written page which means we get ENOSPC checking when writing into
7597 * holes and correct delalloc and unwritten extent mapping on filesystems that
7598 * support these features.
7600 * We are not allowed to take the i_mutex here so we have to play games to
7601 * protect against truncate races as the page could now be beyond EOF. Because
7602 * vmtruncate() writes the inode size before removing pages, once we have the
7603 * page lock we can determine safely if the page is beyond EOF. If it is not
7604 * beyond EOF, then the page is guaranteed safe against truncation until we
7607 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7609 struct page *page = vmf->page;
7610 struct inode *inode = file_inode(vma->vm_file);
7611 struct btrfs_root *root = BTRFS_I(inode)->root;
7612 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7613 struct btrfs_ordered_extent *ordered;
7614 struct extent_state *cached_state = NULL;
7616 unsigned long zero_start;
7623 sb_start_pagefault(inode->i_sb);
7624 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7626 ret = file_update_time(vma->vm_file);
7632 else /* -ENOSPC, -EIO, etc */
7633 ret = VM_FAULT_SIGBUS;
7639 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7642 size = i_size_read(inode);
7643 page_start = page_offset(page);
7644 page_end = page_start + PAGE_CACHE_SIZE - 1;
7646 if ((page->mapping != inode->i_mapping) ||
7647 (page_start >= size)) {
7648 /* page got truncated out from underneath us */
7651 wait_on_page_writeback(page);
7653 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7654 set_page_extent_mapped(page);
7657 * we can't set the delalloc bits if there are pending ordered
7658 * extents. Drop our locks and wait for them to finish
7660 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7662 unlock_extent_cached(io_tree, page_start, page_end,
7663 &cached_state, GFP_NOFS);
7665 btrfs_start_ordered_extent(inode, ordered, 1);
7666 btrfs_put_ordered_extent(ordered);
7671 * XXX - page_mkwrite gets called every time the page is dirtied, even
7672 * if it was already dirty, so for space accounting reasons we need to
7673 * clear any delalloc bits for the range we are fixing to save. There
7674 * is probably a better way to do this, but for now keep consistent with
7675 * prepare_pages in the normal write path.
7677 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7678 EXTENT_DIRTY | EXTENT_DELALLOC |
7679 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7680 0, 0, &cached_state, GFP_NOFS);
7682 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7685 unlock_extent_cached(io_tree, page_start, page_end,
7686 &cached_state, GFP_NOFS);
7687 ret = VM_FAULT_SIGBUS;
7692 /* page is wholly or partially inside EOF */
7693 if (page_start + PAGE_CACHE_SIZE > size)
7694 zero_start = size & ~PAGE_CACHE_MASK;
7696 zero_start = PAGE_CACHE_SIZE;
7698 if (zero_start != PAGE_CACHE_SIZE) {
7700 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7701 flush_dcache_page(page);
7704 ClearPageChecked(page);
7705 set_page_dirty(page);
7706 SetPageUptodate(page);
7708 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7709 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7710 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7712 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7716 sb_end_pagefault(inode->i_sb);
7717 return VM_FAULT_LOCKED;
7721 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7723 sb_end_pagefault(inode->i_sb);
7727 static int btrfs_truncate(struct inode *inode)
7729 struct btrfs_root *root = BTRFS_I(inode)->root;
7730 struct btrfs_block_rsv *rsv;
7733 struct btrfs_trans_handle *trans;
7734 u64 mask = root->sectorsize - 1;
7735 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7737 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
7743 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7744 * 3 things going on here
7746 * 1) We need to reserve space for our orphan item and the space to
7747 * delete our orphan item. Lord knows we don't want to have a dangling
7748 * orphan item because we didn't reserve space to remove it.
7750 * 2) We need to reserve space to update our inode.
7752 * 3) We need to have something to cache all the space that is going to
7753 * be free'd up by the truncate operation, but also have some slack
7754 * space reserved in case it uses space during the truncate (thank you
7755 * very much snapshotting).
7757 * And we need these to all be seperate. The fact is we can use alot of
7758 * space doing the truncate, and we have no earthly idea how much space
7759 * we will use, so we need the truncate reservation to be seperate so it
7760 * doesn't end up using space reserved for updating the inode or
7761 * removing the orphan item. We also need to be able to stop the
7762 * transaction and start a new one, which means we need to be able to
7763 * update the inode several times, and we have no idea of knowing how
7764 * many times that will be, so we can't just reserve 1 item for the
7765 * entirety of the opration, so that has to be done seperately as well.
7766 * Then there is the orphan item, which does indeed need to be held on
7767 * to for the whole operation, and we need nobody to touch this reserved
7768 * space except the orphan code.
7770 * So that leaves us with
7772 * 1) root->orphan_block_rsv - for the orphan deletion.
7773 * 2) rsv - for the truncate reservation, which we will steal from the
7774 * transaction reservation.
7775 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7776 * updating the inode.
7778 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7781 rsv->size = min_size;
7785 * 1 for the truncate slack space
7786 * 1 for updating the inode.
7788 trans = btrfs_start_transaction(root, 2);
7789 if (IS_ERR(trans)) {
7790 err = PTR_ERR(trans);
7794 /* Migrate the slack space for the truncate to our reserve */
7795 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7800 * setattr is responsible for setting the ordered_data_close flag,
7801 * but that is only tested during the last file release. That
7802 * could happen well after the next commit, leaving a great big
7803 * window where new writes may get lost if someone chooses to write
7804 * to this file after truncating to zero
7806 * The inode doesn't have any dirty data here, and so if we commit
7807 * this is a noop. If someone immediately starts writing to the inode
7808 * it is very likely we'll catch some of their writes in this
7809 * transaction, and the commit will find this file on the ordered
7810 * data list with good things to send down.
7812 * This is a best effort solution, there is still a window where
7813 * using truncate to replace the contents of the file will
7814 * end up with a zero length file after a crash.
7816 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7817 &BTRFS_I(inode)->runtime_flags))
7818 btrfs_add_ordered_operation(trans, root, inode);
7821 * So if we truncate and then write and fsync we normally would just
7822 * write the extents that changed, which is a problem if we need to
7823 * first truncate that entire inode. So set this flag so we write out
7824 * all of the extents in the inode to the sync log so we're completely
7827 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7828 trans->block_rsv = rsv;
7831 ret = btrfs_truncate_inode_items(trans, root, inode,
7833 BTRFS_EXTENT_DATA_KEY);
7834 if (ret != -ENOSPC) {
7839 trans->block_rsv = &root->fs_info->trans_block_rsv;
7840 ret = btrfs_update_inode(trans, root, inode);
7846 btrfs_end_transaction(trans, root);
7847 btrfs_btree_balance_dirty(root);
7849 trans = btrfs_start_transaction(root, 2);
7850 if (IS_ERR(trans)) {
7851 ret = err = PTR_ERR(trans);
7856 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7858 BUG_ON(ret); /* shouldn't happen */
7859 trans->block_rsv = rsv;
7862 if (ret == 0 && inode->i_nlink > 0) {
7863 trans->block_rsv = root->orphan_block_rsv;
7864 ret = btrfs_orphan_del(trans, inode);
7870 trans->block_rsv = &root->fs_info->trans_block_rsv;
7871 ret = btrfs_update_inode(trans, root, inode);
7875 ret = btrfs_end_transaction(trans, root);
7876 btrfs_btree_balance_dirty(root);
7880 btrfs_free_block_rsv(root, rsv);
7889 * create a new subvolume directory/inode (helper for the ioctl).
7891 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7892 struct btrfs_root *new_root, u64 new_dirid)
7894 struct inode *inode;
7898 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7899 new_dirid, new_dirid,
7900 S_IFDIR | (~current_umask() & S_IRWXUGO),
7903 return PTR_ERR(inode);
7904 inode->i_op = &btrfs_dir_inode_operations;
7905 inode->i_fop = &btrfs_dir_file_operations;
7907 set_nlink(inode, 1);
7908 btrfs_i_size_write(inode, 0);
7910 err = btrfs_update_inode(trans, new_root, inode);
7916 struct inode *btrfs_alloc_inode(struct super_block *sb)
7918 struct btrfs_inode *ei;
7919 struct inode *inode;
7921 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7928 ei->last_sub_trans = 0;
7929 ei->logged_trans = 0;
7930 ei->delalloc_bytes = 0;
7931 ei->disk_i_size = 0;
7934 ei->index_cnt = (u64)-1;
7936 ei->last_unlink_trans = 0;
7937 ei->last_log_commit = 0;
7939 spin_lock_init(&ei->lock);
7940 ei->outstanding_extents = 0;
7941 ei->reserved_extents = 0;
7943 ei->runtime_flags = 0;
7944 ei->force_compress = BTRFS_COMPRESS_NONE;
7946 ei->delayed_node = NULL;
7948 inode = &ei->vfs_inode;
7949 extent_map_tree_init(&ei->extent_tree);
7950 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7951 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7952 ei->io_tree.track_uptodate = 1;
7953 ei->io_failure_tree.track_uptodate = 1;
7954 atomic_set(&ei->sync_writers, 0);
7955 mutex_init(&ei->log_mutex);
7956 mutex_init(&ei->delalloc_mutex);
7957 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7958 INIT_LIST_HEAD(&ei->delalloc_inodes);
7959 INIT_LIST_HEAD(&ei->ordered_operations);
7960 RB_CLEAR_NODE(&ei->rb_node);
7965 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
7966 void btrfs_test_destroy_inode(struct inode *inode)
7968 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7969 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7973 static void btrfs_i_callback(struct rcu_head *head)
7975 struct inode *inode = container_of(head, struct inode, i_rcu);
7976 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7979 void btrfs_destroy_inode(struct inode *inode)
7981 struct btrfs_ordered_extent *ordered;
7982 struct btrfs_root *root = BTRFS_I(inode)->root;
7984 WARN_ON(!hlist_empty(&inode->i_dentry));
7985 WARN_ON(inode->i_data.nrpages);
7986 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7987 WARN_ON(BTRFS_I(inode)->reserved_extents);
7988 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7989 WARN_ON(BTRFS_I(inode)->csum_bytes);
7992 * This can happen where we create an inode, but somebody else also
7993 * created the same inode and we need to destroy the one we already
8000 * Make sure we're properly removed from the ordered operation
8004 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
8005 spin_lock(&root->fs_info->ordered_root_lock);
8006 list_del_init(&BTRFS_I(inode)->ordered_operations);
8007 spin_unlock(&root->fs_info->ordered_root_lock);
8010 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8011 &BTRFS_I(inode)->runtime_flags)) {
8012 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
8014 atomic_dec(&root->orphan_inodes);
8018 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8022 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
8023 ordered->file_offset, ordered->len);
8024 btrfs_remove_ordered_extent(inode, ordered);
8025 btrfs_put_ordered_extent(ordered);
8026 btrfs_put_ordered_extent(ordered);
8029 inode_tree_del(inode);
8030 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8032 call_rcu(&inode->i_rcu, btrfs_i_callback);
8035 int btrfs_drop_inode(struct inode *inode)
8037 struct btrfs_root *root = BTRFS_I(inode)->root;
8042 /* the snap/subvol tree is on deleting */
8043 if (btrfs_root_refs(&root->root_item) == 0)
8046 return generic_drop_inode(inode);
8049 static void init_once(void *foo)
8051 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8053 inode_init_once(&ei->vfs_inode);
8056 void btrfs_destroy_cachep(void)
8059 * Make sure all delayed rcu free inodes are flushed before we
8063 if (btrfs_inode_cachep)
8064 kmem_cache_destroy(btrfs_inode_cachep);
8065 if (btrfs_trans_handle_cachep)
8066 kmem_cache_destroy(btrfs_trans_handle_cachep);
8067 if (btrfs_transaction_cachep)
8068 kmem_cache_destroy(btrfs_transaction_cachep);
8069 if (btrfs_path_cachep)
8070 kmem_cache_destroy(btrfs_path_cachep);
8071 if (btrfs_free_space_cachep)
8072 kmem_cache_destroy(btrfs_free_space_cachep);
8073 if (btrfs_delalloc_work_cachep)
8074 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8077 int btrfs_init_cachep(void)
8079 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8080 sizeof(struct btrfs_inode), 0,
8081 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8082 if (!btrfs_inode_cachep)
8085 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8086 sizeof(struct btrfs_trans_handle), 0,
8087 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8088 if (!btrfs_trans_handle_cachep)
8091 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8092 sizeof(struct btrfs_transaction), 0,
8093 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8094 if (!btrfs_transaction_cachep)
8097 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8098 sizeof(struct btrfs_path), 0,
8099 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8100 if (!btrfs_path_cachep)
8103 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8104 sizeof(struct btrfs_free_space), 0,
8105 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8106 if (!btrfs_free_space_cachep)
8109 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8110 sizeof(struct btrfs_delalloc_work), 0,
8111 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8113 if (!btrfs_delalloc_work_cachep)
8118 btrfs_destroy_cachep();
8122 static int btrfs_getattr(struct vfsmount *mnt,
8123 struct dentry *dentry, struct kstat *stat)
8126 struct inode *inode = dentry->d_inode;
8127 u32 blocksize = inode->i_sb->s_blocksize;
8129 generic_fillattr(inode, stat);
8130 stat->dev = BTRFS_I(inode)->root->anon_dev;
8131 stat->blksize = PAGE_CACHE_SIZE;
8133 spin_lock(&BTRFS_I(inode)->lock);
8134 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8135 spin_unlock(&BTRFS_I(inode)->lock);
8136 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8137 ALIGN(delalloc_bytes, blocksize)) >> 9;
8141 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8142 struct inode *new_dir, struct dentry *new_dentry)
8144 struct btrfs_trans_handle *trans;
8145 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8146 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8147 struct inode *new_inode = new_dentry->d_inode;
8148 struct inode *old_inode = old_dentry->d_inode;
8149 struct timespec ctime = CURRENT_TIME;
8153 u64 old_ino = btrfs_ino(old_inode);
8155 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8158 /* we only allow rename subvolume link between subvolumes */
8159 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8162 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8163 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8166 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8167 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8171 /* check for collisions, even if the name isn't there */
8172 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8173 new_dentry->d_name.name,
8174 new_dentry->d_name.len);
8177 if (ret == -EEXIST) {
8179 * eexist without a new_inode */
8180 if (WARN_ON(!new_inode)) {
8184 /* maybe -EOVERFLOW */
8191 * we're using rename to replace one file with another.
8192 * and the replacement file is large. Start IO on it now so
8193 * we don't add too much work to the end of the transaction
8195 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8196 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8197 filemap_flush(old_inode->i_mapping);
8199 /* close the racy window with snapshot create/destroy ioctl */
8200 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8201 down_read(&root->fs_info->subvol_sem);
8203 * We want to reserve the absolute worst case amount of items. So if
8204 * both inodes are subvols and we need to unlink them then that would
8205 * require 4 item modifications, but if they are both normal inodes it
8206 * would require 5 item modifications, so we'll assume their normal
8207 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8208 * should cover the worst case number of items we'll modify.
8210 trans = btrfs_start_transaction(root, 11);
8211 if (IS_ERR(trans)) {
8212 ret = PTR_ERR(trans);
8217 btrfs_record_root_in_trans(trans, dest);
8219 ret = btrfs_set_inode_index(new_dir, &index);
8223 BTRFS_I(old_inode)->dir_index = 0ULL;
8224 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8225 /* force full log commit if subvolume involved. */
8226 root->fs_info->last_trans_log_full_commit = trans->transid;
8228 ret = btrfs_insert_inode_ref(trans, dest,
8229 new_dentry->d_name.name,
8230 new_dentry->d_name.len,
8232 btrfs_ino(new_dir), index);
8236 * this is an ugly little race, but the rename is required
8237 * to make sure that if we crash, the inode is either at the
8238 * old name or the new one. pinning the log transaction lets
8239 * us make sure we don't allow a log commit to come in after
8240 * we unlink the name but before we add the new name back in.
8242 btrfs_pin_log_trans(root);
8245 * make sure the inode gets flushed if it is replacing
8248 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8249 btrfs_add_ordered_operation(trans, root, old_inode);
8251 inode_inc_iversion(old_dir);
8252 inode_inc_iversion(new_dir);
8253 inode_inc_iversion(old_inode);
8254 old_dir->i_ctime = old_dir->i_mtime = ctime;
8255 new_dir->i_ctime = new_dir->i_mtime = ctime;
8256 old_inode->i_ctime = ctime;
8258 if (old_dentry->d_parent != new_dentry->d_parent)
8259 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8261 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8262 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8263 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8264 old_dentry->d_name.name,
8265 old_dentry->d_name.len);
8267 ret = __btrfs_unlink_inode(trans, root, old_dir,
8268 old_dentry->d_inode,
8269 old_dentry->d_name.name,
8270 old_dentry->d_name.len);
8272 ret = btrfs_update_inode(trans, root, old_inode);
8275 btrfs_abort_transaction(trans, root, ret);
8280 inode_inc_iversion(new_inode);
8281 new_inode->i_ctime = CURRENT_TIME;
8282 if (unlikely(btrfs_ino(new_inode) ==
8283 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8284 root_objectid = BTRFS_I(new_inode)->location.objectid;
8285 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8287 new_dentry->d_name.name,
8288 new_dentry->d_name.len);
8289 BUG_ON(new_inode->i_nlink == 0);
8291 ret = btrfs_unlink_inode(trans, dest, new_dir,
8292 new_dentry->d_inode,
8293 new_dentry->d_name.name,
8294 new_dentry->d_name.len);
8296 if (!ret && new_inode->i_nlink == 0)
8297 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8299 btrfs_abort_transaction(trans, root, ret);
8304 ret = btrfs_add_link(trans, new_dir, old_inode,
8305 new_dentry->d_name.name,
8306 new_dentry->d_name.len, 0, index);
8308 btrfs_abort_transaction(trans, root, ret);
8312 if (old_inode->i_nlink == 1)
8313 BTRFS_I(old_inode)->dir_index = index;
8315 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8316 struct dentry *parent = new_dentry->d_parent;
8317 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8318 btrfs_end_log_trans(root);
8321 btrfs_end_transaction(trans, root);
8323 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8324 up_read(&root->fs_info->subvol_sem);
8329 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8331 struct btrfs_delalloc_work *delalloc_work;
8332 struct inode *inode;
8334 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8336 inode = delalloc_work->inode;
8337 if (delalloc_work->wait) {
8338 btrfs_wait_ordered_range(inode, 0, (u64)-1);
8340 filemap_flush(inode->i_mapping);
8341 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8342 &BTRFS_I(inode)->runtime_flags))
8343 filemap_flush(inode->i_mapping);
8346 if (delalloc_work->delay_iput)
8347 btrfs_add_delayed_iput(inode);
8350 complete(&delalloc_work->completion);
8353 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8354 int wait, int delay_iput)
8356 struct btrfs_delalloc_work *work;
8358 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8362 init_completion(&work->completion);
8363 INIT_LIST_HEAD(&work->list);
8364 work->inode = inode;
8366 work->delay_iput = delay_iput;
8367 work->work.func = btrfs_run_delalloc_work;
8372 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8374 wait_for_completion(&work->completion);
8375 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8379 * some fairly slow code that needs optimization. This walks the list
8380 * of all the inodes with pending delalloc and forces them to disk.
8382 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8384 struct btrfs_inode *binode;
8385 struct inode *inode;
8386 struct btrfs_delalloc_work *work, *next;
8387 struct list_head works;
8388 struct list_head splice;
8391 INIT_LIST_HEAD(&works);
8392 INIT_LIST_HEAD(&splice);
8394 spin_lock(&root->delalloc_lock);
8395 list_splice_init(&root->delalloc_inodes, &splice);
8396 while (!list_empty(&splice)) {
8397 binode = list_entry(splice.next, struct btrfs_inode,
8400 list_move_tail(&binode->delalloc_inodes,
8401 &root->delalloc_inodes);
8402 inode = igrab(&binode->vfs_inode);
8404 cond_resched_lock(&root->delalloc_lock);
8407 spin_unlock(&root->delalloc_lock);
8409 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8410 if (unlikely(!work)) {
8412 btrfs_add_delayed_iput(inode);
8418 list_add_tail(&work->list, &works);
8419 btrfs_queue_worker(&root->fs_info->flush_workers,
8423 spin_lock(&root->delalloc_lock);
8425 spin_unlock(&root->delalloc_lock);
8427 list_for_each_entry_safe(work, next, &works, list) {
8428 list_del_init(&work->list);
8429 btrfs_wait_and_free_delalloc_work(work);
8433 list_for_each_entry_safe(work, next, &works, list) {
8434 list_del_init(&work->list);
8435 btrfs_wait_and_free_delalloc_work(work);
8438 if (!list_empty_careful(&splice)) {
8439 spin_lock(&root->delalloc_lock);
8440 list_splice_tail(&splice, &root->delalloc_inodes);
8441 spin_unlock(&root->delalloc_lock);
8446 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8450 if (root->fs_info->sb->s_flags & MS_RDONLY)
8453 ret = __start_delalloc_inodes(root, delay_iput);
8455 * the filemap_flush will queue IO into the worker threads, but
8456 * we have to make sure the IO is actually started and that
8457 * ordered extents get created before we return
8459 atomic_inc(&root->fs_info->async_submit_draining);
8460 while (atomic_read(&root->fs_info->nr_async_submits) ||
8461 atomic_read(&root->fs_info->async_delalloc_pages)) {
8462 wait_event(root->fs_info->async_submit_wait,
8463 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8464 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8466 atomic_dec(&root->fs_info->async_submit_draining);
8470 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput)
8472 struct btrfs_root *root;
8473 struct list_head splice;
8476 if (fs_info->sb->s_flags & MS_RDONLY)
8479 INIT_LIST_HEAD(&splice);
8481 spin_lock(&fs_info->delalloc_root_lock);
8482 list_splice_init(&fs_info->delalloc_roots, &splice);
8483 while (!list_empty(&splice)) {
8484 root = list_first_entry(&splice, struct btrfs_root,
8486 root = btrfs_grab_fs_root(root);
8488 list_move_tail(&root->delalloc_root,
8489 &fs_info->delalloc_roots);
8490 spin_unlock(&fs_info->delalloc_root_lock);
8492 ret = __start_delalloc_inodes(root, delay_iput);
8493 btrfs_put_fs_root(root);
8497 spin_lock(&fs_info->delalloc_root_lock);
8499 spin_unlock(&fs_info->delalloc_root_lock);
8501 atomic_inc(&fs_info->async_submit_draining);
8502 while (atomic_read(&fs_info->nr_async_submits) ||
8503 atomic_read(&fs_info->async_delalloc_pages)) {
8504 wait_event(fs_info->async_submit_wait,
8505 (atomic_read(&fs_info->nr_async_submits) == 0 &&
8506 atomic_read(&fs_info->async_delalloc_pages) == 0));
8508 atomic_dec(&fs_info->async_submit_draining);
8511 if (!list_empty_careful(&splice)) {
8512 spin_lock(&fs_info->delalloc_root_lock);
8513 list_splice_tail(&splice, &fs_info->delalloc_roots);
8514 spin_unlock(&fs_info->delalloc_root_lock);
8519 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8520 const char *symname)
8522 struct btrfs_trans_handle *trans;
8523 struct btrfs_root *root = BTRFS_I(dir)->root;
8524 struct btrfs_path *path;
8525 struct btrfs_key key;
8526 struct inode *inode = NULL;
8534 struct btrfs_file_extent_item *ei;
8535 struct extent_buffer *leaf;
8537 name_len = strlen(symname);
8538 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8539 return -ENAMETOOLONG;
8542 * 2 items for inode item and ref
8543 * 2 items for dir items
8544 * 1 item for xattr if selinux is on
8546 trans = btrfs_start_transaction(root, 5);
8548 return PTR_ERR(trans);
8550 err = btrfs_find_free_ino(root, &objectid);
8554 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8555 dentry->d_name.len, btrfs_ino(dir), objectid,
8556 S_IFLNK|S_IRWXUGO, &index);
8557 if (IS_ERR(inode)) {
8558 err = PTR_ERR(inode);
8562 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8569 * If the active LSM wants to access the inode during
8570 * d_instantiate it needs these. Smack checks to see
8571 * if the filesystem supports xattrs by looking at the
8574 inode->i_fop = &btrfs_file_operations;
8575 inode->i_op = &btrfs_file_inode_operations;
8577 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8581 inode->i_mapping->a_ops = &btrfs_aops;
8582 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8583 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8588 path = btrfs_alloc_path();
8594 key.objectid = btrfs_ino(inode);
8596 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8597 datasize = btrfs_file_extent_calc_inline_size(name_len);
8598 err = btrfs_insert_empty_item(trans, root, path, &key,
8602 btrfs_free_path(path);
8605 leaf = path->nodes[0];
8606 ei = btrfs_item_ptr(leaf, path->slots[0],
8607 struct btrfs_file_extent_item);
8608 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8609 btrfs_set_file_extent_type(leaf, ei,
8610 BTRFS_FILE_EXTENT_INLINE);
8611 btrfs_set_file_extent_encryption(leaf, ei, 0);
8612 btrfs_set_file_extent_compression(leaf, ei, 0);
8613 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8614 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8616 ptr = btrfs_file_extent_inline_start(ei);
8617 write_extent_buffer(leaf, symname, ptr, name_len);
8618 btrfs_mark_buffer_dirty(leaf);
8619 btrfs_free_path(path);
8621 inode->i_op = &btrfs_symlink_inode_operations;
8622 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8623 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8624 inode_set_bytes(inode, name_len);
8625 btrfs_i_size_write(inode, name_len);
8626 err = btrfs_update_inode(trans, root, inode);
8632 d_instantiate(dentry, inode);
8633 btrfs_end_transaction(trans, root);
8635 inode_dec_link_count(inode);
8638 btrfs_btree_balance_dirty(root);
8642 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8643 u64 start, u64 num_bytes, u64 min_size,
8644 loff_t actual_len, u64 *alloc_hint,
8645 struct btrfs_trans_handle *trans)
8647 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8648 struct extent_map *em;
8649 struct btrfs_root *root = BTRFS_I(inode)->root;
8650 struct btrfs_key ins;
8651 u64 cur_offset = start;
8655 bool own_trans = true;
8659 while (num_bytes > 0) {
8661 trans = btrfs_start_transaction(root, 3);
8662 if (IS_ERR(trans)) {
8663 ret = PTR_ERR(trans);
8668 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8669 cur_bytes = max(cur_bytes, min_size);
8670 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
8671 *alloc_hint, &ins, 1);
8674 btrfs_end_transaction(trans, root);
8678 ret = insert_reserved_file_extent(trans, inode,
8679 cur_offset, ins.objectid,
8680 ins.offset, ins.offset,
8681 ins.offset, 0, 0, 0,
8682 BTRFS_FILE_EXTENT_PREALLOC);
8684 btrfs_free_reserved_extent(root, ins.objectid,
8686 btrfs_abort_transaction(trans, root, ret);
8688 btrfs_end_transaction(trans, root);
8691 btrfs_drop_extent_cache(inode, cur_offset,
8692 cur_offset + ins.offset -1, 0);
8694 em = alloc_extent_map();
8696 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8697 &BTRFS_I(inode)->runtime_flags);
8701 em->start = cur_offset;
8702 em->orig_start = cur_offset;
8703 em->len = ins.offset;
8704 em->block_start = ins.objectid;
8705 em->block_len = ins.offset;
8706 em->orig_block_len = ins.offset;
8707 em->ram_bytes = ins.offset;
8708 em->bdev = root->fs_info->fs_devices->latest_bdev;
8709 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8710 em->generation = trans->transid;
8713 write_lock(&em_tree->lock);
8714 ret = add_extent_mapping(em_tree, em, 1);
8715 write_unlock(&em_tree->lock);
8718 btrfs_drop_extent_cache(inode, cur_offset,
8719 cur_offset + ins.offset - 1,
8722 free_extent_map(em);
8724 num_bytes -= ins.offset;
8725 cur_offset += ins.offset;
8726 *alloc_hint = ins.objectid + ins.offset;
8728 inode_inc_iversion(inode);
8729 inode->i_ctime = CURRENT_TIME;
8730 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8731 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8732 (actual_len > inode->i_size) &&
8733 (cur_offset > inode->i_size)) {
8734 if (cur_offset > actual_len)
8735 i_size = actual_len;
8737 i_size = cur_offset;
8738 i_size_write(inode, i_size);
8739 btrfs_ordered_update_i_size(inode, i_size, NULL);
8742 ret = btrfs_update_inode(trans, root, inode);
8745 btrfs_abort_transaction(trans, root, ret);
8747 btrfs_end_transaction(trans, root);
8752 btrfs_end_transaction(trans, root);
8757 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8758 u64 start, u64 num_bytes, u64 min_size,
8759 loff_t actual_len, u64 *alloc_hint)
8761 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8762 min_size, actual_len, alloc_hint,
8766 int btrfs_prealloc_file_range_trans(struct inode *inode,
8767 struct btrfs_trans_handle *trans, int mode,
8768 u64 start, u64 num_bytes, u64 min_size,
8769 loff_t actual_len, u64 *alloc_hint)
8771 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8772 min_size, actual_len, alloc_hint, trans);
8775 static int btrfs_set_page_dirty(struct page *page)
8777 return __set_page_dirty_nobuffers(page);
8780 static int btrfs_permission(struct inode *inode, int mask)
8782 struct btrfs_root *root = BTRFS_I(inode)->root;
8783 umode_t mode = inode->i_mode;
8785 if (mask & MAY_WRITE &&
8786 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8787 if (btrfs_root_readonly(root))
8789 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8792 return generic_permission(inode, mask);
8795 static const struct inode_operations btrfs_dir_inode_operations = {
8796 .getattr = btrfs_getattr,
8797 .lookup = btrfs_lookup,
8798 .create = btrfs_create,
8799 .unlink = btrfs_unlink,
8801 .mkdir = btrfs_mkdir,
8802 .rmdir = btrfs_rmdir,
8803 .rename = btrfs_rename,
8804 .symlink = btrfs_symlink,
8805 .setattr = btrfs_setattr,
8806 .mknod = btrfs_mknod,
8807 .setxattr = btrfs_setxattr,
8808 .getxattr = btrfs_getxattr,
8809 .listxattr = btrfs_listxattr,
8810 .removexattr = btrfs_removexattr,
8811 .permission = btrfs_permission,
8812 .get_acl = btrfs_get_acl,
8813 .update_time = btrfs_update_time,
8815 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8816 .lookup = btrfs_lookup,
8817 .permission = btrfs_permission,
8818 .get_acl = btrfs_get_acl,
8819 .update_time = btrfs_update_time,
8822 static const struct file_operations btrfs_dir_file_operations = {
8823 .llseek = generic_file_llseek,
8824 .read = generic_read_dir,
8825 .iterate = btrfs_real_readdir,
8826 .unlocked_ioctl = btrfs_ioctl,
8827 #ifdef CONFIG_COMPAT
8828 .compat_ioctl = btrfs_ioctl,
8830 .release = btrfs_release_file,
8831 .fsync = btrfs_sync_file,
8834 static struct extent_io_ops btrfs_extent_io_ops = {
8835 .fill_delalloc = run_delalloc_range,
8836 .submit_bio_hook = btrfs_submit_bio_hook,
8837 .merge_bio_hook = btrfs_merge_bio_hook,
8838 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8839 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8840 .writepage_start_hook = btrfs_writepage_start_hook,
8841 .set_bit_hook = btrfs_set_bit_hook,
8842 .clear_bit_hook = btrfs_clear_bit_hook,
8843 .merge_extent_hook = btrfs_merge_extent_hook,
8844 .split_extent_hook = btrfs_split_extent_hook,
8848 * btrfs doesn't support the bmap operation because swapfiles
8849 * use bmap to make a mapping of extents in the file. They assume
8850 * these extents won't change over the life of the file and they
8851 * use the bmap result to do IO directly to the drive.
8853 * the btrfs bmap call would return logical addresses that aren't
8854 * suitable for IO and they also will change frequently as COW
8855 * operations happen. So, swapfile + btrfs == corruption.
8857 * For now we're avoiding this by dropping bmap.
8859 static const struct address_space_operations btrfs_aops = {
8860 .readpage = btrfs_readpage,
8861 .writepage = btrfs_writepage,
8862 .writepages = btrfs_writepages,
8863 .readpages = btrfs_readpages,
8864 .direct_IO = btrfs_direct_IO,
8865 .invalidatepage = btrfs_invalidatepage,
8866 .releasepage = btrfs_releasepage,
8867 .set_page_dirty = btrfs_set_page_dirty,
8868 .error_remove_page = generic_error_remove_page,
8871 static const struct address_space_operations btrfs_symlink_aops = {
8872 .readpage = btrfs_readpage,
8873 .writepage = btrfs_writepage,
8874 .invalidatepage = btrfs_invalidatepage,
8875 .releasepage = btrfs_releasepage,
8878 static const struct inode_operations btrfs_file_inode_operations = {
8879 .getattr = btrfs_getattr,
8880 .setattr = btrfs_setattr,
8881 .setxattr = btrfs_setxattr,
8882 .getxattr = btrfs_getxattr,
8883 .listxattr = btrfs_listxattr,
8884 .removexattr = btrfs_removexattr,
8885 .permission = btrfs_permission,
8886 .fiemap = btrfs_fiemap,
8887 .get_acl = btrfs_get_acl,
8888 .update_time = btrfs_update_time,
8890 static const struct inode_operations btrfs_special_inode_operations = {
8891 .getattr = btrfs_getattr,
8892 .setattr = btrfs_setattr,
8893 .permission = btrfs_permission,
8894 .setxattr = btrfs_setxattr,
8895 .getxattr = btrfs_getxattr,
8896 .listxattr = btrfs_listxattr,
8897 .removexattr = btrfs_removexattr,
8898 .get_acl = btrfs_get_acl,
8899 .update_time = btrfs_update_time,
8901 static const struct inode_operations btrfs_symlink_inode_operations = {
8902 .readlink = generic_readlink,
8903 .follow_link = page_follow_link_light,
8904 .put_link = page_put_link,
8905 .getattr = btrfs_getattr,
8906 .setattr = btrfs_setattr,
8907 .permission = btrfs_permission,
8908 .setxattr = btrfs_setxattr,
8909 .getxattr = btrfs_getxattr,
8910 .listxattr = btrfs_listxattr,
8911 .removexattr = btrfs_removexattr,
8912 .get_acl = btrfs_get_acl,
8913 .update_time = btrfs_update_time,
8916 const struct dentry_operations btrfs_dentry_operations = {
8917 .d_delete = btrfs_dentry_delete,
8918 .d_release = btrfs_dentry_release,