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>
49 #include "transaction.h"
50 #include "btrfs_inode.h"
51 #include "print-tree.h"
52 #include "ordered-data.h"
56 #include "compression.h"
58 #include "free-space-cache.h"
59 #include "inode-map.h"
63 struct btrfs_iget_args {
65 struct btrfs_root *root;
68 static const struct inode_operations btrfs_dir_inode_operations;
69 static const struct inode_operations btrfs_symlink_inode_operations;
70 static const struct inode_operations btrfs_dir_ro_inode_operations;
71 static const struct inode_operations btrfs_special_inode_operations;
72 static const struct inode_operations btrfs_file_inode_operations;
73 static const struct address_space_operations btrfs_aops;
74 static const struct address_space_operations btrfs_symlink_aops;
75 static const struct file_operations btrfs_dir_file_operations;
76 static struct extent_io_ops btrfs_extent_io_ops;
78 static struct kmem_cache *btrfs_inode_cachep;
79 static struct kmem_cache *btrfs_delalloc_work_cachep;
80 struct kmem_cache *btrfs_trans_handle_cachep;
81 struct kmem_cache *btrfs_transaction_cachep;
82 struct kmem_cache *btrfs_path_cachep;
83 struct kmem_cache *btrfs_free_space_cachep;
86 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
87 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
88 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
89 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
90 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
91 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
92 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
93 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
96 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
97 static int btrfs_truncate(struct inode *inode);
98 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
99 static noinline int cow_file_range(struct inode *inode,
100 struct page *locked_page,
101 u64 start, u64 end, int *page_started,
102 unsigned long *nr_written, int unlock);
103 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
104 u64 len, u64 orig_start,
105 u64 block_start, u64 block_len,
106 u64 orig_block_len, u64 ram_bytes,
109 static int btrfs_dirty_inode(struct inode *inode);
111 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
112 struct inode *inode, struct inode *dir,
113 const struct qstr *qstr)
117 err = btrfs_init_acl(trans, inode, dir);
119 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
124 * this does all the hard work for inserting an inline extent into
125 * the btree. The caller should have done a btrfs_drop_extents so that
126 * no overlapping inline items exist in the btree
128 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
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 btrfs_key key;
135 struct btrfs_path *path;
136 struct extent_buffer *leaf;
137 struct page *page = NULL;
140 struct btrfs_file_extent_item *ei;
143 size_t cur_size = size;
145 unsigned long offset;
147 if (compressed_size && compressed_pages)
148 cur_size = compressed_size;
150 path = btrfs_alloc_path();
154 path->leave_spinning = 1;
156 key.objectid = btrfs_ino(inode);
158 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
159 datasize = btrfs_file_extent_calc_inline_size(cur_size);
161 inode_add_bytes(inode, size);
162 ret = btrfs_insert_empty_item(trans, root, path, &key,
168 leaf = path->nodes[0];
169 ei = btrfs_item_ptr(leaf, path->slots[0],
170 struct btrfs_file_extent_item);
171 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
172 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
173 btrfs_set_file_extent_encryption(leaf, ei, 0);
174 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
175 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
176 ptr = btrfs_file_extent_inline_start(ei);
178 if (compress_type != BTRFS_COMPRESS_NONE) {
181 while (compressed_size > 0) {
182 cpage = compressed_pages[i];
183 cur_size = min_t(unsigned long, compressed_size,
186 kaddr = kmap_atomic(cpage);
187 write_extent_buffer(leaf, kaddr, ptr, cur_size);
188 kunmap_atomic(kaddr);
192 compressed_size -= cur_size;
194 btrfs_set_file_extent_compression(leaf, ei,
197 page = find_get_page(inode->i_mapping,
198 start >> PAGE_CACHE_SHIFT);
199 btrfs_set_file_extent_compression(leaf, ei, 0);
200 kaddr = kmap_atomic(page);
201 offset = start & (PAGE_CACHE_SIZE - 1);
202 write_extent_buffer(leaf, kaddr + offset, ptr, size);
203 kunmap_atomic(kaddr);
204 page_cache_release(page);
206 btrfs_mark_buffer_dirty(leaf);
207 btrfs_free_path(path);
210 * we're an inline extent, so nobody can
211 * extend the file past i_size without locking
212 * a page we already have locked.
214 * We must do any isize and inode updates
215 * before we unlock the pages. Otherwise we
216 * could end up racing with unlink.
218 BTRFS_I(inode)->disk_i_size = inode->i_size;
219 ret = btrfs_update_inode(trans, root, inode);
223 btrfs_free_path(path);
229 * conditionally insert an inline extent into the file. This
230 * does the checks required to make sure the data is small enough
231 * to fit as an inline extent.
233 static noinline int cow_file_range_inline(struct btrfs_root *root,
234 struct inode *inode, u64 start,
235 u64 end, size_t compressed_size,
237 struct page **compressed_pages)
239 struct btrfs_trans_handle *trans;
240 u64 isize = i_size_read(inode);
241 u64 actual_end = min(end + 1, isize);
242 u64 inline_len = actual_end - start;
243 u64 aligned_end = ALIGN(end, root->sectorsize);
244 u64 data_len = inline_len;
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 trans = btrfs_join_transaction(root);
262 return PTR_ERR(trans);
263 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
265 ret = btrfs_drop_extents(trans, root, inode, start, aligned_end, 1);
267 btrfs_abort_transaction(trans, root, ret);
271 if (isize > actual_end)
272 inline_len = min_t(u64, isize, actual_end);
273 ret = insert_inline_extent(trans, root, inode, start,
274 inline_len, compressed_size,
275 compress_type, compressed_pages);
276 if (ret && ret != -ENOSPC) {
277 btrfs_abort_transaction(trans, root, ret);
279 } else if (ret == -ENOSPC) {
284 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
285 btrfs_delalloc_release_metadata(inode, end + 1 - start);
286 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
288 btrfs_end_transaction(trans, root);
292 struct async_extent {
297 unsigned long nr_pages;
299 struct list_head list;
304 struct btrfs_root *root;
305 struct page *locked_page;
308 struct list_head extents;
309 struct btrfs_work work;
312 static noinline int add_async_extent(struct async_cow *cow,
313 u64 start, u64 ram_size,
316 unsigned long nr_pages,
319 struct async_extent *async_extent;
321 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
322 BUG_ON(!async_extent); /* -ENOMEM */
323 async_extent->start = start;
324 async_extent->ram_size = ram_size;
325 async_extent->compressed_size = compressed_size;
326 async_extent->pages = pages;
327 async_extent->nr_pages = nr_pages;
328 async_extent->compress_type = compress_type;
329 list_add_tail(&async_extent->list, &cow->extents);
334 * we create compressed extents in two phases. The first
335 * phase compresses a range of pages that have already been
336 * locked (both pages and state bits are locked).
338 * This is done inside an ordered work queue, and the compression
339 * is spread across many cpus. The actual IO submission is step
340 * two, and the ordered work queue takes care of making sure that
341 * happens in the same order things were put onto the queue by
342 * writepages and friends.
344 * If this code finds it can't get good compression, it puts an
345 * entry onto the work queue to write the uncompressed bytes. This
346 * makes sure that both compressed inodes and uncompressed inodes
347 * are written in the same order that the flusher thread sent them
350 static noinline int compress_file_range(struct inode *inode,
351 struct page *locked_page,
353 struct async_cow *async_cow,
356 struct btrfs_root *root = BTRFS_I(inode)->root;
358 u64 blocksize = root->sectorsize;
360 u64 isize = i_size_read(inode);
362 struct page **pages = NULL;
363 unsigned long nr_pages;
364 unsigned long nr_pages_ret = 0;
365 unsigned long total_compressed = 0;
366 unsigned long total_in = 0;
367 unsigned long max_compressed = 128 * 1024;
368 unsigned long max_uncompressed = 128 * 1024;
371 int compress_type = root->fs_info->compress_type;
374 /* if this is a small write inside eof, kick off a defrag */
375 if ((end - start + 1) < 16 * 1024 &&
376 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
377 btrfs_add_inode_defrag(NULL, inode);
379 actual_end = min_t(u64, isize, end + 1);
382 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
383 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
386 * we don't want to send crud past the end of i_size through
387 * compression, that's just a waste of CPU time. So, if the
388 * end of the file is before the start of our current
389 * requested range of bytes, we bail out to the uncompressed
390 * cleanup code that can deal with all of this.
392 * It isn't really the fastest way to fix things, but this is a
393 * very uncommon corner.
395 if (actual_end <= start)
396 goto cleanup_and_bail_uncompressed;
398 total_compressed = actual_end - start;
400 /* we want to make sure that amount of ram required to uncompress
401 * an extent is reasonable, so we limit the total size in ram
402 * of a compressed extent to 128k. This is a crucial number
403 * because it also controls how easily we can spread reads across
404 * cpus for decompression.
406 * We also want to make sure the amount of IO required to do
407 * a random read is reasonably small, so we limit the size of
408 * a compressed extent to 128k.
410 total_compressed = min(total_compressed, max_uncompressed);
411 num_bytes = ALIGN(end - start + 1, blocksize);
412 num_bytes = max(blocksize, num_bytes);
417 * we do compression for mount -o compress and when the
418 * inode has not been flagged as nocompress. This flag can
419 * change at any time if we discover bad compression ratios.
421 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
422 (btrfs_test_opt(root, COMPRESS) ||
423 (BTRFS_I(inode)->force_compress) ||
424 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
426 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
428 /* just bail out to the uncompressed code */
432 if (BTRFS_I(inode)->force_compress)
433 compress_type = BTRFS_I(inode)->force_compress;
436 * we need to call clear_page_dirty_for_io on each
437 * page in the range. Otherwise applications with the file
438 * mmap'd can wander in and change the page contents while
439 * we are compressing them.
441 * If the compression fails for any reason, we set the pages
442 * dirty again later on.
444 extent_range_clear_dirty_for_io(inode, start, end);
446 ret = btrfs_compress_pages(compress_type,
447 inode->i_mapping, start,
448 total_compressed, pages,
449 nr_pages, &nr_pages_ret,
455 unsigned long offset = total_compressed &
456 (PAGE_CACHE_SIZE - 1);
457 struct page *page = pages[nr_pages_ret - 1];
460 /* zero the tail end of the last page, we might be
461 * sending it down to disk
464 kaddr = kmap_atomic(page);
465 memset(kaddr + offset, 0,
466 PAGE_CACHE_SIZE - offset);
467 kunmap_atomic(kaddr);
474 /* lets try to make an inline extent */
475 if (ret || total_in < (actual_end - start)) {
476 /* we didn't compress the entire range, try
477 * to make an uncompressed inline extent.
479 ret = cow_file_range_inline(root, inode, start, end,
482 /* try making a compressed inline extent */
483 ret = cow_file_range_inline(root, inode, start, end,
485 compress_type, pages);
488 unsigned long clear_flags = EXTENT_DELALLOC |
490 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
493 * inline extent creation worked or returned error,
494 * we don't need to create any more async work items.
495 * Unlock and free up our temp pages.
497 extent_clear_unlock_delalloc(inode, start, end, NULL,
498 clear_flags, PAGE_UNLOCK |
508 * we aren't doing an inline extent round the compressed size
509 * up to a block size boundary so the allocator does sane
512 total_compressed = ALIGN(total_compressed, blocksize);
515 * one last check to make sure the compression is really a
516 * win, compare the page count read with the blocks on disk
518 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
519 if (total_compressed >= total_in) {
522 num_bytes = total_in;
525 if (!will_compress && pages) {
527 * the compression code ran but failed to make things smaller,
528 * free any pages it allocated and our page pointer array
530 for (i = 0; i < nr_pages_ret; i++) {
531 WARN_ON(pages[i]->mapping);
532 page_cache_release(pages[i]);
536 total_compressed = 0;
539 /* flag the file so we don't compress in the future */
540 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
541 !(BTRFS_I(inode)->force_compress)) {
542 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
548 /* the async work queues will take care of doing actual
549 * allocation on disk for these compressed pages,
550 * and will submit them to the elevator.
552 add_async_extent(async_cow, start, num_bytes,
553 total_compressed, pages, nr_pages_ret,
556 if (start + num_bytes < end) {
563 cleanup_and_bail_uncompressed:
565 * No compression, but we still need to write the pages in
566 * the file we've been given so far. redirty the locked
567 * page if it corresponds to our extent and set things up
568 * for the async work queue to run cow_file_range to do
569 * the normal delalloc dance
571 if (page_offset(locked_page) >= start &&
572 page_offset(locked_page) <= end) {
573 __set_page_dirty_nobuffers(locked_page);
574 /* unlocked later on in the async handlers */
577 extent_range_redirty_for_io(inode, start, end);
578 add_async_extent(async_cow, start, end - start + 1,
579 0, NULL, 0, BTRFS_COMPRESS_NONE);
587 for (i = 0; i < nr_pages_ret; i++) {
588 WARN_ON(pages[i]->mapping);
589 page_cache_release(pages[i]);
597 * phase two of compressed writeback. This is the ordered portion
598 * of the code, which only gets called in the order the work was
599 * queued. We walk all the async extents created by compress_file_range
600 * and send them down to the disk.
602 static noinline int submit_compressed_extents(struct inode *inode,
603 struct async_cow *async_cow)
605 struct async_extent *async_extent;
607 struct btrfs_key ins;
608 struct extent_map *em;
609 struct btrfs_root *root = BTRFS_I(inode)->root;
610 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
611 struct extent_io_tree *io_tree;
614 if (list_empty(&async_cow->extents))
618 while (!list_empty(&async_cow->extents)) {
619 async_extent = list_entry(async_cow->extents.next,
620 struct async_extent, list);
621 list_del(&async_extent->list);
623 io_tree = &BTRFS_I(inode)->io_tree;
626 /* did the compression code fall back to uncompressed IO? */
627 if (!async_extent->pages) {
628 int page_started = 0;
629 unsigned long nr_written = 0;
631 lock_extent(io_tree, async_extent->start,
632 async_extent->start +
633 async_extent->ram_size - 1);
635 /* allocate blocks */
636 ret = cow_file_range(inode, async_cow->locked_page,
638 async_extent->start +
639 async_extent->ram_size - 1,
640 &page_started, &nr_written, 0);
645 * if page_started, cow_file_range inserted an
646 * inline extent and took care of all the unlocking
647 * and IO for us. Otherwise, we need to submit
648 * all those pages down to the drive.
650 if (!page_started && !ret)
651 extent_write_locked_range(io_tree,
652 inode, async_extent->start,
653 async_extent->start +
654 async_extent->ram_size - 1,
658 unlock_page(async_cow->locked_page);
664 lock_extent(io_tree, async_extent->start,
665 async_extent->start + async_extent->ram_size - 1);
667 ret = btrfs_reserve_extent(root,
668 async_extent->compressed_size,
669 async_extent->compressed_size,
670 0, alloc_hint, &ins, 1);
674 for (i = 0; i < async_extent->nr_pages; i++) {
675 WARN_ON(async_extent->pages[i]->mapping);
676 page_cache_release(async_extent->pages[i]);
678 kfree(async_extent->pages);
679 async_extent->nr_pages = 0;
680 async_extent->pages = NULL;
682 if (ret == -ENOSPC) {
683 unlock_extent(io_tree, async_extent->start,
684 async_extent->start +
685 async_extent->ram_size - 1);
692 * here we're doing allocation and writeback of the
695 btrfs_drop_extent_cache(inode, async_extent->start,
696 async_extent->start +
697 async_extent->ram_size - 1, 0);
699 em = alloc_extent_map();
702 goto out_free_reserve;
704 em->start = async_extent->start;
705 em->len = async_extent->ram_size;
706 em->orig_start = em->start;
707 em->mod_start = em->start;
708 em->mod_len = em->len;
710 em->block_start = ins.objectid;
711 em->block_len = ins.offset;
712 em->orig_block_len = ins.offset;
713 em->ram_bytes = async_extent->ram_size;
714 em->bdev = root->fs_info->fs_devices->latest_bdev;
715 em->compress_type = async_extent->compress_type;
716 set_bit(EXTENT_FLAG_PINNED, &em->flags);
717 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
721 write_lock(&em_tree->lock);
722 ret = add_extent_mapping(em_tree, em, 1);
723 write_unlock(&em_tree->lock);
724 if (ret != -EEXIST) {
728 btrfs_drop_extent_cache(inode, async_extent->start,
729 async_extent->start +
730 async_extent->ram_size - 1, 0);
734 goto out_free_reserve;
736 ret = btrfs_add_ordered_extent_compress(inode,
739 async_extent->ram_size,
741 BTRFS_ORDERED_COMPRESSED,
742 async_extent->compress_type);
744 goto out_free_reserve;
747 * clear dirty, set writeback and unlock the pages.
749 extent_clear_unlock_delalloc(inode, async_extent->start,
750 async_extent->start +
751 async_extent->ram_size - 1,
752 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
753 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
755 ret = btrfs_submit_compressed_write(inode,
757 async_extent->ram_size,
759 ins.offset, async_extent->pages,
760 async_extent->nr_pages);
761 alloc_hint = ins.objectid + ins.offset;
771 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
773 extent_clear_unlock_delalloc(inode, async_extent->start,
774 async_extent->start +
775 async_extent->ram_size - 1,
776 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
777 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
778 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
779 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
784 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
787 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
788 struct extent_map *em;
791 read_lock(&em_tree->lock);
792 em = search_extent_mapping(em_tree, start, num_bytes);
795 * if block start isn't an actual block number then find the
796 * first block in this inode and use that as a hint. If that
797 * block is also bogus then just don't worry about it.
799 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
801 em = search_extent_mapping(em_tree, 0, 0);
802 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
803 alloc_hint = em->block_start;
807 alloc_hint = em->block_start;
811 read_unlock(&em_tree->lock);
817 * when extent_io.c finds a delayed allocation range in the file,
818 * the call backs end up in this code. The basic idea is to
819 * allocate extents on disk for the range, and create ordered data structs
820 * in ram to track those extents.
822 * locked_page is the page that writepage had locked already. We use
823 * it to make sure we don't do extra locks or unlocks.
825 * *page_started is set to one if we unlock locked_page and do everything
826 * required to start IO on it. It may be clean and already done with
829 static noinline int cow_file_range(struct inode *inode,
830 struct page *locked_page,
831 u64 start, u64 end, int *page_started,
832 unsigned long *nr_written,
835 struct btrfs_root *root = BTRFS_I(inode)->root;
838 unsigned long ram_size;
841 u64 blocksize = root->sectorsize;
842 struct btrfs_key ins;
843 struct extent_map *em;
844 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
847 BUG_ON(btrfs_is_free_space_inode(inode));
849 num_bytes = ALIGN(end - start + 1, blocksize);
850 num_bytes = max(blocksize, num_bytes);
851 disk_num_bytes = num_bytes;
853 /* if this is a small write inside eof, kick off defrag */
854 if (num_bytes < 64 * 1024 &&
855 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
856 btrfs_add_inode_defrag(NULL, inode);
859 /* lets try to make an inline extent */
860 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
863 extent_clear_unlock_delalloc(inode, start, end, NULL,
864 EXTENT_LOCKED | EXTENT_DELALLOC |
865 EXTENT_DEFRAG, PAGE_UNLOCK |
866 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
869 *nr_written = *nr_written +
870 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
873 } else if (ret < 0) {
878 BUG_ON(disk_num_bytes >
879 btrfs_super_total_bytes(root->fs_info->super_copy));
881 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
882 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
884 while (disk_num_bytes > 0) {
887 cur_alloc_size = disk_num_bytes;
888 ret = btrfs_reserve_extent(root, cur_alloc_size,
889 root->sectorsize, 0, alloc_hint,
894 em = alloc_extent_map();
900 em->orig_start = em->start;
901 ram_size = ins.offset;
902 em->len = ins.offset;
903 em->mod_start = em->start;
904 em->mod_len = em->len;
906 em->block_start = ins.objectid;
907 em->block_len = ins.offset;
908 em->orig_block_len = ins.offset;
909 em->ram_bytes = ram_size;
910 em->bdev = root->fs_info->fs_devices->latest_bdev;
911 set_bit(EXTENT_FLAG_PINNED, &em->flags);
915 write_lock(&em_tree->lock);
916 ret = add_extent_mapping(em_tree, em, 1);
917 write_unlock(&em_tree->lock);
918 if (ret != -EEXIST) {
922 btrfs_drop_extent_cache(inode, start,
923 start + ram_size - 1, 0);
928 cur_alloc_size = ins.offset;
929 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
930 ram_size, cur_alloc_size, 0);
934 if (root->root_key.objectid ==
935 BTRFS_DATA_RELOC_TREE_OBJECTID) {
936 ret = btrfs_reloc_clone_csums(inode, start,
942 if (disk_num_bytes < cur_alloc_size)
945 /* we're not doing compressed IO, don't unlock the first
946 * page (which the caller expects to stay locked), don't
947 * clear any dirty bits and don't set any writeback bits
949 * Do set the Private2 bit so we know this page was properly
950 * setup for writepage
952 op = unlock ? PAGE_UNLOCK : 0;
953 op |= PAGE_SET_PRIVATE2;
955 extent_clear_unlock_delalloc(inode, start,
956 start + ram_size - 1, locked_page,
957 EXTENT_LOCKED | EXTENT_DELALLOC,
959 disk_num_bytes -= cur_alloc_size;
960 num_bytes -= cur_alloc_size;
961 alloc_hint = ins.objectid + ins.offset;
962 start += cur_alloc_size;
968 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
970 extent_clear_unlock_delalloc(inode, start, end, locked_page,
971 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
972 EXTENT_DELALLOC | EXTENT_DEFRAG,
973 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
974 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
979 * work queue call back to started compression on a file and pages
981 static noinline void async_cow_start(struct btrfs_work *work)
983 struct async_cow *async_cow;
985 async_cow = container_of(work, struct async_cow, work);
987 compress_file_range(async_cow->inode, async_cow->locked_page,
988 async_cow->start, async_cow->end, async_cow,
990 if (num_added == 0) {
991 btrfs_add_delayed_iput(async_cow->inode);
992 async_cow->inode = NULL;
997 * work queue call back to submit previously compressed pages
999 static noinline void async_cow_submit(struct btrfs_work *work)
1001 struct async_cow *async_cow;
1002 struct btrfs_root *root;
1003 unsigned long nr_pages;
1005 async_cow = container_of(work, struct async_cow, work);
1007 root = async_cow->root;
1008 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1011 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1013 waitqueue_active(&root->fs_info->async_submit_wait))
1014 wake_up(&root->fs_info->async_submit_wait);
1016 if (async_cow->inode)
1017 submit_compressed_extents(async_cow->inode, async_cow);
1020 static noinline void async_cow_free(struct btrfs_work *work)
1022 struct async_cow *async_cow;
1023 async_cow = container_of(work, struct async_cow, work);
1024 if (async_cow->inode)
1025 btrfs_add_delayed_iput(async_cow->inode);
1029 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1030 u64 start, u64 end, int *page_started,
1031 unsigned long *nr_written)
1033 struct async_cow *async_cow;
1034 struct btrfs_root *root = BTRFS_I(inode)->root;
1035 unsigned long nr_pages;
1037 int limit = 10 * 1024 * 1024;
1039 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1040 1, 0, NULL, GFP_NOFS);
1041 while (start < end) {
1042 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1043 BUG_ON(!async_cow); /* -ENOMEM */
1044 async_cow->inode = igrab(inode);
1045 async_cow->root = root;
1046 async_cow->locked_page = locked_page;
1047 async_cow->start = start;
1049 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1052 cur_end = min(end, start + 512 * 1024 - 1);
1054 async_cow->end = cur_end;
1055 INIT_LIST_HEAD(&async_cow->extents);
1057 async_cow->work.func = async_cow_start;
1058 async_cow->work.ordered_func = async_cow_submit;
1059 async_cow->work.ordered_free = async_cow_free;
1060 async_cow->work.flags = 0;
1062 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1064 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1066 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1069 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1070 wait_event(root->fs_info->async_submit_wait,
1071 (atomic_read(&root->fs_info->async_delalloc_pages) <
1075 while (atomic_read(&root->fs_info->async_submit_draining) &&
1076 atomic_read(&root->fs_info->async_delalloc_pages)) {
1077 wait_event(root->fs_info->async_submit_wait,
1078 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1082 *nr_written += nr_pages;
1083 start = cur_end + 1;
1089 static noinline int csum_exist_in_range(struct btrfs_root *root,
1090 u64 bytenr, u64 num_bytes)
1093 struct btrfs_ordered_sum *sums;
1096 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1097 bytenr + num_bytes - 1, &list, 0);
1098 if (ret == 0 && list_empty(&list))
1101 while (!list_empty(&list)) {
1102 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1103 list_del(&sums->list);
1110 * when nowcow writeback call back. This checks for snapshots or COW copies
1111 * of the extents that exist in the file, and COWs the file as required.
1113 * If no cow copies or snapshots exist, we write directly to the existing
1116 static noinline int run_delalloc_nocow(struct inode *inode,
1117 struct page *locked_page,
1118 u64 start, u64 end, int *page_started, int force,
1119 unsigned long *nr_written)
1121 struct btrfs_root *root = BTRFS_I(inode)->root;
1122 struct btrfs_trans_handle *trans;
1123 struct extent_buffer *leaf;
1124 struct btrfs_path *path;
1125 struct btrfs_file_extent_item *fi;
1126 struct btrfs_key found_key;
1141 u64 ino = btrfs_ino(inode);
1143 path = btrfs_alloc_path();
1145 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1146 EXTENT_LOCKED | EXTENT_DELALLOC |
1147 EXTENT_DO_ACCOUNTING |
1148 EXTENT_DEFRAG, PAGE_UNLOCK |
1150 PAGE_SET_WRITEBACK |
1151 PAGE_END_WRITEBACK);
1155 nolock = btrfs_is_free_space_inode(inode);
1158 trans = btrfs_join_transaction_nolock(root);
1160 trans = btrfs_join_transaction(root);
1162 if (IS_ERR(trans)) {
1163 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1164 EXTENT_LOCKED | EXTENT_DELALLOC |
1165 EXTENT_DO_ACCOUNTING |
1166 EXTENT_DEFRAG, PAGE_UNLOCK |
1168 PAGE_SET_WRITEBACK |
1169 PAGE_END_WRITEBACK);
1170 btrfs_free_path(path);
1171 return PTR_ERR(trans);
1174 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1176 cow_start = (u64)-1;
1179 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1182 btrfs_abort_transaction(trans, root, ret);
1185 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1186 leaf = path->nodes[0];
1187 btrfs_item_key_to_cpu(leaf, &found_key,
1188 path->slots[0] - 1);
1189 if (found_key.objectid == ino &&
1190 found_key.type == BTRFS_EXTENT_DATA_KEY)
1195 leaf = path->nodes[0];
1196 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1197 ret = btrfs_next_leaf(root, path);
1199 btrfs_abort_transaction(trans, root, ret);
1204 leaf = path->nodes[0];
1210 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1212 if (found_key.objectid > ino ||
1213 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1214 found_key.offset > end)
1217 if (found_key.offset > cur_offset) {
1218 extent_end = found_key.offset;
1223 fi = btrfs_item_ptr(leaf, path->slots[0],
1224 struct btrfs_file_extent_item);
1225 extent_type = btrfs_file_extent_type(leaf, fi);
1227 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1228 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1229 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1230 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1231 extent_offset = btrfs_file_extent_offset(leaf, fi);
1232 extent_end = found_key.offset +
1233 btrfs_file_extent_num_bytes(leaf, fi);
1235 btrfs_file_extent_disk_num_bytes(leaf, fi);
1236 if (extent_end <= start) {
1240 if (disk_bytenr == 0)
1242 if (btrfs_file_extent_compression(leaf, fi) ||
1243 btrfs_file_extent_encryption(leaf, fi) ||
1244 btrfs_file_extent_other_encoding(leaf, fi))
1246 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1248 if (btrfs_extent_readonly(root, disk_bytenr))
1250 if (btrfs_cross_ref_exist(trans, root, ino,
1252 extent_offset, disk_bytenr))
1254 disk_bytenr += extent_offset;
1255 disk_bytenr += cur_offset - found_key.offset;
1256 num_bytes = min(end + 1, extent_end) - cur_offset;
1258 * force cow if csum exists in the range.
1259 * this ensure that csum for a given extent are
1260 * either valid or do not exist.
1262 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1265 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1266 extent_end = found_key.offset +
1267 btrfs_file_extent_inline_len(leaf, fi);
1268 extent_end = ALIGN(extent_end, root->sectorsize);
1273 if (extent_end <= start) {
1278 if (cow_start == (u64)-1)
1279 cow_start = cur_offset;
1280 cur_offset = extent_end;
1281 if (cur_offset > end)
1287 btrfs_release_path(path);
1288 if (cow_start != (u64)-1) {
1289 ret = cow_file_range(inode, locked_page,
1290 cow_start, found_key.offset - 1,
1291 page_started, nr_written, 1);
1293 btrfs_abort_transaction(trans, root, ret);
1296 cow_start = (u64)-1;
1299 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1300 struct extent_map *em;
1301 struct extent_map_tree *em_tree;
1302 em_tree = &BTRFS_I(inode)->extent_tree;
1303 em = alloc_extent_map();
1304 BUG_ON(!em); /* -ENOMEM */
1305 em->start = cur_offset;
1306 em->orig_start = found_key.offset - extent_offset;
1307 em->len = num_bytes;
1308 em->block_len = num_bytes;
1309 em->block_start = disk_bytenr;
1310 em->orig_block_len = disk_num_bytes;
1311 em->ram_bytes = ram_bytes;
1312 em->bdev = root->fs_info->fs_devices->latest_bdev;
1313 em->mod_start = em->start;
1314 em->mod_len = em->len;
1315 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1316 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1317 em->generation = -1;
1319 write_lock(&em_tree->lock);
1320 ret = add_extent_mapping(em_tree, em, 1);
1321 write_unlock(&em_tree->lock);
1322 if (ret != -EEXIST) {
1323 free_extent_map(em);
1326 btrfs_drop_extent_cache(inode, em->start,
1327 em->start + em->len - 1, 0);
1329 type = BTRFS_ORDERED_PREALLOC;
1331 type = BTRFS_ORDERED_NOCOW;
1334 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1335 num_bytes, num_bytes, type);
1336 BUG_ON(ret); /* -ENOMEM */
1338 if (root->root_key.objectid ==
1339 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1340 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1343 btrfs_abort_transaction(trans, root, ret);
1348 extent_clear_unlock_delalloc(inode, cur_offset,
1349 cur_offset + num_bytes - 1,
1350 locked_page, EXTENT_LOCKED |
1351 EXTENT_DELALLOC, PAGE_UNLOCK |
1353 cur_offset = extent_end;
1354 if (cur_offset > end)
1357 btrfs_release_path(path);
1359 if (cur_offset <= end && cow_start == (u64)-1) {
1360 cow_start = cur_offset;
1364 if (cow_start != (u64)-1) {
1365 ret = cow_file_range(inode, locked_page, cow_start, end,
1366 page_started, nr_written, 1);
1368 btrfs_abort_transaction(trans, root, ret);
1374 err = btrfs_end_transaction(trans, root);
1378 if (ret && cur_offset < end)
1379 extent_clear_unlock_delalloc(inode, cur_offset, end,
1380 locked_page, EXTENT_LOCKED |
1381 EXTENT_DELALLOC | EXTENT_DEFRAG |
1382 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1384 PAGE_SET_WRITEBACK |
1385 PAGE_END_WRITEBACK);
1386 btrfs_free_path(path);
1391 * extent_io.c call back to do delayed allocation processing
1393 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1394 u64 start, u64 end, int *page_started,
1395 unsigned long *nr_written)
1398 struct btrfs_root *root = BTRFS_I(inode)->root;
1400 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1401 ret = run_delalloc_nocow(inode, locked_page, start, end,
1402 page_started, 1, nr_written);
1403 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1404 ret = run_delalloc_nocow(inode, locked_page, start, end,
1405 page_started, 0, nr_written);
1406 } else if (!btrfs_test_opt(root, COMPRESS) &&
1407 !(BTRFS_I(inode)->force_compress) &&
1408 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1409 ret = cow_file_range(inode, locked_page, start, end,
1410 page_started, nr_written, 1);
1412 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1413 &BTRFS_I(inode)->runtime_flags);
1414 ret = cow_file_range_async(inode, locked_page, start, end,
1415 page_started, nr_written);
1420 static void btrfs_split_extent_hook(struct inode *inode,
1421 struct extent_state *orig, u64 split)
1423 /* not delalloc, ignore it */
1424 if (!(orig->state & EXTENT_DELALLOC))
1427 spin_lock(&BTRFS_I(inode)->lock);
1428 BTRFS_I(inode)->outstanding_extents++;
1429 spin_unlock(&BTRFS_I(inode)->lock);
1433 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1434 * extents so we can keep track of new extents that are just merged onto old
1435 * extents, such as when we are doing sequential writes, so we can properly
1436 * account for the metadata space we'll need.
1438 static void btrfs_merge_extent_hook(struct inode *inode,
1439 struct extent_state *new,
1440 struct extent_state *other)
1442 /* not delalloc, ignore it */
1443 if (!(other->state & EXTENT_DELALLOC))
1446 spin_lock(&BTRFS_I(inode)->lock);
1447 BTRFS_I(inode)->outstanding_extents--;
1448 spin_unlock(&BTRFS_I(inode)->lock);
1451 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1452 struct inode *inode)
1454 spin_lock(&root->delalloc_lock);
1455 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1456 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1457 &root->delalloc_inodes);
1458 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1459 &BTRFS_I(inode)->runtime_flags);
1460 root->nr_delalloc_inodes++;
1461 if (root->nr_delalloc_inodes == 1) {
1462 spin_lock(&root->fs_info->delalloc_root_lock);
1463 BUG_ON(!list_empty(&root->delalloc_root));
1464 list_add_tail(&root->delalloc_root,
1465 &root->fs_info->delalloc_roots);
1466 spin_unlock(&root->fs_info->delalloc_root_lock);
1469 spin_unlock(&root->delalloc_lock);
1472 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1473 struct inode *inode)
1475 spin_lock(&root->delalloc_lock);
1476 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1477 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1478 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1479 &BTRFS_I(inode)->runtime_flags);
1480 root->nr_delalloc_inodes--;
1481 if (!root->nr_delalloc_inodes) {
1482 spin_lock(&root->fs_info->delalloc_root_lock);
1483 BUG_ON(list_empty(&root->delalloc_root));
1484 list_del_init(&root->delalloc_root);
1485 spin_unlock(&root->fs_info->delalloc_root_lock);
1488 spin_unlock(&root->delalloc_lock);
1492 * extent_io.c set_bit_hook, used to track delayed allocation
1493 * bytes in this file, and to maintain the list of inodes that
1494 * have pending delalloc work to be done.
1496 static void btrfs_set_bit_hook(struct inode *inode,
1497 struct extent_state *state, unsigned long *bits)
1501 * set_bit and clear bit hooks normally require _irqsave/restore
1502 * but in this case, we are only testing for the DELALLOC
1503 * bit, which is only set or cleared with irqs on
1505 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1506 struct btrfs_root *root = BTRFS_I(inode)->root;
1507 u64 len = state->end + 1 - state->start;
1508 bool do_list = !btrfs_is_free_space_inode(inode);
1510 if (*bits & EXTENT_FIRST_DELALLOC) {
1511 *bits &= ~EXTENT_FIRST_DELALLOC;
1513 spin_lock(&BTRFS_I(inode)->lock);
1514 BTRFS_I(inode)->outstanding_extents++;
1515 spin_unlock(&BTRFS_I(inode)->lock);
1518 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1519 root->fs_info->delalloc_batch);
1520 spin_lock(&BTRFS_I(inode)->lock);
1521 BTRFS_I(inode)->delalloc_bytes += len;
1522 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1523 &BTRFS_I(inode)->runtime_flags))
1524 btrfs_add_delalloc_inodes(root, inode);
1525 spin_unlock(&BTRFS_I(inode)->lock);
1530 * extent_io.c clear_bit_hook, see set_bit_hook for why
1532 static void btrfs_clear_bit_hook(struct inode *inode,
1533 struct extent_state *state,
1534 unsigned long *bits)
1537 * set_bit and clear bit hooks normally require _irqsave/restore
1538 * but in this case, we are only testing for the DELALLOC
1539 * bit, which is only set or cleared with irqs on
1541 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1542 struct btrfs_root *root = BTRFS_I(inode)->root;
1543 u64 len = state->end + 1 - state->start;
1544 bool do_list = !btrfs_is_free_space_inode(inode);
1546 if (*bits & EXTENT_FIRST_DELALLOC) {
1547 *bits &= ~EXTENT_FIRST_DELALLOC;
1548 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1549 spin_lock(&BTRFS_I(inode)->lock);
1550 BTRFS_I(inode)->outstanding_extents--;
1551 spin_unlock(&BTRFS_I(inode)->lock);
1555 * We don't reserve metadata space for space cache inodes so we
1556 * don't need to call dellalloc_release_metadata if there is an
1559 if (*bits & EXTENT_DO_ACCOUNTING &&
1560 root != root->fs_info->tree_root)
1561 btrfs_delalloc_release_metadata(inode, len);
1563 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1564 && do_list && !(state->state & EXTENT_NORESERVE))
1565 btrfs_free_reserved_data_space(inode, len);
1567 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1568 root->fs_info->delalloc_batch);
1569 spin_lock(&BTRFS_I(inode)->lock);
1570 BTRFS_I(inode)->delalloc_bytes -= len;
1571 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1572 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1573 &BTRFS_I(inode)->runtime_flags))
1574 btrfs_del_delalloc_inode(root, inode);
1575 spin_unlock(&BTRFS_I(inode)->lock);
1580 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1581 * we don't create bios that span stripes or chunks
1583 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1584 size_t size, struct bio *bio,
1585 unsigned long bio_flags)
1587 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1588 u64 logical = (u64)bio->bi_sector << 9;
1593 if (bio_flags & EXTENT_BIO_COMPRESSED)
1596 length = bio->bi_size;
1597 map_length = length;
1598 ret = btrfs_map_block(root->fs_info, rw, logical,
1599 &map_length, NULL, 0);
1600 /* Will always return 0 with map_multi == NULL */
1602 if (map_length < length + size)
1608 * in order to insert checksums into the metadata in large chunks,
1609 * we wait until bio submission time. All the pages in the bio are
1610 * checksummed and sums are attached onto the ordered extent record.
1612 * At IO completion time the cums attached on the ordered extent record
1613 * are inserted into the btree
1615 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1616 struct bio *bio, int mirror_num,
1617 unsigned long bio_flags,
1620 struct btrfs_root *root = BTRFS_I(inode)->root;
1623 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1624 BUG_ON(ret); /* -ENOMEM */
1629 * in order to insert checksums into the metadata in large chunks,
1630 * we wait until bio submission time. All the pages in the bio are
1631 * checksummed and sums are attached onto the ordered extent record.
1633 * At IO completion time the cums attached on the ordered extent record
1634 * are inserted into the btree
1636 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1637 int mirror_num, unsigned long bio_flags,
1640 struct btrfs_root *root = BTRFS_I(inode)->root;
1643 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1645 bio_endio(bio, ret);
1650 * extent_io.c submission hook. This does the right thing for csum calculation
1651 * on write, or reading the csums from the tree before a read
1653 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1654 int mirror_num, unsigned long bio_flags,
1657 struct btrfs_root *root = BTRFS_I(inode)->root;
1661 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1663 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1665 if (btrfs_is_free_space_inode(inode))
1668 if (!(rw & REQ_WRITE)) {
1669 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1673 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1674 ret = btrfs_submit_compressed_read(inode, bio,
1678 } else if (!skip_sum) {
1679 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1684 } else if (async && !skip_sum) {
1685 /* csum items have already been cloned */
1686 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1688 /* we're doing a write, do the async checksumming */
1689 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1690 inode, rw, bio, mirror_num,
1691 bio_flags, bio_offset,
1692 __btrfs_submit_bio_start,
1693 __btrfs_submit_bio_done);
1695 } else if (!skip_sum) {
1696 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1702 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1706 bio_endio(bio, ret);
1711 * given a list of ordered sums record them in the inode. This happens
1712 * at IO completion time based on sums calculated at bio submission time.
1714 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1715 struct inode *inode, u64 file_offset,
1716 struct list_head *list)
1718 struct btrfs_ordered_sum *sum;
1720 list_for_each_entry(sum, list, list) {
1721 trans->adding_csums = 1;
1722 btrfs_csum_file_blocks(trans,
1723 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1724 trans->adding_csums = 0;
1729 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1730 struct extent_state **cached_state)
1732 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1733 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1734 cached_state, GFP_NOFS);
1737 /* see btrfs_writepage_start_hook for details on why this is required */
1738 struct btrfs_writepage_fixup {
1740 struct btrfs_work work;
1743 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1745 struct btrfs_writepage_fixup *fixup;
1746 struct btrfs_ordered_extent *ordered;
1747 struct extent_state *cached_state = NULL;
1749 struct inode *inode;
1754 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1758 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1759 ClearPageChecked(page);
1763 inode = page->mapping->host;
1764 page_start = page_offset(page);
1765 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1767 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1770 /* already ordered? We're done */
1771 if (PagePrivate2(page))
1774 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1776 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1777 page_end, &cached_state, GFP_NOFS);
1779 btrfs_start_ordered_extent(inode, ordered, 1);
1780 btrfs_put_ordered_extent(ordered);
1784 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1786 mapping_set_error(page->mapping, ret);
1787 end_extent_writepage(page, ret, page_start, page_end);
1788 ClearPageChecked(page);
1792 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1793 ClearPageChecked(page);
1794 set_page_dirty(page);
1796 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1797 &cached_state, GFP_NOFS);
1800 page_cache_release(page);
1805 * There are a few paths in the higher layers of the kernel that directly
1806 * set the page dirty bit without asking the filesystem if it is a
1807 * good idea. This causes problems because we want to make sure COW
1808 * properly happens and the data=ordered rules are followed.
1810 * In our case any range that doesn't have the ORDERED bit set
1811 * hasn't been properly setup for IO. We kick off an async process
1812 * to fix it up. The async helper will wait for ordered extents, set
1813 * the delalloc bit and make it safe to write the page.
1815 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1817 struct inode *inode = page->mapping->host;
1818 struct btrfs_writepage_fixup *fixup;
1819 struct btrfs_root *root = BTRFS_I(inode)->root;
1821 /* this page is properly in the ordered list */
1822 if (TestClearPagePrivate2(page))
1825 if (PageChecked(page))
1828 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1832 SetPageChecked(page);
1833 page_cache_get(page);
1834 fixup->work.func = btrfs_writepage_fixup_worker;
1836 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1840 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1841 struct inode *inode, u64 file_pos,
1842 u64 disk_bytenr, u64 disk_num_bytes,
1843 u64 num_bytes, u64 ram_bytes,
1844 u8 compression, u8 encryption,
1845 u16 other_encoding, int extent_type)
1847 struct btrfs_root *root = BTRFS_I(inode)->root;
1848 struct btrfs_file_extent_item *fi;
1849 struct btrfs_path *path;
1850 struct extent_buffer *leaf;
1851 struct btrfs_key ins;
1854 path = btrfs_alloc_path();
1858 path->leave_spinning = 1;
1861 * we may be replacing one extent in the tree with another.
1862 * The new extent is pinned in the extent map, and we don't want
1863 * to drop it from the cache until it is completely in the btree.
1865 * So, tell btrfs_drop_extents to leave this extent in the cache.
1866 * the caller is expected to unpin it and allow it to be merged
1869 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1870 file_pos + num_bytes, 0);
1874 ins.objectid = btrfs_ino(inode);
1875 ins.offset = file_pos;
1876 ins.type = BTRFS_EXTENT_DATA_KEY;
1877 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1880 leaf = path->nodes[0];
1881 fi = btrfs_item_ptr(leaf, path->slots[0],
1882 struct btrfs_file_extent_item);
1883 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1884 btrfs_set_file_extent_type(leaf, fi, extent_type);
1885 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1886 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1887 btrfs_set_file_extent_offset(leaf, fi, 0);
1888 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1889 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1890 btrfs_set_file_extent_compression(leaf, fi, compression);
1891 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1892 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1894 btrfs_mark_buffer_dirty(leaf);
1895 btrfs_release_path(path);
1897 inode_add_bytes(inode, num_bytes);
1899 ins.objectid = disk_bytenr;
1900 ins.offset = disk_num_bytes;
1901 ins.type = BTRFS_EXTENT_ITEM_KEY;
1902 ret = btrfs_alloc_reserved_file_extent(trans, root,
1903 root->root_key.objectid,
1904 btrfs_ino(inode), file_pos, &ins);
1906 btrfs_free_path(path);
1911 /* snapshot-aware defrag */
1912 struct sa_defrag_extent_backref {
1913 struct rb_node node;
1914 struct old_sa_defrag_extent *old;
1923 struct old_sa_defrag_extent {
1924 struct list_head list;
1925 struct new_sa_defrag_extent *new;
1934 struct new_sa_defrag_extent {
1935 struct rb_root root;
1936 struct list_head head;
1937 struct btrfs_path *path;
1938 struct inode *inode;
1946 static int backref_comp(struct sa_defrag_extent_backref *b1,
1947 struct sa_defrag_extent_backref *b2)
1949 if (b1->root_id < b2->root_id)
1951 else if (b1->root_id > b2->root_id)
1954 if (b1->inum < b2->inum)
1956 else if (b1->inum > b2->inum)
1959 if (b1->file_pos < b2->file_pos)
1961 else if (b1->file_pos > b2->file_pos)
1965 * [------------------------------] ===> (a range of space)
1966 * |<--->| |<---->| =============> (fs/file tree A)
1967 * |<---------------------------->| ===> (fs/file tree B)
1969 * A range of space can refer to two file extents in one tree while
1970 * refer to only one file extent in another tree.
1972 * So we may process a disk offset more than one time(two extents in A)
1973 * and locate at the same extent(one extent in B), then insert two same
1974 * backrefs(both refer to the extent in B).
1979 static void backref_insert(struct rb_root *root,
1980 struct sa_defrag_extent_backref *backref)
1982 struct rb_node **p = &root->rb_node;
1983 struct rb_node *parent = NULL;
1984 struct sa_defrag_extent_backref *entry;
1989 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
1991 ret = backref_comp(backref, entry);
1995 p = &(*p)->rb_right;
1998 rb_link_node(&backref->node, parent, p);
1999 rb_insert_color(&backref->node, root);
2003 * Note the backref might has changed, and in this case we just return 0.
2005 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2008 struct btrfs_file_extent_item *extent;
2009 struct btrfs_fs_info *fs_info;
2010 struct old_sa_defrag_extent *old = ctx;
2011 struct new_sa_defrag_extent *new = old->new;
2012 struct btrfs_path *path = new->path;
2013 struct btrfs_key key;
2014 struct btrfs_root *root;
2015 struct sa_defrag_extent_backref *backref;
2016 struct extent_buffer *leaf;
2017 struct inode *inode = new->inode;
2023 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2024 inum == btrfs_ino(inode))
2027 key.objectid = root_id;
2028 key.type = BTRFS_ROOT_ITEM_KEY;
2029 key.offset = (u64)-1;
2031 fs_info = BTRFS_I(inode)->root->fs_info;
2032 root = btrfs_read_fs_root_no_name(fs_info, &key);
2034 if (PTR_ERR(root) == -ENOENT)
2037 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2038 inum, offset, root_id);
2039 return PTR_ERR(root);
2042 key.objectid = inum;
2043 key.type = BTRFS_EXTENT_DATA_KEY;
2044 if (offset > (u64)-1 << 32)
2047 key.offset = offset;
2049 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2059 leaf = path->nodes[0];
2060 slot = path->slots[0];
2062 if (slot >= btrfs_header_nritems(leaf)) {
2063 ret = btrfs_next_leaf(root, path);
2066 } else if (ret > 0) {
2075 btrfs_item_key_to_cpu(leaf, &key, slot);
2077 if (key.objectid > inum)
2080 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2083 extent = btrfs_item_ptr(leaf, slot,
2084 struct btrfs_file_extent_item);
2086 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2090 * 'offset' refers to the exact key.offset,
2091 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2092 * (key.offset - extent_offset).
2094 if (key.offset != offset)
2097 extent_offset = btrfs_file_extent_offset(leaf, extent);
2098 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2100 if (extent_offset >= old->extent_offset + old->offset +
2101 old->len || extent_offset + num_bytes <=
2102 old->extent_offset + old->offset)
2107 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2113 backref->root_id = root_id;
2114 backref->inum = inum;
2115 backref->file_pos = offset;
2116 backref->num_bytes = num_bytes;
2117 backref->extent_offset = extent_offset;
2118 backref->generation = btrfs_file_extent_generation(leaf, extent);
2120 backref_insert(&new->root, backref);
2123 btrfs_release_path(path);
2128 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2129 struct new_sa_defrag_extent *new)
2131 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2132 struct old_sa_defrag_extent *old, *tmp;
2137 list_for_each_entry_safe(old, tmp, &new->head, list) {
2138 ret = iterate_inodes_from_logical(old->bytenr +
2139 old->extent_offset, fs_info,
2140 path, record_one_backref,
2142 BUG_ON(ret < 0 && ret != -ENOENT);
2144 /* no backref to be processed for this extent */
2146 list_del(&old->list);
2151 if (list_empty(&new->head))
2157 static int relink_is_mergable(struct extent_buffer *leaf,
2158 struct btrfs_file_extent_item *fi,
2159 struct new_sa_defrag_extent *new)
2161 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2164 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2167 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2170 if (btrfs_file_extent_encryption(leaf, fi) ||
2171 btrfs_file_extent_other_encoding(leaf, fi))
2178 * Note the backref might has changed, and in this case we just return 0.
2180 static noinline int relink_extent_backref(struct btrfs_path *path,
2181 struct sa_defrag_extent_backref *prev,
2182 struct sa_defrag_extent_backref *backref)
2184 struct btrfs_file_extent_item *extent;
2185 struct btrfs_file_extent_item *item;
2186 struct btrfs_ordered_extent *ordered;
2187 struct btrfs_trans_handle *trans;
2188 struct btrfs_fs_info *fs_info;
2189 struct btrfs_root *root;
2190 struct btrfs_key key;
2191 struct extent_buffer *leaf;
2192 struct old_sa_defrag_extent *old = backref->old;
2193 struct new_sa_defrag_extent *new = old->new;
2194 struct inode *src_inode = new->inode;
2195 struct inode *inode;
2196 struct extent_state *cached = NULL;
2205 if (prev && prev->root_id == backref->root_id &&
2206 prev->inum == backref->inum &&
2207 prev->file_pos + prev->num_bytes == backref->file_pos)
2210 /* step 1: get root */
2211 key.objectid = backref->root_id;
2212 key.type = BTRFS_ROOT_ITEM_KEY;
2213 key.offset = (u64)-1;
2215 fs_info = BTRFS_I(src_inode)->root->fs_info;
2216 index = srcu_read_lock(&fs_info->subvol_srcu);
2218 root = btrfs_read_fs_root_no_name(fs_info, &key);
2220 srcu_read_unlock(&fs_info->subvol_srcu, index);
2221 if (PTR_ERR(root) == -ENOENT)
2223 return PTR_ERR(root);
2226 /* step 2: get inode */
2227 key.objectid = backref->inum;
2228 key.type = BTRFS_INODE_ITEM_KEY;
2231 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2232 if (IS_ERR(inode)) {
2233 srcu_read_unlock(&fs_info->subvol_srcu, index);
2237 srcu_read_unlock(&fs_info->subvol_srcu, index);
2239 /* step 3: relink backref */
2240 lock_start = backref->file_pos;
2241 lock_end = backref->file_pos + backref->num_bytes - 1;
2242 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2245 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2247 btrfs_put_ordered_extent(ordered);
2251 trans = btrfs_join_transaction(root);
2252 if (IS_ERR(trans)) {
2253 ret = PTR_ERR(trans);
2257 key.objectid = backref->inum;
2258 key.type = BTRFS_EXTENT_DATA_KEY;
2259 key.offset = backref->file_pos;
2261 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2264 } else if (ret > 0) {
2269 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2270 struct btrfs_file_extent_item);
2272 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2273 backref->generation)
2276 btrfs_release_path(path);
2278 start = backref->file_pos;
2279 if (backref->extent_offset < old->extent_offset + old->offset)
2280 start += old->extent_offset + old->offset -
2281 backref->extent_offset;
2283 len = min(backref->extent_offset + backref->num_bytes,
2284 old->extent_offset + old->offset + old->len);
2285 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2287 ret = btrfs_drop_extents(trans, root, inode, start,
2292 key.objectid = btrfs_ino(inode);
2293 key.type = BTRFS_EXTENT_DATA_KEY;
2296 path->leave_spinning = 1;
2298 struct btrfs_file_extent_item *fi;
2300 struct btrfs_key found_key;
2302 ret = btrfs_search_slot(trans, root, &key, path, 1, 1);
2307 leaf = path->nodes[0];
2308 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2310 fi = btrfs_item_ptr(leaf, path->slots[0],
2311 struct btrfs_file_extent_item);
2312 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2314 if (extent_len + found_key.offset == start &&
2315 relink_is_mergable(leaf, fi, new)) {
2316 btrfs_set_file_extent_num_bytes(leaf, fi,
2318 btrfs_mark_buffer_dirty(leaf);
2319 inode_add_bytes(inode, len);
2325 btrfs_release_path(path);
2330 ret = btrfs_insert_empty_item(trans, root, path, &key,
2333 btrfs_abort_transaction(trans, root, ret);
2337 leaf = path->nodes[0];
2338 item = btrfs_item_ptr(leaf, path->slots[0],
2339 struct btrfs_file_extent_item);
2340 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2341 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2342 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2343 btrfs_set_file_extent_num_bytes(leaf, item, len);
2344 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2345 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2346 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2347 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2348 btrfs_set_file_extent_encryption(leaf, item, 0);
2349 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2351 btrfs_mark_buffer_dirty(leaf);
2352 inode_add_bytes(inode, len);
2353 btrfs_release_path(path);
2355 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2357 backref->root_id, backref->inum,
2358 new->file_pos, 0); /* start - extent_offset */
2360 btrfs_abort_transaction(trans, root, ret);
2366 btrfs_release_path(path);
2367 path->leave_spinning = 0;
2368 btrfs_end_transaction(trans, root);
2370 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2376 static void relink_file_extents(struct new_sa_defrag_extent *new)
2378 struct btrfs_path *path;
2379 struct old_sa_defrag_extent *old, *tmp;
2380 struct sa_defrag_extent_backref *backref;
2381 struct sa_defrag_extent_backref *prev = NULL;
2382 struct inode *inode;
2383 struct btrfs_root *root;
2384 struct rb_node *node;
2388 root = BTRFS_I(inode)->root;
2390 path = btrfs_alloc_path();
2394 if (!record_extent_backrefs(path, new)) {
2395 btrfs_free_path(path);
2398 btrfs_release_path(path);
2401 node = rb_first(&new->root);
2404 rb_erase(node, &new->root);
2406 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2408 ret = relink_extent_backref(path, prev, backref);
2421 btrfs_free_path(path);
2423 list_for_each_entry_safe(old, tmp, &new->head, list) {
2424 list_del(&old->list);
2428 atomic_dec(&root->fs_info->defrag_running);
2429 wake_up(&root->fs_info->transaction_wait);
2434 static struct new_sa_defrag_extent *
2435 record_old_file_extents(struct inode *inode,
2436 struct btrfs_ordered_extent *ordered)
2438 struct btrfs_root *root = BTRFS_I(inode)->root;
2439 struct btrfs_path *path;
2440 struct btrfs_key key;
2441 struct old_sa_defrag_extent *old, *tmp;
2442 struct new_sa_defrag_extent *new;
2445 new = kmalloc(sizeof(*new), GFP_NOFS);
2450 new->file_pos = ordered->file_offset;
2451 new->len = ordered->len;
2452 new->bytenr = ordered->start;
2453 new->disk_len = ordered->disk_len;
2454 new->compress_type = ordered->compress_type;
2455 new->root = RB_ROOT;
2456 INIT_LIST_HEAD(&new->head);
2458 path = btrfs_alloc_path();
2462 key.objectid = btrfs_ino(inode);
2463 key.type = BTRFS_EXTENT_DATA_KEY;
2464 key.offset = new->file_pos;
2466 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2469 if (ret > 0 && path->slots[0] > 0)
2472 /* find out all the old extents for the file range */
2474 struct btrfs_file_extent_item *extent;
2475 struct extent_buffer *l;
2484 slot = path->slots[0];
2486 if (slot >= btrfs_header_nritems(l)) {
2487 ret = btrfs_next_leaf(root, path);
2495 btrfs_item_key_to_cpu(l, &key, slot);
2497 if (key.objectid != btrfs_ino(inode))
2499 if (key.type != BTRFS_EXTENT_DATA_KEY)
2501 if (key.offset >= new->file_pos + new->len)
2504 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2506 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2507 if (key.offset + num_bytes < new->file_pos)
2510 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2514 extent_offset = btrfs_file_extent_offset(l, extent);
2516 old = kmalloc(sizeof(*old), GFP_NOFS);
2520 offset = max(new->file_pos, key.offset);
2521 end = min(new->file_pos + new->len, key.offset + num_bytes);
2523 old->bytenr = disk_bytenr;
2524 old->extent_offset = extent_offset;
2525 old->offset = offset - key.offset;
2526 old->len = end - offset;
2529 list_add_tail(&old->list, &new->head);
2535 btrfs_free_path(path);
2536 atomic_inc(&root->fs_info->defrag_running);
2541 list_for_each_entry_safe(old, tmp, &new->head, list) {
2542 list_del(&old->list);
2546 btrfs_free_path(path);
2553 * helper function for btrfs_finish_ordered_io, this
2554 * just reads in some of the csum leaves to prime them into ram
2555 * before we start the transaction. It limits the amount of btree
2556 * reads required while inside the transaction.
2558 /* as ordered data IO finishes, this gets called so we can finish
2559 * an ordered extent if the range of bytes in the file it covers are
2562 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2564 struct inode *inode = ordered_extent->inode;
2565 struct btrfs_root *root = BTRFS_I(inode)->root;
2566 struct btrfs_trans_handle *trans = NULL;
2567 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2568 struct extent_state *cached_state = NULL;
2569 struct new_sa_defrag_extent *new = NULL;
2570 int compress_type = 0;
2572 u64 logical_len = ordered_extent->len;
2574 bool truncated = false;
2576 nolock = btrfs_is_free_space_inode(inode);
2578 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2583 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2585 logical_len = ordered_extent->truncated_len;
2586 /* Truncated the entire extent, don't bother adding */
2591 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2592 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2593 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2595 trans = btrfs_join_transaction_nolock(root);
2597 trans = btrfs_join_transaction(root);
2598 if (IS_ERR(trans)) {
2599 ret = PTR_ERR(trans);
2603 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2604 ret = btrfs_update_inode_fallback(trans, root, inode);
2605 if (ret) /* -ENOMEM or corruption */
2606 btrfs_abort_transaction(trans, root, ret);
2610 lock_extent_bits(io_tree, ordered_extent->file_offset,
2611 ordered_extent->file_offset + ordered_extent->len - 1,
2614 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2615 ordered_extent->file_offset + ordered_extent->len - 1,
2616 EXTENT_DEFRAG, 1, cached_state);
2618 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2619 if (last_snapshot >= BTRFS_I(inode)->generation)
2620 /* the inode is shared */
2621 new = record_old_file_extents(inode, ordered_extent);
2623 clear_extent_bit(io_tree, ordered_extent->file_offset,
2624 ordered_extent->file_offset + ordered_extent->len - 1,
2625 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2629 trans = btrfs_join_transaction_nolock(root);
2631 trans = btrfs_join_transaction(root);
2632 if (IS_ERR(trans)) {
2633 ret = PTR_ERR(trans);
2637 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2639 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2640 compress_type = ordered_extent->compress_type;
2641 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2642 BUG_ON(compress_type);
2643 ret = btrfs_mark_extent_written(trans, inode,
2644 ordered_extent->file_offset,
2645 ordered_extent->file_offset +
2648 BUG_ON(root == root->fs_info->tree_root);
2649 ret = insert_reserved_file_extent(trans, inode,
2650 ordered_extent->file_offset,
2651 ordered_extent->start,
2652 ordered_extent->disk_len,
2653 logical_len, logical_len,
2654 compress_type, 0, 0,
2655 BTRFS_FILE_EXTENT_REG);
2657 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2658 ordered_extent->file_offset, ordered_extent->len,
2661 btrfs_abort_transaction(trans, root, ret);
2665 add_pending_csums(trans, inode, ordered_extent->file_offset,
2666 &ordered_extent->list);
2668 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2669 ret = btrfs_update_inode_fallback(trans, root, inode);
2670 if (ret) { /* -ENOMEM or corruption */
2671 btrfs_abort_transaction(trans, root, ret);
2676 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2677 ordered_extent->file_offset +
2678 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2680 if (root != root->fs_info->tree_root)
2681 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2683 btrfs_end_transaction(trans, root);
2685 if (ret || truncated) {
2689 start = ordered_extent->file_offset + logical_len;
2691 start = ordered_extent->file_offset;
2692 end = ordered_extent->file_offset + ordered_extent->len - 1;
2693 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2695 /* Drop the cache for the part of the extent we didn't write. */
2696 btrfs_drop_extent_cache(inode, start, end, 0);
2699 * If the ordered extent had an IOERR or something else went
2700 * wrong we need to return the space for this ordered extent
2701 * back to the allocator. We only free the extent in the
2702 * truncated case if we didn't write out the extent at all.
2704 if ((ret || !logical_len) &&
2705 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2706 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2707 btrfs_free_reserved_extent(root, ordered_extent->start,
2708 ordered_extent->disk_len);
2713 * This needs to be done to make sure anybody waiting knows we are done
2714 * updating everything for this ordered extent.
2716 btrfs_remove_ordered_extent(inode, ordered_extent);
2718 /* for snapshot-aware defrag */
2720 relink_file_extents(new);
2723 btrfs_put_ordered_extent(ordered_extent);
2724 /* once for the tree */
2725 btrfs_put_ordered_extent(ordered_extent);
2730 static void finish_ordered_fn(struct btrfs_work *work)
2732 struct btrfs_ordered_extent *ordered_extent;
2733 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2734 btrfs_finish_ordered_io(ordered_extent);
2737 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2738 struct extent_state *state, int uptodate)
2740 struct inode *inode = page->mapping->host;
2741 struct btrfs_root *root = BTRFS_I(inode)->root;
2742 struct btrfs_ordered_extent *ordered_extent = NULL;
2743 struct btrfs_workers *workers;
2745 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2747 ClearPagePrivate2(page);
2748 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2749 end - start + 1, uptodate))
2752 ordered_extent->work.func = finish_ordered_fn;
2753 ordered_extent->work.flags = 0;
2755 if (btrfs_is_free_space_inode(inode))
2756 workers = &root->fs_info->endio_freespace_worker;
2758 workers = &root->fs_info->endio_write_workers;
2759 btrfs_queue_worker(workers, &ordered_extent->work);
2765 * when reads are done, we need to check csums to verify the data is correct
2766 * if there's a match, we allow the bio to finish. If not, the code in
2767 * extent_io.c will try to find good copies for us.
2769 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2770 u64 phy_offset, struct page *page,
2771 u64 start, u64 end, int mirror)
2773 size_t offset = start - page_offset(page);
2774 struct inode *inode = page->mapping->host;
2775 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2777 struct btrfs_root *root = BTRFS_I(inode)->root;
2780 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2781 DEFAULT_RATELIMIT_BURST);
2783 if (PageChecked(page)) {
2784 ClearPageChecked(page);
2788 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2791 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2792 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2793 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2798 phy_offset >>= inode->i_sb->s_blocksize_bits;
2799 csum_expected = *(((u32 *)io_bio->csum) + phy_offset);
2801 kaddr = kmap_atomic(page);
2802 csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
2803 btrfs_csum_final(csum, (char *)&csum);
2804 if (csum != csum_expected)
2807 kunmap_atomic(kaddr);
2812 if (__ratelimit(&_rs))
2813 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
2814 btrfs_ino(page->mapping->host), start, csum, csum_expected);
2815 memset(kaddr + offset, 1, end - start + 1);
2816 flush_dcache_page(page);
2817 kunmap_atomic(kaddr);
2818 if (csum_expected == 0)
2823 struct delayed_iput {
2824 struct list_head list;
2825 struct inode *inode;
2828 /* JDM: If this is fs-wide, why can't we add a pointer to
2829 * btrfs_inode instead and avoid the allocation? */
2830 void btrfs_add_delayed_iput(struct inode *inode)
2832 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2833 struct delayed_iput *delayed;
2835 if (atomic_add_unless(&inode->i_count, -1, 1))
2838 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2839 delayed->inode = inode;
2841 spin_lock(&fs_info->delayed_iput_lock);
2842 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2843 spin_unlock(&fs_info->delayed_iput_lock);
2846 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2849 struct btrfs_fs_info *fs_info = root->fs_info;
2850 struct delayed_iput *delayed;
2853 spin_lock(&fs_info->delayed_iput_lock);
2854 empty = list_empty(&fs_info->delayed_iputs);
2855 spin_unlock(&fs_info->delayed_iput_lock);
2859 spin_lock(&fs_info->delayed_iput_lock);
2860 list_splice_init(&fs_info->delayed_iputs, &list);
2861 spin_unlock(&fs_info->delayed_iput_lock);
2863 while (!list_empty(&list)) {
2864 delayed = list_entry(list.next, struct delayed_iput, list);
2865 list_del(&delayed->list);
2866 iput(delayed->inode);
2872 * This is called in transaction commit time. If there are no orphan
2873 * files in the subvolume, it removes orphan item and frees block_rsv
2876 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2877 struct btrfs_root *root)
2879 struct btrfs_block_rsv *block_rsv;
2882 if (atomic_read(&root->orphan_inodes) ||
2883 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2886 spin_lock(&root->orphan_lock);
2887 if (atomic_read(&root->orphan_inodes)) {
2888 spin_unlock(&root->orphan_lock);
2892 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2893 spin_unlock(&root->orphan_lock);
2897 block_rsv = root->orphan_block_rsv;
2898 root->orphan_block_rsv = NULL;
2899 spin_unlock(&root->orphan_lock);
2901 if (root->orphan_item_inserted &&
2902 btrfs_root_refs(&root->root_item) > 0) {
2903 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2904 root->root_key.objectid);
2906 btrfs_abort_transaction(trans, root, ret);
2908 root->orphan_item_inserted = 0;
2912 WARN_ON(block_rsv->size > 0);
2913 btrfs_free_block_rsv(root, block_rsv);
2918 * This creates an orphan entry for the given inode in case something goes
2919 * wrong in the middle of an unlink/truncate.
2921 * NOTE: caller of this function should reserve 5 units of metadata for
2924 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2926 struct btrfs_root *root = BTRFS_I(inode)->root;
2927 struct btrfs_block_rsv *block_rsv = NULL;
2932 if (!root->orphan_block_rsv) {
2933 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2938 spin_lock(&root->orphan_lock);
2939 if (!root->orphan_block_rsv) {
2940 root->orphan_block_rsv = block_rsv;
2941 } else if (block_rsv) {
2942 btrfs_free_block_rsv(root, block_rsv);
2946 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2947 &BTRFS_I(inode)->runtime_flags)) {
2950 * For proper ENOSPC handling, we should do orphan
2951 * cleanup when mounting. But this introduces backward
2952 * compatibility issue.
2954 if (!xchg(&root->orphan_item_inserted, 1))
2960 atomic_inc(&root->orphan_inodes);
2963 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2964 &BTRFS_I(inode)->runtime_flags))
2966 spin_unlock(&root->orphan_lock);
2968 /* grab metadata reservation from transaction handle */
2970 ret = btrfs_orphan_reserve_metadata(trans, inode);
2971 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
2974 /* insert an orphan item to track this unlinked/truncated file */
2976 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2978 atomic_dec(&root->orphan_inodes);
2980 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2981 &BTRFS_I(inode)->runtime_flags);
2982 btrfs_orphan_release_metadata(inode);
2984 if (ret != -EEXIST) {
2985 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2986 &BTRFS_I(inode)->runtime_flags);
2987 btrfs_abort_transaction(trans, root, ret);
2994 /* insert an orphan item to track subvolume contains orphan files */
2996 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2997 root->root_key.objectid);
2998 if (ret && ret != -EEXIST) {
2999 btrfs_abort_transaction(trans, root, ret);
3007 * We have done the truncate/delete so we can go ahead and remove the orphan
3008 * item for this particular inode.
3010 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3011 struct inode *inode)
3013 struct btrfs_root *root = BTRFS_I(inode)->root;
3014 int delete_item = 0;
3015 int release_rsv = 0;
3018 spin_lock(&root->orphan_lock);
3019 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3020 &BTRFS_I(inode)->runtime_flags))
3023 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3024 &BTRFS_I(inode)->runtime_flags))
3026 spin_unlock(&root->orphan_lock);
3029 atomic_dec(&root->orphan_inodes);
3031 ret = btrfs_del_orphan_item(trans, root,
3036 btrfs_orphan_release_metadata(inode);
3042 * this cleans up any orphans that may be left on the list from the last use
3045 int btrfs_orphan_cleanup(struct btrfs_root *root)
3047 struct btrfs_path *path;
3048 struct extent_buffer *leaf;
3049 struct btrfs_key key, found_key;
3050 struct btrfs_trans_handle *trans;
3051 struct inode *inode;
3052 u64 last_objectid = 0;
3053 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3055 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3058 path = btrfs_alloc_path();
3065 key.objectid = BTRFS_ORPHAN_OBJECTID;
3066 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3067 key.offset = (u64)-1;
3070 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3075 * if ret == 0 means we found what we were searching for, which
3076 * is weird, but possible, so only screw with path if we didn't
3077 * find the key and see if we have stuff that matches
3081 if (path->slots[0] == 0)
3086 /* pull out the item */
3087 leaf = path->nodes[0];
3088 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3090 /* make sure the item matches what we want */
3091 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3093 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3096 /* release the path since we're done with it */
3097 btrfs_release_path(path);
3100 * this is where we are basically btrfs_lookup, without the
3101 * crossing root thing. we store the inode number in the
3102 * offset of the orphan item.
3105 if (found_key.offset == last_objectid) {
3106 btrfs_err(root->fs_info,
3107 "Error removing orphan entry, stopping orphan cleanup");
3112 last_objectid = found_key.offset;
3114 found_key.objectid = found_key.offset;
3115 found_key.type = BTRFS_INODE_ITEM_KEY;
3116 found_key.offset = 0;
3117 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3118 ret = PTR_ERR_OR_ZERO(inode);
3119 if (ret && ret != -ESTALE)
3122 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3123 struct btrfs_root *dead_root;
3124 struct btrfs_fs_info *fs_info = root->fs_info;
3125 int is_dead_root = 0;
3128 * this is an orphan in the tree root. Currently these
3129 * could come from 2 sources:
3130 * a) a snapshot deletion in progress
3131 * b) a free space cache inode
3132 * We need to distinguish those two, as the snapshot
3133 * orphan must not get deleted.
3134 * find_dead_roots already ran before us, so if this
3135 * is a snapshot deletion, we should find the root
3136 * in the dead_roots list
3138 spin_lock(&fs_info->trans_lock);
3139 list_for_each_entry(dead_root, &fs_info->dead_roots,
3141 if (dead_root->root_key.objectid ==
3142 found_key.objectid) {
3147 spin_unlock(&fs_info->trans_lock);
3149 /* prevent this orphan from being found again */
3150 key.offset = found_key.objectid - 1;
3155 * Inode is already gone but the orphan item is still there,
3156 * kill the orphan item.
3158 if (ret == -ESTALE) {
3159 trans = btrfs_start_transaction(root, 1);
3160 if (IS_ERR(trans)) {
3161 ret = PTR_ERR(trans);
3164 btrfs_debug(root->fs_info, "auto deleting %Lu",
3165 found_key.objectid);
3166 ret = btrfs_del_orphan_item(trans, root,
3167 found_key.objectid);
3168 btrfs_end_transaction(trans, root);
3175 * add this inode to the orphan list so btrfs_orphan_del does
3176 * the proper thing when we hit it
3178 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3179 &BTRFS_I(inode)->runtime_flags);
3180 atomic_inc(&root->orphan_inodes);
3182 /* if we have links, this was a truncate, lets do that */
3183 if (inode->i_nlink) {
3184 if (!S_ISREG(inode->i_mode)) {
3191 /* 1 for the orphan item deletion. */
3192 trans = btrfs_start_transaction(root, 1);
3193 if (IS_ERR(trans)) {
3195 ret = PTR_ERR(trans);
3198 ret = btrfs_orphan_add(trans, inode);
3199 btrfs_end_transaction(trans, root);
3205 ret = btrfs_truncate(inode);
3207 btrfs_orphan_del(NULL, inode);
3212 /* this will do delete_inode and everything for us */
3217 /* release the path since we're done with it */
3218 btrfs_release_path(path);
3220 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3222 if (root->orphan_block_rsv)
3223 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3226 if (root->orphan_block_rsv || root->orphan_item_inserted) {
3227 trans = btrfs_join_transaction(root);
3229 btrfs_end_transaction(trans, root);
3233 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3235 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3239 btrfs_crit(root->fs_info,
3240 "could not do orphan cleanup %d", ret);
3241 btrfs_free_path(path);
3246 * very simple check to peek ahead in the leaf looking for xattrs. If we
3247 * don't find any xattrs, we know there can't be any acls.
3249 * slot is the slot the inode is in, objectid is the objectid of the inode
3251 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3252 int slot, u64 objectid)
3254 u32 nritems = btrfs_header_nritems(leaf);
3255 struct btrfs_key found_key;
3256 static u64 xattr_access = 0;
3257 static u64 xattr_default = 0;
3260 if (!xattr_access) {
3261 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3262 strlen(POSIX_ACL_XATTR_ACCESS));
3263 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3264 strlen(POSIX_ACL_XATTR_DEFAULT));
3268 while (slot < nritems) {
3269 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3271 /* we found a different objectid, there must not be acls */
3272 if (found_key.objectid != objectid)
3275 /* we found an xattr, assume we've got an acl */
3276 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3277 if (found_key.offset == xattr_access ||
3278 found_key.offset == xattr_default)
3283 * we found a key greater than an xattr key, there can't
3284 * be any acls later on
3286 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3293 * it goes inode, inode backrefs, xattrs, extents,
3294 * so if there are a ton of hard links to an inode there can
3295 * be a lot of backrefs. Don't waste time searching too hard,
3296 * this is just an optimization
3301 /* we hit the end of the leaf before we found an xattr or
3302 * something larger than an xattr. We have to assume the inode
3309 * read an inode from the btree into the in-memory inode
3311 static void btrfs_read_locked_inode(struct inode *inode)
3313 struct btrfs_path *path;
3314 struct extent_buffer *leaf;
3315 struct btrfs_inode_item *inode_item;
3316 struct btrfs_timespec *tspec;
3317 struct btrfs_root *root = BTRFS_I(inode)->root;
3318 struct btrfs_key location;
3322 bool filled = false;
3324 ret = btrfs_fill_inode(inode, &rdev);
3328 path = btrfs_alloc_path();
3332 path->leave_spinning = 1;
3333 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3335 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3339 leaf = path->nodes[0];
3344 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3345 struct btrfs_inode_item);
3346 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3347 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3348 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3349 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3350 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3352 tspec = btrfs_inode_atime(inode_item);
3353 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3354 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3356 tspec = btrfs_inode_mtime(inode_item);
3357 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3358 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3360 tspec = btrfs_inode_ctime(inode_item);
3361 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3362 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3364 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3365 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3366 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3369 * If we were modified in the current generation and evicted from memory
3370 * and then re-read we need to do a full sync since we don't have any
3371 * idea about which extents were modified before we were evicted from
3374 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3375 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3376 &BTRFS_I(inode)->runtime_flags);
3378 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3379 inode->i_generation = BTRFS_I(inode)->generation;
3381 rdev = btrfs_inode_rdev(leaf, inode_item);
3383 BTRFS_I(inode)->index_cnt = (u64)-1;
3384 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3387 * try to precache a NULL acl entry for files that don't have
3388 * any xattrs or acls
3390 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3393 cache_no_acl(inode);
3395 btrfs_free_path(path);
3397 switch (inode->i_mode & S_IFMT) {
3399 inode->i_mapping->a_ops = &btrfs_aops;
3400 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3401 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3402 inode->i_fop = &btrfs_file_operations;
3403 inode->i_op = &btrfs_file_inode_operations;
3406 inode->i_fop = &btrfs_dir_file_operations;
3407 if (root == root->fs_info->tree_root)
3408 inode->i_op = &btrfs_dir_ro_inode_operations;
3410 inode->i_op = &btrfs_dir_inode_operations;
3413 inode->i_op = &btrfs_symlink_inode_operations;
3414 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3415 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3418 inode->i_op = &btrfs_special_inode_operations;
3419 init_special_inode(inode, inode->i_mode, rdev);
3423 btrfs_update_iflags(inode);
3427 btrfs_free_path(path);
3428 make_bad_inode(inode);
3432 * given a leaf and an inode, copy the inode fields into the leaf
3434 static void fill_inode_item(struct btrfs_trans_handle *trans,
3435 struct extent_buffer *leaf,
3436 struct btrfs_inode_item *item,
3437 struct inode *inode)
3439 struct btrfs_map_token token;
3441 btrfs_init_map_token(&token);
3443 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3444 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3445 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3447 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3448 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3450 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3451 inode->i_atime.tv_sec, &token);
3452 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3453 inode->i_atime.tv_nsec, &token);
3455 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3456 inode->i_mtime.tv_sec, &token);
3457 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3458 inode->i_mtime.tv_nsec, &token);
3460 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3461 inode->i_ctime.tv_sec, &token);
3462 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3463 inode->i_ctime.tv_nsec, &token);
3465 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3467 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3469 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3470 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3471 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3472 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3473 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3477 * copy everything in the in-memory inode into the btree.
3479 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3480 struct btrfs_root *root, struct inode *inode)
3482 struct btrfs_inode_item *inode_item;
3483 struct btrfs_path *path;
3484 struct extent_buffer *leaf;
3487 path = btrfs_alloc_path();
3491 path->leave_spinning = 1;
3492 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3500 btrfs_unlock_up_safe(path, 1);
3501 leaf = path->nodes[0];
3502 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3503 struct btrfs_inode_item);
3505 fill_inode_item(trans, leaf, inode_item, inode);
3506 btrfs_mark_buffer_dirty(leaf);
3507 btrfs_set_inode_last_trans(trans, inode);
3510 btrfs_free_path(path);
3515 * copy everything in the in-memory inode into the btree.
3517 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3518 struct btrfs_root *root, struct inode *inode)
3523 * If the inode is a free space inode, we can deadlock during commit
3524 * if we put it into the delayed code.
3526 * The data relocation inode should also be directly updated
3529 if (!btrfs_is_free_space_inode(inode)
3530 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3531 btrfs_update_root_times(trans, root);
3533 ret = btrfs_delayed_update_inode(trans, root, inode);
3535 btrfs_set_inode_last_trans(trans, inode);
3539 return btrfs_update_inode_item(trans, root, inode);
3542 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3543 struct btrfs_root *root,
3544 struct inode *inode)
3548 ret = btrfs_update_inode(trans, root, inode);
3550 return btrfs_update_inode_item(trans, root, inode);
3555 * unlink helper that gets used here in inode.c and in the tree logging
3556 * recovery code. It remove a link in a directory with a given name, and
3557 * also drops the back refs in the inode to the directory
3559 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3560 struct btrfs_root *root,
3561 struct inode *dir, struct inode *inode,
3562 const char *name, int name_len)
3564 struct btrfs_path *path;
3566 struct extent_buffer *leaf;
3567 struct btrfs_dir_item *di;
3568 struct btrfs_key key;
3570 u64 ino = btrfs_ino(inode);
3571 u64 dir_ino = btrfs_ino(dir);
3573 path = btrfs_alloc_path();
3579 path->leave_spinning = 1;
3580 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3581 name, name_len, -1);
3590 leaf = path->nodes[0];
3591 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3592 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3595 btrfs_release_path(path);
3597 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3600 btrfs_info(root->fs_info,
3601 "failed to delete reference to %.*s, inode %llu parent %llu",
3602 name_len, name, ino, dir_ino);
3603 btrfs_abort_transaction(trans, root, ret);
3607 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3609 btrfs_abort_transaction(trans, root, ret);
3613 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3615 if (ret != 0 && ret != -ENOENT) {
3616 btrfs_abort_transaction(trans, root, ret);
3620 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3625 btrfs_abort_transaction(trans, root, ret);
3627 btrfs_free_path(path);
3631 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3632 inode_inc_iversion(inode);
3633 inode_inc_iversion(dir);
3634 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3635 ret = btrfs_update_inode(trans, root, dir);
3640 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3641 struct btrfs_root *root,
3642 struct inode *dir, struct inode *inode,
3643 const char *name, int name_len)
3646 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3648 btrfs_drop_nlink(inode);
3649 ret = btrfs_update_inode(trans, root, inode);
3655 * helper to start transaction for unlink and rmdir.
3657 * unlink and rmdir are special in btrfs, they do not always free space, so
3658 * if we cannot make our reservations the normal way try and see if there is
3659 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3660 * allow the unlink to occur.
3662 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3664 struct btrfs_trans_handle *trans;
3665 struct btrfs_root *root = BTRFS_I(dir)->root;
3669 * 1 for the possible orphan item
3670 * 1 for the dir item
3671 * 1 for the dir index
3672 * 1 for the inode ref
3675 trans = btrfs_start_transaction(root, 5);
3676 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3679 if (PTR_ERR(trans) == -ENOSPC) {
3680 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3682 trans = btrfs_start_transaction(root, 0);
3685 ret = btrfs_cond_migrate_bytes(root->fs_info,
3686 &root->fs_info->trans_block_rsv,
3689 btrfs_end_transaction(trans, root);
3690 return ERR_PTR(ret);
3692 trans->block_rsv = &root->fs_info->trans_block_rsv;
3693 trans->bytes_reserved = num_bytes;
3698 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3700 struct btrfs_root *root = BTRFS_I(dir)->root;
3701 struct btrfs_trans_handle *trans;
3702 struct inode *inode = dentry->d_inode;
3705 trans = __unlink_start_trans(dir);
3707 return PTR_ERR(trans);
3709 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3711 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3712 dentry->d_name.name, dentry->d_name.len);
3716 if (inode->i_nlink == 0) {
3717 ret = btrfs_orphan_add(trans, inode);
3723 btrfs_end_transaction(trans, root);
3724 btrfs_btree_balance_dirty(root);
3728 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3729 struct btrfs_root *root,
3730 struct inode *dir, u64 objectid,
3731 const char *name, int name_len)
3733 struct btrfs_path *path;
3734 struct extent_buffer *leaf;
3735 struct btrfs_dir_item *di;
3736 struct btrfs_key key;
3739 u64 dir_ino = btrfs_ino(dir);
3741 path = btrfs_alloc_path();
3745 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3746 name, name_len, -1);
3747 if (IS_ERR_OR_NULL(di)) {
3755 leaf = path->nodes[0];
3756 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3757 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3758 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3760 btrfs_abort_transaction(trans, root, ret);
3763 btrfs_release_path(path);
3765 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3766 objectid, root->root_key.objectid,
3767 dir_ino, &index, name, name_len);
3769 if (ret != -ENOENT) {
3770 btrfs_abort_transaction(trans, root, ret);
3773 di = btrfs_search_dir_index_item(root, path, dir_ino,
3775 if (IS_ERR_OR_NULL(di)) {
3780 btrfs_abort_transaction(trans, root, ret);
3784 leaf = path->nodes[0];
3785 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3786 btrfs_release_path(path);
3789 btrfs_release_path(path);
3791 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3793 btrfs_abort_transaction(trans, root, ret);
3797 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3798 inode_inc_iversion(dir);
3799 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3800 ret = btrfs_update_inode_fallback(trans, root, dir);
3802 btrfs_abort_transaction(trans, root, ret);
3804 btrfs_free_path(path);
3808 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3810 struct inode *inode = dentry->d_inode;
3812 struct btrfs_root *root = BTRFS_I(dir)->root;
3813 struct btrfs_trans_handle *trans;
3815 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3817 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3820 trans = __unlink_start_trans(dir);
3822 return PTR_ERR(trans);
3824 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3825 err = btrfs_unlink_subvol(trans, root, dir,
3826 BTRFS_I(inode)->location.objectid,
3827 dentry->d_name.name,
3828 dentry->d_name.len);
3832 err = btrfs_orphan_add(trans, inode);
3836 /* now the directory is empty */
3837 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3838 dentry->d_name.name, dentry->d_name.len);
3840 btrfs_i_size_write(inode, 0);
3842 btrfs_end_transaction(trans, root);
3843 btrfs_btree_balance_dirty(root);
3849 * this can truncate away extent items, csum items and directory items.
3850 * It starts at a high offset and removes keys until it can't find
3851 * any higher than new_size
3853 * csum items that cross the new i_size are truncated to the new size
3856 * min_type is the minimum key type to truncate down to. If set to 0, this
3857 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3859 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3860 struct btrfs_root *root,
3861 struct inode *inode,
3862 u64 new_size, u32 min_type)
3864 struct btrfs_path *path;
3865 struct extent_buffer *leaf;
3866 struct btrfs_file_extent_item *fi;
3867 struct btrfs_key key;
3868 struct btrfs_key found_key;
3869 u64 extent_start = 0;
3870 u64 extent_num_bytes = 0;
3871 u64 extent_offset = 0;
3873 u64 last_size = (u64)-1;
3874 u32 found_type = (u8)-1;
3877 int pending_del_nr = 0;
3878 int pending_del_slot = 0;
3879 int extent_type = -1;
3882 u64 ino = btrfs_ino(inode);
3884 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3886 path = btrfs_alloc_path();
3892 * We want to drop from the next block forward in case this new size is
3893 * not block aligned since we will be keeping the last block of the
3894 * extent just the way it is.
3896 if (root->ref_cows || root == root->fs_info->tree_root)
3897 btrfs_drop_extent_cache(inode, ALIGN(new_size,
3898 root->sectorsize), (u64)-1, 0);
3901 * This function is also used to drop the items in the log tree before
3902 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3903 * it is used to drop the loged items. So we shouldn't kill the delayed
3906 if (min_type == 0 && root == BTRFS_I(inode)->root)
3907 btrfs_kill_delayed_inode_items(inode);
3910 key.offset = (u64)-1;
3914 path->leave_spinning = 1;
3915 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3922 /* there are no items in the tree for us to truncate, we're
3925 if (path->slots[0] == 0)
3932 leaf = path->nodes[0];
3933 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3934 found_type = btrfs_key_type(&found_key);
3936 if (found_key.objectid != ino)
3939 if (found_type < min_type)
3942 item_end = found_key.offset;
3943 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3944 fi = btrfs_item_ptr(leaf, path->slots[0],
3945 struct btrfs_file_extent_item);
3946 extent_type = btrfs_file_extent_type(leaf, fi);
3947 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3949 btrfs_file_extent_num_bytes(leaf, fi);
3950 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3951 item_end += btrfs_file_extent_inline_len(leaf,
3956 if (found_type > min_type) {
3959 if (item_end < new_size)
3961 if (found_key.offset >= new_size)
3967 /* FIXME, shrink the extent if the ref count is only 1 */
3968 if (found_type != BTRFS_EXTENT_DATA_KEY)
3972 last_size = found_key.offset;
3974 last_size = new_size;
3976 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3978 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3980 u64 orig_num_bytes =
3981 btrfs_file_extent_num_bytes(leaf, fi);
3982 extent_num_bytes = ALIGN(new_size -
3985 btrfs_set_file_extent_num_bytes(leaf, fi,
3987 num_dec = (orig_num_bytes -
3989 if (root->ref_cows && extent_start != 0)
3990 inode_sub_bytes(inode, num_dec);
3991 btrfs_mark_buffer_dirty(leaf);
3994 btrfs_file_extent_disk_num_bytes(leaf,
3996 extent_offset = found_key.offset -
3997 btrfs_file_extent_offset(leaf, fi);
3999 /* FIXME blocksize != 4096 */
4000 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4001 if (extent_start != 0) {
4004 inode_sub_bytes(inode, num_dec);
4007 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4009 * we can't truncate inline items that have had
4013 btrfs_file_extent_compression(leaf, fi) == 0 &&
4014 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4015 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4016 u32 size = new_size - found_key.offset;
4018 if (root->ref_cows) {
4019 inode_sub_bytes(inode, item_end + 1 -
4023 btrfs_file_extent_calc_inline_size(size);
4024 btrfs_truncate_item(root, path, size, 1);
4025 } else if (root->ref_cows) {
4026 inode_sub_bytes(inode, item_end + 1 -
4032 if (!pending_del_nr) {
4033 /* no pending yet, add ourselves */
4034 pending_del_slot = path->slots[0];
4036 } else if (pending_del_nr &&
4037 path->slots[0] + 1 == pending_del_slot) {
4038 /* hop on the pending chunk */
4040 pending_del_slot = path->slots[0];
4047 if (found_extent && (root->ref_cows ||
4048 root == root->fs_info->tree_root)) {
4049 btrfs_set_path_blocking(path);
4050 ret = btrfs_free_extent(trans, root, extent_start,
4051 extent_num_bytes, 0,
4052 btrfs_header_owner(leaf),
4053 ino, extent_offset, 0);
4057 if (found_type == BTRFS_INODE_ITEM_KEY)
4060 if (path->slots[0] == 0 ||
4061 path->slots[0] != pending_del_slot) {
4062 if (pending_del_nr) {
4063 ret = btrfs_del_items(trans, root, path,
4067 btrfs_abort_transaction(trans,
4073 btrfs_release_path(path);
4080 if (pending_del_nr) {
4081 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4084 btrfs_abort_transaction(trans, root, ret);
4087 if (last_size != (u64)-1)
4088 btrfs_ordered_update_i_size(inode, last_size, NULL);
4089 btrfs_free_path(path);
4094 * btrfs_truncate_page - read, zero a chunk and write a page
4095 * @inode - inode that we're zeroing
4096 * @from - the offset to start zeroing
4097 * @len - the length to zero, 0 to zero the entire range respective to the
4099 * @front - zero up to the offset instead of from the offset on
4101 * This will find the page for the "from" offset and cow the page and zero the
4102 * part we want to zero. This is used with truncate and hole punching.
4104 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4107 struct address_space *mapping = inode->i_mapping;
4108 struct btrfs_root *root = BTRFS_I(inode)->root;
4109 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4110 struct btrfs_ordered_extent *ordered;
4111 struct extent_state *cached_state = NULL;
4113 u32 blocksize = root->sectorsize;
4114 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4115 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4117 gfp_t mask = btrfs_alloc_write_mask(mapping);
4122 if ((offset & (blocksize - 1)) == 0 &&
4123 (!len || ((len & (blocksize - 1)) == 0)))
4125 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4130 page = find_or_create_page(mapping, index, mask);
4132 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4137 page_start = page_offset(page);
4138 page_end = page_start + PAGE_CACHE_SIZE - 1;
4140 if (!PageUptodate(page)) {
4141 ret = btrfs_readpage(NULL, page);
4143 if (page->mapping != mapping) {
4145 page_cache_release(page);
4148 if (!PageUptodate(page)) {
4153 wait_on_page_writeback(page);
4155 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4156 set_page_extent_mapped(page);
4158 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4160 unlock_extent_cached(io_tree, page_start, page_end,
4161 &cached_state, GFP_NOFS);
4163 page_cache_release(page);
4164 btrfs_start_ordered_extent(inode, ordered, 1);
4165 btrfs_put_ordered_extent(ordered);
4169 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4170 EXTENT_DIRTY | EXTENT_DELALLOC |
4171 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4172 0, 0, &cached_state, GFP_NOFS);
4174 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4177 unlock_extent_cached(io_tree, page_start, page_end,
4178 &cached_state, GFP_NOFS);
4182 if (offset != PAGE_CACHE_SIZE) {
4184 len = PAGE_CACHE_SIZE - offset;
4187 memset(kaddr, 0, offset);
4189 memset(kaddr + offset, 0, len);
4190 flush_dcache_page(page);
4193 ClearPageChecked(page);
4194 set_page_dirty(page);
4195 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4200 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4202 page_cache_release(page);
4208 * This function puts in dummy file extents for the area we're creating a hole
4209 * for. So if we are truncating this file to a larger size we need to insert
4210 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4211 * the range between oldsize and size
4213 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4215 struct btrfs_trans_handle *trans;
4216 struct btrfs_root *root = BTRFS_I(inode)->root;
4217 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4218 struct extent_map *em = NULL;
4219 struct extent_state *cached_state = NULL;
4220 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4221 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4222 u64 block_end = ALIGN(size, root->sectorsize);
4229 * If our size started in the middle of a page we need to zero out the
4230 * rest of the page before we expand the i_size, otherwise we could
4231 * expose stale data.
4233 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4237 if (size <= hole_start)
4241 struct btrfs_ordered_extent *ordered;
4243 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4245 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4246 block_end - hole_start);
4249 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4250 &cached_state, GFP_NOFS);
4251 btrfs_start_ordered_extent(inode, ordered, 1);
4252 btrfs_put_ordered_extent(ordered);
4255 cur_offset = hole_start;
4257 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4258 block_end - cur_offset, 0);
4264 last_byte = min(extent_map_end(em), block_end);
4265 last_byte = ALIGN(last_byte , root->sectorsize);
4266 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4267 struct extent_map *hole_em;
4268 hole_size = last_byte - cur_offset;
4270 trans = btrfs_start_transaction(root, 3);
4271 if (IS_ERR(trans)) {
4272 err = PTR_ERR(trans);
4276 err = btrfs_drop_extents(trans, root, inode,
4278 cur_offset + hole_size, 1);
4280 btrfs_abort_transaction(trans, root, err);
4281 btrfs_end_transaction(trans, root);
4285 err = btrfs_insert_file_extent(trans, root,
4286 btrfs_ino(inode), cur_offset, 0,
4287 0, hole_size, 0, hole_size,
4290 btrfs_abort_transaction(trans, root, err);
4291 btrfs_end_transaction(trans, root);
4295 btrfs_drop_extent_cache(inode, cur_offset,
4296 cur_offset + hole_size - 1, 0);
4297 hole_em = alloc_extent_map();
4299 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4300 &BTRFS_I(inode)->runtime_flags);
4303 hole_em->start = cur_offset;
4304 hole_em->len = hole_size;
4305 hole_em->orig_start = cur_offset;
4307 hole_em->block_start = EXTENT_MAP_HOLE;
4308 hole_em->block_len = 0;
4309 hole_em->orig_block_len = 0;
4310 hole_em->ram_bytes = hole_size;
4311 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4312 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4313 hole_em->generation = trans->transid;
4316 write_lock(&em_tree->lock);
4317 err = add_extent_mapping(em_tree, hole_em, 1);
4318 write_unlock(&em_tree->lock);
4321 btrfs_drop_extent_cache(inode, cur_offset,
4325 free_extent_map(hole_em);
4327 btrfs_update_inode(trans, root, inode);
4328 btrfs_end_transaction(trans, root);
4330 free_extent_map(em);
4332 cur_offset = last_byte;
4333 if (cur_offset >= block_end)
4337 free_extent_map(em);
4338 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4343 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4345 struct btrfs_root *root = BTRFS_I(inode)->root;
4346 struct btrfs_trans_handle *trans;
4347 loff_t oldsize = i_size_read(inode);
4348 loff_t newsize = attr->ia_size;
4349 int mask = attr->ia_valid;
4353 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4354 * special case where we need to update the times despite not having
4355 * these flags set. For all other operations the VFS set these flags
4356 * explicitly if it wants a timestamp update.
4358 if (newsize != oldsize && (!(mask & (ATTR_CTIME | ATTR_MTIME))))
4359 inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb);
4361 if (newsize > oldsize) {
4362 truncate_pagecache(inode, newsize);
4363 ret = btrfs_cont_expand(inode, oldsize, newsize);
4367 trans = btrfs_start_transaction(root, 1);
4369 return PTR_ERR(trans);
4371 i_size_write(inode, newsize);
4372 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4373 ret = btrfs_update_inode(trans, root, inode);
4374 btrfs_end_transaction(trans, root);
4378 * We're truncating a file that used to have good data down to
4379 * zero. Make sure it gets into the ordered flush list so that
4380 * any new writes get down to disk quickly.
4383 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4384 &BTRFS_I(inode)->runtime_flags);
4387 * 1 for the orphan item we're going to add
4388 * 1 for the orphan item deletion.
4390 trans = btrfs_start_transaction(root, 2);
4392 return PTR_ERR(trans);
4395 * We need to do this in case we fail at _any_ point during the
4396 * actual truncate. Once we do the truncate_setsize we could
4397 * invalidate pages which forces any outstanding ordered io to
4398 * be instantly completed which will give us extents that need
4399 * to be truncated. If we fail to get an orphan inode down we
4400 * could have left over extents that were never meant to live,
4401 * so we need to garuntee from this point on that everything
4402 * will be consistent.
4404 ret = btrfs_orphan_add(trans, inode);
4405 btrfs_end_transaction(trans, root);
4409 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4410 truncate_setsize(inode, newsize);
4412 /* Disable nonlocked read DIO to avoid the end less truncate */
4413 btrfs_inode_block_unlocked_dio(inode);
4414 inode_dio_wait(inode);
4415 btrfs_inode_resume_unlocked_dio(inode);
4417 ret = btrfs_truncate(inode);
4418 if (ret && inode->i_nlink) {
4422 * failed to truncate, disk_i_size is only adjusted down
4423 * as we remove extents, so it should represent the true
4424 * size of the inode, so reset the in memory size and
4425 * delete our orphan entry.
4427 trans = btrfs_join_transaction(root);
4428 if (IS_ERR(trans)) {
4429 btrfs_orphan_del(NULL, inode);
4432 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4433 err = btrfs_orphan_del(trans, inode);
4435 btrfs_abort_transaction(trans, root, err);
4436 btrfs_end_transaction(trans, root);
4443 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4445 struct inode *inode = dentry->d_inode;
4446 struct btrfs_root *root = BTRFS_I(inode)->root;
4449 if (btrfs_root_readonly(root))
4452 err = inode_change_ok(inode, attr);
4456 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4457 err = btrfs_setsize(inode, attr);
4462 if (attr->ia_valid) {
4463 setattr_copy(inode, attr);
4464 inode_inc_iversion(inode);
4465 err = btrfs_dirty_inode(inode);
4467 if (!err && attr->ia_valid & ATTR_MODE)
4468 err = btrfs_acl_chmod(inode);
4474 void btrfs_evict_inode(struct inode *inode)
4476 struct btrfs_trans_handle *trans;
4477 struct btrfs_root *root = BTRFS_I(inode)->root;
4478 struct btrfs_block_rsv *rsv, *global_rsv;
4479 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4482 trace_btrfs_inode_evict(inode);
4484 truncate_inode_pages(&inode->i_data, 0);
4485 if (inode->i_nlink &&
4486 ((btrfs_root_refs(&root->root_item) != 0 &&
4487 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4488 btrfs_is_free_space_inode(inode)))
4491 if (is_bad_inode(inode)) {
4492 btrfs_orphan_del(NULL, inode);
4495 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4496 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4498 if (root->fs_info->log_root_recovering) {
4499 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4500 &BTRFS_I(inode)->runtime_flags));
4504 if (inode->i_nlink > 0) {
4505 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4506 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4510 ret = btrfs_commit_inode_delayed_inode(inode);
4512 btrfs_orphan_del(NULL, inode);
4516 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4518 btrfs_orphan_del(NULL, inode);
4521 rsv->size = min_size;
4523 global_rsv = &root->fs_info->global_block_rsv;
4525 btrfs_i_size_write(inode, 0);
4528 * This is a bit simpler than btrfs_truncate since we've already
4529 * reserved our space for our orphan item in the unlink, so we just
4530 * need to reserve some slack space in case we add bytes and update
4531 * inode item when doing the truncate.
4534 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4535 BTRFS_RESERVE_FLUSH_LIMIT);
4538 * Try and steal from the global reserve since we will
4539 * likely not use this space anyway, we want to try as
4540 * hard as possible to get this to work.
4543 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4546 btrfs_warn(root->fs_info,
4547 "Could not get space for a delete, will truncate on mount %d",
4549 btrfs_orphan_del(NULL, inode);
4550 btrfs_free_block_rsv(root, rsv);
4554 trans = btrfs_join_transaction(root);
4555 if (IS_ERR(trans)) {
4556 btrfs_orphan_del(NULL, inode);
4557 btrfs_free_block_rsv(root, rsv);
4561 trans->block_rsv = rsv;
4563 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4567 trans->block_rsv = &root->fs_info->trans_block_rsv;
4568 btrfs_end_transaction(trans, root);
4570 btrfs_btree_balance_dirty(root);
4573 btrfs_free_block_rsv(root, rsv);
4576 * Errors here aren't a big deal, it just means we leave orphan items
4577 * in the tree. They will be cleaned up on the next mount.
4580 trans->block_rsv = root->orphan_block_rsv;
4581 btrfs_orphan_del(trans, inode);
4583 btrfs_orphan_del(NULL, inode);
4586 trans->block_rsv = &root->fs_info->trans_block_rsv;
4587 if (!(root == root->fs_info->tree_root ||
4588 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4589 btrfs_return_ino(root, btrfs_ino(inode));
4591 btrfs_end_transaction(trans, root);
4592 btrfs_btree_balance_dirty(root);
4594 btrfs_remove_delayed_node(inode);
4600 * this returns the key found in the dir entry in the location pointer.
4601 * If no dir entries were found, location->objectid is 0.
4603 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4604 struct btrfs_key *location)
4606 const char *name = dentry->d_name.name;
4607 int namelen = dentry->d_name.len;
4608 struct btrfs_dir_item *di;
4609 struct btrfs_path *path;
4610 struct btrfs_root *root = BTRFS_I(dir)->root;
4613 path = btrfs_alloc_path();
4617 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4622 if (IS_ERR_OR_NULL(di))
4625 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4627 btrfs_free_path(path);
4630 location->objectid = 0;
4635 * when we hit a tree root in a directory, the btrfs part of the inode
4636 * needs to be changed to reflect the root directory of the tree root. This
4637 * is kind of like crossing a mount point.
4639 static int fixup_tree_root_location(struct btrfs_root *root,
4641 struct dentry *dentry,
4642 struct btrfs_key *location,
4643 struct btrfs_root **sub_root)
4645 struct btrfs_path *path;
4646 struct btrfs_root *new_root;
4647 struct btrfs_root_ref *ref;
4648 struct extent_buffer *leaf;
4652 path = btrfs_alloc_path();
4659 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
4660 BTRFS_I(dir)->root->root_key.objectid,
4661 location->objectid);
4668 leaf = path->nodes[0];
4669 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4670 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4671 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4674 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4675 (unsigned long)(ref + 1),
4676 dentry->d_name.len);
4680 btrfs_release_path(path);
4682 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4683 if (IS_ERR(new_root)) {
4684 err = PTR_ERR(new_root);
4688 *sub_root = new_root;
4689 location->objectid = btrfs_root_dirid(&new_root->root_item);
4690 location->type = BTRFS_INODE_ITEM_KEY;
4691 location->offset = 0;
4694 btrfs_free_path(path);
4698 static void inode_tree_add(struct inode *inode)
4700 struct btrfs_root *root = BTRFS_I(inode)->root;
4701 struct btrfs_inode *entry;
4703 struct rb_node *parent;
4704 struct rb_node *new = &BTRFS_I(inode)->rb_node;
4705 u64 ino = btrfs_ino(inode);
4707 if (inode_unhashed(inode))
4710 spin_lock(&root->inode_lock);
4711 p = &root->inode_tree.rb_node;
4714 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4716 if (ino < btrfs_ino(&entry->vfs_inode))
4717 p = &parent->rb_left;
4718 else if (ino > btrfs_ino(&entry->vfs_inode))
4719 p = &parent->rb_right;
4721 WARN_ON(!(entry->vfs_inode.i_state &
4722 (I_WILL_FREE | I_FREEING)));
4723 rb_replace_node(parent, new, &root->inode_tree);
4724 RB_CLEAR_NODE(parent);
4725 spin_unlock(&root->inode_lock);
4729 rb_link_node(new, parent, p);
4730 rb_insert_color(new, &root->inode_tree);
4731 spin_unlock(&root->inode_lock);
4734 static void inode_tree_del(struct inode *inode)
4736 struct btrfs_root *root = BTRFS_I(inode)->root;
4739 spin_lock(&root->inode_lock);
4740 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4741 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4742 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4743 empty = RB_EMPTY_ROOT(&root->inode_tree);
4745 spin_unlock(&root->inode_lock);
4747 if (empty && btrfs_root_refs(&root->root_item) == 0) {
4748 synchronize_srcu(&root->fs_info->subvol_srcu);
4749 spin_lock(&root->inode_lock);
4750 empty = RB_EMPTY_ROOT(&root->inode_tree);
4751 spin_unlock(&root->inode_lock);
4753 btrfs_add_dead_root(root);
4757 void btrfs_invalidate_inodes(struct btrfs_root *root)
4759 struct rb_node *node;
4760 struct rb_node *prev;
4761 struct btrfs_inode *entry;
4762 struct inode *inode;
4765 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4767 spin_lock(&root->inode_lock);
4769 node = root->inode_tree.rb_node;
4773 entry = rb_entry(node, struct btrfs_inode, rb_node);
4775 if (objectid < btrfs_ino(&entry->vfs_inode))
4776 node = node->rb_left;
4777 else if (objectid > btrfs_ino(&entry->vfs_inode))
4778 node = node->rb_right;
4784 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4785 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4789 prev = rb_next(prev);
4793 entry = rb_entry(node, struct btrfs_inode, rb_node);
4794 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4795 inode = igrab(&entry->vfs_inode);
4797 spin_unlock(&root->inode_lock);
4798 if (atomic_read(&inode->i_count) > 1)
4799 d_prune_aliases(inode);
4801 * btrfs_drop_inode will have it removed from
4802 * the inode cache when its usage count
4807 spin_lock(&root->inode_lock);
4811 if (cond_resched_lock(&root->inode_lock))
4814 node = rb_next(node);
4816 spin_unlock(&root->inode_lock);
4819 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4821 struct btrfs_iget_args *args = p;
4822 inode->i_ino = args->ino;
4823 BTRFS_I(inode)->root = args->root;
4827 static int btrfs_find_actor(struct inode *inode, void *opaque)
4829 struct btrfs_iget_args *args = opaque;
4830 return args->ino == btrfs_ino(inode) &&
4831 args->root == BTRFS_I(inode)->root;
4834 static struct inode *btrfs_iget_locked(struct super_block *s,
4836 struct btrfs_root *root)
4838 struct inode *inode;
4839 struct btrfs_iget_args args;
4840 unsigned long hashval = btrfs_inode_hash(objectid, root);
4842 args.ino = objectid;
4845 inode = iget5_locked(s, hashval, btrfs_find_actor,
4846 btrfs_init_locked_inode,
4851 /* Get an inode object given its location and corresponding root.
4852 * Returns in *is_new if the inode was read from disk
4854 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4855 struct btrfs_root *root, int *new)
4857 struct inode *inode;
4859 inode = btrfs_iget_locked(s, location->objectid, root);
4861 return ERR_PTR(-ENOMEM);
4863 if (inode->i_state & I_NEW) {
4864 BTRFS_I(inode)->root = root;
4865 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4866 btrfs_read_locked_inode(inode);
4867 if (!is_bad_inode(inode)) {
4868 inode_tree_add(inode);
4869 unlock_new_inode(inode);
4873 unlock_new_inode(inode);
4875 inode = ERR_PTR(-ESTALE);
4882 static struct inode *new_simple_dir(struct super_block *s,
4883 struct btrfs_key *key,
4884 struct btrfs_root *root)
4886 struct inode *inode = new_inode(s);
4889 return ERR_PTR(-ENOMEM);
4891 BTRFS_I(inode)->root = root;
4892 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4893 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4895 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4896 inode->i_op = &btrfs_dir_ro_inode_operations;
4897 inode->i_fop = &simple_dir_operations;
4898 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4899 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4904 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4906 struct inode *inode;
4907 struct btrfs_root *root = BTRFS_I(dir)->root;
4908 struct btrfs_root *sub_root = root;
4909 struct btrfs_key location;
4913 if (dentry->d_name.len > BTRFS_NAME_LEN)
4914 return ERR_PTR(-ENAMETOOLONG);
4916 ret = btrfs_inode_by_name(dir, dentry, &location);
4918 return ERR_PTR(ret);
4920 if (location.objectid == 0)
4923 if (location.type == BTRFS_INODE_ITEM_KEY) {
4924 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4928 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4930 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4931 ret = fixup_tree_root_location(root, dir, dentry,
4932 &location, &sub_root);
4935 inode = ERR_PTR(ret);
4937 inode = new_simple_dir(dir->i_sb, &location, sub_root);
4939 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4941 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4943 if (!IS_ERR(inode) && root != sub_root) {
4944 down_read(&root->fs_info->cleanup_work_sem);
4945 if (!(inode->i_sb->s_flags & MS_RDONLY))
4946 ret = btrfs_orphan_cleanup(sub_root);
4947 up_read(&root->fs_info->cleanup_work_sem);
4950 inode = ERR_PTR(ret);
4957 static int btrfs_dentry_delete(const struct dentry *dentry)
4959 struct btrfs_root *root;
4960 struct inode *inode = dentry->d_inode;
4962 if (!inode && !IS_ROOT(dentry))
4963 inode = dentry->d_parent->d_inode;
4966 root = BTRFS_I(inode)->root;
4967 if (btrfs_root_refs(&root->root_item) == 0)
4970 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
4976 static void btrfs_dentry_release(struct dentry *dentry)
4978 if (dentry->d_fsdata)
4979 kfree(dentry->d_fsdata);
4982 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4987 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
4991 unsigned char btrfs_filetype_table[] = {
4992 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4995 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
4997 struct inode *inode = file_inode(file);
4998 struct btrfs_root *root = BTRFS_I(inode)->root;
4999 struct btrfs_item *item;
5000 struct btrfs_dir_item *di;
5001 struct btrfs_key key;
5002 struct btrfs_key found_key;
5003 struct btrfs_path *path;
5004 struct list_head ins_list;
5005 struct list_head del_list;
5007 struct extent_buffer *leaf;
5009 unsigned char d_type;
5014 int key_type = BTRFS_DIR_INDEX_KEY;
5018 int is_curr = 0; /* ctx->pos points to the current index? */
5020 /* FIXME, use a real flag for deciding about the key type */
5021 if (root->fs_info->tree_root == root)
5022 key_type = BTRFS_DIR_ITEM_KEY;
5024 if (!dir_emit_dots(file, ctx))
5027 path = btrfs_alloc_path();
5033 if (key_type == BTRFS_DIR_INDEX_KEY) {
5034 INIT_LIST_HEAD(&ins_list);
5035 INIT_LIST_HEAD(&del_list);
5036 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5039 btrfs_set_key_type(&key, key_type);
5040 key.offset = ctx->pos;
5041 key.objectid = btrfs_ino(inode);
5043 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5048 leaf = path->nodes[0];
5049 slot = path->slots[0];
5050 if (slot >= btrfs_header_nritems(leaf)) {
5051 ret = btrfs_next_leaf(root, path);
5059 item = btrfs_item_nr(slot);
5060 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5062 if (found_key.objectid != key.objectid)
5064 if (btrfs_key_type(&found_key) != key_type)
5066 if (found_key.offset < ctx->pos)
5068 if (key_type == BTRFS_DIR_INDEX_KEY &&
5069 btrfs_should_delete_dir_index(&del_list,
5073 ctx->pos = found_key.offset;
5076 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5078 di_total = btrfs_item_size(leaf, item);
5080 while (di_cur < di_total) {
5081 struct btrfs_key location;
5083 if (verify_dir_item(root, leaf, di))
5086 name_len = btrfs_dir_name_len(leaf, di);
5087 if (name_len <= sizeof(tmp_name)) {
5088 name_ptr = tmp_name;
5090 name_ptr = kmalloc(name_len, GFP_NOFS);
5096 read_extent_buffer(leaf, name_ptr,
5097 (unsigned long)(di + 1), name_len);
5099 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5100 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5103 /* is this a reference to our own snapshot? If so
5106 * In contrast to old kernels, we insert the snapshot's
5107 * dir item and dir index after it has been created, so
5108 * we won't find a reference to our own snapshot. We
5109 * still keep the following code for backward
5112 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5113 location.objectid == root->root_key.objectid) {
5117 over = !dir_emit(ctx, name_ptr, name_len,
5118 location.objectid, d_type);
5121 if (name_ptr != tmp_name)
5126 di_len = btrfs_dir_name_len(leaf, di) +
5127 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5129 di = (struct btrfs_dir_item *)((char *)di + di_len);
5135 if (key_type == BTRFS_DIR_INDEX_KEY) {
5138 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5143 /* Reached end of directory/root. Bump pos past the last item. */
5147 * Stop new entries from being returned after we return the last
5150 * New directory entries are assigned a strictly increasing
5151 * offset. This means that new entries created during readdir
5152 * are *guaranteed* to be seen in the future by that readdir.
5153 * This has broken buggy programs which operate on names as
5154 * they're returned by readdir. Until we re-use freed offsets
5155 * we have this hack to stop new entries from being returned
5156 * under the assumption that they'll never reach this huge
5159 * This is being careful not to overflow 32bit loff_t unless the
5160 * last entry requires it because doing so has broken 32bit apps
5163 if (key_type == BTRFS_DIR_INDEX_KEY) {
5164 if (ctx->pos >= INT_MAX)
5165 ctx->pos = LLONG_MAX;
5172 if (key_type == BTRFS_DIR_INDEX_KEY)
5173 btrfs_put_delayed_items(&ins_list, &del_list);
5174 btrfs_free_path(path);
5178 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5180 struct btrfs_root *root = BTRFS_I(inode)->root;
5181 struct btrfs_trans_handle *trans;
5183 bool nolock = false;
5185 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5188 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5191 if (wbc->sync_mode == WB_SYNC_ALL) {
5193 trans = btrfs_join_transaction_nolock(root);
5195 trans = btrfs_join_transaction(root);
5197 return PTR_ERR(trans);
5198 ret = btrfs_commit_transaction(trans, root);
5204 * This is somewhat expensive, updating the tree every time the
5205 * inode changes. But, it is most likely to find the inode in cache.
5206 * FIXME, needs more benchmarking...there are no reasons other than performance
5207 * to keep or drop this code.
5209 static int btrfs_dirty_inode(struct inode *inode)
5211 struct btrfs_root *root = BTRFS_I(inode)->root;
5212 struct btrfs_trans_handle *trans;
5215 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5218 trans = btrfs_join_transaction(root);
5220 return PTR_ERR(trans);
5222 ret = btrfs_update_inode(trans, root, inode);
5223 if (ret && ret == -ENOSPC) {
5224 /* whoops, lets try again with the full transaction */
5225 btrfs_end_transaction(trans, root);
5226 trans = btrfs_start_transaction(root, 1);
5228 return PTR_ERR(trans);
5230 ret = btrfs_update_inode(trans, root, inode);
5232 btrfs_end_transaction(trans, root);
5233 if (BTRFS_I(inode)->delayed_node)
5234 btrfs_balance_delayed_items(root);
5240 * This is a copy of file_update_time. We need this so we can return error on
5241 * ENOSPC for updating the inode in the case of file write and mmap writes.
5243 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5246 struct btrfs_root *root = BTRFS_I(inode)->root;
5248 if (btrfs_root_readonly(root))
5251 if (flags & S_VERSION)
5252 inode_inc_iversion(inode);
5253 if (flags & S_CTIME)
5254 inode->i_ctime = *now;
5255 if (flags & S_MTIME)
5256 inode->i_mtime = *now;
5257 if (flags & S_ATIME)
5258 inode->i_atime = *now;
5259 return btrfs_dirty_inode(inode);
5263 * find the highest existing sequence number in a directory
5264 * and then set the in-memory index_cnt variable to reflect
5265 * free sequence numbers
5267 static int btrfs_set_inode_index_count(struct inode *inode)
5269 struct btrfs_root *root = BTRFS_I(inode)->root;
5270 struct btrfs_key key, found_key;
5271 struct btrfs_path *path;
5272 struct extent_buffer *leaf;
5275 key.objectid = btrfs_ino(inode);
5276 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5277 key.offset = (u64)-1;
5279 path = btrfs_alloc_path();
5283 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5286 /* FIXME: we should be able to handle this */
5292 * MAGIC NUMBER EXPLANATION:
5293 * since we search a directory based on f_pos we have to start at 2
5294 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5295 * else has to start at 2
5297 if (path->slots[0] == 0) {
5298 BTRFS_I(inode)->index_cnt = 2;
5304 leaf = path->nodes[0];
5305 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5307 if (found_key.objectid != btrfs_ino(inode) ||
5308 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5309 BTRFS_I(inode)->index_cnt = 2;
5313 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5315 btrfs_free_path(path);
5320 * helper to find a free sequence number in a given directory. This current
5321 * code is very simple, later versions will do smarter things in the btree
5323 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5327 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5328 ret = btrfs_inode_delayed_dir_index_count(dir);
5330 ret = btrfs_set_inode_index_count(dir);
5336 *index = BTRFS_I(dir)->index_cnt;
5337 BTRFS_I(dir)->index_cnt++;
5342 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5343 struct btrfs_root *root,
5345 const char *name, int name_len,
5346 u64 ref_objectid, u64 objectid,
5347 umode_t mode, u64 *index)
5349 struct inode *inode;
5350 struct btrfs_inode_item *inode_item;
5351 struct btrfs_key *location;
5352 struct btrfs_path *path;
5353 struct btrfs_inode_ref *ref;
5354 struct btrfs_key key[2];
5360 path = btrfs_alloc_path();
5362 return ERR_PTR(-ENOMEM);
5364 inode = new_inode(root->fs_info->sb);
5366 btrfs_free_path(path);
5367 return ERR_PTR(-ENOMEM);
5371 * we have to initialize this early, so we can reclaim the inode
5372 * number if we fail afterwards in this function.
5374 inode->i_ino = objectid;
5377 trace_btrfs_inode_request(dir);
5379 ret = btrfs_set_inode_index(dir, index);
5381 btrfs_free_path(path);
5383 return ERR_PTR(ret);
5387 * index_cnt is ignored for everything but a dir,
5388 * btrfs_get_inode_index_count has an explanation for the magic
5391 BTRFS_I(inode)->index_cnt = 2;
5392 BTRFS_I(inode)->root = root;
5393 BTRFS_I(inode)->generation = trans->transid;
5394 inode->i_generation = BTRFS_I(inode)->generation;
5397 * We could have gotten an inode number from somebody who was fsynced
5398 * and then removed in this same transaction, so let's just set full
5399 * sync since it will be a full sync anyway and this will blow away the
5400 * old info in the log.
5402 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5409 key[0].objectid = objectid;
5410 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5414 * Start new inodes with an inode_ref. This is slightly more
5415 * efficient for small numbers of hard links since they will
5416 * be packed into one item. Extended refs will kick in if we
5417 * add more hard links than can fit in the ref item.
5419 key[1].objectid = objectid;
5420 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5421 key[1].offset = ref_objectid;
5423 sizes[0] = sizeof(struct btrfs_inode_item);
5424 sizes[1] = name_len + sizeof(*ref);
5426 path->leave_spinning = 1;
5427 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
5431 inode_init_owner(inode, dir, mode);
5432 inode_set_bytes(inode, 0);
5433 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5434 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5435 struct btrfs_inode_item);
5436 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5437 sizeof(*inode_item));
5438 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5440 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5441 struct btrfs_inode_ref);
5442 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5443 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5444 ptr = (unsigned long)(ref + 1);
5445 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5447 btrfs_mark_buffer_dirty(path->nodes[0]);
5448 btrfs_free_path(path);
5450 location = &BTRFS_I(inode)->location;
5451 location->objectid = objectid;
5452 location->offset = 0;
5453 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5455 btrfs_inherit_iflags(inode, dir);
5457 if (S_ISREG(mode)) {
5458 if (btrfs_test_opt(root, NODATASUM))
5459 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5460 if (btrfs_test_opt(root, NODATACOW))
5461 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5462 BTRFS_INODE_NODATASUM;
5465 btrfs_insert_inode_hash(inode);
5466 inode_tree_add(inode);
5468 trace_btrfs_inode_new(inode);
5469 btrfs_set_inode_last_trans(trans, inode);
5471 btrfs_update_root_times(trans, root);
5476 BTRFS_I(dir)->index_cnt--;
5477 btrfs_free_path(path);
5479 return ERR_PTR(ret);
5482 static inline u8 btrfs_inode_type(struct inode *inode)
5484 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5488 * utility function to add 'inode' into 'parent_inode' with
5489 * a give name and a given sequence number.
5490 * if 'add_backref' is true, also insert a backref from the
5491 * inode to the parent directory.
5493 int btrfs_add_link(struct btrfs_trans_handle *trans,
5494 struct inode *parent_inode, struct inode *inode,
5495 const char *name, int name_len, int add_backref, u64 index)
5498 struct btrfs_key key;
5499 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5500 u64 ino = btrfs_ino(inode);
5501 u64 parent_ino = btrfs_ino(parent_inode);
5503 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5504 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5507 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5511 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5512 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5513 key.objectid, root->root_key.objectid,
5514 parent_ino, index, name, name_len);
5515 } else if (add_backref) {
5516 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5520 /* Nothing to clean up yet */
5524 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5526 btrfs_inode_type(inode), index);
5527 if (ret == -EEXIST || ret == -EOVERFLOW)
5530 btrfs_abort_transaction(trans, root, ret);
5534 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5536 inode_inc_iversion(parent_inode);
5537 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5538 ret = btrfs_update_inode(trans, root, parent_inode);
5540 btrfs_abort_transaction(trans, root, ret);
5544 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5547 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5548 key.objectid, root->root_key.objectid,
5549 parent_ino, &local_index, name, name_len);
5551 } else if (add_backref) {
5555 err = btrfs_del_inode_ref(trans, root, name, name_len,
5556 ino, parent_ino, &local_index);
5561 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5562 struct inode *dir, struct dentry *dentry,
5563 struct inode *inode, int backref, u64 index)
5565 int err = btrfs_add_link(trans, dir, inode,
5566 dentry->d_name.name, dentry->d_name.len,
5573 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5574 umode_t mode, dev_t rdev)
5576 struct btrfs_trans_handle *trans;
5577 struct btrfs_root *root = BTRFS_I(dir)->root;
5578 struct inode *inode = NULL;
5584 if (!new_valid_dev(rdev))
5588 * 2 for inode item and ref
5590 * 1 for xattr if selinux is on
5592 trans = btrfs_start_transaction(root, 5);
5594 return PTR_ERR(trans);
5596 err = btrfs_find_free_ino(root, &objectid);
5600 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5601 dentry->d_name.len, btrfs_ino(dir), objectid,
5603 if (IS_ERR(inode)) {
5604 err = PTR_ERR(inode);
5608 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5615 * If the active LSM wants to access the inode during
5616 * d_instantiate it needs these. Smack checks to see
5617 * if the filesystem supports xattrs by looking at the
5621 inode->i_op = &btrfs_special_inode_operations;
5622 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5626 init_special_inode(inode, inode->i_mode, rdev);
5627 btrfs_update_inode(trans, root, inode);
5628 d_instantiate(dentry, inode);
5631 btrfs_end_transaction(trans, root);
5632 btrfs_btree_balance_dirty(root);
5634 inode_dec_link_count(inode);
5640 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5641 umode_t mode, bool excl)
5643 struct btrfs_trans_handle *trans;
5644 struct btrfs_root *root = BTRFS_I(dir)->root;
5645 struct inode *inode = NULL;
5646 int drop_inode_on_err = 0;
5652 * 2 for inode item and ref
5654 * 1 for xattr if selinux is on
5656 trans = btrfs_start_transaction(root, 5);
5658 return PTR_ERR(trans);
5660 err = btrfs_find_free_ino(root, &objectid);
5664 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5665 dentry->d_name.len, btrfs_ino(dir), objectid,
5667 if (IS_ERR(inode)) {
5668 err = PTR_ERR(inode);
5671 drop_inode_on_err = 1;
5673 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5677 err = btrfs_update_inode(trans, root, inode);
5682 * If the active LSM wants to access the inode during
5683 * d_instantiate it needs these. Smack checks to see
5684 * if the filesystem supports xattrs by looking at the
5687 inode->i_fop = &btrfs_file_operations;
5688 inode->i_op = &btrfs_file_inode_operations;
5690 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5694 inode->i_mapping->a_ops = &btrfs_aops;
5695 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5696 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5697 d_instantiate(dentry, inode);
5700 btrfs_end_transaction(trans, root);
5701 if (err && drop_inode_on_err) {
5702 inode_dec_link_count(inode);
5705 btrfs_btree_balance_dirty(root);
5709 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5710 struct dentry *dentry)
5712 struct btrfs_trans_handle *trans;
5713 struct btrfs_root *root = BTRFS_I(dir)->root;
5714 struct inode *inode = old_dentry->d_inode;
5719 /* do not allow sys_link's with other subvols of the same device */
5720 if (root->objectid != BTRFS_I(inode)->root->objectid)
5723 if (inode->i_nlink >= BTRFS_LINK_MAX)
5726 err = btrfs_set_inode_index(dir, &index);
5731 * 2 items for inode and inode ref
5732 * 2 items for dir items
5733 * 1 item for parent inode
5735 trans = btrfs_start_transaction(root, 5);
5736 if (IS_ERR(trans)) {
5737 err = PTR_ERR(trans);
5741 btrfs_inc_nlink(inode);
5742 inode_inc_iversion(inode);
5743 inode->i_ctime = CURRENT_TIME;
5745 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5747 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5752 struct dentry *parent = dentry->d_parent;
5753 err = btrfs_update_inode(trans, root, inode);
5756 d_instantiate(dentry, inode);
5757 btrfs_log_new_name(trans, inode, NULL, parent);
5760 btrfs_end_transaction(trans, root);
5763 inode_dec_link_count(inode);
5766 btrfs_btree_balance_dirty(root);
5770 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5772 struct inode *inode = NULL;
5773 struct btrfs_trans_handle *trans;
5774 struct btrfs_root *root = BTRFS_I(dir)->root;
5776 int drop_on_err = 0;
5781 * 2 items for inode and ref
5782 * 2 items for dir items
5783 * 1 for xattr if selinux is on
5785 trans = btrfs_start_transaction(root, 5);
5787 return PTR_ERR(trans);
5789 err = btrfs_find_free_ino(root, &objectid);
5793 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5794 dentry->d_name.len, btrfs_ino(dir), objectid,
5795 S_IFDIR | mode, &index);
5796 if (IS_ERR(inode)) {
5797 err = PTR_ERR(inode);
5803 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5807 inode->i_op = &btrfs_dir_inode_operations;
5808 inode->i_fop = &btrfs_dir_file_operations;
5810 btrfs_i_size_write(inode, 0);
5811 err = btrfs_update_inode(trans, root, inode);
5815 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5816 dentry->d_name.len, 0, index);
5820 d_instantiate(dentry, inode);
5824 btrfs_end_transaction(trans, root);
5827 btrfs_btree_balance_dirty(root);
5831 /* helper for btfs_get_extent. Given an existing extent in the tree,
5832 * and an extent that you want to insert, deal with overlap and insert
5833 * the new extent into the tree.
5835 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5836 struct extent_map *existing,
5837 struct extent_map *em,
5838 u64 map_start, u64 map_len)
5842 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5843 start_diff = map_start - em->start;
5844 em->start = map_start;
5846 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5847 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5848 em->block_start += start_diff;
5849 em->block_len -= start_diff;
5851 return add_extent_mapping(em_tree, em, 0);
5854 static noinline int uncompress_inline(struct btrfs_path *path,
5855 struct inode *inode, struct page *page,
5856 size_t pg_offset, u64 extent_offset,
5857 struct btrfs_file_extent_item *item)
5860 struct extent_buffer *leaf = path->nodes[0];
5863 unsigned long inline_size;
5867 WARN_ON(pg_offset != 0);
5868 compress_type = btrfs_file_extent_compression(leaf, item);
5869 max_size = btrfs_file_extent_ram_bytes(leaf, item);
5870 inline_size = btrfs_file_extent_inline_item_len(leaf,
5871 btrfs_item_nr(path->slots[0]));
5872 tmp = kmalloc(inline_size, GFP_NOFS);
5875 ptr = btrfs_file_extent_inline_start(item);
5877 read_extent_buffer(leaf, tmp, ptr, inline_size);
5879 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
5880 ret = btrfs_decompress(compress_type, tmp, page,
5881 extent_offset, inline_size, max_size);
5883 char *kaddr = kmap_atomic(page);
5884 unsigned long copy_size = min_t(u64,
5885 PAGE_CACHE_SIZE - pg_offset,
5886 max_size - extent_offset);
5887 memset(kaddr + pg_offset, 0, copy_size);
5888 kunmap_atomic(kaddr);
5895 * a bit scary, this does extent mapping from logical file offset to the disk.
5896 * the ugly parts come from merging extents from the disk with the in-ram
5897 * representation. This gets more complex because of the data=ordered code,
5898 * where the in-ram extents might be locked pending data=ordered completion.
5900 * This also copies inline extents directly into the page.
5903 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
5904 size_t pg_offset, u64 start, u64 len,
5910 u64 extent_start = 0;
5912 u64 objectid = btrfs_ino(inode);
5914 struct btrfs_path *path = NULL;
5915 struct btrfs_root *root = BTRFS_I(inode)->root;
5916 struct btrfs_file_extent_item *item;
5917 struct extent_buffer *leaf;
5918 struct btrfs_key found_key;
5919 struct extent_map *em = NULL;
5920 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5921 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5922 struct btrfs_trans_handle *trans = NULL;
5926 read_lock(&em_tree->lock);
5927 em = lookup_extent_mapping(em_tree, start, len);
5929 em->bdev = root->fs_info->fs_devices->latest_bdev;
5930 read_unlock(&em_tree->lock);
5933 if (em->start > start || em->start + em->len <= start)
5934 free_extent_map(em);
5935 else if (em->block_start == EXTENT_MAP_INLINE && page)
5936 free_extent_map(em);
5940 em = alloc_extent_map();
5945 em->bdev = root->fs_info->fs_devices->latest_bdev;
5946 em->start = EXTENT_MAP_HOLE;
5947 em->orig_start = EXTENT_MAP_HOLE;
5949 em->block_len = (u64)-1;
5952 path = btrfs_alloc_path();
5958 * Chances are we'll be called again, so go ahead and do
5964 ret = btrfs_lookup_file_extent(trans, root, path,
5965 objectid, start, trans != NULL);
5972 if (path->slots[0] == 0)
5977 leaf = path->nodes[0];
5978 item = btrfs_item_ptr(leaf, path->slots[0],
5979 struct btrfs_file_extent_item);
5980 /* are we inside the extent that was found? */
5981 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5982 found_type = btrfs_key_type(&found_key);
5983 if (found_key.objectid != objectid ||
5984 found_type != BTRFS_EXTENT_DATA_KEY) {
5986 * If we backup past the first extent we want to move forward
5987 * and see if there is an extent in front of us, otherwise we'll
5988 * say there is a hole for our whole search range which can
5995 found_type = btrfs_file_extent_type(leaf, item);
5996 extent_start = found_key.offset;
5997 compress_type = btrfs_file_extent_compression(leaf, item);
5998 if (found_type == BTRFS_FILE_EXTENT_REG ||
5999 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6000 extent_end = extent_start +
6001 btrfs_file_extent_num_bytes(leaf, item);
6002 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6004 size = btrfs_file_extent_inline_len(leaf, item);
6005 extent_end = ALIGN(extent_start + size, root->sectorsize);
6008 if (start >= extent_end) {
6010 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6011 ret = btrfs_next_leaf(root, path);
6018 leaf = path->nodes[0];
6020 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6021 if (found_key.objectid != objectid ||
6022 found_key.type != BTRFS_EXTENT_DATA_KEY)
6024 if (start + len <= found_key.offset)
6027 em->orig_start = start;
6028 em->len = found_key.offset - start;
6032 em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
6033 if (found_type == BTRFS_FILE_EXTENT_REG ||
6034 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6035 em->start = extent_start;
6036 em->len = extent_end - extent_start;
6037 em->orig_start = extent_start -
6038 btrfs_file_extent_offset(leaf, item);
6039 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6041 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6043 em->block_start = EXTENT_MAP_HOLE;
6046 if (compress_type != BTRFS_COMPRESS_NONE) {
6047 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6048 em->compress_type = compress_type;
6049 em->block_start = bytenr;
6050 em->block_len = em->orig_block_len;
6052 bytenr += btrfs_file_extent_offset(leaf, item);
6053 em->block_start = bytenr;
6054 em->block_len = em->len;
6055 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6056 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6059 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6063 size_t extent_offset;
6066 em->block_start = EXTENT_MAP_INLINE;
6067 if (!page || create) {
6068 em->start = extent_start;
6069 em->len = extent_end - extent_start;
6073 size = btrfs_file_extent_inline_len(leaf, item);
6074 extent_offset = page_offset(page) + pg_offset - extent_start;
6075 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6076 size - extent_offset);
6077 em->start = extent_start + extent_offset;
6078 em->len = ALIGN(copy_size, root->sectorsize);
6079 em->orig_block_len = em->len;
6080 em->orig_start = em->start;
6081 if (compress_type) {
6082 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6083 em->compress_type = compress_type;
6085 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6086 if (create == 0 && !PageUptodate(page)) {
6087 if (btrfs_file_extent_compression(leaf, item) !=
6088 BTRFS_COMPRESS_NONE) {
6089 ret = uncompress_inline(path, inode, page,
6091 extent_offset, item);
6092 BUG_ON(ret); /* -ENOMEM */
6095 read_extent_buffer(leaf, map + pg_offset, ptr,
6097 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6098 memset(map + pg_offset + copy_size, 0,
6099 PAGE_CACHE_SIZE - pg_offset -
6104 flush_dcache_page(page);
6105 } else if (create && PageUptodate(page)) {
6109 free_extent_map(em);
6112 btrfs_release_path(path);
6113 trans = btrfs_join_transaction(root);
6116 return ERR_CAST(trans);
6120 write_extent_buffer(leaf, map + pg_offset, ptr,
6123 btrfs_mark_buffer_dirty(leaf);
6125 set_extent_uptodate(io_tree, em->start,
6126 extent_map_end(em) - 1, NULL, GFP_NOFS);
6129 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6133 em->orig_start = start;
6136 em->block_start = EXTENT_MAP_HOLE;
6137 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6139 btrfs_release_path(path);
6140 if (em->start > start || extent_map_end(em) <= start) {
6141 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6142 em->start, em->len, start, len);
6148 write_lock(&em_tree->lock);
6149 ret = add_extent_mapping(em_tree, em, 0);
6150 /* it is possible that someone inserted the extent into the tree
6151 * while we had the lock dropped. It is also possible that
6152 * an overlapping map exists in the tree
6154 if (ret == -EEXIST) {
6155 struct extent_map *existing;
6159 existing = lookup_extent_mapping(em_tree, start, len);
6160 if (existing && (existing->start > start ||
6161 existing->start + existing->len <= start)) {
6162 free_extent_map(existing);
6166 existing = lookup_extent_mapping(em_tree, em->start,
6169 err = merge_extent_mapping(em_tree, existing,
6172 free_extent_map(existing);
6174 free_extent_map(em);
6179 free_extent_map(em);
6183 free_extent_map(em);
6188 write_unlock(&em_tree->lock);
6192 trace_btrfs_get_extent(root, em);
6195 btrfs_free_path(path);
6197 ret = btrfs_end_transaction(trans, root);
6202 free_extent_map(em);
6203 return ERR_PTR(err);
6205 BUG_ON(!em); /* Error is always set */
6209 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6210 size_t pg_offset, u64 start, u64 len,
6213 struct extent_map *em;
6214 struct extent_map *hole_em = NULL;
6215 u64 range_start = start;
6221 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6228 * - a pre-alloc extent,
6229 * there might actually be delalloc bytes behind it.
6231 if (em->block_start != EXTENT_MAP_HOLE &&
6232 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6238 /* check to see if we've wrapped (len == -1 or similar) */
6247 /* ok, we didn't find anything, lets look for delalloc */
6248 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6249 end, len, EXTENT_DELALLOC, 1);
6250 found_end = range_start + found;
6251 if (found_end < range_start)
6252 found_end = (u64)-1;
6255 * we didn't find anything useful, return
6256 * the original results from get_extent()
6258 if (range_start > end || found_end <= start) {
6264 /* adjust the range_start to make sure it doesn't
6265 * go backwards from the start they passed in
6267 range_start = max(start,range_start);
6268 found = found_end - range_start;
6271 u64 hole_start = start;
6274 em = alloc_extent_map();
6280 * when btrfs_get_extent can't find anything it
6281 * returns one huge hole
6283 * make sure what it found really fits our range, and
6284 * adjust to make sure it is based on the start from
6288 u64 calc_end = extent_map_end(hole_em);
6290 if (calc_end <= start || (hole_em->start > end)) {
6291 free_extent_map(hole_em);
6294 hole_start = max(hole_em->start, start);
6295 hole_len = calc_end - hole_start;
6299 if (hole_em && range_start > hole_start) {
6300 /* our hole starts before our delalloc, so we
6301 * have to return just the parts of the hole
6302 * that go until the delalloc starts
6304 em->len = min(hole_len,
6305 range_start - hole_start);
6306 em->start = hole_start;
6307 em->orig_start = hole_start;
6309 * don't adjust block start at all,
6310 * it is fixed at EXTENT_MAP_HOLE
6312 em->block_start = hole_em->block_start;
6313 em->block_len = hole_len;
6314 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6315 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6317 em->start = range_start;
6319 em->orig_start = range_start;
6320 em->block_start = EXTENT_MAP_DELALLOC;
6321 em->block_len = found;
6323 } else if (hole_em) {
6328 free_extent_map(hole_em);
6330 free_extent_map(em);
6331 return ERR_PTR(err);
6336 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6339 struct btrfs_root *root = BTRFS_I(inode)->root;
6340 struct extent_map *em;
6341 struct btrfs_key ins;
6345 alloc_hint = get_extent_allocation_hint(inode, start, len);
6346 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
6347 alloc_hint, &ins, 1);
6349 return ERR_PTR(ret);
6351 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6352 ins.offset, ins.offset, ins.offset, 0);
6354 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6358 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6359 ins.offset, ins.offset, 0);
6361 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6362 free_extent_map(em);
6363 return ERR_PTR(ret);
6370 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6371 * block must be cow'd
6373 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6374 u64 *orig_start, u64 *orig_block_len,
6377 struct btrfs_trans_handle *trans;
6378 struct btrfs_path *path;
6380 struct extent_buffer *leaf;
6381 struct btrfs_root *root = BTRFS_I(inode)->root;
6382 struct btrfs_file_extent_item *fi;
6383 struct btrfs_key key;
6390 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6391 path = btrfs_alloc_path();
6395 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
6400 slot = path->slots[0];
6403 /* can't find the item, must cow */
6410 leaf = path->nodes[0];
6411 btrfs_item_key_to_cpu(leaf, &key, slot);
6412 if (key.objectid != btrfs_ino(inode) ||
6413 key.type != BTRFS_EXTENT_DATA_KEY) {
6414 /* not our file or wrong item type, must cow */
6418 if (key.offset > offset) {
6419 /* Wrong offset, must cow */
6423 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6424 found_type = btrfs_file_extent_type(leaf, fi);
6425 if (found_type != BTRFS_FILE_EXTENT_REG &&
6426 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6427 /* not a regular extent, must cow */
6431 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6434 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6435 if (disk_bytenr == 0)
6438 if (btrfs_file_extent_compression(leaf, fi) ||
6439 btrfs_file_extent_encryption(leaf, fi) ||
6440 btrfs_file_extent_other_encoding(leaf, fi))
6443 backref_offset = btrfs_file_extent_offset(leaf, fi);
6446 *orig_start = key.offset - backref_offset;
6447 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6448 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6451 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6453 if (btrfs_extent_readonly(root, disk_bytenr))
6455 btrfs_release_path(path);
6458 * look for other files referencing this extent, if we
6459 * find any we must cow
6461 trans = btrfs_join_transaction(root);
6462 if (IS_ERR(trans)) {
6467 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6468 key.offset - backref_offset, disk_bytenr);
6469 btrfs_end_transaction(trans, root);
6476 * adjust disk_bytenr and num_bytes to cover just the bytes
6477 * in this extent we are about to write. If there
6478 * are any csums in that range we have to cow in order
6479 * to keep the csums correct
6481 disk_bytenr += backref_offset;
6482 disk_bytenr += offset - key.offset;
6483 num_bytes = min(offset + *len, extent_end) - offset;
6484 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6487 * all of the above have passed, it is safe to overwrite this extent
6493 btrfs_free_path(path);
6497 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6498 struct extent_state **cached_state, int writing)
6500 struct btrfs_ordered_extent *ordered;
6504 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6507 * We're concerned with the entire range that we're going to be
6508 * doing DIO to, so we need to make sure theres no ordered
6509 * extents in this range.
6511 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6512 lockend - lockstart + 1);
6515 * We need to make sure there are no buffered pages in this
6516 * range either, we could have raced between the invalidate in
6517 * generic_file_direct_write and locking the extent. The
6518 * invalidate needs to happen so that reads after a write do not
6521 if (!ordered && (!writing ||
6522 !test_range_bit(&BTRFS_I(inode)->io_tree,
6523 lockstart, lockend, EXTENT_UPTODATE, 0,
6527 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6528 cached_state, GFP_NOFS);
6531 btrfs_start_ordered_extent(inode, ordered, 1);
6532 btrfs_put_ordered_extent(ordered);
6534 /* Screw you mmap */
6535 ret = filemap_write_and_wait_range(inode->i_mapping,
6542 * If we found a page that couldn't be invalidated just
6543 * fall back to buffered.
6545 ret = invalidate_inode_pages2_range(inode->i_mapping,
6546 lockstart >> PAGE_CACHE_SHIFT,
6547 lockend >> PAGE_CACHE_SHIFT);
6558 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6559 u64 len, u64 orig_start,
6560 u64 block_start, u64 block_len,
6561 u64 orig_block_len, u64 ram_bytes,
6564 struct extent_map_tree *em_tree;
6565 struct extent_map *em;
6566 struct btrfs_root *root = BTRFS_I(inode)->root;
6569 em_tree = &BTRFS_I(inode)->extent_tree;
6570 em = alloc_extent_map();
6572 return ERR_PTR(-ENOMEM);
6575 em->orig_start = orig_start;
6576 em->mod_start = start;
6579 em->block_len = block_len;
6580 em->block_start = block_start;
6581 em->bdev = root->fs_info->fs_devices->latest_bdev;
6582 em->orig_block_len = orig_block_len;
6583 em->ram_bytes = ram_bytes;
6584 em->generation = -1;
6585 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6586 if (type == BTRFS_ORDERED_PREALLOC)
6587 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6590 btrfs_drop_extent_cache(inode, em->start,
6591 em->start + em->len - 1, 0);
6592 write_lock(&em_tree->lock);
6593 ret = add_extent_mapping(em_tree, em, 1);
6594 write_unlock(&em_tree->lock);
6595 } while (ret == -EEXIST);
6598 free_extent_map(em);
6599 return ERR_PTR(ret);
6606 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6607 struct buffer_head *bh_result, int create)
6609 struct extent_map *em;
6610 struct btrfs_root *root = BTRFS_I(inode)->root;
6611 struct extent_state *cached_state = NULL;
6612 u64 start = iblock << inode->i_blkbits;
6613 u64 lockstart, lockend;
6614 u64 len = bh_result->b_size;
6615 int unlock_bits = EXTENT_LOCKED;
6619 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6621 len = min_t(u64, len, root->sectorsize);
6624 lockend = start + len - 1;
6627 * If this errors out it's because we couldn't invalidate pagecache for
6628 * this range and we need to fallback to buffered.
6630 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6633 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6640 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6641 * io. INLINE is special, and we could probably kludge it in here, but
6642 * it's still buffered so for safety lets just fall back to the generic
6645 * For COMPRESSED we _have_ to read the entire extent in so we can
6646 * decompress it, so there will be buffering required no matter what we
6647 * do, so go ahead and fallback to buffered.
6649 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6650 * to buffered IO. Don't blame me, this is the price we pay for using
6653 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6654 em->block_start == EXTENT_MAP_INLINE) {
6655 free_extent_map(em);
6660 /* Just a good old fashioned hole, return */
6661 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6662 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6663 free_extent_map(em);
6668 * We don't allocate a new extent in the following cases
6670 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6672 * 2) The extent is marked as PREALLOC. We're good to go here and can
6673 * just use the extent.
6677 len = min(len, em->len - (start - em->start));
6678 lockstart = start + len;
6682 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6683 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6684 em->block_start != EXTENT_MAP_HOLE)) {
6687 u64 block_start, orig_start, orig_block_len, ram_bytes;
6689 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6690 type = BTRFS_ORDERED_PREALLOC;
6692 type = BTRFS_ORDERED_NOCOW;
6693 len = min(len, em->len - (start - em->start));
6694 block_start = em->block_start + (start - em->start);
6696 if (can_nocow_extent(inode, start, &len, &orig_start,
6697 &orig_block_len, &ram_bytes) == 1) {
6698 if (type == BTRFS_ORDERED_PREALLOC) {
6699 free_extent_map(em);
6700 em = create_pinned_em(inode, start, len,
6709 ret = btrfs_add_ordered_extent_dio(inode, start,
6710 block_start, len, len, type);
6712 free_extent_map(em);
6720 * this will cow the extent, reset the len in case we changed
6723 len = bh_result->b_size;
6724 free_extent_map(em);
6725 em = btrfs_new_extent_direct(inode, start, len);
6730 len = min(len, em->len - (start - em->start));
6732 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6734 bh_result->b_size = len;
6735 bh_result->b_bdev = em->bdev;
6736 set_buffer_mapped(bh_result);
6738 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6739 set_buffer_new(bh_result);
6742 * Need to update the i_size under the extent lock so buffered
6743 * readers will get the updated i_size when we unlock.
6745 if (start + len > i_size_read(inode))
6746 i_size_write(inode, start + len);
6748 spin_lock(&BTRFS_I(inode)->lock);
6749 BTRFS_I(inode)->outstanding_extents++;
6750 spin_unlock(&BTRFS_I(inode)->lock);
6752 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6753 lockstart + len - 1, EXTENT_DELALLOC, NULL,
6754 &cached_state, GFP_NOFS);
6759 * In the case of write we need to clear and unlock the entire range,
6760 * in the case of read we need to unlock only the end area that we
6761 * aren't using if there is any left over space.
6763 if (lockstart < lockend) {
6764 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6765 lockend, unlock_bits, 1, 0,
6766 &cached_state, GFP_NOFS);
6768 free_extent_state(cached_state);
6771 free_extent_map(em);
6776 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6777 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6781 static void btrfs_endio_direct_read(struct bio *bio, int err)
6783 struct btrfs_dio_private *dip = bio->bi_private;
6784 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6785 struct bio_vec *bvec = bio->bi_io_vec;
6786 struct inode *inode = dip->inode;
6787 struct btrfs_root *root = BTRFS_I(inode)->root;
6788 struct bio *dio_bio;
6789 u32 *csums = (u32 *)dip->csum;
6793 start = dip->logical_offset;
6795 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6796 struct page *page = bvec->bv_page;
6799 unsigned long flags;
6801 local_irq_save(flags);
6802 kaddr = kmap_atomic(page);
6803 csum = btrfs_csum_data(kaddr + bvec->bv_offset,
6804 csum, bvec->bv_len);
6805 btrfs_csum_final(csum, (char *)&csum);
6806 kunmap_atomic(kaddr);
6807 local_irq_restore(flags);
6809 flush_dcache_page(bvec->bv_page);
6810 if (csum != csums[index]) {
6811 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
6812 btrfs_ino(inode), start, csum,
6818 start += bvec->bv_len;
6821 } while (bvec <= bvec_end);
6823 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6824 dip->logical_offset + dip->bytes - 1);
6825 dio_bio = dip->dio_bio;
6829 /* If we had a csum failure make sure to clear the uptodate flag */
6831 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
6832 dio_end_io(dio_bio, err);
6836 static void btrfs_endio_direct_write(struct bio *bio, int err)
6838 struct btrfs_dio_private *dip = bio->bi_private;
6839 struct inode *inode = dip->inode;
6840 struct btrfs_root *root = BTRFS_I(inode)->root;
6841 struct btrfs_ordered_extent *ordered = NULL;
6842 u64 ordered_offset = dip->logical_offset;
6843 u64 ordered_bytes = dip->bytes;
6844 struct bio *dio_bio;
6850 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
6852 ordered_bytes, !err);
6856 ordered->work.func = finish_ordered_fn;
6857 ordered->work.flags = 0;
6858 btrfs_queue_worker(&root->fs_info->endio_write_workers,
6862 * our bio might span multiple ordered extents. If we haven't
6863 * completed the accounting for the whole dio, go back and try again
6865 if (ordered_offset < dip->logical_offset + dip->bytes) {
6866 ordered_bytes = dip->logical_offset + dip->bytes -
6872 dio_bio = dip->dio_bio;
6876 /* If we had an error make sure to clear the uptodate flag */
6878 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
6879 dio_end_io(dio_bio, err);
6883 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
6884 struct bio *bio, int mirror_num,
6885 unsigned long bio_flags, u64 offset)
6888 struct btrfs_root *root = BTRFS_I(inode)->root;
6889 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
6890 BUG_ON(ret); /* -ENOMEM */
6894 static void btrfs_end_dio_bio(struct bio *bio, int err)
6896 struct btrfs_dio_private *dip = bio->bi_private;
6899 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
6900 "sector %#Lx len %u err no %d\n",
6901 btrfs_ino(dip->inode), bio->bi_rw,
6902 (unsigned long long)bio->bi_sector, bio->bi_size, err);
6906 * before atomic variable goto zero, we must make sure
6907 * dip->errors is perceived to be set.
6909 smp_mb__before_atomic_dec();
6912 /* if there are more bios still pending for this dio, just exit */
6913 if (!atomic_dec_and_test(&dip->pending_bios))
6917 bio_io_error(dip->orig_bio);
6919 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
6920 bio_endio(dip->orig_bio, 0);
6926 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
6927 u64 first_sector, gfp_t gfp_flags)
6929 int nr_vecs = bio_get_nr_vecs(bdev);
6930 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
6933 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
6934 int rw, u64 file_offset, int skip_sum,
6937 struct btrfs_dio_private *dip = bio->bi_private;
6938 int write = rw & REQ_WRITE;
6939 struct btrfs_root *root = BTRFS_I(inode)->root;
6943 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
6948 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
6956 if (write && async_submit) {
6957 ret = btrfs_wq_submit_bio(root->fs_info,
6958 inode, rw, bio, 0, 0,
6960 __btrfs_submit_bio_start_direct_io,
6961 __btrfs_submit_bio_done);
6965 * If we aren't doing async submit, calculate the csum of the
6968 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
6971 } else if (!skip_sum) {
6972 ret = btrfs_lookup_bio_sums_dio(root, inode, dip, bio,
6979 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
6985 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
6988 struct inode *inode = dip->inode;
6989 struct btrfs_root *root = BTRFS_I(inode)->root;
6991 struct bio *orig_bio = dip->orig_bio;
6992 struct bio_vec *bvec = orig_bio->bi_io_vec;
6993 u64 start_sector = orig_bio->bi_sector;
6994 u64 file_offset = dip->logical_offset;
6999 int async_submit = 0;
7001 map_length = orig_bio->bi_size;
7002 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7003 &map_length, NULL, 0);
7009 if (map_length >= orig_bio->bi_size) {
7014 /* async crcs make it difficult to collect full stripe writes. */
7015 if (btrfs_get_alloc_profile(root, 1) &
7016 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7021 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7024 bio->bi_private = dip;
7025 bio->bi_end_io = btrfs_end_dio_bio;
7026 atomic_inc(&dip->pending_bios);
7028 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7029 if (unlikely(map_length < submit_len + bvec->bv_len ||
7030 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7031 bvec->bv_offset) < bvec->bv_len)) {
7033 * inc the count before we submit the bio so
7034 * we know the end IO handler won't happen before
7035 * we inc the count. Otherwise, the dip might get freed
7036 * before we're done setting it up
7038 atomic_inc(&dip->pending_bios);
7039 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7040 file_offset, skip_sum,
7044 atomic_dec(&dip->pending_bios);
7048 start_sector += submit_len >> 9;
7049 file_offset += submit_len;
7054 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7055 start_sector, GFP_NOFS);
7058 bio->bi_private = dip;
7059 bio->bi_end_io = btrfs_end_dio_bio;
7061 map_length = orig_bio->bi_size;
7062 ret = btrfs_map_block(root->fs_info, rw,
7064 &map_length, NULL, 0);
7070 submit_len += bvec->bv_len;
7077 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7086 * before atomic variable goto zero, we must
7087 * make sure dip->errors is perceived to be set.
7089 smp_mb__before_atomic_dec();
7090 if (atomic_dec_and_test(&dip->pending_bios))
7091 bio_io_error(dip->orig_bio);
7093 /* bio_end_io() will handle error, so we needn't return it */
7097 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7098 struct inode *inode, loff_t file_offset)
7100 struct btrfs_root *root = BTRFS_I(inode)->root;
7101 struct btrfs_dio_private *dip;
7105 int write = rw & REQ_WRITE;
7109 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7111 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7117 if (!skip_sum && !write) {
7118 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
7119 sum_len = dio_bio->bi_size >> inode->i_sb->s_blocksize_bits;
7120 sum_len *= csum_size;
7125 dip = kmalloc(sizeof(*dip) + sum_len, GFP_NOFS);
7131 dip->private = dio_bio->bi_private;
7133 dip->logical_offset = file_offset;
7134 dip->bytes = dio_bio->bi_size;
7135 dip->disk_bytenr = (u64)dio_bio->bi_sector << 9;
7136 io_bio->bi_private = dip;
7138 dip->orig_bio = io_bio;
7139 dip->dio_bio = dio_bio;
7140 atomic_set(&dip->pending_bios, 0);
7143 io_bio->bi_end_io = btrfs_endio_direct_write;
7145 io_bio->bi_end_io = btrfs_endio_direct_read;
7147 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7156 * If this is a write, we need to clean up the reserved space and kill
7157 * the ordered extent.
7160 struct btrfs_ordered_extent *ordered;
7161 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7162 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7163 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7164 btrfs_free_reserved_extent(root, ordered->start,
7166 btrfs_put_ordered_extent(ordered);
7167 btrfs_put_ordered_extent(ordered);
7169 bio_endio(dio_bio, ret);
7172 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7173 const struct iovec *iov, loff_t offset,
7174 unsigned long nr_segs)
7180 unsigned blocksize_mask = root->sectorsize - 1;
7181 ssize_t retval = -EINVAL;
7182 loff_t end = offset;
7184 if (offset & blocksize_mask)
7187 /* Check the memory alignment. Blocks cannot straddle pages */
7188 for (seg = 0; seg < nr_segs; seg++) {
7189 addr = (unsigned long)iov[seg].iov_base;
7190 size = iov[seg].iov_len;
7192 if ((addr & blocksize_mask) || (size & blocksize_mask))
7195 /* If this is a write we don't need to check anymore */
7200 * Check to make sure we don't have duplicate iov_base's in this
7201 * iovec, if so return EINVAL, otherwise we'll get csum errors
7202 * when reading back.
7204 for (i = seg + 1; i < nr_segs; i++) {
7205 if (iov[seg].iov_base == iov[i].iov_base)
7214 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7215 const struct iovec *iov, loff_t offset,
7216 unsigned long nr_segs)
7218 struct file *file = iocb->ki_filp;
7219 struct inode *inode = file->f_mapping->host;
7223 bool relock = false;
7226 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7230 atomic_inc(&inode->i_dio_count);
7231 smp_mb__after_atomic_inc();
7234 * The generic stuff only does filemap_write_and_wait_range, which isn't
7235 * enough if we've written compressed pages to this area, so we need to
7236 * call btrfs_wait_ordered_range to make absolutely sure that any
7237 * outstanding dirty pages are on disk.
7239 count = iov_length(iov, nr_segs);
7240 btrfs_wait_ordered_range(inode, offset, count);
7244 * If the write DIO is beyond the EOF, we need update
7245 * the isize, but it is protected by i_mutex. So we can
7246 * not unlock the i_mutex at this case.
7248 if (offset + count <= inode->i_size) {
7249 mutex_unlock(&inode->i_mutex);
7252 ret = btrfs_delalloc_reserve_space(inode, count);
7255 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7256 &BTRFS_I(inode)->runtime_flags))) {
7257 inode_dio_done(inode);
7258 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7262 ret = __blockdev_direct_IO(rw, iocb, inode,
7263 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7264 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7265 btrfs_submit_direct, flags);
7267 if (ret < 0 && ret != -EIOCBQUEUED)
7268 btrfs_delalloc_release_space(inode, count);
7269 else if (ret >= 0 && (size_t)ret < count)
7270 btrfs_delalloc_release_space(inode,
7271 count - (size_t)ret);
7273 btrfs_delalloc_release_metadata(inode, 0);
7277 inode_dio_done(inode);
7279 mutex_lock(&inode->i_mutex);
7284 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7286 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7287 __u64 start, __u64 len)
7291 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7295 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7298 int btrfs_readpage(struct file *file, struct page *page)
7300 struct extent_io_tree *tree;
7301 tree = &BTRFS_I(page->mapping->host)->io_tree;
7302 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7305 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7307 struct extent_io_tree *tree;
7310 if (current->flags & PF_MEMALLOC) {
7311 redirty_page_for_writepage(wbc, page);
7315 tree = &BTRFS_I(page->mapping->host)->io_tree;
7316 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7319 static int btrfs_writepages(struct address_space *mapping,
7320 struct writeback_control *wbc)
7322 struct extent_io_tree *tree;
7324 tree = &BTRFS_I(mapping->host)->io_tree;
7325 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7329 btrfs_readpages(struct file *file, struct address_space *mapping,
7330 struct list_head *pages, unsigned nr_pages)
7332 struct extent_io_tree *tree;
7333 tree = &BTRFS_I(mapping->host)->io_tree;
7334 return extent_readpages(tree, mapping, pages, nr_pages,
7337 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7339 struct extent_io_tree *tree;
7340 struct extent_map_tree *map;
7343 tree = &BTRFS_I(page->mapping->host)->io_tree;
7344 map = &BTRFS_I(page->mapping->host)->extent_tree;
7345 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7347 ClearPagePrivate(page);
7348 set_page_private(page, 0);
7349 page_cache_release(page);
7354 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7356 if (PageWriteback(page) || PageDirty(page))
7358 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7361 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
7362 unsigned int length)
7364 struct inode *inode = page->mapping->host;
7365 struct extent_io_tree *tree;
7366 struct btrfs_ordered_extent *ordered;
7367 struct extent_state *cached_state = NULL;
7368 u64 page_start = page_offset(page);
7369 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7372 * we have the page locked, so new writeback can't start,
7373 * and the dirty bit won't be cleared while we are here.
7375 * Wait for IO on this page so that we can safely clear
7376 * the PagePrivate2 bit and do ordered accounting
7378 wait_on_page_writeback(page);
7380 tree = &BTRFS_I(inode)->io_tree;
7382 btrfs_releasepage(page, GFP_NOFS);
7385 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7386 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
7389 * IO on this page will never be started, so we need
7390 * to account for any ordered extents now
7392 clear_extent_bit(tree, page_start, page_end,
7393 EXTENT_DIRTY | EXTENT_DELALLOC |
7394 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7395 EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS);
7397 * whoever cleared the private bit is responsible
7398 * for the finish_ordered_io
7400 if (TestClearPagePrivate2(page)) {
7401 struct btrfs_ordered_inode_tree *tree;
7404 tree = &BTRFS_I(inode)->ordered_tree;
7406 spin_lock_irq(&tree->lock);
7407 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
7408 new_len = page_start - ordered->file_offset;
7409 if (new_len < ordered->truncated_len)
7410 ordered->truncated_len = new_len;
7411 spin_unlock_irq(&tree->lock);
7413 if (btrfs_dec_test_ordered_pending(inode, &ordered,
7415 PAGE_CACHE_SIZE, 1))
7416 btrfs_finish_ordered_io(ordered);
7418 btrfs_put_ordered_extent(ordered);
7419 cached_state = NULL;
7420 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7422 clear_extent_bit(tree, page_start, page_end,
7423 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
7424 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
7425 &cached_state, GFP_NOFS);
7426 __btrfs_releasepage(page, GFP_NOFS);
7428 ClearPageChecked(page);
7429 if (PagePrivate(page)) {
7430 ClearPagePrivate(page);
7431 set_page_private(page, 0);
7432 page_cache_release(page);
7437 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7438 * called from a page fault handler when a page is first dirtied. Hence we must
7439 * be careful to check for EOF conditions here. We set the page up correctly
7440 * for a written page which means we get ENOSPC checking when writing into
7441 * holes and correct delalloc and unwritten extent mapping on filesystems that
7442 * support these features.
7444 * We are not allowed to take the i_mutex here so we have to play games to
7445 * protect against truncate races as the page could now be beyond EOF. Because
7446 * vmtruncate() writes the inode size before removing pages, once we have the
7447 * page lock we can determine safely if the page is beyond EOF. If it is not
7448 * beyond EOF, then the page is guaranteed safe against truncation until we
7451 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7453 struct page *page = vmf->page;
7454 struct inode *inode = file_inode(vma->vm_file);
7455 struct btrfs_root *root = BTRFS_I(inode)->root;
7456 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7457 struct btrfs_ordered_extent *ordered;
7458 struct extent_state *cached_state = NULL;
7460 unsigned long zero_start;
7467 sb_start_pagefault(inode->i_sb);
7468 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7470 ret = file_update_time(vma->vm_file);
7476 else /* -ENOSPC, -EIO, etc */
7477 ret = VM_FAULT_SIGBUS;
7483 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7486 size = i_size_read(inode);
7487 page_start = page_offset(page);
7488 page_end = page_start + PAGE_CACHE_SIZE - 1;
7490 if ((page->mapping != inode->i_mapping) ||
7491 (page_start >= size)) {
7492 /* page got truncated out from underneath us */
7495 wait_on_page_writeback(page);
7497 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7498 set_page_extent_mapped(page);
7501 * we can't set the delalloc bits if there are pending ordered
7502 * extents. Drop our locks and wait for them to finish
7504 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7506 unlock_extent_cached(io_tree, page_start, page_end,
7507 &cached_state, GFP_NOFS);
7509 btrfs_start_ordered_extent(inode, ordered, 1);
7510 btrfs_put_ordered_extent(ordered);
7515 * XXX - page_mkwrite gets called every time the page is dirtied, even
7516 * if it was already dirty, so for space accounting reasons we need to
7517 * clear any delalloc bits for the range we are fixing to save. There
7518 * is probably a better way to do this, but for now keep consistent with
7519 * prepare_pages in the normal write path.
7521 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7522 EXTENT_DIRTY | EXTENT_DELALLOC |
7523 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7524 0, 0, &cached_state, GFP_NOFS);
7526 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7529 unlock_extent_cached(io_tree, page_start, page_end,
7530 &cached_state, GFP_NOFS);
7531 ret = VM_FAULT_SIGBUS;
7536 /* page is wholly or partially inside EOF */
7537 if (page_start + PAGE_CACHE_SIZE > size)
7538 zero_start = size & ~PAGE_CACHE_MASK;
7540 zero_start = PAGE_CACHE_SIZE;
7542 if (zero_start != PAGE_CACHE_SIZE) {
7544 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7545 flush_dcache_page(page);
7548 ClearPageChecked(page);
7549 set_page_dirty(page);
7550 SetPageUptodate(page);
7552 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7553 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7554 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7556 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7560 sb_end_pagefault(inode->i_sb);
7561 return VM_FAULT_LOCKED;
7565 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7567 sb_end_pagefault(inode->i_sb);
7571 static int btrfs_truncate(struct inode *inode)
7573 struct btrfs_root *root = BTRFS_I(inode)->root;
7574 struct btrfs_block_rsv *rsv;
7577 struct btrfs_trans_handle *trans;
7578 u64 mask = root->sectorsize - 1;
7579 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7581 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
7584 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7585 * 3 things going on here
7587 * 1) We need to reserve space for our orphan item and the space to
7588 * delete our orphan item. Lord knows we don't want to have a dangling
7589 * orphan item because we didn't reserve space to remove it.
7591 * 2) We need to reserve space to update our inode.
7593 * 3) We need to have something to cache all the space that is going to
7594 * be free'd up by the truncate operation, but also have some slack
7595 * space reserved in case it uses space during the truncate (thank you
7596 * very much snapshotting).
7598 * And we need these to all be seperate. The fact is we can use alot of
7599 * space doing the truncate, and we have no earthly idea how much space
7600 * we will use, so we need the truncate reservation to be seperate so it
7601 * doesn't end up using space reserved for updating the inode or
7602 * removing the orphan item. We also need to be able to stop the
7603 * transaction and start a new one, which means we need to be able to
7604 * update the inode several times, and we have no idea of knowing how
7605 * many times that will be, so we can't just reserve 1 item for the
7606 * entirety of the opration, so that has to be done seperately as well.
7607 * Then there is the orphan item, which does indeed need to be held on
7608 * to for the whole operation, and we need nobody to touch this reserved
7609 * space except the orphan code.
7611 * So that leaves us with
7613 * 1) root->orphan_block_rsv - for the orphan deletion.
7614 * 2) rsv - for the truncate reservation, which we will steal from the
7615 * transaction reservation.
7616 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7617 * updating the inode.
7619 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7622 rsv->size = min_size;
7626 * 1 for the truncate slack space
7627 * 1 for updating the inode.
7629 trans = btrfs_start_transaction(root, 2);
7630 if (IS_ERR(trans)) {
7631 err = PTR_ERR(trans);
7635 /* Migrate the slack space for the truncate to our reserve */
7636 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7641 * setattr is responsible for setting the ordered_data_close flag,
7642 * but that is only tested during the last file release. That
7643 * could happen well after the next commit, leaving a great big
7644 * window where new writes may get lost if someone chooses to write
7645 * to this file after truncating to zero
7647 * The inode doesn't have any dirty data here, and so if we commit
7648 * this is a noop. If someone immediately starts writing to the inode
7649 * it is very likely we'll catch some of their writes in this
7650 * transaction, and the commit will find this file on the ordered
7651 * data list with good things to send down.
7653 * This is a best effort solution, there is still a window where
7654 * using truncate to replace the contents of the file will
7655 * end up with a zero length file after a crash.
7657 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7658 &BTRFS_I(inode)->runtime_flags))
7659 btrfs_add_ordered_operation(trans, root, inode);
7662 * So if we truncate and then write and fsync we normally would just
7663 * write the extents that changed, which is a problem if we need to
7664 * first truncate that entire inode. So set this flag so we write out
7665 * all of the extents in the inode to the sync log so we're completely
7668 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7669 trans->block_rsv = rsv;
7672 ret = btrfs_truncate_inode_items(trans, root, inode,
7674 BTRFS_EXTENT_DATA_KEY);
7675 if (ret != -ENOSPC) {
7680 trans->block_rsv = &root->fs_info->trans_block_rsv;
7681 ret = btrfs_update_inode(trans, root, inode);
7687 btrfs_end_transaction(trans, root);
7688 btrfs_btree_balance_dirty(root);
7690 trans = btrfs_start_transaction(root, 2);
7691 if (IS_ERR(trans)) {
7692 ret = err = PTR_ERR(trans);
7697 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7699 BUG_ON(ret); /* shouldn't happen */
7700 trans->block_rsv = rsv;
7703 if (ret == 0 && inode->i_nlink > 0) {
7704 trans->block_rsv = root->orphan_block_rsv;
7705 ret = btrfs_orphan_del(trans, inode);
7711 trans->block_rsv = &root->fs_info->trans_block_rsv;
7712 ret = btrfs_update_inode(trans, root, inode);
7716 ret = btrfs_end_transaction(trans, root);
7717 btrfs_btree_balance_dirty(root);
7721 btrfs_free_block_rsv(root, rsv);
7730 * create a new subvolume directory/inode (helper for the ioctl).
7732 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7733 struct btrfs_root *new_root, u64 new_dirid)
7735 struct inode *inode;
7739 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7740 new_dirid, new_dirid,
7741 S_IFDIR | (~current_umask() & S_IRWXUGO),
7744 return PTR_ERR(inode);
7745 inode->i_op = &btrfs_dir_inode_operations;
7746 inode->i_fop = &btrfs_dir_file_operations;
7748 set_nlink(inode, 1);
7749 btrfs_i_size_write(inode, 0);
7751 err = btrfs_update_inode(trans, new_root, inode);
7757 struct inode *btrfs_alloc_inode(struct super_block *sb)
7759 struct btrfs_inode *ei;
7760 struct inode *inode;
7762 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7769 ei->last_sub_trans = 0;
7770 ei->logged_trans = 0;
7771 ei->delalloc_bytes = 0;
7772 ei->disk_i_size = 0;
7775 ei->index_cnt = (u64)-1;
7776 ei->last_unlink_trans = 0;
7777 ei->last_log_commit = 0;
7779 spin_lock_init(&ei->lock);
7780 ei->outstanding_extents = 0;
7781 ei->reserved_extents = 0;
7783 ei->runtime_flags = 0;
7784 ei->force_compress = BTRFS_COMPRESS_NONE;
7786 ei->delayed_node = NULL;
7788 inode = &ei->vfs_inode;
7789 extent_map_tree_init(&ei->extent_tree);
7790 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7791 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7792 ei->io_tree.track_uptodate = 1;
7793 ei->io_failure_tree.track_uptodate = 1;
7794 atomic_set(&ei->sync_writers, 0);
7795 mutex_init(&ei->log_mutex);
7796 mutex_init(&ei->delalloc_mutex);
7797 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7798 INIT_LIST_HEAD(&ei->delalloc_inodes);
7799 INIT_LIST_HEAD(&ei->ordered_operations);
7800 RB_CLEAR_NODE(&ei->rb_node);
7805 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
7806 void btrfs_test_destroy_inode(struct inode *inode)
7808 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7809 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7813 static void btrfs_i_callback(struct rcu_head *head)
7815 struct inode *inode = container_of(head, struct inode, i_rcu);
7816 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7819 void btrfs_destroy_inode(struct inode *inode)
7821 struct btrfs_ordered_extent *ordered;
7822 struct btrfs_root *root = BTRFS_I(inode)->root;
7824 WARN_ON(!hlist_empty(&inode->i_dentry));
7825 WARN_ON(inode->i_data.nrpages);
7826 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7827 WARN_ON(BTRFS_I(inode)->reserved_extents);
7828 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7829 WARN_ON(BTRFS_I(inode)->csum_bytes);
7832 * This can happen where we create an inode, but somebody else also
7833 * created the same inode and we need to destroy the one we already
7840 * Make sure we're properly removed from the ordered operation
7844 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7845 spin_lock(&root->fs_info->ordered_root_lock);
7846 list_del_init(&BTRFS_I(inode)->ordered_operations);
7847 spin_unlock(&root->fs_info->ordered_root_lock);
7850 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7851 &BTRFS_I(inode)->runtime_flags)) {
7852 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
7854 atomic_dec(&root->orphan_inodes);
7858 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7862 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
7863 ordered->file_offset, ordered->len);
7864 btrfs_remove_ordered_extent(inode, ordered);
7865 btrfs_put_ordered_extent(ordered);
7866 btrfs_put_ordered_extent(ordered);
7869 inode_tree_del(inode);
7870 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7872 call_rcu(&inode->i_rcu, btrfs_i_callback);
7875 int btrfs_drop_inode(struct inode *inode)
7877 struct btrfs_root *root = BTRFS_I(inode)->root;
7882 /* the snap/subvol tree is on deleting */
7883 if (btrfs_root_refs(&root->root_item) == 0)
7886 return generic_drop_inode(inode);
7889 static void init_once(void *foo)
7891 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
7893 inode_init_once(&ei->vfs_inode);
7896 void btrfs_destroy_cachep(void)
7899 * Make sure all delayed rcu free inodes are flushed before we
7903 if (btrfs_inode_cachep)
7904 kmem_cache_destroy(btrfs_inode_cachep);
7905 if (btrfs_trans_handle_cachep)
7906 kmem_cache_destroy(btrfs_trans_handle_cachep);
7907 if (btrfs_transaction_cachep)
7908 kmem_cache_destroy(btrfs_transaction_cachep);
7909 if (btrfs_path_cachep)
7910 kmem_cache_destroy(btrfs_path_cachep);
7911 if (btrfs_free_space_cachep)
7912 kmem_cache_destroy(btrfs_free_space_cachep);
7913 if (btrfs_delalloc_work_cachep)
7914 kmem_cache_destroy(btrfs_delalloc_work_cachep);
7917 int btrfs_init_cachep(void)
7919 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
7920 sizeof(struct btrfs_inode), 0,
7921 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
7922 if (!btrfs_inode_cachep)
7925 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
7926 sizeof(struct btrfs_trans_handle), 0,
7927 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7928 if (!btrfs_trans_handle_cachep)
7931 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
7932 sizeof(struct btrfs_transaction), 0,
7933 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7934 if (!btrfs_transaction_cachep)
7937 btrfs_path_cachep = kmem_cache_create("btrfs_path",
7938 sizeof(struct btrfs_path), 0,
7939 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7940 if (!btrfs_path_cachep)
7943 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
7944 sizeof(struct btrfs_free_space), 0,
7945 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7946 if (!btrfs_free_space_cachep)
7949 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
7950 sizeof(struct btrfs_delalloc_work), 0,
7951 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
7953 if (!btrfs_delalloc_work_cachep)
7958 btrfs_destroy_cachep();
7962 static int btrfs_getattr(struct vfsmount *mnt,
7963 struct dentry *dentry, struct kstat *stat)
7966 struct inode *inode = dentry->d_inode;
7967 u32 blocksize = inode->i_sb->s_blocksize;
7969 generic_fillattr(inode, stat);
7970 stat->dev = BTRFS_I(inode)->root->anon_dev;
7971 stat->blksize = PAGE_CACHE_SIZE;
7973 spin_lock(&BTRFS_I(inode)->lock);
7974 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
7975 spin_unlock(&BTRFS_I(inode)->lock);
7976 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
7977 ALIGN(delalloc_bytes, blocksize)) >> 9;
7981 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
7982 struct inode *new_dir, struct dentry *new_dentry)
7984 struct btrfs_trans_handle *trans;
7985 struct btrfs_root *root = BTRFS_I(old_dir)->root;
7986 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
7987 struct inode *new_inode = new_dentry->d_inode;
7988 struct inode *old_inode = old_dentry->d_inode;
7989 struct timespec ctime = CURRENT_TIME;
7993 u64 old_ino = btrfs_ino(old_inode);
7995 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
7998 /* we only allow rename subvolume link between subvolumes */
7999 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8002 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8003 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8006 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8007 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8011 /* check for collisions, even if the name isn't there */
8012 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8013 new_dentry->d_name.name,
8014 new_dentry->d_name.len);
8017 if (ret == -EEXIST) {
8019 * eexist without a new_inode */
8025 /* maybe -EOVERFLOW */
8032 * we're using rename to replace one file with another.
8033 * and the replacement file is large. Start IO on it now so
8034 * we don't add too much work to the end of the transaction
8036 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8037 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8038 filemap_flush(old_inode->i_mapping);
8040 /* close the racy window with snapshot create/destroy ioctl */
8041 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8042 down_read(&root->fs_info->subvol_sem);
8044 * We want to reserve the absolute worst case amount of items. So if
8045 * both inodes are subvols and we need to unlink them then that would
8046 * require 4 item modifications, but if they are both normal inodes it
8047 * would require 5 item modifications, so we'll assume their normal
8048 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8049 * should cover the worst case number of items we'll modify.
8051 trans = btrfs_start_transaction(root, 11);
8052 if (IS_ERR(trans)) {
8053 ret = PTR_ERR(trans);
8058 btrfs_record_root_in_trans(trans, dest);
8060 ret = btrfs_set_inode_index(new_dir, &index);
8064 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8065 /* force full log commit if subvolume involved. */
8066 root->fs_info->last_trans_log_full_commit = trans->transid;
8068 ret = btrfs_insert_inode_ref(trans, dest,
8069 new_dentry->d_name.name,
8070 new_dentry->d_name.len,
8072 btrfs_ino(new_dir), index);
8076 * this is an ugly little race, but the rename is required
8077 * to make sure that if we crash, the inode is either at the
8078 * old name or the new one. pinning the log transaction lets
8079 * us make sure we don't allow a log commit to come in after
8080 * we unlink the name but before we add the new name back in.
8082 btrfs_pin_log_trans(root);
8085 * make sure the inode gets flushed if it is replacing
8088 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8089 btrfs_add_ordered_operation(trans, root, old_inode);
8091 inode_inc_iversion(old_dir);
8092 inode_inc_iversion(new_dir);
8093 inode_inc_iversion(old_inode);
8094 old_dir->i_ctime = old_dir->i_mtime = ctime;
8095 new_dir->i_ctime = new_dir->i_mtime = ctime;
8096 old_inode->i_ctime = ctime;
8098 if (old_dentry->d_parent != new_dentry->d_parent)
8099 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8101 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8102 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8103 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8104 old_dentry->d_name.name,
8105 old_dentry->d_name.len);
8107 ret = __btrfs_unlink_inode(trans, root, old_dir,
8108 old_dentry->d_inode,
8109 old_dentry->d_name.name,
8110 old_dentry->d_name.len);
8112 ret = btrfs_update_inode(trans, root, old_inode);
8115 btrfs_abort_transaction(trans, root, ret);
8120 inode_inc_iversion(new_inode);
8121 new_inode->i_ctime = CURRENT_TIME;
8122 if (unlikely(btrfs_ino(new_inode) ==
8123 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8124 root_objectid = BTRFS_I(new_inode)->location.objectid;
8125 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8127 new_dentry->d_name.name,
8128 new_dentry->d_name.len);
8129 BUG_ON(new_inode->i_nlink == 0);
8131 ret = btrfs_unlink_inode(trans, dest, new_dir,
8132 new_dentry->d_inode,
8133 new_dentry->d_name.name,
8134 new_dentry->d_name.len);
8136 if (!ret && new_inode->i_nlink == 0)
8137 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8139 btrfs_abort_transaction(trans, root, ret);
8144 ret = btrfs_add_link(trans, new_dir, old_inode,
8145 new_dentry->d_name.name,
8146 new_dentry->d_name.len, 0, index);
8148 btrfs_abort_transaction(trans, root, ret);
8152 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8153 struct dentry *parent = new_dentry->d_parent;
8154 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8155 btrfs_end_log_trans(root);
8158 btrfs_end_transaction(trans, root);
8160 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8161 up_read(&root->fs_info->subvol_sem);
8166 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8168 struct btrfs_delalloc_work *delalloc_work;
8170 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8172 if (delalloc_work->wait)
8173 btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1);
8175 filemap_flush(delalloc_work->inode->i_mapping);
8177 if (delalloc_work->delay_iput)
8178 btrfs_add_delayed_iput(delalloc_work->inode);
8180 iput(delalloc_work->inode);
8181 complete(&delalloc_work->completion);
8184 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8185 int wait, int delay_iput)
8187 struct btrfs_delalloc_work *work;
8189 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8193 init_completion(&work->completion);
8194 INIT_LIST_HEAD(&work->list);
8195 work->inode = inode;
8197 work->delay_iput = delay_iput;
8198 work->work.func = btrfs_run_delalloc_work;
8203 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8205 wait_for_completion(&work->completion);
8206 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8210 * some fairly slow code that needs optimization. This walks the list
8211 * of all the inodes with pending delalloc and forces them to disk.
8213 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8215 struct btrfs_inode *binode;
8216 struct inode *inode;
8217 struct btrfs_delalloc_work *work, *next;
8218 struct list_head works;
8219 struct list_head splice;
8222 INIT_LIST_HEAD(&works);
8223 INIT_LIST_HEAD(&splice);
8225 spin_lock(&root->delalloc_lock);
8226 list_splice_init(&root->delalloc_inodes, &splice);
8227 while (!list_empty(&splice)) {
8228 binode = list_entry(splice.next, struct btrfs_inode,
8231 list_move_tail(&binode->delalloc_inodes,
8232 &root->delalloc_inodes);
8233 inode = igrab(&binode->vfs_inode);
8235 cond_resched_lock(&root->delalloc_lock);
8238 spin_unlock(&root->delalloc_lock);
8240 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8241 if (unlikely(!work)) {
8243 btrfs_add_delayed_iput(inode);
8249 list_add_tail(&work->list, &works);
8250 btrfs_queue_worker(&root->fs_info->flush_workers,
8254 spin_lock(&root->delalloc_lock);
8256 spin_unlock(&root->delalloc_lock);
8258 list_for_each_entry_safe(work, next, &works, list) {
8259 list_del_init(&work->list);
8260 btrfs_wait_and_free_delalloc_work(work);
8264 list_for_each_entry_safe(work, next, &works, list) {
8265 list_del_init(&work->list);
8266 btrfs_wait_and_free_delalloc_work(work);
8269 if (!list_empty_careful(&splice)) {
8270 spin_lock(&root->delalloc_lock);
8271 list_splice_tail(&splice, &root->delalloc_inodes);
8272 spin_unlock(&root->delalloc_lock);
8277 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8281 if (root->fs_info->sb->s_flags & MS_RDONLY)
8284 ret = __start_delalloc_inodes(root, delay_iput);
8286 * the filemap_flush will queue IO into the worker threads, but
8287 * we have to make sure the IO is actually started and that
8288 * ordered extents get created before we return
8290 atomic_inc(&root->fs_info->async_submit_draining);
8291 while (atomic_read(&root->fs_info->nr_async_submits) ||
8292 atomic_read(&root->fs_info->async_delalloc_pages)) {
8293 wait_event(root->fs_info->async_submit_wait,
8294 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8295 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8297 atomic_dec(&root->fs_info->async_submit_draining);
8301 int btrfs_start_all_delalloc_inodes(struct btrfs_fs_info *fs_info,
8304 struct btrfs_root *root;
8305 struct list_head splice;
8308 if (fs_info->sb->s_flags & MS_RDONLY)
8311 INIT_LIST_HEAD(&splice);
8313 spin_lock(&fs_info->delalloc_root_lock);
8314 list_splice_init(&fs_info->delalloc_roots, &splice);
8315 while (!list_empty(&splice)) {
8316 root = list_first_entry(&splice, struct btrfs_root,
8318 root = btrfs_grab_fs_root(root);
8320 list_move_tail(&root->delalloc_root,
8321 &fs_info->delalloc_roots);
8322 spin_unlock(&fs_info->delalloc_root_lock);
8324 ret = __start_delalloc_inodes(root, delay_iput);
8325 btrfs_put_fs_root(root);
8329 spin_lock(&fs_info->delalloc_root_lock);
8331 spin_unlock(&fs_info->delalloc_root_lock);
8333 atomic_inc(&fs_info->async_submit_draining);
8334 while (atomic_read(&fs_info->nr_async_submits) ||
8335 atomic_read(&fs_info->async_delalloc_pages)) {
8336 wait_event(fs_info->async_submit_wait,
8337 (atomic_read(&fs_info->nr_async_submits) == 0 &&
8338 atomic_read(&fs_info->async_delalloc_pages) == 0));
8340 atomic_dec(&fs_info->async_submit_draining);
8343 if (!list_empty_careful(&splice)) {
8344 spin_lock(&fs_info->delalloc_root_lock);
8345 list_splice_tail(&splice, &fs_info->delalloc_roots);
8346 spin_unlock(&fs_info->delalloc_root_lock);
8351 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8352 const char *symname)
8354 struct btrfs_trans_handle *trans;
8355 struct btrfs_root *root = BTRFS_I(dir)->root;
8356 struct btrfs_path *path;
8357 struct btrfs_key key;
8358 struct inode *inode = NULL;
8366 struct btrfs_file_extent_item *ei;
8367 struct extent_buffer *leaf;
8369 name_len = strlen(symname);
8370 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8371 return -ENAMETOOLONG;
8374 * 2 items for inode item and ref
8375 * 2 items for dir items
8376 * 1 item for xattr if selinux is on
8378 trans = btrfs_start_transaction(root, 5);
8380 return PTR_ERR(trans);
8382 err = btrfs_find_free_ino(root, &objectid);
8386 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8387 dentry->d_name.len, btrfs_ino(dir), objectid,
8388 S_IFLNK|S_IRWXUGO, &index);
8389 if (IS_ERR(inode)) {
8390 err = PTR_ERR(inode);
8394 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8401 * If the active LSM wants to access the inode during
8402 * d_instantiate it needs these. Smack checks to see
8403 * if the filesystem supports xattrs by looking at the
8406 inode->i_fop = &btrfs_file_operations;
8407 inode->i_op = &btrfs_file_inode_operations;
8409 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8413 inode->i_mapping->a_ops = &btrfs_aops;
8414 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8415 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8420 path = btrfs_alloc_path();
8426 key.objectid = btrfs_ino(inode);
8428 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8429 datasize = btrfs_file_extent_calc_inline_size(name_len);
8430 err = btrfs_insert_empty_item(trans, root, path, &key,
8434 btrfs_free_path(path);
8437 leaf = path->nodes[0];
8438 ei = btrfs_item_ptr(leaf, path->slots[0],
8439 struct btrfs_file_extent_item);
8440 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8441 btrfs_set_file_extent_type(leaf, ei,
8442 BTRFS_FILE_EXTENT_INLINE);
8443 btrfs_set_file_extent_encryption(leaf, ei, 0);
8444 btrfs_set_file_extent_compression(leaf, ei, 0);
8445 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8446 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8448 ptr = btrfs_file_extent_inline_start(ei);
8449 write_extent_buffer(leaf, symname, ptr, name_len);
8450 btrfs_mark_buffer_dirty(leaf);
8451 btrfs_free_path(path);
8453 inode->i_op = &btrfs_symlink_inode_operations;
8454 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8455 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8456 inode_set_bytes(inode, name_len);
8457 btrfs_i_size_write(inode, name_len);
8458 err = btrfs_update_inode(trans, root, inode);
8464 d_instantiate(dentry, inode);
8465 btrfs_end_transaction(trans, root);
8467 inode_dec_link_count(inode);
8470 btrfs_btree_balance_dirty(root);
8474 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8475 u64 start, u64 num_bytes, u64 min_size,
8476 loff_t actual_len, u64 *alloc_hint,
8477 struct btrfs_trans_handle *trans)
8479 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8480 struct extent_map *em;
8481 struct btrfs_root *root = BTRFS_I(inode)->root;
8482 struct btrfs_key ins;
8483 u64 cur_offset = start;
8487 bool own_trans = true;
8491 while (num_bytes > 0) {
8493 trans = btrfs_start_transaction(root, 3);
8494 if (IS_ERR(trans)) {
8495 ret = PTR_ERR(trans);
8500 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8501 cur_bytes = max(cur_bytes, min_size);
8502 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
8503 *alloc_hint, &ins, 1);
8506 btrfs_end_transaction(trans, root);
8510 ret = insert_reserved_file_extent(trans, inode,
8511 cur_offset, ins.objectid,
8512 ins.offset, ins.offset,
8513 ins.offset, 0, 0, 0,
8514 BTRFS_FILE_EXTENT_PREALLOC);
8516 btrfs_free_reserved_extent(root, ins.objectid,
8518 btrfs_abort_transaction(trans, root, ret);
8520 btrfs_end_transaction(trans, root);
8523 btrfs_drop_extent_cache(inode, cur_offset,
8524 cur_offset + ins.offset -1, 0);
8526 em = alloc_extent_map();
8528 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8529 &BTRFS_I(inode)->runtime_flags);
8533 em->start = cur_offset;
8534 em->orig_start = cur_offset;
8535 em->len = ins.offset;
8536 em->block_start = ins.objectid;
8537 em->block_len = ins.offset;
8538 em->orig_block_len = ins.offset;
8539 em->ram_bytes = ins.offset;
8540 em->bdev = root->fs_info->fs_devices->latest_bdev;
8541 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8542 em->generation = trans->transid;
8545 write_lock(&em_tree->lock);
8546 ret = add_extent_mapping(em_tree, em, 1);
8547 write_unlock(&em_tree->lock);
8550 btrfs_drop_extent_cache(inode, cur_offset,
8551 cur_offset + ins.offset - 1,
8554 free_extent_map(em);
8556 num_bytes -= ins.offset;
8557 cur_offset += ins.offset;
8558 *alloc_hint = ins.objectid + ins.offset;
8560 inode_inc_iversion(inode);
8561 inode->i_ctime = CURRENT_TIME;
8562 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8563 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8564 (actual_len > inode->i_size) &&
8565 (cur_offset > inode->i_size)) {
8566 if (cur_offset > actual_len)
8567 i_size = actual_len;
8569 i_size = cur_offset;
8570 i_size_write(inode, i_size);
8571 btrfs_ordered_update_i_size(inode, i_size, NULL);
8574 ret = btrfs_update_inode(trans, root, inode);
8577 btrfs_abort_transaction(trans, root, ret);
8579 btrfs_end_transaction(trans, root);
8584 btrfs_end_transaction(trans, root);
8589 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8590 u64 start, u64 num_bytes, u64 min_size,
8591 loff_t actual_len, u64 *alloc_hint)
8593 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8594 min_size, actual_len, alloc_hint,
8598 int btrfs_prealloc_file_range_trans(struct inode *inode,
8599 struct btrfs_trans_handle *trans, int mode,
8600 u64 start, u64 num_bytes, u64 min_size,
8601 loff_t actual_len, u64 *alloc_hint)
8603 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8604 min_size, actual_len, alloc_hint, trans);
8607 static int btrfs_set_page_dirty(struct page *page)
8609 return __set_page_dirty_nobuffers(page);
8612 static int btrfs_permission(struct inode *inode, int mask)
8614 struct btrfs_root *root = BTRFS_I(inode)->root;
8615 umode_t mode = inode->i_mode;
8617 if (mask & MAY_WRITE &&
8618 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8619 if (btrfs_root_readonly(root))
8621 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8624 return generic_permission(inode, mask);
8627 static const struct inode_operations btrfs_dir_inode_operations = {
8628 .getattr = btrfs_getattr,
8629 .lookup = btrfs_lookup,
8630 .create = btrfs_create,
8631 .unlink = btrfs_unlink,
8633 .mkdir = btrfs_mkdir,
8634 .rmdir = btrfs_rmdir,
8635 .rename = btrfs_rename,
8636 .symlink = btrfs_symlink,
8637 .setattr = btrfs_setattr,
8638 .mknod = btrfs_mknod,
8639 .setxattr = btrfs_setxattr,
8640 .getxattr = btrfs_getxattr,
8641 .listxattr = btrfs_listxattr,
8642 .removexattr = btrfs_removexattr,
8643 .permission = btrfs_permission,
8644 .get_acl = btrfs_get_acl,
8645 .update_time = btrfs_update_time,
8647 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8648 .lookup = btrfs_lookup,
8649 .permission = btrfs_permission,
8650 .get_acl = btrfs_get_acl,
8651 .update_time = btrfs_update_time,
8654 static const struct file_operations btrfs_dir_file_operations = {
8655 .llseek = generic_file_llseek,
8656 .read = generic_read_dir,
8657 .iterate = btrfs_real_readdir,
8658 .unlocked_ioctl = btrfs_ioctl,
8659 #ifdef CONFIG_COMPAT
8660 .compat_ioctl = btrfs_ioctl,
8662 .release = btrfs_release_file,
8663 .fsync = btrfs_sync_file,
8666 static struct extent_io_ops btrfs_extent_io_ops = {
8667 .fill_delalloc = run_delalloc_range,
8668 .submit_bio_hook = btrfs_submit_bio_hook,
8669 .merge_bio_hook = btrfs_merge_bio_hook,
8670 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8671 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8672 .writepage_start_hook = btrfs_writepage_start_hook,
8673 .set_bit_hook = btrfs_set_bit_hook,
8674 .clear_bit_hook = btrfs_clear_bit_hook,
8675 .merge_extent_hook = btrfs_merge_extent_hook,
8676 .split_extent_hook = btrfs_split_extent_hook,
8680 * btrfs doesn't support the bmap operation because swapfiles
8681 * use bmap to make a mapping of extents in the file. They assume
8682 * these extents won't change over the life of the file and they
8683 * use the bmap result to do IO directly to the drive.
8685 * the btrfs bmap call would return logical addresses that aren't
8686 * suitable for IO and they also will change frequently as COW
8687 * operations happen. So, swapfile + btrfs == corruption.
8689 * For now we're avoiding this by dropping bmap.
8691 static const struct address_space_operations btrfs_aops = {
8692 .readpage = btrfs_readpage,
8693 .writepage = btrfs_writepage,
8694 .writepages = btrfs_writepages,
8695 .readpages = btrfs_readpages,
8696 .direct_IO = btrfs_direct_IO,
8697 .invalidatepage = btrfs_invalidatepage,
8698 .releasepage = btrfs_releasepage,
8699 .set_page_dirty = btrfs_set_page_dirty,
8700 .error_remove_page = generic_error_remove_page,
8703 static const struct address_space_operations btrfs_symlink_aops = {
8704 .readpage = btrfs_readpage,
8705 .writepage = btrfs_writepage,
8706 .invalidatepage = btrfs_invalidatepage,
8707 .releasepage = btrfs_releasepage,
8710 static const struct inode_operations btrfs_file_inode_operations = {
8711 .getattr = btrfs_getattr,
8712 .setattr = btrfs_setattr,
8713 .setxattr = btrfs_setxattr,
8714 .getxattr = btrfs_getxattr,
8715 .listxattr = btrfs_listxattr,
8716 .removexattr = btrfs_removexattr,
8717 .permission = btrfs_permission,
8718 .fiemap = btrfs_fiemap,
8719 .get_acl = btrfs_get_acl,
8720 .update_time = btrfs_update_time,
8722 static const struct inode_operations btrfs_special_inode_operations = {
8723 .getattr = btrfs_getattr,
8724 .setattr = btrfs_setattr,
8725 .permission = btrfs_permission,
8726 .setxattr = btrfs_setxattr,
8727 .getxattr = btrfs_getxattr,
8728 .listxattr = btrfs_listxattr,
8729 .removexattr = btrfs_removexattr,
8730 .get_acl = btrfs_get_acl,
8731 .update_time = btrfs_update_time,
8733 static const struct inode_operations btrfs_symlink_inode_operations = {
8734 .readlink = generic_readlink,
8735 .follow_link = page_follow_link_light,
8736 .put_link = page_put_link,
8737 .getattr = btrfs_getattr,
8738 .setattr = btrfs_setattr,
8739 .permission = btrfs_permission,
8740 .setxattr = btrfs_setxattr,
8741 .getxattr = btrfs_getxattr,
8742 .listxattr = btrfs_listxattr,
8743 .removexattr = btrfs_removexattr,
8744 .get_acl = btrfs_get_acl,
8745 .update_time = btrfs_update_time,
8748 const struct dentry_operations btrfs_dentry_operations = {
8749 .d_delete = btrfs_dentry_delete,
8750 .d_release = btrfs_dentry_release,