2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/aio.h>
36 #include <linux/bit_spinlock.h>
37 #include <linux/xattr.h>
38 #include <linux/posix_acl.h>
39 #include <linux/falloc.h>
40 #include <linux/slab.h>
41 #include <linux/ratelimit.h>
42 #include <linux/mount.h>
43 #include <linux/btrfs.h>
44 #include <linux/blkdev.h>
45 #include <linux/posix_acl_xattr.h>
48 #include "transaction.h"
49 #include "btrfs_inode.h"
50 #include "print-tree.h"
51 #include "ordered-data.h"
55 #include "compression.h"
57 #include "free-space-cache.h"
58 #include "inode-map.h"
63 struct btrfs_iget_args {
64 struct btrfs_key *location;
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 int insert_inline_extent(struct btrfs_trans_handle *trans,
129 struct btrfs_path *path, int extent_inserted,
130 struct btrfs_root *root, struct inode *inode,
131 u64 start, size_t size, size_t compressed_size,
133 struct page **compressed_pages)
135 struct extent_buffer *leaf;
136 struct page *page = NULL;
139 struct btrfs_file_extent_item *ei;
142 size_t cur_size = size;
143 unsigned long offset;
145 if (compressed_size && compressed_pages)
146 cur_size = compressed_size;
148 inode_add_bytes(inode, size);
150 if (!extent_inserted) {
151 struct btrfs_key key;
154 key.objectid = btrfs_ino(inode);
156 key.type = BTRFS_EXTENT_DATA_KEY;
158 datasize = btrfs_file_extent_calc_inline_size(cur_size);
159 path->leave_spinning = 1;
160 ret = btrfs_insert_empty_item(trans, root, path, &key,
167 leaf = path->nodes[0];
168 ei = btrfs_item_ptr(leaf, path->slots[0],
169 struct btrfs_file_extent_item);
170 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
171 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
172 btrfs_set_file_extent_encryption(leaf, ei, 0);
173 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
174 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
175 ptr = btrfs_file_extent_inline_start(ei);
177 if (compress_type != BTRFS_COMPRESS_NONE) {
180 while (compressed_size > 0) {
181 cpage = compressed_pages[i];
182 cur_size = min_t(unsigned long, compressed_size,
185 kaddr = kmap_atomic(cpage);
186 write_extent_buffer(leaf, kaddr, ptr, cur_size);
187 kunmap_atomic(kaddr);
191 compressed_size -= cur_size;
193 btrfs_set_file_extent_compression(leaf, ei,
196 page = find_get_page(inode->i_mapping,
197 start >> PAGE_CACHE_SHIFT);
198 btrfs_set_file_extent_compression(leaf, ei, 0);
199 kaddr = kmap_atomic(page);
200 offset = start & (PAGE_CACHE_SIZE - 1);
201 write_extent_buffer(leaf, kaddr + offset, ptr, size);
202 kunmap_atomic(kaddr);
203 page_cache_release(page);
205 btrfs_mark_buffer_dirty(leaf);
206 btrfs_release_path(path);
209 * we're an inline extent, so nobody can
210 * extend the file past i_size without locking
211 * a page we already have locked.
213 * We must do any isize and inode updates
214 * before we unlock the pages. Otherwise we
215 * could end up racing with unlink.
217 BTRFS_I(inode)->disk_i_size = inode->i_size;
218 ret = btrfs_update_inode(trans, root, inode);
227 * conditionally insert an inline extent into the file. This
228 * does the checks required to make sure the data is small enough
229 * to fit as an inline extent.
231 static noinline int cow_file_range_inline(struct btrfs_root *root,
232 struct inode *inode, u64 start,
233 u64 end, size_t compressed_size,
235 struct page **compressed_pages)
237 struct btrfs_trans_handle *trans;
238 u64 isize = i_size_read(inode);
239 u64 actual_end = min(end + 1, isize);
240 u64 inline_len = actual_end - start;
241 u64 aligned_end = ALIGN(end, root->sectorsize);
242 u64 data_len = inline_len;
244 struct btrfs_path *path;
245 int extent_inserted = 0;
246 u32 extent_item_size;
249 data_len = compressed_size;
252 actual_end > PAGE_CACHE_SIZE ||
253 data_len > BTRFS_MAX_INLINE_DATA_SIZE(root) ||
255 (actual_end & (root->sectorsize - 1)) == 0) ||
257 data_len > root->fs_info->max_inline) {
261 path = btrfs_alloc_path();
265 trans = btrfs_join_transaction(root);
267 btrfs_free_path(path);
268 return PTR_ERR(trans);
270 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
272 if (compressed_size && compressed_pages)
273 extent_item_size = btrfs_file_extent_calc_inline_size(
276 extent_item_size = btrfs_file_extent_calc_inline_size(
279 ret = __btrfs_drop_extents(trans, root, inode, path,
280 start, aligned_end, NULL,
281 1, 1, extent_item_size, &extent_inserted);
283 btrfs_abort_transaction(trans, root, ret);
287 if (isize > actual_end)
288 inline_len = min_t(u64, isize, actual_end);
289 ret = insert_inline_extent(trans, path, extent_inserted,
291 inline_len, compressed_size,
292 compress_type, compressed_pages);
293 if (ret && ret != -ENOSPC) {
294 btrfs_abort_transaction(trans, root, ret);
296 } else if (ret == -ENOSPC) {
301 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
302 btrfs_delalloc_release_metadata(inode, end + 1 - start);
303 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
305 btrfs_free_path(path);
306 btrfs_end_transaction(trans, root);
310 struct async_extent {
315 unsigned long nr_pages;
317 struct list_head list;
322 struct btrfs_root *root;
323 struct page *locked_page;
326 struct list_head extents;
327 struct btrfs_work work;
330 static noinline int add_async_extent(struct async_cow *cow,
331 u64 start, u64 ram_size,
334 unsigned long nr_pages,
337 struct async_extent *async_extent;
339 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
340 BUG_ON(!async_extent); /* -ENOMEM */
341 async_extent->start = start;
342 async_extent->ram_size = ram_size;
343 async_extent->compressed_size = compressed_size;
344 async_extent->pages = pages;
345 async_extent->nr_pages = nr_pages;
346 async_extent->compress_type = compress_type;
347 list_add_tail(&async_extent->list, &cow->extents);
351 static inline int inode_need_compress(struct inode *inode)
353 struct btrfs_root *root = BTRFS_I(inode)->root;
356 if (btrfs_test_opt(root, FORCE_COMPRESS))
358 /* bad compression ratios */
359 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
361 if (btrfs_test_opt(root, COMPRESS) ||
362 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
363 BTRFS_I(inode)->force_compress)
369 * we create compressed extents in two phases. The first
370 * phase compresses a range of pages that have already been
371 * locked (both pages and state bits are locked).
373 * This is done inside an ordered work queue, and the compression
374 * is spread across many cpus. The actual IO submission is step
375 * two, and the ordered work queue takes care of making sure that
376 * happens in the same order things were put onto the queue by
377 * writepages and friends.
379 * If this code finds it can't get good compression, it puts an
380 * entry onto the work queue to write the uncompressed bytes. This
381 * makes sure that both compressed inodes and uncompressed inodes
382 * are written in the same order that the flusher thread sent them
385 static noinline void compress_file_range(struct inode *inode,
386 struct page *locked_page,
388 struct async_cow *async_cow,
391 struct btrfs_root *root = BTRFS_I(inode)->root;
393 u64 blocksize = root->sectorsize;
395 u64 isize = i_size_read(inode);
397 struct page **pages = NULL;
398 unsigned long nr_pages;
399 unsigned long nr_pages_ret = 0;
400 unsigned long total_compressed = 0;
401 unsigned long total_in = 0;
402 unsigned long max_compressed = 128 * 1024;
403 unsigned long max_uncompressed = 128 * 1024;
406 int compress_type = root->fs_info->compress_type;
409 /* if this is a small write inside eof, kick off a defrag */
410 if ((end - start + 1) < 16 * 1024 &&
411 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
412 btrfs_add_inode_defrag(NULL, inode);
414 actual_end = min_t(u64, isize, end + 1);
417 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
418 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
421 * we don't want to send crud past the end of i_size through
422 * compression, that's just a waste of CPU time. So, if the
423 * end of the file is before the start of our current
424 * requested range of bytes, we bail out to the uncompressed
425 * cleanup code that can deal with all of this.
427 * It isn't really the fastest way to fix things, but this is a
428 * very uncommon corner.
430 if (actual_end <= start)
431 goto cleanup_and_bail_uncompressed;
433 total_compressed = actual_end - start;
436 * skip compression for a small file range(<=blocksize) that
437 * isn't an inline extent, since it dosen't save disk space at all.
439 if (total_compressed <= blocksize &&
440 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
441 goto cleanup_and_bail_uncompressed;
443 /* we want to make sure that amount of ram required to uncompress
444 * an extent is reasonable, so we limit the total size in ram
445 * of a compressed extent to 128k. This is a crucial number
446 * because it also controls how easily we can spread reads across
447 * cpus for decompression.
449 * We also want to make sure the amount of IO required to do
450 * a random read is reasonably small, so we limit the size of
451 * a compressed extent to 128k.
453 total_compressed = min(total_compressed, max_uncompressed);
454 num_bytes = ALIGN(end - start + 1, blocksize);
455 num_bytes = max(blocksize, num_bytes);
460 * we do compression for mount -o compress and when the
461 * inode has not been flagged as nocompress. This flag can
462 * change at any time if we discover bad compression ratios.
464 if (inode_need_compress(inode)) {
466 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
468 /* just bail out to the uncompressed code */
472 if (BTRFS_I(inode)->force_compress)
473 compress_type = BTRFS_I(inode)->force_compress;
476 * we need to call clear_page_dirty_for_io on each
477 * page in the range. Otherwise applications with the file
478 * mmap'd can wander in and change the page contents while
479 * we are compressing them.
481 * If the compression fails for any reason, we set the pages
482 * dirty again later on.
484 extent_range_clear_dirty_for_io(inode, start, end);
486 ret = btrfs_compress_pages(compress_type,
487 inode->i_mapping, start,
488 total_compressed, pages,
489 nr_pages, &nr_pages_ret,
495 unsigned long offset = total_compressed &
496 (PAGE_CACHE_SIZE - 1);
497 struct page *page = pages[nr_pages_ret - 1];
500 /* zero the tail end of the last page, we might be
501 * sending it down to disk
504 kaddr = kmap_atomic(page);
505 memset(kaddr + offset, 0,
506 PAGE_CACHE_SIZE - offset);
507 kunmap_atomic(kaddr);
514 /* lets try to make an inline extent */
515 if (ret || total_in < (actual_end - start)) {
516 /* we didn't compress the entire range, try
517 * to make an uncompressed inline extent.
519 ret = cow_file_range_inline(root, inode, start, end,
522 /* try making a compressed inline extent */
523 ret = cow_file_range_inline(root, inode, start, end,
525 compress_type, pages);
528 unsigned long clear_flags = EXTENT_DELALLOC |
530 unsigned long page_error_op;
532 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
533 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
536 * inline extent creation worked or returned error,
537 * we don't need to create any more async work items.
538 * Unlock and free up our temp pages.
540 extent_clear_unlock_delalloc(inode, start, end, NULL,
541 clear_flags, PAGE_UNLOCK |
552 * we aren't doing an inline extent round the compressed size
553 * up to a block size boundary so the allocator does sane
556 total_compressed = ALIGN(total_compressed, blocksize);
559 * one last check to make sure the compression is really a
560 * win, compare the page count read with the blocks on disk
562 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
563 if (total_compressed >= total_in) {
566 num_bytes = total_in;
569 if (!will_compress && pages) {
571 * the compression code ran but failed to make things smaller,
572 * free any pages it allocated and our page pointer array
574 for (i = 0; i < nr_pages_ret; i++) {
575 WARN_ON(pages[i]->mapping);
576 page_cache_release(pages[i]);
580 total_compressed = 0;
583 /* flag the file so we don't compress in the future */
584 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
585 !(BTRFS_I(inode)->force_compress)) {
586 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
592 /* the async work queues will take care of doing actual
593 * allocation on disk for these compressed pages,
594 * and will submit them to the elevator.
596 add_async_extent(async_cow, start, num_bytes,
597 total_compressed, pages, nr_pages_ret,
600 if (start + num_bytes < end) {
607 cleanup_and_bail_uncompressed:
609 * No compression, but we still need to write the pages in
610 * the file we've been given so far. redirty the locked
611 * page if it corresponds to our extent and set things up
612 * for the async work queue to run cow_file_range to do
613 * the normal delalloc dance
615 if (page_offset(locked_page) >= start &&
616 page_offset(locked_page) <= end) {
617 __set_page_dirty_nobuffers(locked_page);
618 /* unlocked later on in the async handlers */
621 extent_range_redirty_for_io(inode, start, end);
622 add_async_extent(async_cow, start, end - start + 1,
623 0, NULL, 0, BTRFS_COMPRESS_NONE);
630 for (i = 0; i < nr_pages_ret; i++) {
631 WARN_ON(pages[i]->mapping);
632 page_cache_release(pages[i]);
637 static void free_async_extent_pages(struct async_extent *async_extent)
641 if (!async_extent->pages)
644 for (i = 0; i < async_extent->nr_pages; i++) {
645 WARN_ON(async_extent->pages[i]->mapping);
646 page_cache_release(async_extent->pages[i]);
648 kfree(async_extent->pages);
649 async_extent->nr_pages = 0;
650 async_extent->pages = NULL;
654 * phase two of compressed writeback. This is the ordered portion
655 * of the code, which only gets called in the order the work was
656 * queued. We walk all the async extents created by compress_file_range
657 * and send them down to the disk.
659 static noinline void submit_compressed_extents(struct inode *inode,
660 struct async_cow *async_cow)
662 struct async_extent *async_extent;
664 struct btrfs_key ins;
665 struct extent_map *em;
666 struct btrfs_root *root = BTRFS_I(inode)->root;
667 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
668 struct extent_io_tree *io_tree;
672 while (!list_empty(&async_cow->extents)) {
673 async_extent = list_entry(async_cow->extents.next,
674 struct async_extent, list);
675 list_del(&async_extent->list);
677 io_tree = &BTRFS_I(inode)->io_tree;
680 /* did the compression code fall back to uncompressed IO? */
681 if (!async_extent->pages) {
682 int page_started = 0;
683 unsigned long nr_written = 0;
685 lock_extent(io_tree, async_extent->start,
686 async_extent->start +
687 async_extent->ram_size - 1);
689 /* allocate blocks */
690 ret = cow_file_range(inode, async_cow->locked_page,
692 async_extent->start +
693 async_extent->ram_size - 1,
694 &page_started, &nr_written, 0);
699 * if page_started, cow_file_range inserted an
700 * inline extent and took care of all the unlocking
701 * and IO for us. Otherwise, we need to submit
702 * all those pages down to the drive.
704 if (!page_started && !ret)
705 extent_write_locked_range(io_tree,
706 inode, async_extent->start,
707 async_extent->start +
708 async_extent->ram_size - 1,
712 unlock_page(async_cow->locked_page);
718 lock_extent(io_tree, async_extent->start,
719 async_extent->start + async_extent->ram_size - 1);
721 ret = btrfs_reserve_extent(root,
722 async_extent->compressed_size,
723 async_extent->compressed_size,
724 0, alloc_hint, &ins, 1, 1);
726 free_async_extent_pages(async_extent);
728 if (ret == -ENOSPC) {
729 unlock_extent(io_tree, async_extent->start,
730 async_extent->start +
731 async_extent->ram_size - 1);
734 * we need to redirty the pages if we decide to
735 * fallback to uncompressed IO, otherwise we
736 * will not submit these pages down to lower
739 extent_range_redirty_for_io(inode,
741 async_extent->start +
742 async_extent->ram_size - 1);
750 * here we're doing allocation and writeback of the
753 btrfs_drop_extent_cache(inode, async_extent->start,
754 async_extent->start +
755 async_extent->ram_size - 1, 0);
757 em = alloc_extent_map();
760 goto out_free_reserve;
762 em->start = async_extent->start;
763 em->len = async_extent->ram_size;
764 em->orig_start = em->start;
765 em->mod_start = em->start;
766 em->mod_len = em->len;
768 em->block_start = ins.objectid;
769 em->block_len = ins.offset;
770 em->orig_block_len = ins.offset;
771 em->ram_bytes = async_extent->ram_size;
772 em->bdev = root->fs_info->fs_devices->latest_bdev;
773 em->compress_type = async_extent->compress_type;
774 set_bit(EXTENT_FLAG_PINNED, &em->flags);
775 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
779 write_lock(&em_tree->lock);
780 ret = add_extent_mapping(em_tree, em, 1);
781 write_unlock(&em_tree->lock);
782 if (ret != -EEXIST) {
786 btrfs_drop_extent_cache(inode, async_extent->start,
787 async_extent->start +
788 async_extent->ram_size - 1, 0);
792 goto out_free_reserve;
794 ret = btrfs_add_ordered_extent_compress(inode,
797 async_extent->ram_size,
799 BTRFS_ORDERED_COMPRESSED,
800 async_extent->compress_type);
802 btrfs_drop_extent_cache(inode, async_extent->start,
803 async_extent->start +
804 async_extent->ram_size - 1, 0);
805 goto out_free_reserve;
809 * clear dirty, set writeback and unlock the pages.
811 extent_clear_unlock_delalloc(inode, async_extent->start,
812 async_extent->start +
813 async_extent->ram_size - 1,
814 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
815 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
817 ret = btrfs_submit_compressed_write(inode,
819 async_extent->ram_size,
821 ins.offset, async_extent->pages,
822 async_extent->nr_pages);
824 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
825 struct page *p = async_extent->pages[0];
826 const u64 start = async_extent->start;
827 const u64 end = start + async_extent->ram_size - 1;
829 p->mapping = inode->i_mapping;
830 tree->ops->writepage_end_io_hook(p, start, end,
833 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
836 free_async_extent_pages(async_extent);
838 alloc_hint = ins.objectid + ins.offset;
844 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
846 extent_clear_unlock_delalloc(inode, async_extent->start,
847 async_extent->start +
848 async_extent->ram_size - 1,
849 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
850 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
851 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
852 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
854 free_async_extent_pages(async_extent);
859 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
862 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
863 struct extent_map *em;
866 read_lock(&em_tree->lock);
867 em = search_extent_mapping(em_tree, start, num_bytes);
870 * if block start isn't an actual block number then find the
871 * first block in this inode and use that as a hint. If that
872 * block is also bogus then just don't worry about it.
874 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
876 em = search_extent_mapping(em_tree, 0, 0);
877 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
878 alloc_hint = em->block_start;
882 alloc_hint = em->block_start;
886 read_unlock(&em_tree->lock);
892 * when extent_io.c finds a delayed allocation range in the file,
893 * the call backs end up in this code. The basic idea is to
894 * allocate extents on disk for the range, and create ordered data structs
895 * in ram to track those extents.
897 * locked_page is the page that writepage had locked already. We use
898 * it to make sure we don't do extra locks or unlocks.
900 * *page_started is set to one if we unlock locked_page and do everything
901 * required to start IO on it. It may be clean and already done with
904 static noinline int cow_file_range(struct inode *inode,
905 struct page *locked_page,
906 u64 start, u64 end, int *page_started,
907 unsigned long *nr_written,
910 struct btrfs_root *root = BTRFS_I(inode)->root;
913 unsigned long ram_size;
916 u64 blocksize = root->sectorsize;
917 struct btrfs_key ins;
918 struct extent_map *em;
919 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
922 if (btrfs_is_free_space_inode(inode)) {
928 num_bytes = ALIGN(end - start + 1, blocksize);
929 num_bytes = max(blocksize, num_bytes);
930 disk_num_bytes = num_bytes;
932 /* if this is a small write inside eof, kick off defrag */
933 if (num_bytes < 64 * 1024 &&
934 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
935 btrfs_add_inode_defrag(NULL, inode);
938 /* lets try to make an inline extent */
939 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
942 extent_clear_unlock_delalloc(inode, start, end, NULL,
943 EXTENT_LOCKED | EXTENT_DELALLOC |
944 EXTENT_DEFRAG, PAGE_UNLOCK |
945 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
948 *nr_written = *nr_written +
949 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
952 } else if (ret < 0) {
957 BUG_ON(disk_num_bytes >
958 btrfs_super_total_bytes(root->fs_info->super_copy));
960 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
961 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
963 while (disk_num_bytes > 0) {
966 cur_alloc_size = disk_num_bytes;
967 ret = btrfs_reserve_extent(root, cur_alloc_size,
968 root->sectorsize, 0, alloc_hint,
973 em = alloc_extent_map();
979 em->orig_start = em->start;
980 ram_size = ins.offset;
981 em->len = ins.offset;
982 em->mod_start = em->start;
983 em->mod_len = em->len;
985 em->block_start = ins.objectid;
986 em->block_len = ins.offset;
987 em->orig_block_len = ins.offset;
988 em->ram_bytes = ram_size;
989 em->bdev = root->fs_info->fs_devices->latest_bdev;
990 set_bit(EXTENT_FLAG_PINNED, &em->flags);
994 write_lock(&em_tree->lock);
995 ret = add_extent_mapping(em_tree, em, 1);
996 write_unlock(&em_tree->lock);
997 if (ret != -EEXIST) {
1001 btrfs_drop_extent_cache(inode, start,
1002 start + ram_size - 1, 0);
1007 cur_alloc_size = ins.offset;
1008 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1009 ram_size, cur_alloc_size, 0);
1011 goto out_drop_extent_cache;
1013 if (root->root_key.objectid ==
1014 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1015 ret = btrfs_reloc_clone_csums(inode, start,
1018 goto out_drop_extent_cache;
1021 if (disk_num_bytes < cur_alloc_size)
1024 /* we're not doing compressed IO, don't unlock the first
1025 * page (which the caller expects to stay locked), don't
1026 * clear any dirty bits and don't set any writeback bits
1028 * Do set the Private2 bit so we know this page was properly
1029 * setup for writepage
1031 op = unlock ? PAGE_UNLOCK : 0;
1032 op |= PAGE_SET_PRIVATE2;
1034 extent_clear_unlock_delalloc(inode, start,
1035 start + ram_size - 1, locked_page,
1036 EXTENT_LOCKED | EXTENT_DELALLOC,
1038 disk_num_bytes -= cur_alloc_size;
1039 num_bytes -= cur_alloc_size;
1040 alloc_hint = ins.objectid + ins.offset;
1041 start += cur_alloc_size;
1046 out_drop_extent_cache:
1047 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1049 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1051 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1052 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1053 EXTENT_DELALLOC | EXTENT_DEFRAG,
1054 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1055 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1060 * work queue call back to started compression on a file and pages
1062 static noinline void async_cow_start(struct btrfs_work *work)
1064 struct async_cow *async_cow;
1066 async_cow = container_of(work, struct async_cow, work);
1068 compress_file_range(async_cow->inode, async_cow->locked_page,
1069 async_cow->start, async_cow->end, async_cow,
1071 if (num_added == 0) {
1072 btrfs_add_delayed_iput(async_cow->inode);
1073 async_cow->inode = NULL;
1078 * work queue call back to submit previously compressed pages
1080 static noinline void async_cow_submit(struct btrfs_work *work)
1082 struct async_cow *async_cow;
1083 struct btrfs_root *root;
1084 unsigned long nr_pages;
1086 async_cow = container_of(work, struct async_cow, work);
1088 root = async_cow->root;
1089 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1092 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1094 waitqueue_active(&root->fs_info->async_submit_wait))
1095 wake_up(&root->fs_info->async_submit_wait);
1097 if (async_cow->inode)
1098 submit_compressed_extents(async_cow->inode, async_cow);
1101 static noinline void async_cow_free(struct btrfs_work *work)
1103 struct async_cow *async_cow;
1104 async_cow = container_of(work, struct async_cow, work);
1105 if (async_cow->inode)
1106 btrfs_add_delayed_iput(async_cow->inode);
1110 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1111 u64 start, u64 end, int *page_started,
1112 unsigned long *nr_written)
1114 struct async_cow *async_cow;
1115 struct btrfs_root *root = BTRFS_I(inode)->root;
1116 unsigned long nr_pages;
1118 int limit = 10 * 1024 * 1024;
1120 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1121 1, 0, NULL, GFP_NOFS);
1122 while (start < end) {
1123 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1124 BUG_ON(!async_cow); /* -ENOMEM */
1125 async_cow->inode = igrab(inode);
1126 async_cow->root = root;
1127 async_cow->locked_page = locked_page;
1128 async_cow->start = start;
1130 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1131 !btrfs_test_opt(root, FORCE_COMPRESS))
1134 cur_end = min(end, start + 512 * 1024 - 1);
1136 async_cow->end = cur_end;
1137 INIT_LIST_HEAD(&async_cow->extents);
1139 btrfs_init_work(&async_cow->work,
1140 btrfs_delalloc_helper,
1141 async_cow_start, async_cow_submit,
1144 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1146 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1148 btrfs_queue_work(root->fs_info->delalloc_workers,
1151 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1152 wait_event(root->fs_info->async_submit_wait,
1153 (atomic_read(&root->fs_info->async_delalloc_pages) <
1157 while (atomic_read(&root->fs_info->async_submit_draining) &&
1158 atomic_read(&root->fs_info->async_delalloc_pages)) {
1159 wait_event(root->fs_info->async_submit_wait,
1160 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1164 *nr_written += nr_pages;
1165 start = cur_end + 1;
1171 static noinline int csum_exist_in_range(struct btrfs_root *root,
1172 u64 bytenr, u64 num_bytes)
1175 struct btrfs_ordered_sum *sums;
1178 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1179 bytenr + num_bytes - 1, &list, 0);
1180 if (ret == 0 && list_empty(&list))
1183 while (!list_empty(&list)) {
1184 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1185 list_del(&sums->list);
1192 * when nowcow writeback call back. This checks for snapshots or COW copies
1193 * of the extents that exist in the file, and COWs the file as required.
1195 * If no cow copies or snapshots exist, we write directly to the existing
1198 static noinline int run_delalloc_nocow(struct inode *inode,
1199 struct page *locked_page,
1200 u64 start, u64 end, int *page_started, int force,
1201 unsigned long *nr_written)
1203 struct btrfs_root *root = BTRFS_I(inode)->root;
1204 struct btrfs_trans_handle *trans;
1205 struct extent_buffer *leaf;
1206 struct btrfs_path *path;
1207 struct btrfs_file_extent_item *fi;
1208 struct btrfs_key found_key;
1223 u64 ino = btrfs_ino(inode);
1225 path = btrfs_alloc_path();
1227 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1228 EXTENT_LOCKED | EXTENT_DELALLOC |
1229 EXTENT_DO_ACCOUNTING |
1230 EXTENT_DEFRAG, PAGE_UNLOCK |
1232 PAGE_SET_WRITEBACK |
1233 PAGE_END_WRITEBACK);
1237 nolock = btrfs_is_free_space_inode(inode);
1240 trans = btrfs_join_transaction_nolock(root);
1242 trans = btrfs_join_transaction(root);
1244 if (IS_ERR(trans)) {
1245 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1246 EXTENT_LOCKED | EXTENT_DELALLOC |
1247 EXTENT_DO_ACCOUNTING |
1248 EXTENT_DEFRAG, PAGE_UNLOCK |
1250 PAGE_SET_WRITEBACK |
1251 PAGE_END_WRITEBACK);
1252 btrfs_free_path(path);
1253 return PTR_ERR(trans);
1256 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1258 cow_start = (u64)-1;
1261 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1265 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1266 leaf = path->nodes[0];
1267 btrfs_item_key_to_cpu(leaf, &found_key,
1268 path->slots[0] - 1);
1269 if (found_key.objectid == ino &&
1270 found_key.type == BTRFS_EXTENT_DATA_KEY)
1275 leaf = path->nodes[0];
1276 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1277 ret = btrfs_next_leaf(root, path);
1282 leaf = path->nodes[0];
1288 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1290 if (found_key.objectid > ino ||
1291 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1292 found_key.offset > end)
1295 if (found_key.offset > cur_offset) {
1296 extent_end = found_key.offset;
1301 fi = btrfs_item_ptr(leaf, path->slots[0],
1302 struct btrfs_file_extent_item);
1303 extent_type = btrfs_file_extent_type(leaf, fi);
1305 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1306 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1307 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1308 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1309 extent_offset = btrfs_file_extent_offset(leaf, fi);
1310 extent_end = found_key.offset +
1311 btrfs_file_extent_num_bytes(leaf, fi);
1313 btrfs_file_extent_disk_num_bytes(leaf, fi);
1314 if (extent_end <= start) {
1318 if (disk_bytenr == 0)
1320 if (btrfs_file_extent_compression(leaf, fi) ||
1321 btrfs_file_extent_encryption(leaf, fi) ||
1322 btrfs_file_extent_other_encoding(leaf, fi))
1324 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1326 if (btrfs_extent_readonly(root, disk_bytenr))
1328 if (btrfs_cross_ref_exist(trans, root, ino,
1330 extent_offset, disk_bytenr))
1332 disk_bytenr += extent_offset;
1333 disk_bytenr += cur_offset - found_key.offset;
1334 num_bytes = min(end + 1, extent_end) - cur_offset;
1336 * if there are pending snapshots for this root,
1337 * we fall into common COW way.
1340 err = btrfs_start_write_no_snapshoting(root);
1345 * force cow if csum exists in the range.
1346 * this ensure that csum for a given extent are
1347 * either valid or do not exist.
1349 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1352 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1353 extent_end = found_key.offset +
1354 btrfs_file_extent_inline_len(leaf,
1355 path->slots[0], fi);
1356 extent_end = ALIGN(extent_end, root->sectorsize);
1361 if (extent_end <= start) {
1363 if (!nolock && nocow)
1364 btrfs_end_write_no_snapshoting(root);
1368 if (cow_start == (u64)-1)
1369 cow_start = cur_offset;
1370 cur_offset = extent_end;
1371 if (cur_offset > end)
1377 btrfs_release_path(path);
1378 if (cow_start != (u64)-1) {
1379 ret = cow_file_range(inode, locked_page,
1380 cow_start, found_key.offset - 1,
1381 page_started, nr_written, 1);
1383 if (!nolock && nocow)
1384 btrfs_end_write_no_snapshoting(root);
1387 cow_start = (u64)-1;
1390 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1391 struct extent_map *em;
1392 struct extent_map_tree *em_tree;
1393 em_tree = &BTRFS_I(inode)->extent_tree;
1394 em = alloc_extent_map();
1395 BUG_ON(!em); /* -ENOMEM */
1396 em->start = cur_offset;
1397 em->orig_start = found_key.offset - extent_offset;
1398 em->len = num_bytes;
1399 em->block_len = num_bytes;
1400 em->block_start = disk_bytenr;
1401 em->orig_block_len = disk_num_bytes;
1402 em->ram_bytes = ram_bytes;
1403 em->bdev = root->fs_info->fs_devices->latest_bdev;
1404 em->mod_start = em->start;
1405 em->mod_len = em->len;
1406 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1407 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1408 em->generation = -1;
1410 write_lock(&em_tree->lock);
1411 ret = add_extent_mapping(em_tree, em, 1);
1412 write_unlock(&em_tree->lock);
1413 if (ret != -EEXIST) {
1414 free_extent_map(em);
1417 btrfs_drop_extent_cache(inode, em->start,
1418 em->start + em->len - 1, 0);
1420 type = BTRFS_ORDERED_PREALLOC;
1422 type = BTRFS_ORDERED_NOCOW;
1425 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1426 num_bytes, num_bytes, type);
1427 BUG_ON(ret); /* -ENOMEM */
1429 if (root->root_key.objectid ==
1430 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1431 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1434 if (!nolock && nocow)
1435 btrfs_end_write_no_snapshoting(root);
1440 extent_clear_unlock_delalloc(inode, cur_offset,
1441 cur_offset + num_bytes - 1,
1442 locked_page, EXTENT_LOCKED |
1443 EXTENT_DELALLOC, PAGE_UNLOCK |
1445 if (!nolock && nocow)
1446 btrfs_end_write_no_snapshoting(root);
1447 cur_offset = extent_end;
1448 if (cur_offset > end)
1451 btrfs_release_path(path);
1453 if (cur_offset <= end && cow_start == (u64)-1) {
1454 cow_start = cur_offset;
1458 if (cow_start != (u64)-1) {
1459 ret = cow_file_range(inode, locked_page, cow_start, end,
1460 page_started, nr_written, 1);
1466 err = btrfs_end_transaction(trans, root);
1470 if (ret && cur_offset < end)
1471 extent_clear_unlock_delalloc(inode, cur_offset, end,
1472 locked_page, EXTENT_LOCKED |
1473 EXTENT_DELALLOC | EXTENT_DEFRAG |
1474 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1476 PAGE_SET_WRITEBACK |
1477 PAGE_END_WRITEBACK);
1478 btrfs_free_path(path);
1482 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1485 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1486 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1490 * @defrag_bytes is a hint value, no spinlock held here,
1491 * if is not zero, it means the file is defragging.
1492 * Force cow if given extent needs to be defragged.
1494 if (BTRFS_I(inode)->defrag_bytes &&
1495 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1496 EXTENT_DEFRAG, 0, NULL))
1503 * extent_io.c call back to do delayed allocation processing
1505 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1506 u64 start, u64 end, int *page_started,
1507 unsigned long *nr_written)
1510 int force_cow = need_force_cow(inode, start, end);
1512 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1513 ret = run_delalloc_nocow(inode, locked_page, start, end,
1514 page_started, 1, nr_written);
1515 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1516 ret = run_delalloc_nocow(inode, locked_page, start, end,
1517 page_started, 0, nr_written);
1518 } else if (!inode_need_compress(inode)) {
1519 ret = cow_file_range(inode, locked_page, start, end,
1520 page_started, nr_written, 1);
1522 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1523 &BTRFS_I(inode)->runtime_flags);
1524 ret = cow_file_range_async(inode, locked_page, start, end,
1525 page_started, nr_written);
1530 static void btrfs_split_extent_hook(struct inode *inode,
1531 struct extent_state *orig, u64 split)
1535 /* not delalloc, ignore it */
1536 if (!(orig->state & EXTENT_DELALLOC))
1539 size = orig->end - orig->start + 1;
1540 if (size > BTRFS_MAX_EXTENT_SIZE) {
1545 * We need the largest size of the remaining extent to see if we
1546 * need to add a new outstanding extent. Think of the following
1549 * [MEAX_EXTENT_SIZEx2 - 4k][4k]
1551 * The new_size would just be 4k and we'd think we had enough
1552 * outstanding extents for this if we only took one side of the
1553 * split, same goes for the other direction. We need to see if
1554 * the larger size still is the same amount of extents as the
1555 * original size, because if it is we need to add a new
1556 * outstanding extent. But if we split up and the larger size
1557 * is less than the original then we are good to go since we've
1558 * already accounted for the extra extent in our original
1561 new_size = orig->end - split + 1;
1562 if ((split - orig->start) > new_size)
1563 new_size = split - orig->start;
1565 num_extents = div64_u64(size + BTRFS_MAX_EXTENT_SIZE - 1,
1566 BTRFS_MAX_EXTENT_SIZE);
1567 if (div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1568 BTRFS_MAX_EXTENT_SIZE) < num_extents)
1572 spin_lock(&BTRFS_I(inode)->lock);
1573 BTRFS_I(inode)->outstanding_extents++;
1574 spin_unlock(&BTRFS_I(inode)->lock);
1578 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1579 * extents so we can keep track of new extents that are just merged onto old
1580 * extents, such as when we are doing sequential writes, so we can properly
1581 * account for the metadata space we'll need.
1583 static void btrfs_merge_extent_hook(struct inode *inode,
1584 struct extent_state *new,
1585 struct extent_state *other)
1587 u64 new_size, old_size;
1590 /* not delalloc, ignore it */
1591 if (!(other->state & EXTENT_DELALLOC))
1594 old_size = other->end - other->start + 1;
1595 new_size = old_size + (new->end - new->start + 1);
1597 /* we're not bigger than the max, unreserve the space and go */
1598 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1599 spin_lock(&BTRFS_I(inode)->lock);
1600 BTRFS_I(inode)->outstanding_extents--;
1601 spin_unlock(&BTRFS_I(inode)->lock);
1606 * If we grew by another max_extent, just return, we want to keep that
1609 num_extents = div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1610 BTRFS_MAX_EXTENT_SIZE);
1611 if (div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1612 BTRFS_MAX_EXTENT_SIZE) > num_extents)
1615 spin_lock(&BTRFS_I(inode)->lock);
1616 BTRFS_I(inode)->outstanding_extents--;
1617 spin_unlock(&BTRFS_I(inode)->lock);
1620 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1621 struct inode *inode)
1623 spin_lock(&root->delalloc_lock);
1624 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1625 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1626 &root->delalloc_inodes);
1627 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1628 &BTRFS_I(inode)->runtime_flags);
1629 root->nr_delalloc_inodes++;
1630 if (root->nr_delalloc_inodes == 1) {
1631 spin_lock(&root->fs_info->delalloc_root_lock);
1632 BUG_ON(!list_empty(&root->delalloc_root));
1633 list_add_tail(&root->delalloc_root,
1634 &root->fs_info->delalloc_roots);
1635 spin_unlock(&root->fs_info->delalloc_root_lock);
1638 spin_unlock(&root->delalloc_lock);
1641 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1642 struct inode *inode)
1644 spin_lock(&root->delalloc_lock);
1645 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1646 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1647 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1648 &BTRFS_I(inode)->runtime_flags);
1649 root->nr_delalloc_inodes--;
1650 if (!root->nr_delalloc_inodes) {
1651 spin_lock(&root->fs_info->delalloc_root_lock);
1652 BUG_ON(list_empty(&root->delalloc_root));
1653 list_del_init(&root->delalloc_root);
1654 spin_unlock(&root->fs_info->delalloc_root_lock);
1657 spin_unlock(&root->delalloc_lock);
1661 * extent_io.c set_bit_hook, used to track delayed allocation
1662 * bytes in this file, and to maintain the list of inodes that
1663 * have pending delalloc work to be done.
1665 static void btrfs_set_bit_hook(struct inode *inode,
1666 struct extent_state *state, unsigned *bits)
1669 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1672 * set_bit and clear bit hooks normally require _irqsave/restore
1673 * but in this case, we are only testing for the DELALLOC
1674 * bit, which is only set or cleared with irqs on
1676 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1677 struct btrfs_root *root = BTRFS_I(inode)->root;
1678 u64 len = state->end + 1 - state->start;
1679 bool do_list = !btrfs_is_free_space_inode(inode);
1681 if (*bits & EXTENT_FIRST_DELALLOC) {
1682 *bits &= ~EXTENT_FIRST_DELALLOC;
1684 spin_lock(&BTRFS_I(inode)->lock);
1685 BTRFS_I(inode)->outstanding_extents++;
1686 spin_unlock(&BTRFS_I(inode)->lock);
1689 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1690 root->fs_info->delalloc_batch);
1691 spin_lock(&BTRFS_I(inode)->lock);
1692 BTRFS_I(inode)->delalloc_bytes += len;
1693 if (*bits & EXTENT_DEFRAG)
1694 BTRFS_I(inode)->defrag_bytes += len;
1695 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1696 &BTRFS_I(inode)->runtime_flags))
1697 btrfs_add_delalloc_inodes(root, inode);
1698 spin_unlock(&BTRFS_I(inode)->lock);
1703 * extent_io.c clear_bit_hook, see set_bit_hook for why
1705 static void btrfs_clear_bit_hook(struct inode *inode,
1706 struct extent_state *state,
1709 u64 len = state->end + 1 - state->start;
1710 u64 num_extents = div64_u64(len + BTRFS_MAX_EXTENT_SIZE -1,
1711 BTRFS_MAX_EXTENT_SIZE);
1713 spin_lock(&BTRFS_I(inode)->lock);
1714 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1715 BTRFS_I(inode)->defrag_bytes -= len;
1716 spin_unlock(&BTRFS_I(inode)->lock);
1719 * set_bit and clear bit hooks normally require _irqsave/restore
1720 * but in this case, we are only testing for the DELALLOC
1721 * bit, which is only set or cleared with irqs on
1723 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1724 struct btrfs_root *root = BTRFS_I(inode)->root;
1725 bool do_list = !btrfs_is_free_space_inode(inode);
1727 if (*bits & EXTENT_FIRST_DELALLOC) {
1728 *bits &= ~EXTENT_FIRST_DELALLOC;
1729 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1730 spin_lock(&BTRFS_I(inode)->lock);
1731 BTRFS_I(inode)->outstanding_extents -= num_extents;
1732 spin_unlock(&BTRFS_I(inode)->lock);
1736 * We don't reserve metadata space for space cache inodes so we
1737 * don't need to call dellalloc_release_metadata if there is an
1740 if (*bits & EXTENT_DO_ACCOUNTING &&
1741 root != root->fs_info->tree_root)
1742 btrfs_delalloc_release_metadata(inode, len);
1744 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1745 && do_list && !(state->state & EXTENT_NORESERVE))
1746 btrfs_free_reserved_data_space(inode, len);
1748 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1749 root->fs_info->delalloc_batch);
1750 spin_lock(&BTRFS_I(inode)->lock);
1751 BTRFS_I(inode)->delalloc_bytes -= len;
1752 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1753 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1754 &BTRFS_I(inode)->runtime_flags))
1755 btrfs_del_delalloc_inode(root, inode);
1756 spin_unlock(&BTRFS_I(inode)->lock);
1761 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1762 * we don't create bios that span stripes or chunks
1764 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1765 size_t size, struct bio *bio,
1766 unsigned long bio_flags)
1768 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1769 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1774 if (bio_flags & EXTENT_BIO_COMPRESSED)
1777 length = bio->bi_iter.bi_size;
1778 map_length = length;
1779 ret = btrfs_map_block(root->fs_info, rw, logical,
1780 &map_length, NULL, 0);
1781 /* Will always return 0 with map_multi == NULL */
1783 if (map_length < length + size)
1789 * in order to insert checksums into the metadata in large chunks,
1790 * we wait until bio submission time. All the pages in the bio are
1791 * checksummed and sums are attached onto the ordered extent record.
1793 * At IO completion time the cums attached on the ordered extent record
1794 * are inserted into the btree
1796 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1797 struct bio *bio, int mirror_num,
1798 unsigned long bio_flags,
1801 struct btrfs_root *root = BTRFS_I(inode)->root;
1804 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1805 BUG_ON(ret); /* -ENOMEM */
1810 * in order to insert checksums into the metadata in large chunks,
1811 * we wait until bio submission time. All the pages in the bio are
1812 * checksummed and sums are attached onto the ordered extent record.
1814 * At IO completion time the cums attached on the ordered extent record
1815 * are inserted into the btree
1817 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1818 int mirror_num, unsigned long bio_flags,
1821 struct btrfs_root *root = BTRFS_I(inode)->root;
1824 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1826 bio_endio(bio, ret);
1831 * extent_io.c submission hook. This does the right thing for csum calculation
1832 * on write, or reading the csums from the tree before a read
1834 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1835 int mirror_num, unsigned long bio_flags,
1838 struct btrfs_root *root = BTRFS_I(inode)->root;
1842 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1844 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1846 if (btrfs_is_free_space_inode(inode))
1849 if (!(rw & REQ_WRITE)) {
1850 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1854 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1855 ret = btrfs_submit_compressed_read(inode, bio,
1859 } else if (!skip_sum) {
1860 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1865 } else if (async && !skip_sum) {
1866 /* csum items have already been cloned */
1867 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1869 /* we're doing a write, do the async checksumming */
1870 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1871 inode, rw, bio, mirror_num,
1872 bio_flags, bio_offset,
1873 __btrfs_submit_bio_start,
1874 __btrfs_submit_bio_done);
1876 } else if (!skip_sum) {
1877 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1883 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1887 bio_endio(bio, ret);
1892 * given a list of ordered sums record them in the inode. This happens
1893 * at IO completion time based on sums calculated at bio submission time.
1895 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1896 struct inode *inode, u64 file_offset,
1897 struct list_head *list)
1899 struct btrfs_ordered_sum *sum;
1901 list_for_each_entry(sum, list, list) {
1902 trans->adding_csums = 1;
1903 btrfs_csum_file_blocks(trans,
1904 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1905 trans->adding_csums = 0;
1910 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1911 struct extent_state **cached_state)
1913 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1914 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1915 cached_state, GFP_NOFS);
1918 /* see btrfs_writepage_start_hook for details on why this is required */
1919 struct btrfs_writepage_fixup {
1921 struct btrfs_work work;
1924 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1926 struct btrfs_writepage_fixup *fixup;
1927 struct btrfs_ordered_extent *ordered;
1928 struct extent_state *cached_state = NULL;
1930 struct inode *inode;
1935 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1939 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1940 ClearPageChecked(page);
1944 inode = page->mapping->host;
1945 page_start = page_offset(page);
1946 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1948 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1951 /* already ordered? We're done */
1952 if (PagePrivate2(page))
1955 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1957 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1958 page_end, &cached_state, GFP_NOFS);
1960 btrfs_start_ordered_extent(inode, ordered, 1);
1961 btrfs_put_ordered_extent(ordered);
1965 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1967 mapping_set_error(page->mapping, ret);
1968 end_extent_writepage(page, ret, page_start, page_end);
1969 ClearPageChecked(page);
1973 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1974 ClearPageChecked(page);
1975 set_page_dirty(page);
1977 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1978 &cached_state, GFP_NOFS);
1981 page_cache_release(page);
1986 * There are a few paths in the higher layers of the kernel that directly
1987 * set the page dirty bit without asking the filesystem if it is a
1988 * good idea. This causes problems because we want to make sure COW
1989 * properly happens and the data=ordered rules are followed.
1991 * In our case any range that doesn't have the ORDERED bit set
1992 * hasn't been properly setup for IO. We kick off an async process
1993 * to fix it up. The async helper will wait for ordered extents, set
1994 * the delalloc bit and make it safe to write the page.
1996 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1998 struct inode *inode = page->mapping->host;
1999 struct btrfs_writepage_fixup *fixup;
2000 struct btrfs_root *root = BTRFS_I(inode)->root;
2002 /* this page is properly in the ordered list */
2003 if (TestClearPagePrivate2(page))
2006 if (PageChecked(page))
2009 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2013 SetPageChecked(page);
2014 page_cache_get(page);
2015 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2016 btrfs_writepage_fixup_worker, NULL, NULL);
2018 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
2022 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2023 struct inode *inode, u64 file_pos,
2024 u64 disk_bytenr, u64 disk_num_bytes,
2025 u64 num_bytes, u64 ram_bytes,
2026 u8 compression, u8 encryption,
2027 u16 other_encoding, int extent_type)
2029 struct btrfs_root *root = BTRFS_I(inode)->root;
2030 struct btrfs_file_extent_item *fi;
2031 struct btrfs_path *path;
2032 struct extent_buffer *leaf;
2033 struct btrfs_key ins;
2034 int extent_inserted = 0;
2037 path = btrfs_alloc_path();
2042 * we may be replacing one extent in the tree with another.
2043 * The new extent is pinned in the extent map, and we don't want
2044 * to drop it from the cache until it is completely in the btree.
2046 * So, tell btrfs_drop_extents to leave this extent in the cache.
2047 * the caller is expected to unpin it and allow it to be merged
2050 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2051 file_pos + num_bytes, NULL, 0,
2052 1, sizeof(*fi), &extent_inserted);
2056 if (!extent_inserted) {
2057 ins.objectid = btrfs_ino(inode);
2058 ins.offset = file_pos;
2059 ins.type = BTRFS_EXTENT_DATA_KEY;
2061 path->leave_spinning = 1;
2062 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2067 leaf = path->nodes[0];
2068 fi = btrfs_item_ptr(leaf, path->slots[0],
2069 struct btrfs_file_extent_item);
2070 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2071 btrfs_set_file_extent_type(leaf, fi, extent_type);
2072 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2073 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2074 btrfs_set_file_extent_offset(leaf, fi, 0);
2075 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2076 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2077 btrfs_set_file_extent_compression(leaf, fi, compression);
2078 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2079 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2081 btrfs_mark_buffer_dirty(leaf);
2082 btrfs_release_path(path);
2084 inode_add_bytes(inode, num_bytes);
2086 ins.objectid = disk_bytenr;
2087 ins.offset = disk_num_bytes;
2088 ins.type = BTRFS_EXTENT_ITEM_KEY;
2089 ret = btrfs_alloc_reserved_file_extent(trans, root,
2090 root->root_key.objectid,
2091 btrfs_ino(inode), file_pos, &ins);
2093 btrfs_free_path(path);
2098 /* snapshot-aware defrag */
2099 struct sa_defrag_extent_backref {
2100 struct rb_node node;
2101 struct old_sa_defrag_extent *old;
2110 struct old_sa_defrag_extent {
2111 struct list_head list;
2112 struct new_sa_defrag_extent *new;
2121 struct new_sa_defrag_extent {
2122 struct rb_root root;
2123 struct list_head head;
2124 struct btrfs_path *path;
2125 struct inode *inode;
2133 static int backref_comp(struct sa_defrag_extent_backref *b1,
2134 struct sa_defrag_extent_backref *b2)
2136 if (b1->root_id < b2->root_id)
2138 else if (b1->root_id > b2->root_id)
2141 if (b1->inum < b2->inum)
2143 else if (b1->inum > b2->inum)
2146 if (b1->file_pos < b2->file_pos)
2148 else if (b1->file_pos > b2->file_pos)
2152 * [------------------------------] ===> (a range of space)
2153 * |<--->| |<---->| =============> (fs/file tree A)
2154 * |<---------------------------->| ===> (fs/file tree B)
2156 * A range of space can refer to two file extents in one tree while
2157 * refer to only one file extent in another tree.
2159 * So we may process a disk offset more than one time(two extents in A)
2160 * and locate at the same extent(one extent in B), then insert two same
2161 * backrefs(both refer to the extent in B).
2166 static void backref_insert(struct rb_root *root,
2167 struct sa_defrag_extent_backref *backref)
2169 struct rb_node **p = &root->rb_node;
2170 struct rb_node *parent = NULL;
2171 struct sa_defrag_extent_backref *entry;
2176 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2178 ret = backref_comp(backref, entry);
2182 p = &(*p)->rb_right;
2185 rb_link_node(&backref->node, parent, p);
2186 rb_insert_color(&backref->node, root);
2190 * Note the backref might has changed, and in this case we just return 0.
2192 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2195 struct btrfs_file_extent_item *extent;
2196 struct btrfs_fs_info *fs_info;
2197 struct old_sa_defrag_extent *old = ctx;
2198 struct new_sa_defrag_extent *new = old->new;
2199 struct btrfs_path *path = new->path;
2200 struct btrfs_key key;
2201 struct btrfs_root *root;
2202 struct sa_defrag_extent_backref *backref;
2203 struct extent_buffer *leaf;
2204 struct inode *inode = new->inode;
2210 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2211 inum == btrfs_ino(inode))
2214 key.objectid = root_id;
2215 key.type = BTRFS_ROOT_ITEM_KEY;
2216 key.offset = (u64)-1;
2218 fs_info = BTRFS_I(inode)->root->fs_info;
2219 root = btrfs_read_fs_root_no_name(fs_info, &key);
2221 if (PTR_ERR(root) == -ENOENT)
2224 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2225 inum, offset, root_id);
2226 return PTR_ERR(root);
2229 key.objectid = inum;
2230 key.type = BTRFS_EXTENT_DATA_KEY;
2231 if (offset > (u64)-1 << 32)
2234 key.offset = offset;
2236 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2237 if (WARN_ON(ret < 0))
2244 leaf = path->nodes[0];
2245 slot = path->slots[0];
2247 if (slot >= btrfs_header_nritems(leaf)) {
2248 ret = btrfs_next_leaf(root, path);
2251 } else if (ret > 0) {
2260 btrfs_item_key_to_cpu(leaf, &key, slot);
2262 if (key.objectid > inum)
2265 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2268 extent = btrfs_item_ptr(leaf, slot,
2269 struct btrfs_file_extent_item);
2271 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2275 * 'offset' refers to the exact key.offset,
2276 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2277 * (key.offset - extent_offset).
2279 if (key.offset != offset)
2282 extent_offset = btrfs_file_extent_offset(leaf, extent);
2283 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2285 if (extent_offset >= old->extent_offset + old->offset +
2286 old->len || extent_offset + num_bytes <=
2287 old->extent_offset + old->offset)
2292 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2298 backref->root_id = root_id;
2299 backref->inum = inum;
2300 backref->file_pos = offset;
2301 backref->num_bytes = num_bytes;
2302 backref->extent_offset = extent_offset;
2303 backref->generation = btrfs_file_extent_generation(leaf, extent);
2305 backref_insert(&new->root, backref);
2308 btrfs_release_path(path);
2313 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2314 struct new_sa_defrag_extent *new)
2316 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2317 struct old_sa_defrag_extent *old, *tmp;
2322 list_for_each_entry_safe(old, tmp, &new->head, list) {
2323 ret = iterate_inodes_from_logical(old->bytenr +
2324 old->extent_offset, fs_info,
2325 path, record_one_backref,
2327 if (ret < 0 && ret != -ENOENT)
2330 /* no backref to be processed for this extent */
2332 list_del(&old->list);
2337 if (list_empty(&new->head))
2343 static int relink_is_mergable(struct extent_buffer *leaf,
2344 struct btrfs_file_extent_item *fi,
2345 struct new_sa_defrag_extent *new)
2347 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2350 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2353 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2356 if (btrfs_file_extent_encryption(leaf, fi) ||
2357 btrfs_file_extent_other_encoding(leaf, fi))
2364 * Note the backref might has changed, and in this case we just return 0.
2366 static noinline int relink_extent_backref(struct btrfs_path *path,
2367 struct sa_defrag_extent_backref *prev,
2368 struct sa_defrag_extent_backref *backref)
2370 struct btrfs_file_extent_item *extent;
2371 struct btrfs_file_extent_item *item;
2372 struct btrfs_ordered_extent *ordered;
2373 struct btrfs_trans_handle *trans;
2374 struct btrfs_fs_info *fs_info;
2375 struct btrfs_root *root;
2376 struct btrfs_key key;
2377 struct extent_buffer *leaf;
2378 struct old_sa_defrag_extent *old = backref->old;
2379 struct new_sa_defrag_extent *new = old->new;
2380 struct inode *src_inode = new->inode;
2381 struct inode *inode;
2382 struct extent_state *cached = NULL;
2391 if (prev && prev->root_id == backref->root_id &&
2392 prev->inum == backref->inum &&
2393 prev->file_pos + prev->num_bytes == backref->file_pos)
2396 /* step 1: get root */
2397 key.objectid = backref->root_id;
2398 key.type = BTRFS_ROOT_ITEM_KEY;
2399 key.offset = (u64)-1;
2401 fs_info = BTRFS_I(src_inode)->root->fs_info;
2402 index = srcu_read_lock(&fs_info->subvol_srcu);
2404 root = btrfs_read_fs_root_no_name(fs_info, &key);
2406 srcu_read_unlock(&fs_info->subvol_srcu, index);
2407 if (PTR_ERR(root) == -ENOENT)
2409 return PTR_ERR(root);
2412 if (btrfs_root_readonly(root)) {
2413 srcu_read_unlock(&fs_info->subvol_srcu, index);
2417 /* step 2: get inode */
2418 key.objectid = backref->inum;
2419 key.type = BTRFS_INODE_ITEM_KEY;
2422 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2423 if (IS_ERR(inode)) {
2424 srcu_read_unlock(&fs_info->subvol_srcu, index);
2428 srcu_read_unlock(&fs_info->subvol_srcu, index);
2430 /* step 3: relink backref */
2431 lock_start = backref->file_pos;
2432 lock_end = backref->file_pos + backref->num_bytes - 1;
2433 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2436 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2438 btrfs_put_ordered_extent(ordered);
2442 trans = btrfs_join_transaction(root);
2443 if (IS_ERR(trans)) {
2444 ret = PTR_ERR(trans);
2448 key.objectid = backref->inum;
2449 key.type = BTRFS_EXTENT_DATA_KEY;
2450 key.offset = backref->file_pos;
2452 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2455 } else if (ret > 0) {
2460 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2461 struct btrfs_file_extent_item);
2463 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2464 backref->generation)
2467 btrfs_release_path(path);
2469 start = backref->file_pos;
2470 if (backref->extent_offset < old->extent_offset + old->offset)
2471 start += old->extent_offset + old->offset -
2472 backref->extent_offset;
2474 len = min(backref->extent_offset + backref->num_bytes,
2475 old->extent_offset + old->offset + old->len);
2476 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2478 ret = btrfs_drop_extents(trans, root, inode, start,
2483 key.objectid = btrfs_ino(inode);
2484 key.type = BTRFS_EXTENT_DATA_KEY;
2487 path->leave_spinning = 1;
2489 struct btrfs_file_extent_item *fi;
2491 struct btrfs_key found_key;
2493 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2498 leaf = path->nodes[0];
2499 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2501 fi = btrfs_item_ptr(leaf, path->slots[0],
2502 struct btrfs_file_extent_item);
2503 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2505 if (extent_len + found_key.offset == start &&
2506 relink_is_mergable(leaf, fi, new)) {
2507 btrfs_set_file_extent_num_bytes(leaf, fi,
2509 btrfs_mark_buffer_dirty(leaf);
2510 inode_add_bytes(inode, len);
2516 btrfs_release_path(path);
2521 ret = btrfs_insert_empty_item(trans, root, path, &key,
2524 btrfs_abort_transaction(trans, root, ret);
2528 leaf = path->nodes[0];
2529 item = btrfs_item_ptr(leaf, path->slots[0],
2530 struct btrfs_file_extent_item);
2531 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2532 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2533 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2534 btrfs_set_file_extent_num_bytes(leaf, item, len);
2535 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2536 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2537 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2538 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2539 btrfs_set_file_extent_encryption(leaf, item, 0);
2540 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2542 btrfs_mark_buffer_dirty(leaf);
2543 inode_add_bytes(inode, len);
2544 btrfs_release_path(path);
2546 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2548 backref->root_id, backref->inum,
2549 new->file_pos, 0); /* start - extent_offset */
2551 btrfs_abort_transaction(trans, root, ret);
2557 btrfs_release_path(path);
2558 path->leave_spinning = 0;
2559 btrfs_end_transaction(trans, root);
2561 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2567 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2569 struct old_sa_defrag_extent *old, *tmp;
2574 list_for_each_entry_safe(old, tmp, &new->head, list) {
2575 list_del(&old->list);
2581 static void relink_file_extents(struct new_sa_defrag_extent *new)
2583 struct btrfs_path *path;
2584 struct sa_defrag_extent_backref *backref;
2585 struct sa_defrag_extent_backref *prev = NULL;
2586 struct inode *inode;
2587 struct btrfs_root *root;
2588 struct rb_node *node;
2592 root = BTRFS_I(inode)->root;
2594 path = btrfs_alloc_path();
2598 if (!record_extent_backrefs(path, new)) {
2599 btrfs_free_path(path);
2602 btrfs_release_path(path);
2605 node = rb_first(&new->root);
2608 rb_erase(node, &new->root);
2610 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2612 ret = relink_extent_backref(path, prev, backref);
2625 btrfs_free_path(path);
2627 free_sa_defrag_extent(new);
2629 atomic_dec(&root->fs_info->defrag_running);
2630 wake_up(&root->fs_info->transaction_wait);
2633 static struct new_sa_defrag_extent *
2634 record_old_file_extents(struct inode *inode,
2635 struct btrfs_ordered_extent *ordered)
2637 struct btrfs_root *root = BTRFS_I(inode)->root;
2638 struct btrfs_path *path;
2639 struct btrfs_key key;
2640 struct old_sa_defrag_extent *old;
2641 struct new_sa_defrag_extent *new;
2644 new = kmalloc(sizeof(*new), GFP_NOFS);
2649 new->file_pos = ordered->file_offset;
2650 new->len = ordered->len;
2651 new->bytenr = ordered->start;
2652 new->disk_len = ordered->disk_len;
2653 new->compress_type = ordered->compress_type;
2654 new->root = RB_ROOT;
2655 INIT_LIST_HEAD(&new->head);
2657 path = btrfs_alloc_path();
2661 key.objectid = btrfs_ino(inode);
2662 key.type = BTRFS_EXTENT_DATA_KEY;
2663 key.offset = new->file_pos;
2665 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2668 if (ret > 0 && path->slots[0] > 0)
2671 /* find out all the old extents for the file range */
2673 struct btrfs_file_extent_item *extent;
2674 struct extent_buffer *l;
2683 slot = path->slots[0];
2685 if (slot >= btrfs_header_nritems(l)) {
2686 ret = btrfs_next_leaf(root, path);
2694 btrfs_item_key_to_cpu(l, &key, slot);
2696 if (key.objectid != btrfs_ino(inode))
2698 if (key.type != BTRFS_EXTENT_DATA_KEY)
2700 if (key.offset >= new->file_pos + new->len)
2703 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2705 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2706 if (key.offset + num_bytes < new->file_pos)
2709 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2713 extent_offset = btrfs_file_extent_offset(l, extent);
2715 old = kmalloc(sizeof(*old), GFP_NOFS);
2719 offset = max(new->file_pos, key.offset);
2720 end = min(new->file_pos + new->len, key.offset + num_bytes);
2722 old->bytenr = disk_bytenr;
2723 old->extent_offset = extent_offset;
2724 old->offset = offset - key.offset;
2725 old->len = end - offset;
2728 list_add_tail(&old->list, &new->head);
2734 btrfs_free_path(path);
2735 atomic_inc(&root->fs_info->defrag_running);
2740 btrfs_free_path(path);
2742 free_sa_defrag_extent(new);
2746 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2749 struct btrfs_block_group_cache *cache;
2751 cache = btrfs_lookup_block_group(root->fs_info, start);
2754 spin_lock(&cache->lock);
2755 cache->delalloc_bytes -= len;
2756 spin_unlock(&cache->lock);
2758 btrfs_put_block_group(cache);
2761 /* as ordered data IO finishes, this gets called so we can finish
2762 * an ordered extent if the range of bytes in the file it covers are
2765 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2767 struct inode *inode = ordered_extent->inode;
2768 struct btrfs_root *root = BTRFS_I(inode)->root;
2769 struct btrfs_trans_handle *trans = NULL;
2770 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2771 struct extent_state *cached_state = NULL;
2772 struct new_sa_defrag_extent *new = NULL;
2773 int compress_type = 0;
2775 u64 logical_len = ordered_extent->len;
2777 bool truncated = false;
2779 nolock = btrfs_is_free_space_inode(inode);
2781 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2786 btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2787 ordered_extent->file_offset +
2788 ordered_extent->len - 1);
2790 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2792 logical_len = ordered_extent->truncated_len;
2793 /* Truncated the entire extent, don't bother adding */
2798 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2799 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2800 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2802 trans = btrfs_join_transaction_nolock(root);
2804 trans = btrfs_join_transaction(root);
2805 if (IS_ERR(trans)) {
2806 ret = PTR_ERR(trans);
2810 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2811 ret = btrfs_update_inode_fallback(trans, root, inode);
2812 if (ret) /* -ENOMEM or corruption */
2813 btrfs_abort_transaction(trans, root, ret);
2817 lock_extent_bits(io_tree, ordered_extent->file_offset,
2818 ordered_extent->file_offset + ordered_extent->len - 1,
2821 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2822 ordered_extent->file_offset + ordered_extent->len - 1,
2823 EXTENT_DEFRAG, 1, cached_state);
2825 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2826 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2827 /* the inode is shared */
2828 new = record_old_file_extents(inode, ordered_extent);
2830 clear_extent_bit(io_tree, ordered_extent->file_offset,
2831 ordered_extent->file_offset + ordered_extent->len - 1,
2832 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2836 trans = btrfs_join_transaction_nolock(root);
2838 trans = btrfs_join_transaction(root);
2839 if (IS_ERR(trans)) {
2840 ret = PTR_ERR(trans);
2845 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2847 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2848 compress_type = ordered_extent->compress_type;
2849 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2850 BUG_ON(compress_type);
2851 ret = btrfs_mark_extent_written(trans, inode,
2852 ordered_extent->file_offset,
2853 ordered_extent->file_offset +
2856 BUG_ON(root == root->fs_info->tree_root);
2857 ret = insert_reserved_file_extent(trans, inode,
2858 ordered_extent->file_offset,
2859 ordered_extent->start,
2860 ordered_extent->disk_len,
2861 logical_len, logical_len,
2862 compress_type, 0, 0,
2863 BTRFS_FILE_EXTENT_REG);
2865 btrfs_release_delalloc_bytes(root,
2866 ordered_extent->start,
2867 ordered_extent->disk_len);
2869 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2870 ordered_extent->file_offset, ordered_extent->len,
2873 btrfs_abort_transaction(trans, root, ret);
2877 add_pending_csums(trans, inode, ordered_extent->file_offset,
2878 &ordered_extent->list);
2880 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2881 ret = btrfs_update_inode_fallback(trans, root, inode);
2882 if (ret) { /* -ENOMEM or corruption */
2883 btrfs_abort_transaction(trans, root, ret);
2888 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2889 ordered_extent->file_offset +
2890 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2892 if (root != root->fs_info->tree_root)
2893 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2895 btrfs_end_transaction(trans, root);
2897 if (ret || truncated) {
2901 start = ordered_extent->file_offset + logical_len;
2903 start = ordered_extent->file_offset;
2904 end = ordered_extent->file_offset + ordered_extent->len - 1;
2905 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2907 /* Drop the cache for the part of the extent we didn't write. */
2908 btrfs_drop_extent_cache(inode, start, end, 0);
2911 * If the ordered extent had an IOERR or something else went
2912 * wrong we need to return the space for this ordered extent
2913 * back to the allocator. We only free the extent in the
2914 * truncated case if we didn't write out the extent at all.
2916 if ((ret || !logical_len) &&
2917 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2918 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2919 btrfs_free_reserved_extent(root, ordered_extent->start,
2920 ordered_extent->disk_len, 1);
2925 * This needs to be done to make sure anybody waiting knows we are done
2926 * updating everything for this ordered extent.
2928 btrfs_remove_ordered_extent(inode, ordered_extent);
2930 /* for snapshot-aware defrag */
2933 free_sa_defrag_extent(new);
2934 atomic_dec(&root->fs_info->defrag_running);
2936 relink_file_extents(new);
2941 btrfs_put_ordered_extent(ordered_extent);
2942 /* once for the tree */
2943 btrfs_put_ordered_extent(ordered_extent);
2948 static void finish_ordered_fn(struct btrfs_work *work)
2950 struct btrfs_ordered_extent *ordered_extent;
2951 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2952 btrfs_finish_ordered_io(ordered_extent);
2955 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2956 struct extent_state *state, int uptodate)
2958 struct inode *inode = page->mapping->host;
2959 struct btrfs_root *root = BTRFS_I(inode)->root;
2960 struct btrfs_ordered_extent *ordered_extent = NULL;
2961 struct btrfs_workqueue *wq;
2962 btrfs_work_func_t func;
2964 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2966 ClearPagePrivate2(page);
2967 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2968 end - start + 1, uptodate))
2971 if (btrfs_is_free_space_inode(inode)) {
2972 wq = root->fs_info->endio_freespace_worker;
2973 func = btrfs_freespace_write_helper;
2975 wq = root->fs_info->endio_write_workers;
2976 func = btrfs_endio_write_helper;
2979 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
2981 btrfs_queue_work(wq, &ordered_extent->work);
2986 static int __readpage_endio_check(struct inode *inode,
2987 struct btrfs_io_bio *io_bio,
2988 int icsum, struct page *page,
2989 int pgoff, u64 start, size_t len)
2994 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2995 DEFAULT_RATELIMIT_BURST);
2997 csum_expected = *(((u32 *)io_bio->csum) + icsum);
2999 kaddr = kmap_atomic(page);
3000 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3001 btrfs_csum_final(csum, (char *)&csum);
3002 if (csum != csum_expected)
3005 kunmap_atomic(kaddr);
3008 if (__ratelimit(&_rs))
3009 btrfs_warn(BTRFS_I(inode)->root->fs_info,
3010 "csum failed ino %llu off %llu csum %u expected csum %u",
3011 btrfs_ino(inode), start, csum, csum_expected);
3012 memset(kaddr + pgoff, 1, len);
3013 flush_dcache_page(page);
3014 kunmap_atomic(kaddr);
3015 if (csum_expected == 0)
3021 * when reads are done, we need to check csums to verify the data is correct
3022 * if there's a match, we allow the bio to finish. If not, the code in
3023 * extent_io.c will try to find good copies for us.
3025 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3026 u64 phy_offset, struct page *page,
3027 u64 start, u64 end, int mirror)
3029 size_t offset = start - page_offset(page);
3030 struct inode *inode = page->mapping->host;
3031 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3032 struct btrfs_root *root = BTRFS_I(inode)->root;
3034 if (PageChecked(page)) {
3035 ClearPageChecked(page);
3039 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3042 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3043 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3044 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
3049 phy_offset >>= inode->i_sb->s_blocksize_bits;
3050 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3051 start, (size_t)(end - start + 1));
3054 struct delayed_iput {
3055 struct list_head list;
3056 struct inode *inode;
3059 /* JDM: If this is fs-wide, why can't we add a pointer to
3060 * btrfs_inode instead and avoid the allocation? */
3061 void btrfs_add_delayed_iput(struct inode *inode)
3063 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3064 struct delayed_iput *delayed;
3066 if (atomic_add_unless(&inode->i_count, -1, 1))
3069 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
3070 delayed->inode = inode;
3072 spin_lock(&fs_info->delayed_iput_lock);
3073 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
3074 spin_unlock(&fs_info->delayed_iput_lock);
3077 void btrfs_run_delayed_iputs(struct btrfs_root *root)
3080 struct btrfs_fs_info *fs_info = root->fs_info;
3081 struct delayed_iput *delayed;
3084 spin_lock(&fs_info->delayed_iput_lock);
3085 empty = list_empty(&fs_info->delayed_iputs);
3086 spin_unlock(&fs_info->delayed_iput_lock);
3090 spin_lock(&fs_info->delayed_iput_lock);
3091 list_splice_init(&fs_info->delayed_iputs, &list);
3092 spin_unlock(&fs_info->delayed_iput_lock);
3094 while (!list_empty(&list)) {
3095 delayed = list_entry(list.next, struct delayed_iput, list);
3096 list_del(&delayed->list);
3097 iput(delayed->inode);
3103 * This is called in transaction commit time. If there are no orphan
3104 * files in the subvolume, it removes orphan item and frees block_rsv
3107 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3108 struct btrfs_root *root)
3110 struct btrfs_block_rsv *block_rsv;
3113 if (atomic_read(&root->orphan_inodes) ||
3114 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3117 spin_lock(&root->orphan_lock);
3118 if (atomic_read(&root->orphan_inodes)) {
3119 spin_unlock(&root->orphan_lock);
3123 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3124 spin_unlock(&root->orphan_lock);
3128 block_rsv = root->orphan_block_rsv;
3129 root->orphan_block_rsv = NULL;
3130 spin_unlock(&root->orphan_lock);
3132 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3133 btrfs_root_refs(&root->root_item) > 0) {
3134 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
3135 root->root_key.objectid);
3137 btrfs_abort_transaction(trans, root, ret);
3139 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3144 WARN_ON(block_rsv->size > 0);
3145 btrfs_free_block_rsv(root, block_rsv);
3150 * This creates an orphan entry for the given inode in case something goes
3151 * wrong in the middle of an unlink/truncate.
3153 * NOTE: caller of this function should reserve 5 units of metadata for
3156 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3158 struct btrfs_root *root = BTRFS_I(inode)->root;
3159 struct btrfs_block_rsv *block_rsv = NULL;
3164 if (!root->orphan_block_rsv) {
3165 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3170 spin_lock(&root->orphan_lock);
3171 if (!root->orphan_block_rsv) {
3172 root->orphan_block_rsv = block_rsv;
3173 } else if (block_rsv) {
3174 btrfs_free_block_rsv(root, block_rsv);
3178 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3179 &BTRFS_I(inode)->runtime_flags)) {
3182 * For proper ENOSPC handling, we should do orphan
3183 * cleanup when mounting. But this introduces backward
3184 * compatibility issue.
3186 if (!xchg(&root->orphan_item_inserted, 1))
3192 atomic_inc(&root->orphan_inodes);
3195 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3196 &BTRFS_I(inode)->runtime_flags))
3198 spin_unlock(&root->orphan_lock);
3200 /* grab metadata reservation from transaction handle */
3202 ret = btrfs_orphan_reserve_metadata(trans, inode);
3203 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3206 /* insert an orphan item to track this unlinked/truncated file */
3208 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3210 atomic_dec(&root->orphan_inodes);
3212 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3213 &BTRFS_I(inode)->runtime_flags);
3214 btrfs_orphan_release_metadata(inode);
3216 if (ret != -EEXIST) {
3217 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3218 &BTRFS_I(inode)->runtime_flags);
3219 btrfs_abort_transaction(trans, root, ret);
3226 /* insert an orphan item to track subvolume contains orphan files */
3228 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3229 root->root_key.objectid);
3230 if (ret && ret != -EEXIST) {
3231 btrfs_abort_transaction(trans, root, ret);
3239 * We have done the truncate/delete so we can go ahead and remove the orphan
3240 * item for this particular inode.
3242 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3243 struct inode *inode)
3245 struct btrfs_root *root = BTRFS_I(inode)->root;
3246 int delete_item = 0;
3247 int release_rsv = 0;
3250 spin_lock(&root->orphan_lock);
3251 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3252 &BTRFS_I(inode)->runtime_flags))
3255 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3256 &BTRFS_I(inode)->runtime_flags))
3258 spin_unlock(&root->orphan_lock);
3261 atomic_dec(&root->orphan_inodes);
3263 ret = btrfs_del_orphan_item(trans, root,
3268 btrfs_orphan_release_metadata(inode);
3274 * this cleans up any orphans that may be left on the list from the last use
3277 int btrfs_orphan_cleanup(struct btrfs_root *root)
3279 struct btrfs_path *path;
3280 struct extent_buffer *leaf;
3281 struct btrfs_key key, found_key;
3282 struct btrfs_trans_handle *trans;
3283 struct inode *inode;
3284 u64 last_objectid = 0;
3285 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3287 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3290 path = btrfs_alloc_path();
3297 key.objectid = BTRFS_ORPHAN_OBJECTID;
3298 key.type = BTRFS_ORPHAN_ITEM_KEY;
3299 key.offset = (u64)-1;
3302 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3307 * if ret == 0 means we found what we were searching for, which
3308 * is weird, but possible, so only screw with path if we didn't
3309 * find the key and see if we have stuff that matches
3313 if (path->slots[0] == 0)
3318 /* pull out the item */
3319 leaf = path->nodes[0];
3320 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3322 /* make sure the item matches what we want */
3323 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3325 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3328 /* release the path since we're done with it */
3329 btrfs_release_path(path);
3332 * this is where we are basically btrfs_lookup, without the
3333 * crossing root thing. we store the inode number in the
3334 * offset of the orphan item.
3337 if (found_key.offset == last_objectid) {
3338 btrfs_err(root->fs_info,
3339 "Error removing orphan entry, stopping orphan cleanup");
3344 last_objectid = found_key.offset;
3346 found_key.objectid = found_key.offset;
3347 found_key.type = BTRFS_INODE_ITEM_KEY;
3348 found_key.offset = 0;
3349 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3350 ret = PTR_ERR_OR_ZERO(inode);
3351 if (ret && ret != -ESTALE)
3354 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3355 struct btrfs_root *dead_root;
3356 struct btrfs_fs_info *fs_info = root->fs_info;
3357 int is_dead_root = 0;
3360 * this is an orphan in the tree root. Currently these
3361 * could come from 2 sources:
3362 * a) a snapshot deletion in progress
3363 * b) a free space cache inode
3364 * We need to distinguish those two, as the snapshot
3365 * orphan must not get deleted.
3366 * find_dead_roots already ran before us, so if this
3367 * is a snapshot deletion, we should find the root
3368 * in the dead_roots list
3370 spin_lock(&fs_info->trans_lock);
3371 list_for_each_entry(dead_root, &fs_info->dead_roots,
3373 if (dead_root->root_key.objectid ==
3374 found_key.objectid) {
3379 spin_unlock(&fs_info->trans_lock);
3381 /* prevent this orphan from being found again */
3382 key.offset = found_key.objectid - 1;
3387 * Inode is already gone but the orphan item is still there,
3388 * kill the orphan item.
3390 if (ret == -ESTALE) {
3391 trans = btrfs_start_transaction(root, 1);
3392 if (IS_ERR(trans)) {
3393 ret = PTR_ERR(trans);
3396 btrfs_debug(root->fs_info, "auto deleting %Lu",
3397 found_key.objectid);
3398 ret = btrfs_del_orphan_item(trans, root,
3399 found_key.objectid);
3400 btrfs_end_transaction(trans, root);
3407 * add this inode to the orphan list so btrfs_orphan_del does
3408 * the proper thing when we hit it
3410 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3411 &BTRFS_I(inode)->runtime_flags);
3412 atomic_inc(&root->orphan_inodes);
3414 /* if we have links, this was a truncate, lets do that */
3415 if (inode->i_nlink) {
3416 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3422 /* 1 for the orphan item deletion. */
3423 trans = btrfs_start_transaction(root, 1);
3424 if (IS_ERR(trans)) {
3426 ret = PTR_ERR(trans);
3429 ret = btrfs_orphan_add(trans, inode);
3430 btrfs_end_transaction(trans, root);
3436 ret = btrfs_truncate(inode);
3438 btrfs_orphan_del(NULL, inode);
3443 /* this will do delete_inode and everything for us */
3448 /* release the path since we're done with it */
3449 btrfs_release_path(path);
3451 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3453 if (root->orphan_block_rsv)
3454 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3457 if (root->orphan_block_rsv ||
3458 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3459 trans = btrfs_join_transaction(root);
3461 btrfs_end_transaction(trans, root);
3465 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3467 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3471 btrfs_err(root->fs_info,
3472 "could not do orphan cleanup %d", ret);
3473 btrfs_free_path(path);
3478 * very simple check to peek ahead in the leaf looking for xattrs. If we
3479 * don't find any xattrs, we know there can't be any acls.
3481 * slot is the slot the inode is in, objectid is the objectid of the inode
3483 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3484 int slot, u64 objectid,
3485 int *first_xattr_slot)
3487 u32 nritems = btrfs_header_nritems(leaf);
3488 struct btrfs_key found_key;
3489 static u64 xattr_access = 0;
3490 static u64 xattr_default = 0;
3493 if (!xattr_access) {
3494 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3495 strlen(POSIX_ACL_XATTR_ACCESS));
3496 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3497 strlen(POSIX_ACL_XATTR_DEFAULT));
3501 *first_xattr_slot = -1;
3502 while (slot < nritems) {
3503 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3505 /* we found a different objectid, there must not be acls */
3506 if (found_key.objectid != objectid)
3509 /* we found an xattr, assume we've got an acl */
3510 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3511 if (*first_xattr_slot == -1)
3512 *first_xattr_slot = slot;
3513 if (found_key.offset == xattr_access ||
3514 found_key.offset == xattr_default)
3519 * we found a key greater than an xattr key, there can't
3520 * be any acls later on
3522 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3529 * it goes inode, inode backrefs, xattrs, extents,
3530 * so if there are a ton of hard links to an inode there can
3531 * be a lot of backrefs. Don't waste time searching too hard,
3532 * this is just an optimization
3537 /* we hit the end of the leaf before we found an xattr or
3538 * something larger than an xattr. We have to assume the inode
3541 if (*first_xattr_slot == -1)
3542 *first_xattr_slot = slot;
3547 * read an inode from the btree into the in-memory inode
3549 static void btrfs_read_locked_inode(struct inode *inode)
3551 struct btrfs_path *path;
3552 struct extent_buffer *leaf;
3553 struct btrfs_inode_item *inode_item;
3554 struct btrfs_root *root = BTRFS_I(inode)->root;
3555 struct btrfs_key location;
3560 bool filled = false;
3561 int first_xattr_slot;
3563 ret = btrfs_fill_inode(inode, &rdev);
3567 path = btrfs_alloc_path();
3571 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3573 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3577 leaf = path->nodes[0];
3582 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3583 struct btrfs_inode_item);
3584 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3585 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3586 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3587 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3588 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3590 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3591 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3593 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3594 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3596 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3597 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3599 BTRFS_I(inode)->i_otime.tv_sec =
3600 btrfs_timespec_sec(leaf, &inode_item->otime);
3601 BTRFS_I(inode)->i_otime.tv_nsec =
3602 btrfs_timespec_nsec(leaf, &inode_item->otime);
3604 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3605 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3606 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3609 * If we were modified in the current generation and evicted from memory
3610 * and then re-read we need to do a full sync since we don't have any
3611 * idea about which extents were modified before we were evicted from
3614 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3615 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3616 &BTRFS_I(inode)->runtime_flags);
3618 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3619 inode->i_generation = BTRFS_I(inode)->generation;
3621 rdev = btrfs_inode_rdev(leaf, inode_item);
3623 BTRFS_I(inode)->index_cnt = (u64)-1;
3624 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3628 if (inode->i_nlink != 1 ||
3629 path->slots[0] >= btrfs_header_nritems(leaf))
3632 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3633 if (location.objectid != btrfs_ino(inode))
3636 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3637 if (location.type == BTRFS_INODE_REF_KEY) {
3638 struct btrfs_inode_ref *ref;
3640 ref = (struct btrfs_inode_ref *)ptr;
3641 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3642 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3643 struct btrfs_inode_extref *extref;
3645 extref = (struct btrfs_inode_extref *)ptr;
3646 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3651 * try to precache a NULL acl entry for files that don't have
3652 * any xattrs or acls
3654 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3655 btrfs_ino(inode), &first_xattr_slot);
3656 if (first_xattr_slot != -1) {
3657 path->slots[0] = first_xattr_slot;
3658 ret = btrfs_load_inode_props(inode, path);
3660 btrfs_err(root->fs_info,
3661 "error loading props for ino %llu (root %llu): %d",
3663 root->root_key.objectid, ret);
3665 btrfs_free_path(path);
3668 cache_no_acl(inode);
3670 switch (inode->i_mode & S_IFMT) {
3672 inode->i_mapping->a_ops = &btrfs_aops;
3673 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3674 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3675 inode->i_fop = &btrfs_file_operations;
3676 inode->i_op = &btrfs_file_inode_operations;
3679 inode->i_fop = &btrfs_dir_file_operations;
3680 if (root == root->fs_info->tree_root)
3681 inode->i_op = &btrfs_dir_ro_inode_operations;
3683 inode->i_op = &btrfs_dir_inode_operations;
3686 inode->i_op = &btrfs_symlink_inode_operations;
3687 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3688 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3691 inode->i_op = &btrfs_special_inode_operations;
3692 init_special_inode(inode, inode->i_mode, rdev);
3696 btrfs_update_iflags(inode);
3700 btrfs_free_path(path);
3701 make_bad_inode(inode);
3705 * given a leaf and an inode, copy the inode fields into the leaf
3707 static void fill_inode_item(struct btrfs_trans_handle *trans,
3708 struct extent_buffer *leaf,
3709 struct btrfs_inode_item *item,
3710 struct inode *inode)
3712 struct btrfs_map_token token;
3714 btrfs_init_map_token(&token);
3716 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3717 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3718 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3720 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3721 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3723 btrfs_set_token_timespec_sec(leaf, &item->atime,
3724 inode->i_atime.tv_sec, &token);
3725 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3726 inode->i_atime.tv_nsec, &token);
3728 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3729 inode->i_mtime.tv_sec, &token);
3730 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3731 inode->i_mtime.tv_nsec, &token);
3733 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3734 inode->i_ctime.tv_sec, &token);
3735 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3736 inode->i_ctime.tv_nsec, &token);
3738 btrfs_set_token_timespec_sec(leaf, &item->otime,
3739 BTRFS_I(inode)->i_otime.tv_sec, &token);
3740 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3741 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3743 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3745 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3747 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3748 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3749 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3750 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3751 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3755 * copy everything in the in-memory inode into the btree.
3757 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3758 struct btrfs_root *root, struct inode *inode)
3760 struct btrfs_inode_item *inode_item;
3761 struct btrfs_path *path;
3762 struct extent_buffer *leaf;
3765 path = btrfs_alloc_path();
3769 path->leave_spinning = 1;
3770 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3778 leaf = path->nodes[0];
3779 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3780 struct btrfs_inode_item);
3782 fill_inode_item(trans, leaf, inode_item, inode);
3783 btrfs_mark_buffer_dirty(leaf);
3784 btrfs_set_inode_last_trans(trans, inode);
3787 btrfs_free_path(path);
3792 * copy everything in the in-memory inode into the btree.
3794 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3795 struct btrfs_root *root, struct inode *inode)
3800 * If the inode is a free space inode, we can deadlock during commit
3801 * if we put it into the delayed code.
3803 * The data relocation inode should also be directly updated
3806 if (!btrfs_is_free_space_inode(inode)
3807 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3808 && !root->fs_info->log_root_recovering) {
3809 btrfs_update_root_times(trans, root);
3811 ret = btrfs_delayed_update_inode(trans, root, inode);
3813 btrfs_set_inode_last_trans(trans, inode);
3817 return btrfs_update_inode_item(trans, root, inode);
3820 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3821 struct btrfs_root *root,
3822 struct inode *inode)
3826 ret = btrfs_update_inode(trans, root, inode);
3828 return btrfs_update_inode_item(trans, root, inode);
3833 * unlink helper that gets used here in inode.c and in the tree logging
3834 * recovery code. It remove a link in a directory with a given name, and
3835 * also drops the back refs in the inode to the directory
3837 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3838 struct btrfs_root *root,
3839 struct inode *dir, struct inode *inode,
3840 const char *name, int name_len)
3842 struct btrfs_path *path;
3844 struct extent_buffer *leaf;
3845 struct btrfs_dir_item *di;
3846 struct btrfs_key key;
3848 u64 ino = btrfs_ino(inode);
3849 u64 dir_ino = btrfs_ino(dir);
3851 path = btrfs_alloc_path();
3857 path->leave_spinning = 1;
3858 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3859 name, name_len, -1);
3868 leaf = path->nodes[0];
3869 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3870 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3873 btrfs_release_path(path);
3876 * If we don't have dir index, we have to get it by looking up
3877 * the inode ref, since we get the inode ref, remove it directly,
3878 * it is unnecessary to do delayed deletion.
3880 * But if we have dir index, needn't search inode ref to get it.
3881 * Since the inode ref is close to the inode item, it is better
3882 * that we delay to delete it, and just do this deletion when
3883 * we update the inode item.
3885 if (BTRFS_I(inode)->dir_index) {
3886 ret = btrfs_delayed_delete_inode_ref(inode);
3888 index = BTRFS_I(inode)->dir_index;
3893 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3896 btrfs_info(root->fs_info,
3897 "failed to delete reference to %.*s, inode %llu parent %llu",
3898 name_len, name, ino, dir_ino);
3899 btrfs_abort_transaction(trans, root, ret);
3903 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3905 btrfs_abort_transaction(trans, root, ret);
3909 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3911 if (ret != 0 && ret != -ENOENT) {
3912 btrfs_abort_transaction(trans, root, ret);
3916 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3921 btrfs_abort_transaction(trans, root, ret);
3923 btrfs_free_path(path);
3927 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3928 inode_inc_iversion(inode);
3929 inode_inc_iversion(dir);
3930 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3931 ret = btrfs_update_inode(trans, root, dir);
3936 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3937 struct btrfs_root *root,
3938 struct inode *dir, struct inode *inode,
3939 const char *name, int name_len)
3942 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3945 ret = btrfs_update_inode(trans, root, inode);
3951 * helper to start transaction for unlink and rmdir.
3953 * unlink and rmdir are special in btrfs, they do not always free space, so
3954 * if we cannot make our reservations the normal way try and see if there is
3955 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3956 * allow the unlink to occur.
3958 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3960 struct btrfs_trans_handle *trans;
3961 struct btrfs_root *root = BTRFS_I(dir)->root;
3965 * 1 for the possible orphan item
3966 * 1 for the dir item
3967 * 1 for the dir index
3968 * 1 for the inode ref
3971 trans = btrfs_start_transaction(root, 5);
3972 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3975 if (PTR_ERR(trans) == -ENOSPC) {
3976 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3978 trans = btrfs_start_transaction(root, 0);
3981 ret = btrfs_cond_migrate_bytes(root->fs_info,
3982 &root->fs_info->trans_block_rsv,
3985 btrfs_end_transaction(trans, root);
3986 return ERR_PTR(ret);
3988 trans->block_rsv = &root->fs_info->trans_block_rsv;
3989 trans->bytes_reserved = num_bytes;
3994 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3996 struct btrfs_root *root = BTRFS_I(dir)->root;
3997 struct btrfs_trans_handle *trans;
3998 struct inode *inode = dentry->d_inode;
4001 trans = __unlink_start_trans(dir);
4003 return PTR_ERR(trans);
4005 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
4007 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
4008 dentry->d_name.name, dentry->d_name.len);
4012 if (inode->i_nlink == 0) {
4013 ret = btrfs_orphan_add(trans, inode);
4019 btrfs_end_transaction(trans, root);
4020 btrfs_btree_balance_dirty(root);
4024 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4025 struct btrfs_root *root,
4026 struct inode *dir, u64 objectid,
4027 const char *name, int name_len)
4029 struct btrfs_path *path;
4030 struct extent_buffer *leaf;
4031 struct btrfs_dir_item *di;
4032 struct btrfs_key key;
4035 u64 dir_ino = btrfs_ino(dir);
4037 path = btrfs_alloc_path();
4041 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4042 name, name_len, -1);
4043 if (IS_ERR_OR_NULL(di)) {
4051 leaf = path->nodes[0];
4052 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4053 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4054 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4056 btrfs_abort_transaction(trans, root, ret);
4059 btrfs_release_path(path);
4061 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4062 objectid, root->root_key.objectid,
4063 dir_ino, &index, name, name_len);
4065 if (ret != -ENOENT) {
4066 btrfs_abort_transaction(trans, root, ret);
4069 di = btrfs_search_dir_index_item(root, path, dir_ino,
4071 if (IS_ERR_OR_NULL(di)) {
4076 btrfs_abort_transaction(trans, root, ret);
4080 leaf = path->nodes[0];
4081 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4082 btrfs_release_path(path);
4085 btrfs_release_path(path);
4087 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4089 btrfs_abort_transaction(trans, root, ret);
4093 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4094 inode_inc_iversion(dir);
4095 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
4096 ret = btrfs_update_inode_fallback(trans, root, dir);
4098 btrfs_abort_transaction(trans, root, ret);
4100 btrfs_free_path(path);
4104 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4106 struct inode *inode = dentry->d_inode;
4108 struct btrfs_root *root = BTRFS_I(dir)->root;
4109 struct btrfs_trans_handle *trans;
4111 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4113 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
4116 trans = __unlink_start_trans(dir);
4118 return PTR_ERR(trans);
4120 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4121 err = btrfs_unlink_subvol(trans, root, dir,
4122 BTRFS_I(inode)->location.objectid,
4123 dentry->d_name.name,
4124 dentry->d_name.len);
4128 err = btrfs_orphan_add(trans, inode);
4132 /* now the directory is empty */
4133 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
4134 dentry->d_name.name, dentry->d_name.len);
4136 btrfs_i_size_write(inode, 0);
4138 btrfs_end_transaction(trans, root);
4139 btrfs_btree_balance_dirty(root);
4145 * this can truncate away extent items, csum items and directory items.
4146 * It starts at a high offset and removes keys until it can't find
4147 * any higher than new_size
4149 * csum items that cross the new i_size are truncated to the new size
4152 * min_type is the minimum key type to truncate down to. If set to 0, this
4153 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4155 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4156 struct btrfs_root *root,
4157 struct inode *inode,
4158 u64 new_size, u32 min_type)
4160 struct btrfs_path *path;
4161 struct extent_buffer *leaf;
4162 struct btrfs_file_extent_item *fi;
4163 struct btrfs_key key;
4164 struct btrfs_key found_key;
4165 u64 extent_start = 0;
4166 u64 extent_num_bytes = 0;
4167 u64 extent_offset = 0;
4169 u64 last_size = (u64)-1;
4170 u32 found_type = (u8)-1;
4173 int pending_del_nr = 0;
4174 int pending_del_slot = 0;
4175 int extent_type = -1;
4178 u64 ino = btrfs_ino(inode);
4180 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4182 path = btrfs_alloc_path();
4188 * We want to drop from the next block forward in case this new size is
4189 * not block aligned since we will be keeping the last block of the
4190 * extent just the way it is.
4192 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4193 root == root->fs_info->tree_root)
4194 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4195 root->sectorsize), (u64)-1, 0);
4198 * This function is also used to drop the items in the log tree before
4199 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4200 * it is used to drop the loged items. So we shouldn't kill the delayed
4203 if (min_type == 0 && root == BTRFS_I(inode)->root)
4204 btrfs_kill_delayed_inode_items(inode);
4207 key.offset = (u64)-1;
4211 path->leave_spinning = 1;
4212 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4219 /* there are no items in the tree for us to truncate, we're
4222 if (path->slots[0] == 0)
4229 leaf = path->nodes[0];
4230 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4231 found_type = found_key.type;
4233 if (found_key.objectid != ino)
4236 if (found_type < min_type)
4239 item_end = found_key.offset;
4240 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4241 fi = btrfs_item_ptr(leaf, path->slots[0],
4242 struct btrfs_file_extent_item);
4243 extent_type = btrfs_file_extent_type(leaf, fi);
4244 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4246 btrfs_file_extent_num_bytes(leaf, fi);
4247 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4248 item_end += btrfs_file_extent_inline_len(leaf,
4249 path->slots[0], fi);
4253 if (found_type > min_type) {
4256 if (item_end < new_size)
4258 if (found_key.offset >= new_size)
4264 /* FIXME, shrink the extent if the ref count is only 1 */
4265 if (found_type != BTRFS_EXTENT_DATA_KEY)
4269 last_size = found_key.offset;
4271 last_size = new_size;
4273 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4275 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4277 u64 orig_num_bytes =
4278 btrfs_file_extent_num_bytes(leaf, fi);
4279 extent_num_bytes = ALIGN(new_size -
4282 btrfs_set_file_extent_num_bytes(leaf, fi,
4284 num_dec = (orig_num_bytes -
4286 if (test_bit(BTRFS_ROOT_REF_COWS,
4289 inode_sub_bytes(inode, num_dec);
4290 btrfs_mark_buffer_dirty(leaf);
4293 btrfs_file_extent_disk_num_bytes(leaf,
4295 extent_offset = found_key.offset -
4296 btrfs_file_extent_offset(leaf, fi);
4298 /* FIXME blocksize != 4096 */
4299 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4300 if (extent_start != 0) {
4302 if (test_bit(BTRFS_ROOT_REF_COWS,
4304 inode_sub_bytes(inode, num_dec);
4307 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4309 * we can't truncate inline items that have had
4313 btrfs_file_extent_compression(leaf, fi) == 0 &&
4314 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4315 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4316 u32 size = new_size - found_key.offset;
4318 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4319 inode_sub_bytes(inode, item_end + 1 -
4323 * update the ram bytes to properly reflect
4324 * the new size of our item
4326 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4328 btrfs_file_extent_calc_inline_size(size);
4329 btrfs_truncate_item(root, path, size, 1);
4330 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4332 inode_sub_bytes(inode, item_end + 1 -
4338 if (!pending_del_nr) {
4339 /* no pending yet, add ourselves */
4340 pending_del_slot = path->slots[0];
4342 } else if (pending_del_nr &&
4343 path->slots[0] + 1 == pending_del_slot) {
4344 /* hop on the pending chunk */
4346 pending_del_slot = path->slots[0];
4354 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4355 root == root->fs_info->tree_root)) {
4356 btrfs_set_path_blocking(path);
4357 ret = btrfs_free_extent(trans, root, extent_start,
4358 extent_num_bytes, 0,
4359 btrfs_header_owner(leaf),
4360 ino, extent_offset, 0);
4364 if (found_type == BTRFS_INODE_ITEM_KEY)
4367 if (path->slots[0] == 0 ||
4368 path->slots[0] != pending_del_slot) {
4369 if (pending_del_nr) {
4370 ret = btrfs_del_items(trans, root, path,
4374 btrfs_abort_transaction(trans,
4380 btrfs_release_path(path);
4387 if (pending_del_nr) {
4388 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4391 btrfs_abort_transaction(trans, root, ret);
4394 if (last_size != (u64)-1 &&
4395 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4396 btrfs_ordered_update_i_size(inode, last_size, NULL);
4397 btrfs_free_path(path);
4402 * btrfs_truncate_page - read, zero a chunk and write a page
4403 * @inode - inode that we're zeroing
4404 * @from - the offset to start zeroing
4405 * @len - the length to zero, 0 to zero the entire range respective to the
4407 * @front - zero up to the offset instead of from the offset on
4409 * This will find the page for the "from" offset and cow the page and zero the
4410 * part we want to zero. This is used with truncate and hole punching.
4412 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4415 struct address_space *mapping = inode->i_mapping;
4416 struct btrfs_root *root = BTRFS_I(inode)->root;
4417 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4418 struct btrfs_ordered_extent *ordered;
4419 struct extent_state *cached_state = NULL;
4421 u32 blocksize = root->sectorsize;
4422 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4423 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4425 gfp_t mask = btrfs_alloc_write_mask(mapping);
4430 if ((offset & (blocksize - 1)) == 0 &&
4431 (!len || ((len & (blocksize - 1)) == 0)))
4433 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4438 page = find_or_create_page(mapping, index, mask);
4440 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4445 page_start = page_offset(page);
4446 page_end = page_start + PAGE_CACHE_SIZE - 1;
4448 if (!PageUptodate(page)) {
4449 ret = btrfs_readpage(NULL, page);
4451 if (page->mapping != mapping) {
4453 page_cache_release(page);
4456 if (!PageUptodate(page)) {
4461 wait_on_page_writeback(page);
4463 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4464 set_page_extent_mapped(page);
4466 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4468 unlock_extent_cached(io_tree, page_start, page_end,
4469 &cached_state, GFP_NOFS);
4471 page_cache_release(page);
4472 btrfs_start_ordered_extent(inode, ordered, 1);
4473 btrfs_put_ordered_extent(ordered);
4477 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4478 EXTENT_DIRTY | EXTENT_DELALLOC |
4479 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4480 0, 0, &cached_state, GFP_NOFS);
4482 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4485 unlock_extent_cached(io_tree, page_start, page_end,
4486 &cached_state, GFP_NOFS);
4490 if (offset != PAGE_CACHE_SIZE) {
4492 len = PAGE_CACHE_SIZE - offset;
4495 memset(kaddr, 0, offset);
4497 memset(kaddr + offset, 0, len);
4498 flush_dcache_page(page);
4501 ClearPageChecked(page);
4502 set_page_dirty(page);
4503 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4508 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4510 page_cache_release(page);
4515 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4516 u64 offset, u64 len)
4518 struct btrfs_trans_handle *trans;
4522 * Still need to make sure the inode looks like it's been updated so
4523 * that any holes get logged if we fsync.
4525 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4526 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4527 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4528 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4533 * 1 - for the one we're dropping
4534 * 1 - for the one we're adding
4535 * 1 - for updating the inode.
4537 trans = btrfs_start_transaction(root, 3);
4539 return PTR_ERR(trans);
4541 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4543 btrfs_abort_transaction(trans, root, ret);
4544 btrfs_end_transaction(trans, root);
4548 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4549 0, 0, len, 0, len, 0, 0, 0);
4551 btrfs_abort_transaction(trans, root, ret);
4553 btrfs_update_inode(trans, root, inode);
4554 btrfs_end_transaction(trans, root);
4559 * This function puts in dummy file extents for the area we're creating a hole
4560 * for. So if we are truncating this file to a larger size we need to insert
4561 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4562 * the range between oldsize and size
4564 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4566 struct btrfs_root *root = BTRFS_I(inode)->root;
4567 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4568 struct extent_map *em = NULL;
4569 struct extent_state *cached_state = NULL;
4570 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4571 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4572 u64 block_end = ALIGN(size, root->sectorsize);
4579 * If our size started in the middle of a page we need to zero out the
4580 * rest of the page before we expand the i_size, otherwise we could
4581 * expose stale data.
4583 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4587 if (size <= hole_start)
4591 struct btrfs_ordered_extent *ordered;
4593 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4595 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4596 block_end - hole_start);
4599 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4600 &cached_state, GFP_NOFS);
4601 btrfs_start_ordered_extent(inode, ordered, 1);
4602 btrfs_put_ordered_extent(ordered);
4605 cur_offset = hole_start;
4607 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4608 block_end - cur_offset, 0);
4614 last_byte = min(extent_map_end(em), block_end);
4615 last_byte = ALIGN(last_byte , root->sectorsize);
4616 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4617 struct extent_map *hole_em;
4618 hole_size = last_byte - cur_offset;
4620 err = maybe_insert_hole(root, inode, cur_offset,
4624 btrfs_drop_extent_cache(inode, cur_offset,
4625 cur_offset + hole_size - 1, 0);
4626 hole_em = alloc_extent_map();
4628 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4629 &BTRFS_I(inode)->runtime_flags);
4632 hole_em->start = cur_offset;
4633 hole_em->len = hole_size;
4634 hole_em->orig_start = cur_offset;
4636 hole_em->block_start = EXTENT_MAP_HOLE;
4637 hole_em->block_len = 0;
4638 hole_em->orig_block_len = 0;
4639 hole_em->ram_bytes = hole_size;
4640 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4641 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4642 hole_em->generation = root->fs_info->generation;
4645 write_lock(&em_tree->lock);
4646 err = add_extent_mapping(em_tree, hole_em, 1);
4647 write_unlock(&em_tree->lock);
4650 btrfs_drop_extent_cache(inode, cur_offset,
4654 free_extent_map(hole_em);
4657 free_extent_map(em);
4659 cur_offset = last_byte;
4660 if (cur_offset >= block_end)
4663 free_extent_map(em);
4664 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4669 static int wait_snapshoting_atomic_t(atomic_t *a)
4675 static void wait_for_snapshot_creation(struct btrfs_root *root)
4680 ret = btrfs_start_write_no_snapshoting(root);
4683 wait_on_atomic_t(&root->will_be_snapshoted,
4684 wait_snapshoting_atomic_t,
4685 TASK_UNINTERRUPTIBLE);
4689 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4691 struct btrfs_root *root = BTRFS_I(inode)->root;
4692 struct btrfs_trans_handle *trans;
4693 loff_t oldsize = i_size_read(inode);
4694 loff_t newsize = attr->ia_size;
4695 int mask = attr->ia_valid;
4699 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4700 * special case where we need to update the times despite not having
4701 * these flags set. For all other operations the VFS set these flags
4702 * explicitly if it wants a timestamp update.
4704 if (newsize != oldsize) {
4705 inode_inc_iversion(inode);
4706 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4707 inode->i_ctime = inode->i_mtime =
4708 current_fs_time(inode->i_sb);
4711 if (newsize > oldsize) {
4712 truncate_pagecache(inode, newsize);
4714 * Don't do an expanding truncate while snapshoting is ongoing.
4715 * This is to ensure the snapshot captures a fully consistent
4716 * state of this file - if the snapshot captures this expanding
4717 * truncation, it must capture all writes that happened before
4720 wait_for_snapshot_creation(root);
4721 ret = btrfs_cont_expand(inode, oldsize, newsize);
4723 btrfs_end_write_no_snapshoting(root);
4727 trans = btrfs_start_transaction(root, 1);
4728 if (IS_ERR(trans)) {
4729 btrfs_end_write_no_snapshoting(root);
4730 return PTR_ERR(trans);
4733 i_size_write(inode, newsize);
4734 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4735 ret = btrfs_update_inode(trans, root, inode);
4736 btrfs_end_write_no_snapshoting(root);
4737 btrfs_end_transaction(trans, root);
4741 * We're truncating a file that used to have good data down to
4742 * zero. Make sure it gets into the ordered flush list so that
4743 * any new writes get down to disk quickly.
4746 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4747 &BTRFS_I(inode)->runtime_flags);
4750 * 1 for the orphan item we're going to add
4751 * 1 for the orphan item deletion.
4753 trans = btrfs_start_transaction(root, 2);
4755 return PTR_ERR(trans);
4758 * We need to do this in case we fail at _any_ point during the
4759 * actual truncate. Once we do the truncate_setsize we could
4760 * invalidate pages which forces any outstanding ordered io to
4761 * be instantly completed which will give us extents that need
4762 * to be truncated. If we fail to get an orphan inode down we
4763 * could have left over extents that were never meant to live,
4764 * so we need to garuntee from this point on that everything
4765 * will be consistent.
4767 ret = btrfs_orphan_add(trans, inode);
4768 btrfs_end_transaction(trans, root);
4772 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4773 truncate_setsize(inode, newsize);
4775 /* Disable nonlocked read DIO to avoid the end less truncate */
4776 btrfs_inode_block_unlocked_dio(inode);
4777 inode_dio_wait(inode);
4778 btrfs_inode_resume_unlocked_dio(inode);
4780 ret = btrfs_truncate(inode);
4781 if (ret && inode->i_nlink) {
4785 * failed to truncate, disk_i_size is only adjusted down
4786 * as we remove extents, so it should represent the true
4787 * size of the inode, so reset the in memory size and
4788 * delete our orphan entry.
4790 trans = btrfs_join_transaction(root);
4791 if (IS_ERR(trans)) {
4792 btrfs_orphan_del(NULL, inode);
4795 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4796 err = btrfs_orphan_del(trans, inode);
4798 btrfs_abort_transaction(trans, root, err);
4799 btrfs_end_transaction(trans, root);
4806 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4808 struct inode *inode = dentry->d_inode;
4809 struct btrfs_root *root = BTRFS_I(inode)->root;
4812 if (btrfs_root_readonly(root))
4815 err = inode_change_ok(inode, attr);
4819 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4820 err = btrfs_setsize(inode, attr);
4825 if (attr->ia_valid) {
4826 setattr_copy(inode, attr);
4827 inode_inc_iversion(inode);
4828 err = btrfs_dirty_inode(inode);
4830 if (!err && attr->ia_valid & ATTR_MODE)
4831 err = posix_acl_chmod(inode, inode->i_mode);
4838 * While truncating the inode pages during eviction, we get the VFS calling
4839 * btrfs_invalidatepage() against each page of the inode. This is slow because
4840 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4841 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4842 * extent_state structures over and over, wasting lots of time.
4844 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4845 * those expensive operations on a per page basis and do only the ordered io
4846 * finishing, while we release here the extent_map and extent_state structures,
4847 * without the excessive merging and splitting.
4849 static void evict_inode_truncate_pages(struct inode *inode)
4851 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4852 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4853 struct rb_node *node;
4855 ASSERT(inode->i_state & I_FREEING);
4856 truncate_inode_pages_final(&inode->i_data);
4858 write_lock(&map_tree->lock);
4859 while (!RB_EMPTY_ROOT(&map_tree->map)) {
4860 struct extent_map *em;
4862 node = rb_first(&map_tree->map);
4863 em = rb_entry(node, struct extent_map, rb_node);
4864 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4865 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4866 remove_extent_mapping(map_tree, em);
4867 free_extent_map(em);
4868 if (need_resched()) {
4869 write_unlock(&map_tree->lock);
4871 write_lock(&map_tree->lock);
4874 write_unlock(&map_tree->lock);
4876 spin_lock(&io_tree->lock);
4877 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4878 struct extent_state *state;
4879 struct extent_state *cached_state = NULL;
4881 node = rb_first(&io_tree->state);
4882 state = rb_entry(node, struct extent_state, rb_node);
4883 atomic_inc(&state->refs);
4884 spin_unlock(&io_tree->lock);
4886 lock_extent_bits(io_tree, state->start, state->end,
4888 clear_extent_bit(io_tree, state->start, state->end,
4889 EXTENT_LOCKED | EXTENT_DIRTY |
4890 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
4891 EXTENT_DEFRAG, 1, 1,
4892 &cached_state, GFP_NOFS);
4893 free_extent_state(state);
4896 spin_lock(&io_tree->lock);
4898 spin_unlock(&io_tree->lock);
4901 void btrfs_evict_inode(struct inode *inode)
4903 struct btrfs_trans_handle *trans;
4904 struct btrfs_root *root = BTRFS_I(inode)->root;
4905 struct btrfs_block_rsv *rsv, *global_rsv;
4906 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4909 trace_btrfs_inode_evict(inode);
4911 evict_inode_truncate_pages(inode);
4913 if (inode->i_nlink &&
4914 ((btrfs_root_refs(&root->root_item) != 0 &&
4915 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4916 btrfs_is_free_space_inode(inode)))
4919 if (is_bad_inode(inode)) {
4920 btrfs_orphan_del(NULL, inode);
4923 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4924 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4926 btrfs_free_io_failure_record(inode, 0, (u64)-1);
4928 if (root->fs_info->log_root_recovering) {
4929 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4930 &BTRFS_I(inode)->runtime_flags));
4934 if (inode->i_nlink > 0) {
4935 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4936 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4940 ret = btrfs_commit_inode_delayed_inode(inode);
4942 btrfs_orphan_del(NULL, inode);
4946 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4948 btrfs_orphan_del(NULL, inode);
4951 rsv->size = min_size;
4953 global_rsv = &root->fs_info->global_block_rsv;
4955 btrfs_i_size_write(inode, 0);
4958 * This is a bit simpler than btrfs_truncate since we've already
4959 * reserved our space for our orphan item in the unlink, so we just
4960 * need to reserve some slack space in case we add bytes and update
4961 * inode item when doing the truncate.
4964 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4965 BTRFS_RESERVE_FLUSH_LIMIT);
4968 * Try and steal from the global reserve since we will
4969 * likely not use this space anyway, we want to try as
4970 * hard as possible to get this to work.
4973 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4976 btrfs_warn(root->fs_info,
4977 "Could not get space for a delete, will truncate on mount %d",
4979 btrfs_orphan_del(NULL, inode);
4980 btrfs_free_block_rsv(root, rsv);
4984 trans = btrfs_join_transaction(root);
4985 if (IS_ERR(trans)) {
4986 btrfs_orphan_del(NULL, inode);
4987 btrfs_free_block_rsv(root, rsv);
4991 trans->block_rsv = rsv;
4993 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4997 trans->block_rsv = &root->fs_info->trans_block_rsv;
4998 btrfs_end_transaction(trans, root);
5000 btrfs_btree_balance_dirty(root);
5003 btrfs_free_block_rsv(root, rsv);
5006 * Errors here aren't a big deal, it just means we leave orphan items
5007 * in the tree. They will be cleaned up on the next mount.
5010 trans->block_rsv = root->orphan_block_rsv;
5011 btrfs_orphan_del(trans, inode);
5013 btrfs_orphan_del(NULL, inode);
5016 trans->block_rsv = &root->fs_info->trans_block_rsv;
5017 if (!(root == root->fs_info->tree_root ||
5018 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5019 btrfs_return_ino(root, btrfs_ino(inode));
5021 btrfs_end_transaction(trans, root);
5022 btrfs_btree_balance_dirty(root);
5024 btrfs_remove_delayed_node(inode);
5030 * this returns the key found in the dir entry in the location pointer.
5031 * If no dir entries were found, location->objectid is 0.
5033 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5034 struct btrfs_key *location)
5036 const char *name = dentry->d_name.name;
5037 int namelen = dentry->d_name.len;
5038 struct btrfs_dir_item *di;
5039 struct btrfs_path *path;
5040 struct btrfs_root *root = BTRFS_I(dir)->root;
5043 path = btrfs_alloc_path();
5047 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
5052 if (IS_ERR_OR_NULL(di))
5055 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5057 btrfs_free_path(path);
5060 location->objectid = 0;
5065 * when we hit a tree root in a directory, the btrfs part of the inode
5066 * needs to be changed to reflect the root directory of the tree root. This
5067 * is kind of like crossing a mount point.
5069 static int fixup_tree_root_location(struct btrfs_root *root,
5071 struct dentry *dentry,
5072 struct btrfs_key *location,
5073 struct btrfs_root **sub_root)
5075 struct btrfs_path *path;
5076 struct btrfs_root *new_root;
5077 struct btrfs_root_ref *ref;
5078 struct extent_buffer *leaf;
5079 struct btrfs_key key;
5083 path = btrfs_alloc_path();
5090 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5091 key.type = BTRFS_ROOT_REF_KEY;
5092 key.offset = location->objectid;
5094 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, path,
5102 leaf = path->nodes[0];
5103 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5104 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5105 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5108 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5109 (unsigned long)(ref + 1),
5110 dentry->d_name.len);
5114 btrfs_release_path(path);
5116 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
5117 if (IS_ERR(new_root)) {
5118 err = PTR_ERR(new_root);
5122 *sub_root = new_root;
5123 location->objectid = btrfs_root_dirid(&new_root->root_item);
5124 location->type = BTRFS_INODE_ITEM_KEY;
5125 location->offset = 0;
5128 btrfs_free_path(path);
5132 static void inode_tree_add(struct inode *inode)
5134 struct btrfs_root *root = BTRFS_I(inode)->root;
5135 struct btrfs_inode *entry;
5137 struct rb_node *parent;
5138 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5139 u64 ino = btrfs_ino(inode);
5141 if (inode_unhashed(inode))
5144 spin_lock(&root->inode_lock);
5145 p = &root->inode_tree.rb_node;
5148 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5150 if (ino < btrfs_ino(&entry->vfs_inode))
5151 p = &parent->rb_left;
5152 else if (ino > btrfs_ino(&entry->vfs_inode))
5153 p = &parent->rb_right;
5155 WARN_ON(!(entry->vfs_inode.i_state &
5156 (I_WILL_FREE | I_FREEING)));
5157 rb_replace_node(parent, new, &root->inode_tree);
5158 RB_CLEAR_NODE(parent);
5159 spin_unlock(&root->inode_lock);
5163 rb_link_node(new, parent, p);
5164 rb_insert_color(new, &root->inode_tree);
5165 spin_unlock(&root->inode_lock);
5168 static void inode_tree_del(struct inode *inode)
5170 struct btrfs_root *root = BTRFS_I(inode)->root;
5173 spin_lock(&root->inode_lock);
5174 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5175 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5176 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5177 empty = RB_EMPTY_ROOT(&root->inode_tree);
5179 spin_unlock(&root->inode_lock);
5181 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5182 synchronize_srcu(&root->fs_info->subvol_srcu);
5183 spin_lock(&root->inode_lock);
5184 empty = RB_EMPTY_ROOT(&root->inode_tree);
5185 spin_unlock(&root->inode_lock);
5187 btrfs_add_dead_root(root);
5191 void btrfs_invalidate_inodes(struct btrfs_root *root)
5193 struct rb_node *node;
5194 struct rb_node *prev;
5195 struct btrfs_inode *entry;
5196 struct inode *inode;
5199 if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
5200 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5202 spin_lock(&root->inode_lock);
5204 node = root->inode_tree.rb_node;
5208 entry = rb_entry(node, struct btrfs_inode, rb_node);
5210 if (objectid < btrfs_ino(&entry->vfs_inode))
5211 node = node->rb_left;
5212 else if (objectid > btrfs_ino(&entry->vfs_inode))
5213 node = node->rb_right;
5219 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5220 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
5224 prev = rb_next(prev);
5228 entry = rb_entry(node, struct btrfs_inode, rb_node);
5229 objectid = btrfs_ino(&entry->vfs_inode) + 1;
5230 inode = igrab(&entry->vfs_inode);
5232 spin_unlock(&root->inode_lock);
5233 if (atomic_read(&inode->i_count) > 1)
5234 d_prune_aliases(inode);
5236 * btrfs_drop_inode will have it removed from
5237 * the inode cache when its usage count
5242 spin_lock(&root->inode_lock);
5246 if (cond_resched_lock(&root->inode_lock))
5249 node = rb_next(node);
5251 spin_unlock(&root->inode_lock);
5254 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5256 struct btrfs_iget_args *args = p;
5257 inode->i_ino = args->location->objectid;
5258 memcpy(&BTRFS_I(inode)->location, args->location,
5259 sizeof(*args->location));
5260 BTRFS_I(inode)->root = args->root;
5264 static int btrfs_find_actor(struct inode *inode, void *opaque)
5266 struct btrfs_iget_args *args = opaque;
5267 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5268 args->root == BTRFS_I(inode)->root;
5271 static struct inode *btrfs_iget_locked(struct super_block *s,
5272 struct btrfs_key *location,
5273 struct btrfs_root *root)
5275 struct inode *inode;
5276 struct btrfs_iget_args args;
5277 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5279 args.location = location;
5282 inode = iget5_locked(s, hashval, btrfs_find_actor,
5283 btrfs_init_locked_inode,
5288 /* Get an inode object given its location and corresponding root.
5289 * Returns in *is_new if the inode was read from disk
5291 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5292 struct btrfs_root *root, int *new)
5294 struct inode *inode;
5296 inode = btrfs_iget_locked(s, location, root);
5298 return ERR_PTR(-ENOMEM);
5300 if (inode->i_state & I_NEW) {
5301 btrfs_read_locked_inode(inode);
5302 if (!is_bad_inode(inode)) {
5303 inode_tree_add(inode);
5304 unlock_new_inode(inode);
5308 unlock_new_inode(inode);
5310 inode = ERR_PTR(-ESTALE);
5317 static struct inode *new_simple_dir(struct super_block *s,
5318 struct btrfs_key *key,
5319 struct btrfs_root *root)
5321 struct inode *inode = new_inode(s);
5324 return ERR_PTR(-ENOMEM);
5326 BTRFS_I(inode)->root = root;
5327 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5328 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5330 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5331 inode->i_op = &btrfs_dir_ro_inode_operations;
5332 inode->i_fop = &simple_dir_operations;
5333 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5334 inode->i_mtime = CURRENT_TIME;
5335 inode->i_atime = inode->i_mtime;
5336 inode->i_ctime = inode->i_mtime;
5337 BTRFS_I(inode)->i_otime = inode->i_mtime;
5342 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5344 struct inode *inode;
5345 struct btrfs_root *root = BTRFS_I(dir)->root;
5346 struct btrfs_root *sub_root = root;
5347 struct btrfs_key location;
5351 if (dentry->d_name.len > BTRFS_NAME_LEN)
5352 return ERR_PTR(-ENAMETOOLONG);
5354 ret = btrfs_inode_by_name(dir, dentry, &location);
5356 return ERR_PTR(ret);
5358 if (location.objectid == 0)
5359 return ERR_PTR(-ENOENT);
5361 if (location.type == BTRFS_INODE_ITEM_KEY) {
5362 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5366 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5368 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5369 ret = fixup_tree_root_location(root, dir, dentry,
5370 &location, &sub_root);
5373 inode = ERR_PTR(ret);
5375 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5377 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5379 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5381 if (!IS_ERR(inode) && root != sub_root) {
5382 down_read(&root->fs_info->cleanup_work_sem);
5383 if (!(inode->i_sb->s_flags & MS_RDONLY))
5384 ret = btrfs_orphan_cleanup(sub_root);
5385 up_read(&root->fs_info->cleanup_work_sem);
5388 inode = ERR_PTR(ret);
5395 static int btrfs_dentry_delete(const struct dentry *dentry)
5397 struct btrfs_root *root;
5398 struct inode *inode = dentry->d_inode;
5400 if (!inode && !IS_ROOT(dentry))
5401 inode = dentry->d_parent->d_inode;
5404 root = BTRFS_I(inode)->root;
5405 if (btrfs_root_refs(&root->root_item) == 0)
5408 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5414 static void btrfs_dentry_release(struct dentry *dentry)
5416 kfree(dentry->d_fsdata);
5419 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5422 struct inode *inode;
5424 inode = btrfs_lookup_dentry(dir, dentry);
5425 if (IS_ERR(inode)) {
5426 if (PTR_ERR(inode) == -ENOENT)
5429 return ERR_CAST(inode);
5432 return d_splice_alias(inode, dentry);
5435 unsigned char btrfs_filetype_table[] = {
5436 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5439 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5441 struct inode *inode = file_inode(file);
5442 struct btrfs_root *root = BTRFS_I(inode)->root;
5443 struct btrfs_item *item;
5444 struct btrfs_dir_item *di;
5445 struct btrfs_key key;
5446 struct btrfs_key found_key;
5447 struct btrfs_path *path;
5448 struct list_head ins_list;
5449 struct list_head del_list;
5451 struct extent_buffer *leaf;
5453 unsigned char d_type;
5458 int key_type = BTRFS_DIR_INDEX_KEY;
5462 int is_curr = 0; /* ctx->pos points to the current index? */
5464 /* FIXME, use a real flag for deciding about the key type */
5465 if (root->fs_info->tree_root == root)
5466 key_type = BTRFS_DIR_ITEM_KEY;
5468 if (!dir_emit_dots(file, ctx))
5471 path = btrfs_alloc_path();
5477 if (key_type == BTRFS_DIR_INDEX_KEY) {
5478 INIT_LIST_HEAD(&ins_list);
5479 INIT_LIST_HEAD(&del_list);
5480 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5483 key.type = key_type;
5484 key.offset = ctx->pos;
5485 key.objectid = btrfs_ino(inode);
5487 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5492 leaf = path->nodes[0];
5493 slot = path->slots[0];
5494 if (slot >= btrfs_header_nritems(leaf)) {
5495 ret = btrfs_next_leaf(root, path);
5503 item = btrfs_item_nr(slot);
5504 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5506 if (found_key.objectid != key.objectid)
5508 if (found_key.type != key_type)
5510 if (found_key.offset < ctx->pos)
5512 if (key_type == BTRFS_DIR_INDEX_KEY &&
5513 btrfs_should_delete_dir_index(&del_list,
5517 ctx->pos = found_key.offset;
5520 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5522 di_total = btrfs_item_size(leaf, item);
5524 while (di_cur < di_total) {
5525 struct btrfs_key location;
5527 if (verify_dir_item(root, leaf, di))
5530 name_len = btrfs_dir_name_len(leaf, di);
5531 if (name_len <= sizeof(tmp_name)) {
5532 name_ptr = tmp_name;
5534 name_ptr = kmalloc(name_len, GFP_NOFS);
5540 read_extent_buffer(leaf, name_ptr,
5541 (unsigned long)(di + 1), name_len);
5543 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5544 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5547 /* is this a reference to our own snapshot? If so
5550 * In contrast to old kernels, we insert the snapshot's
5551 * dir item and dir index after it has been created, so
5552 * we won't find a reference to our own snapshot. We
5553 * still keep the following code for backward
5556 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5557 location.objectid == root->root_key.objectid) {
5561 over = !dir_emit(ctx, name_ptr, name_len,
5562 location.objectid, d_type);
5565 if (name_ptr != tmp_name)
5570 di_len = btrfs_dir_name_len(leaf, di) +
5571 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5573 di = (struct btrfs_dir_item *)((char *)di + di_len);
5579 if (key_type == BTRFS_DIR_INDEX_KEY) {
5582 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5587 /* Reached end of directory/root. Bump pos past the last item. */
5591 * Stop new entries from being returned after we return the last
5594 * New directory entries are assigned a strictly increasing
5595 * offset. This means that new entries created during readdir
5596 * are *guaranteed* to be seen in the future by that readdir.
5597 * This has broken buggy programs which operate on names as
5598 * they're returned by readdir. Until we re-use freed offsets
5599 * we have this hack to stop new entries from being returned
5600 * under the assumption that they'll never reach this huge
5603 * This is being careful not to overflow 32bit loff_t unless the
5604 * last entry requires it because doing so has broken 32bit apps
5607 if (key_type == BTRFS_DIR_INDEX_KEY) {
5608 if (ctx->pos >= INT_MAX)
5609 ctx->pos = LLONG_MAX;
5616 if (key_type == BTRFS_DIR_INDEX_KEY)
5617 btrfs_put_delayed_items(&ins_list, &del_list);
5618 btrfs_free_path(path);
5622 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5624 struct btrfs_root *root = BTRFS_I(inode)->root;
5625 struct btrfs_trans_handle *trans;
5627 bool nolock = false;
5629 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5632 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5635 if (wbc->sync_mode == WB_SYNC_ALL) {
5637 trans = btrfs_join_transaction_nolock(root);
5639 trans = btrfs_join_transaction(root);
5641 return PTR_ERR(trans);
5642 ret = btrfs_commit_transaction(trans, root);
5648 * This is somewhat expensive, updating the tree every time the
5649 * inode changes. But, it is most likely to find the inode in cache.
5650 * FIXME, needs more benchmarking...there are no reasons other than performance
5651 * to keep or drop this code.
5653 static int btrfs_dirty_inode(struct inode *inode)
5655 struct btrfs_root *root = BTRFS_I(inode)->root;
5656 struct btrfs_trans_handle *trans;
5659 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5662 trans = btrfs_join_transaction(root);
5664 return PTR_ERR(trans);
5666 ret = btrfs_update_inode(trans, root, inode);
5667 if (ret && ret == -ENOSPC) {
5668 /* whoops, lets try again with the full transaction */
5669 btrfs_end_transaction(trans, root);
5670 trans = btrfs_start_transaction(root, 1);
5672 return PTR_ERR(trans);
5674 ret = btrfs_update_inode(trans, root, inode);
5676 btrfs_end_transaction(trans, root);
5677 if (BTRFS_I(inode)->delayed_node)
5678 btrfs_balance_delayed_items(root);
5684 * This is a copy of file_update_time. We need this so we can return error on
5685 * ENOSPC for updating the inode in the case of file write and mmap writes.
5687 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5690 struct btrfs_root *root = BTRFS_I(inode)->root;
5692 if (btrfs_root_readonly(root))
5695 if (flags & S_VERSION)
5696 inode_inc_iversion(inode);
5697 if (flags & S_CTIME)
5698 inode->i_ctime = *now;
5699 if (flags & S_MTIME)
5700 inode->i_mtime = *now;
5701 if (flags & S_ATIME)
5702 inode->i_atime = *now;
5703 return btrfs_dirty_inode(inode);
5707 * find the highest existing sequence number in a directory
5708 * and then set the in-memory index_cnt variable to reflect
5709 * free sequence numbers
5711 static int btrfs_set_inode_index_count(struct inode *inode)
5713 struct btrfs_root *root = BTRFS_I(inode)->root;
5714 struct btrfs_key key, found_key;
5715 struct btrfs_path *path;
5716 struct extent_buffer *leaf;
5719 key.objectid = btrfs_ino(inode);
5720 key.type = BTRFS_DIR_INDEX_KEY;
5721 key.offset = (u64)-1;
5723 path = btrfs_alloc_path();
5727 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5730 /* FIXME: we should be able to handle this */
5736 * MAGIC NUMBER EXPLANATION:
5737 * since we search a directory based on f_pos we have to start at 2
5738 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5739 * else has to start at 2
5741 if (path->slots[0] == 0) {
5742 BTRFS_I(inode)->index_cnt = 2;
5748 leaf = path->nodes[0];
5749 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5751 if (found_key.objectid != btrfs_ino(inode) ||
5752 found_key.type != BTRFS_DIR_INDEX_KEY) {
5753 BTRFS_I(inode)->index_cnt = 2;
5757 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5759 btrfs_free_path(path);
5764 * helper to find a free sequence number in a given directory. This current
5765 * code is very simple, later versions will do smarter things in the btree
5767 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5771 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5772 ret = btrfs_inode_delayed_dir_index_count(dir);
5774 ret = btrfs_set_inode_index_count(dir);
5780 *index = BTRFS_I(dir)->index_cnt;
5781 BTRFS_I(dir)->index_cnt++;
5786 static int btrfs_insert_inode_locked(struct inode *inode)
5788 struct btrfs_iget_args args;
5789 args.location = &BTRFS_I(inode)->location;
5790 args.root = BTRFS_I(inode)->root;
5792 return insert_inode_locked4(inode,
5793 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5794 btrfs_find_actor, &args);
5797 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5798 struct btrfs_root *root,
5800 const char *name, int name_len,
5801 u64 ref_objectid, u64 objectid,
5802 umode_t mode, u64 *index)
5804 struct inode *inode;
5805 struct btrfs_inode_item *inode_item;
5806 struct btrfs_key *location;
5807 struct btrfs_path *path;
5808 struct btrfs_inode_ref *ref;
5809 struct btrfs_key key[2];
5811 int nitems = name ? 2 : 1;
5815 path = btrfs_alloc_path();
5817 return ERR_PTR(-ENOMEM);
5819 inode = new_inode(root->fs_info->sb);
5821 btrfs_free_path(path);
5822 return ERR_PTR(-ENOMEM);
5826 * O_TMPFILE, set link count to 0, so that after this point,
5827 * we fill in an inode item with the correct link count.
5830 set_nlink(inode, 0);
5833 * we have to initialize this early, so we can reclaim the inode
5834 * number if we fail afterwards in this function.
5836 inode->i_ino = objectid;
5839 trace_btrfs_inode_request(dir);
5841 ret = btrfs_set_inode_index(dir, index);
5843 btrfs_free_path(path);
5845 return ERR_PTR(ret);
5851 * index_cnt is ignored for everything but a dir,
5852 * btrfs_get_inode_index_count has an explanation for the magic
5855 BTRFS_I(inode)->index_cnt = 2;
5856 BTRFS_I(inode)->dir_index = *index;
5857 BTRFS_I(inode)->root = root;
5858 BTRFS_I(inode)->generation = trans->transid;
5859 inode->i_generation = BTRFS_I(inode)->generation;
5862 * We could have gotten an inode number from somebody who was fsynced
5863 * and then removed in this same transaction, so let's just set full
5864 * sync since it will be a full sync anyway and this will blow away the
5865 * old info in the log.
5867 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5869 key[0].objectid = objectid;
5870 key[0].type = BTRFS_INODE_ITEM_KEY;
5873 sizes[0] = sizeof(struct btrfs_inode_item);
5877 * Start new inodes with an inode_ref. This is slightly more
5878 * efficient for small numbers of hard links since they will
5879 * be packed into one item. Extended refs will kick in if we
5880 * add more hard links than can fit in the ref item.
5882 key[1].objectid = objectid;
5883 key[1].type = BTRFS_INODE_REF_KEY;
5884 key[1].offset = ref_objectid;
5886 sizes[1] = name_len + sizeof(*ref);
5889 location = &BTRFS_I(inode)->location;
5890 location->objectid = objectid;
5891 location->offset = 0;
5892 location->type = BTRFS_INODE_ITEM_KEY;
5894 ret = btrfs_insert_inode_locked(inode);
5898 path->leave_spinning = 1;
5899 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
5903 inode_init_owner(inode, dir, mode);
5904 inode_set_bytes(inode, 0);
5906 inode->i_mtime = CURRENT_TIME;
5907 inode->i_atime = inode->i_mtime;
5908 inode->i_ctime = inode->i_mtime;
5909 BTRFS_I(inode)->i_otime = inode->i_mtime;
5911 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5912 struct btrfs_inode_item);
5913 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5914 sizeof(*inode_item));
5915 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5918 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5919 struct btrfs_inode_ref);
5920 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5921 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5922 ptr = (unsigned long)(ref + 1);
5923 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5926 btrfs_mark_buffer_dirty(path->nodes[0]);
5927 btrfs_free_path(path);
5929 btrfs_inherit_iflags(inode, dir);
5931 if (S_ISREG(mode)) {
5932 if (btrfs_test_opt(root, NODATASUM))
5933 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5934 if (btrfs_test_opt(root, NODATACOW))
5935 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5936 BTRFS_INODE_NODATASUM;
5939 inode_tree_add(inode);
5941 trace_btrfs_inode_new(inode);
5942 btrfs_set_inode_last_trans(trans, inode);
5944 btrfs_update_root_times(trans, root);
5946 ret = btrfs_inode_inherit_props(trans, inode, dir);
5948 btrfs_err(root->fs_info,
5949 "error inheriting props for ino %llu (root %llu): %d",
5950 btrfs_ino(inode), root->root_key.objectid, ret);
5955 unlock_new_inode(inode);
5958 BTRFS_I(dir)->index_cnt--;
5959 btrfs_free_path(path);
5961 return ERR_PTR(ret);
5964 static inline u8 btrfs_inode_type(struct inode *inode)
5966 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5970 * utility function to add 'inode' into 'parent_inode' with
5971 * a give name and a given sequence number.
5972 * if 'add_backref' is true, also insert a backref from the
5973 * inode to the parent directory.
5975 int btrfs_add_link(struct btrfs_trans_handle *trans,
5976 struct inode *parent_inode, struct inode *inode,
5977 const char *name, int name_len, int add_backref, u64 index)
5980 struct btrfs_key key;
5981 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5982 u64 ino = btrfs_ino(inode);
5983 u64 parent_ino = btrfs_ino(parent_inode);
5985 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5986 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5989 key.type = BTRFS_INODE_ITEM_KEY;
5993 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5994 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5995 key.objectid, root->root_key.objectid,
5996 parent_ino, index, name, name_len);
5997 } else if (add_backref) {
5998 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6002 /* Nothing to clean up yet */
6006 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6008 btrfs_inode_type(inode), index);
6009 if (ret == -EEXIST || ret == -EOVERFLOW)
6012 btrfs_abort_transaction(trans, root, ret);
6016 btrfs_i_size_write(parent_inode, parent_inode->i_size +
6018 inode_inc_iversion(parent_inode);
6019 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
6020 ret = btrfs_update_inode(trans, root, parent_inode);
6022 btrfs_abort_transaction(trans, root, ret);
6026 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6029 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
6030 key.objectid, root->root_key.objectid,
6031 parent_ino, &local_index, name, name_len);
6033 } else if (add_backref) {
6037 err = btrfs_del_inode_ref(trans, root, name, name_len,
6038 ino, parent_ino, &local_index);
6043 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6044 struct inode *dir, struct dentry *dentry,
6045 struct inode *inode, int backref, u64 index)
6047 int err = btrfs_add_link(trans, dir, inode,
6048 dentry->d_name.name, dentry->d_name.len,
6055 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6056 umode_t mode, dev_t rdev)
6058 struct btrfs_trans_handle *trans;
6059 struct btrfs_root *root = BTRFS_I(dir)->root;
6060 struct inode *inode = NULL;
6066 if (!new_valid_dev(rdev))
6070 * 2 for inode item and ref
6072 * 1 for xattr if selinux is on
6074 trans = btrfs_start_transaction(root, 5);
6076 return PTR_ERR(trans);
6078 err = btrfs_find_free_ino(root, &objectid);
6082 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6083 dentry->d_name.len, btrfs_ino(dir), objectid,
6085 if (IS_ERR(inode)) {
6086 err = PTR_ERR(inode);
6091 * If the active LSM wants to access the inode during
6092 * d_instantiate it needs these. Smack checks to see
6093 * if the filesystem supports xattrs by looking at the
6096 inode->i_op = &btrfs_special_inode_operations;
6097 init_special_inode(inode, inode->i_mode, rdev);
6099 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6101 goto out_unlock_inode;
6103 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6105 goto out_unlock_inode;
6107 btrfs_update_inode(trans, root, inode);
6108 unlock_new_inode(inode);
6109 d_instantiate(dentry, inode);
6113 btrfs_end_transaction(trans, root);
6114 btrfs_balance_delayed_items(root);
6115 btrfs_btree_balance_dirty(root);
6117 inode_dec_link_count(inode);
6124 unlock_new_inode(inode);
6129 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6130 umode_t mode, bool excl)
6132 struct btrfs_trans_handle *trans;
6133 struct btrfs_root *root = BTRFS_I(dir)->root;
6134 struct inode *inode = NULL;
6135 int drop_inode_on_err = 0;
6141 * 2 for inode item and ref
6143 * 1 for xattr if selinux is on
6145 trans = btrfs_start_transaction(root, 5);
6147 return PTR_ERR(trans);
6149 err = btrfs_find_free_ino(root, &objectid);
6153 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6154 dentry->d_name.len, btrfs_ino(dir), objectid,
6156 if (IS_ERR(inode)) {
6157 err = PTR_ERR(inode);
6160 drop_inode_on_err = 1;
6162 * If the active LSM wants to access the inode during
6163 * d_instantiate it needs these. Smack checks to see
6164 * if the filesystem supports xattrs by looking at the
6167 inode->i_fop = &btrfs_file_operations;
6168 inode->i_op = &btrfs_file_inode_operations;
6169 inode->i_mapping->a_ops = &btrfs_aops;
6170 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
6172 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6174 goto out_unlock_inode;
6176 err = btrfs_update_inode(trans, root, inode);
6178 goto out_unlock_inode;
6180 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6182 goto out_unlock_inode;
6184 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6185 unlock_new_inode(inode);
6186 d_instantiate(dentry, inode);
6189 btrfs_end_transaction(trans, root);
6190 if (err && drop_inode_on_err) {
6191 inode_dec_link_count(inode);
6194 btrfs_balance_delayed_items(root);
6195 btrfs_btree_balance_dirty(root);
6199 unlock_new_inode(inode);
6204 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6205 struct dentry *dentry)
6207 struct btrfs_trans_handle *trans;
6208 struct btrfs_root *root = BTRFS_I(dir)->root;
6209 struct inode *inode = old_dentry->d_inode;
6214 /* do not allow sys_link's with other subvols of the same device */
6215 if (root->objectid != BTRFS_I(inode)->root->objectid)
6218 if (inode->i_nlink >= BTRFS_LINK_MAX)
6221 err = btrfs_set_inode_index(dir, &index);
6226 * 2 items for inode and inode ref
6227 * 2 items for dir items
6228 * 1 item for parent inode
6230 trans = btrfs_start_transaction(root, 5);
6231 if (IS_ERR(trans)) {
6232 err = PTR_ERR(trans);
6236 /* There are several dir indexes for this inode, clear the cache. */
6237 BTRFS_I(inode)->dir_index = 0ULL;
6239 inode_inc_iversion(inode);
6240 inode->i_ctime = CURRENT_TIME;
6242 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6244 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
6249 struct dentry *parent = dentry->d_parent;
6250 err = btrfs_update_inode(trans, root, inode);
6253 if (inode->i_nlink == 1) {
6255 * If new hard link count is 1, it's a file created
6256 * with open(2) O_TMPFILE flag.
6258 err = btrfs_orphan_del(trans, inode);
6262 d_instantiate(dentry, inode);
6263 btrfs_log_new_name(trans, inode, NULL, parent);
6266 btrfs_end_transaction(trans, root);
6267 btrfs_balance_delayed_items(root);
6270 inode_dec_link_count(inode);
6273 btrfs_btree_balance_dirty(root);
6277 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6279 struct inode *inode = NULL;
6280 struct btrfs_trans_handle *trans;
6281 struct btrfs_root *root = BTRFS_I(dir)->root;
6283 int drop_on_err = 0;
6288 * 2 items for inode and ref
6289 * 2 items for dir items
6290 * 1 for xattr if selinux is on
6292 trans = btrfs_start_transaction(root, 5);
6294 return PTR_ERR(trans);
6296 err = btrfs_find_free_ino(root, &objectid);
6300 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6301 dentry->d_name.len, btrfs_ino(dir), objectid,
6302 S_IFDIR | mode, &index);
6303 if (IS_ERR(inode)) {
6304 err = PTR_ERR(inode);
6309 /* these must be set before we unlock the inode */
6310 inode->i_op = &btrfs_dir_inode_operations;
6311 inode->i_fop = &btrfs_dir_file_operations;
6313 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6315 goto out_fail_inode;
6317 btrfs_i_size_write(inode, 0);
6318 err = btrfs_update_inode(trans, root, inode);
6320 goto out_fail_inode;
6322 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6323 dentry->d_name.len, 0, index);
6325 goto out_fail_inode;
6327 d_instantiate(dentry, inode);
6329 * mkdir is special. We're unlocking after we call d_instantiate
6330 * to avoid a race with nfsd calling d_instantiate.
6332 unlock_new_inode(inode);
6336 btrfs_end_transaction(trans, root);
6338 inode_dec_link_count(inode);
6341 btrfs_balance_delayed_items(root);
6342 btrfs_btree_balance_dirty(root);
6346 unlock_new_inode(inode);
6350 /* Find next extent map of a given extent map, caller needs to ensure locks */
6351 static struct extent_map *next_extent_map(struct extent_map *em)
6353 struct rb_node *next;
6355 next = rb_next(&em->rb_node);
6358 return container_of(next, struct extent_map, rb_node);
6361 static struct extent_map *prev_extent_map(struct extent_map *em)
6363 struct rb_node *prev;
6365 prev = rb_prev(&em->rb_node);
6368 return container_of(prev, struct extent_map, rb_node);
6371 /* helper for btfs_get_extent. Given an existing extent in the tree,
6372 * the existing extent is the nearest extent to map_start,
6373 * and an extent that you want to insert, deal with overlap and insert
6374 * the best fitted new extent into the tree.
6376 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6377 struct extent_map *existing,
6378 struct extent_map *em,
6381 struct extent_map *prev;
6382 struct extent_map *next;
6387 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6389 if (existing->start > map_start) {
6391 prev = prev_extent_map(next);
6394 next = next_extent_map(prev);
6397 start = prev ? extent_map_end(prev) : em->start;
6398 start = max_t(u64, start, em->start);
6399 end = next ? next->start : extent_map_end(em);
6400 end = min_t(u64, end, extent_map_end(em));
6401 start_diff = start - em->start;
6403 em->len = end - start;
6404 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6405 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6406 em->block_start += start_diff;
6407 em->block_len -= start_diff;
6409 return add_extent_mapping(em_tree, em, 0);
6412 static noinline int uncompress_inline(struct btrfs_path *path,
6413 struct inode *inode, struct page *page,
6414 size_t pg_offset, u64 extent_offset,
6415 struct btrfs_file_extent_item *item)
6418 struct extent_buffer *leaf = path->nodes[0];
6421 unsigned long inline_size;
6425 WARN_ON(pg_offset != 0);
6426 compress_type = btrfs_file_extent_compression(leaf, item);
6427 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6428 inline_size = btrfs_file_extent_inline_item_len(leaf,
6429 btrfs_item_nr(path->slots[0]));
6430 tmp = kmalloc(inline_size, GFP_NOFS);
6433 ptr = btrfs_file_extent_inline_start(item);
6435 read_extent_buffer(leaf, tmp, ptr, inline_size);
6437 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6438 ret = btrfs_decompress(compress_type, tmp, page,
6439 extent_offset, inline_size, max_size);
6445 * a bit scary, this does extent mapping from logical file offset to the disk.
6446 * the ugly parts come from merging extents from the disk with the in-ram
6447 * representation. This gets more complex because of the data=ordered code,
6448 * where the in-ram extents might be locked pending data=ordered completion.
6450 * This also copies inline extents directly into the page.
6453 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6454 size_t pg_offset, u64 start, u64 len,
6459 u64 extent_start = 0;
6461 u64 objectid = btrfs_ino(inode);
6463 struct btrfs_path *path = NULL;
6464 struct btrfs_root *root = BTRFS_I(inode)->root;
6465 struct btrfs_file_extent_item *item;
6466 struct extent_buffer *leaf;
6467 struct btrfs_key found_key;
6468 struct extent_map *em = NULL;
6469 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6470 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6471 struct btrfs_trans_handle *trans = NULL;
6472 const bool new_inline = !page || create;
6475 read_lock(&em_tree->lock);
6476 em = lookup_extent_mapping(em_tree, start, len);
6478 em->bdev = root->fs_info->fs_devices->latest_bdev;
6479 read_unlock(&em_tree->lock);
6482 if (em->start > start || em->start + em->len <= start)
6483 free_extent_map(em);
6484 else if (em->block_start == EXTENT_MAP_INLINE && page)
6485 free_extent_map(em);
6489 em = alloc_extent_map();
6494 em->bdev = root->fs_info->fs_devices->latest_bdev;
6495 em->start = EXTENT_MAP_HOLE;
6496 em->orig_start = EXTENT_MAP_HOLE;
6498 em->block_len = (u64)-1;
6501 path = btrfs_alloc_path();
6507 * Chances are we'll be called again, so go ahead and do
6513 ret = btrfs_lookup_file_extent(trans, root, path,
6514 objectid, start, trans != NULL);
6521 if (path->slots[0] == 0)
6526 leaf = path->nodes[0];
6527 item = btrfs_item_ptr(leaf, path->slots[0],
6528 struct btrfs_file_extent_item);
6529 /* are we inside the extent that was found? */
6530 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6531 found_type = found_key.type;
6532 if (found_key.objectid != objectid ||
6533 found_type != BTRFS_EXTENT_DATA_KEY) {
6535 * If we backup past the first extent we want to move forward
6536 * and see if there is an extent in front of us, otherwise we'll
6537 * say there is a hole for our whole search range which can
6544 found_type = btrfs_file_extent_type(leaf, item);
6545 extent_start = found_key.offset;
6546 if (found_type == BTRFS_FILE_EXTENT_REG ||
6547 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6548 extent_end = extent_start +
6549 btrfs_file_extent_num_bytes(leaf, item);
6550 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6552 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6553 extent_end = ALIGN(extent_start + size, root->sectorsize);
6556 if (start >= extent_end) {
6558 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6559 ret = btrfs_next_leaf(root, path);
6566 leaf = path->nodes[0];
6568 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6569 if (found_key.objectid != objectid ||
6570 found_key.type != BTRFS_EXTENT_DATA_KEY)
6572 if (start + len <= found_key.offset)
6574 if (start > found_key.offset)
6577 em->orig_start = start;
6578 em->len = found_key.offset - start;
6582 btrfs_extent_item_to_extent_map(inode, path, item, new_inline, em);
6584 if (found_type == BTRFS_FILE_EXTENT_REG ||
6585 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6587 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6591 size_t extent_offset;
6597 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6598 extent_offset = page_offset(page) + pg_offset - extent_start;
6599 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6600 size - extent_offset);
6601 em->start = extent_start + extent_offset;
6602 em->len = ALIGN(copy_size, root->sectorsize);
6603 em->orig_block_len = em->len;
6604 em->orig_start = em->start;
6605 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6606 if (create == 0 && !PageUptodate(page)) {
6607 if (btrfs_file_extent_compression(leaf, item) !=
6608 BTRFS_COMPRESS_NONE) {
6609 ret = uncompress_inline(path, inode, page,
6611 extent_offset, item);
6618 read_extent_buffer(leaf, map + pg_offset, ptr,
6620 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6621 memset(map + pg_offset + copy_size, 0,
6622 PAGE_CACHE_SIZE - pg_offset -
6627 flush_dcache_page(page);
6628 } else if (create && PageUptodate(page)) {
6632 free_extent_map(em);
6635 btrfs_release_path(path);
6636 trans = btrfs_join_transaction(root);
6639 return ERR_CAST(trans);
6643 write_extent_buffer(leaf, map + pg_offset, ptr,
6646 btrfs_mark_buffer_dirty(leaf);
6648 set_extent_uptodate(io_tree, em->start,
6649 extent_map_end(em) - 1, NULL, GFP_NOFS);
6654 em->orig_start = start;
6657 em->block_start = EXTENT_MAP_HOLE;
6658 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6660 btrfs_release_path(path);
6661 if (em->start > start || extent_map_end(em) <= start) {
6662 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6663 em->start, em->len, start, len);
6669 write_lock(&em_tree->lock);
6670 ret = add_extent_mapping(em_tree, em, 0);
6671 /* it is possible that someone inserted the extent into the tree
6672 * while we had the lock dropped. It is also possible that
6673 * an overlapping map exists in the tree
6675 if (ret == -EEXIST) {
6676 struct extent_map *existing;
6680 existing = search_extent_mapping(em_tree, start, len);
6682 * existing will always be non-NULL, since there must be
6683 * extent causing the -EEXIST.
6685 if (start >= extent_map_end(existing) ||
6686 start <= existing->start) {
6688 * The existing extent map is the one nearest to
6689 * the [start, start + len) range which overlaps
6691 err = merge_extent_mapping(em_tree, existing,
6693 free_extent_map(existing);
6695 free_extent_map(em);
6699 free_extent_map(em);
6704 write_unlock(&em_tree->lock);
6707 trace_btrfs_get_extent(root, em);
6710 btrfs_free_path(path);
6712 ret = btrfs_end_transaction(trans, root);
6717 free_extent_map(em);
6718 return ERR_PTR(err);
6720 BUG_ON(!em); /* Error is always set */
6724 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6725 size_t pg_offset, u64 start, u64 len,
6728 struct extent_map *em;
6729 struct extent_map *hole_em = NULL;
6730 u64 range_start = start;
6736 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6743 * - a pre-alloc extent,
6744 * there might actually be delalloc bytes behind it.
6746 if (em->block_start != EXTENT_MAP_HOLE &&
6747 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6753 /* check to see if we've wrapped (len == -1 or similar) */
6762 /* ok, we didn't find anything, lets look for delalloc */
6763 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6764 end, len, EXTENT_DELALLOC, 1);
6765 found_end = range_start + found;
6766 if (found_end < range_start)
6767 found_end = (u64)-1;
6770 * we didn't find anything useful, return
6771 * the original results from get_extent()
6773 if (range_start > end || found_end <= start) {
6779 /* adjust the range_start to make sure it doesn't
6780 * go backwards from the start they passed in
6782 range_start = max(start, range_start);
6783 found = found_end - range_start;
6786 u64 hole_start = start;
6789 em = alloc_extent_map();
6795 * when btrfs_get_extent can't find anything it
6796 * returns one huge hole
6798 * make sure what it found really fits our range, and
6799 * adjust to make sure it is based on the start from
6803 u64 calc_end = extent_map_end(hole_em);
6805 if (calc_end <= start || (hole_em->start > end)) {
6806 free_extent_map(hole_em);
6809 hole_start = max(hole_em->start, start);
6810 hole_len = calc_end - hole_start;
6814 if (hole_em && range_start > hole_start) {
6815 /* our hole starts before our delalloc, so we
6816 * have to return just the parts of the hole
6817 * that go until the delalloc starts
6819 em->len = min(hole_len,
6820 range_start - hole_start);
6821 em->start = hole_start;
6822 em->orig_start = hole_start;
6824 * don't adjust block start at all,
6825 * it is fixed at EXTENT_MAP_HOLE
6827 em->block_start = hole_em->block_start;
6828 em->block_len = hole_len;
6829 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6830 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6832 em->start = range_start;
6834 em->orig_start = range_start;
6835 em->block_start = EXTENT_MAP_DELALLOC;
6836 em->block_len = found;
6838 } else if (hole_em) {
6843 free_extent_map(hole_em);
6845 free_extent_map(em);
6846 return ERR_PTR(err);
6851 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6854 struct btrfs_root *root = BTRFS_I(inode)->root;
6855 struct extent_map *em;
6856 struct btrfs_key ins;
6860 alloc_hint = get_extent_allocation_hint(inode, start, len);
6861 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
6862 alloc_hint, &ins, 1, 1);
6864 return ERR_PTR(ret);
6866 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6867 ins.offset, ins.offset, ins.offset, 0);
6869 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
6873 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6874 ins.offset, ins.offset, 0);
6876 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
6877 free_extent_map(em);
6878 return ERR_PTR(ret);
6885 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6886 * block must be cow'd
6888 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6889 u64 *orig_start, u64 *orig_block_len,
6892 struct btrfs_trans_handle *trans;
6893 struct btrfs_path *path;
6895 struct extent_buffer *leaf;
6896 struct btrfs_root *root = BTRFS_I(inode)->root;
6897 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6898 struct btrfs_file_extent_item *fi;
6899 struct btrfs_key key;
6906 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6908 path = btrfs_alloc_path();
6912 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
6917 slot = path->slots[0];
6920 /* can't find the item, must cow */
6927 leaf = path->nodes[0];
6928 btrfs_item_key_to_cpu(leaf, &key, slot);
6929 if (key.objectid != btrfs_ino(inode) ||
6930 key.type != BTRFS_EXTENT_DATA_KEY) {
6931 /* not our file or wrong item type, must cow */
6935 if (key.offset > offset) {
6936 /* Wrong offset, must cow */
6940 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6941 found_type = btrfs_file_extent_type(leaf, fi);
6942 if (found_type != BTRFS_FILE_EXTENT_REG &&
6943 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6944 /* not a regular extent, must cow */
6948 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6951 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6952 if (extent_end <= offset)
6955 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6956 if (disk_bytenr == 0)
6959 if (btrfs_file_extent_compression(leaf, fi) ||
6960 btrfs_file_extent_encryption(leaf, fi) ||
6961 btrfs_file_extent_other_encoding(leaf, fi))
6964 backref_offset = btrfs_file_extent_offset(leaf, fi);
6967 *orig_start = key.offset - backref_offset;
6968 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6969 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6972 if (btrfs_extent_readonly(root, disk_bytenr))
6975 num_bytes = min(offset + *len, extent_end) - offset;
6976 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6979 range_end = round_up(offset + num_bytes, root->sectorsize) - 1;
6980 ret = test_range_bit(io_tree, offset, range_end,
6981 EXTENT_DELALLOC, 0, NULL);
6988 btrfs_release_path(path);
6991 * look for other files referencing this extent, if we
6992 * find any we must cow
6994 trans = btrfs_join_transaction(root);
6995 if (IS_ERR(trans)) {
7000 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
7001 key.offset - backref_offset, disk_bytenr);
7002 btrfs_end_transaction(trans, root);
7009 * adjust disk_bytenr and num_bytes to cover just the bytes
7010 * in this extent we are about to write. If there
7011 * are any csums in that range we have to cow in order
7012 * to keep the csums correct
7014 disk_bytenr += backref_offset;
7015 disk_bytenr += offset - key.offset;
7016 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
7019 * all of the above have passed, it is safe to overwrite this extent
7025 btrfs_free_path(path);
7029 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7031 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7033 void **pagep = NULL;
7034 struct page *page = NULL;
7038 start_idx = start >> PAGE_CACHE_SHIFT;
7041 * end is the last byte in the last page. end == start is legal
7043 end_idx = end >> PAGE_CACHE_SHIFT;
7047 /* Most of the code in this while loop is lifted from
7048 * find_get_page. It's been modified to begin searching from a
7049 * page and return just the first page found in that range. If the
7050 * found idx is less than or equal to the end idx then we know that
7051 * a page exists. If no pages are found or if those pages are
7052 * outside of the range then we're fine (yay!) */
7053 while (page == NULL &&
7054 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7055 page = radix_tree_deref_slot(pagep);
7056 if (unlikely(!page))
7059 if (radix_tree_exception(page)) {
7060 if (radix_tree_deref_retry(page)) {
7065 * Otherwise, shmem/tmpfs must be storing a swap entry
7066 * here as an exceptional entry: so return it without
7067 * attempting to raise page count.
7070 break; /* TODO: Is this relevant for this use case? */
7073 if (!page_cache_get_speculative(page)) {
7079 * Has the page moved?
7080 * This is part of the lockless pagecache protocol. See
7081 * include/linux/pagemap.h for details.
7083 if (unlikely(page != *pagep)) {
7084 page_cache_release(page);
7090 if (page->index <= end_idx)
7092 page_cache_release(page);
7099 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7100 struct extent_state **cached_state, int writing)
7102 struct btrfs_ordered_extent *ordered;
7106 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7109 * We're concerned with the entire range that we're going to be
7110 * doing DIO to, so we need to make sure theres no ordered
7111 * extents in this range.
7113 ordered = btrfs_lookup_ordered_range(inode, lockstart,
7114 lockend - lockstart + 1);
7117 * We need to make sure there are no buffered pages in this
7118 * range either, we could have raced between the invalidate in
7119 * generic_file_direct_write and locking the extent. The
7120 * invalidate needs to happen so that reads after a write do not
7125 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7128 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7129 cached_state, GFP_NOFS);
7132 btrfs_start_ordered_extent(inode, ordered, 1);
7133 btrfs_put_ordered_extent(ordered);
7135 /* Screw you mmap */
7136 ret = btrfs_fdatawrite_range(inode, lockstart, lockend);
7139 ret = filemap_fdatawait_range(inode->i_mapping,
7146 * If we found a page that couldn't be invalidated just
7147 * fall back to buffered.
7149 ret = invalidate_inode_pages2_range(inode->i_mapping,
7150 lockstart >> PAGE_CACHE_SHIFT,
7151 lockend >> PAGE_CACHE_SHIFT);
7162 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
7163 u64 len, u64 orig_start,
7164 u64 block_start, u64 block_len,
7165 u64 orig_block_len, u64 ram_bytes,
7168 struct extent_map_tree *em_tree;
7169 struct extent_map *em;
7170 struct btrfs_root *root = BTRFS_I(inode)->root;
7173 em_tree = &BTRFS_I(inode)->extent_tree;
7174 em = alloc_extent_map();
7176 return ERR_PTR(-ENOMEM);
7179 em->orig_start = orig_start;
7180 em->mod_start = start;
7183 em->block_len = block_len;
7184 em->block_start = block_start;
7185 em->bdev = root->fs_info->fs_devices->latest_bdev;
7186 em->orig_block_len = orig_block_len;
7187 em->ram_bytes = ram_bytes;
7188 em->generation = -1;
7189 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7190 if (type == BTRFS_ORDERED_PREALLOC)
7191 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7194 btrfs_drop_extent_cache(inode, em->start,
7195 em->start + em->len - 1, 0);
7196 write_lock(&em_tree->lock);
7197 ret = add_extent_mapping(em_tree, em, 1);
7198 write_unlock(&em_tree->lock);
7199 } while (ret == -EEXIST);
7202 free_extent_map(em);
7203 return ERR_PTR(ret);
7210 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7211 struct buffer_head *bh_result, int create)
7213 struct extent_map *em;
7214 struct btrfs_root *root = BTRFS_I(inode)->root;
7215 struct extent_state *cached_state = NULL;
7216 u64 start = iblock << inode->i_blkbits;
7217 u64 lockstart, lockend;
7218 u64 len = bh_result->b_size;
7220 int unlock_bits = EXTENT_LOCKED;
7224 unlock_bits |= EXTENT_DIRTY;
7226 len = min_t(u64, len, root->sectorsize);
7229 lockend = start + len - 1;
7232 * If this errors out it's because we couldn't invalidate pagecache for
7233 * this range and we need to fallback to buffered.
7235 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
7238 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7245 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7246 * io. INLINE is special, and we could probably kludge it in here, but
7247 * it's still buffered so for safety lets just fall back to the generic
7250 * For COMPRESSED we _have_ to read the entire extent in so we can
7251 * decompress it, so there will be buffering required no matter what we
7252 * do, so go ahead and fallback to buffered.
7254 * We return -ENOTBLK because thats what makes DIO go ahead and go back
7255 * to buffered IO. Don't blame me, this is the price we pay for using
7258 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7259 em->block_start == EXTENT_MAP_INLINE) {
7260 free_extent_map(em);
7265 /* Just a good old fashioned hole, return */
7266 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7267 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7268 free_extent_map(em);
7273 * We don't allocate a new extent in the following cases
7275 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7277 * 2) The extent is marked as PREALLOC. We're good to go here and can
7278 * just use the extent.
7282 len = min(len, em->len - (start - em->start));
7283 lockstart = start + len;
7287 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7288 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7289 em->block_start != EXTENT_MAP_HOLE)) {
7291 u64 block_start, orig_start, orig_block_len, ram_bytes;
7293 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7294 type = BTRFS_ORDERED_PREALLOC;
7296 type = BTRFS_ORDERED_NOCOW;
7297 len = min(len, em->len - (start - em->start));
7298 block_start = em->block_start + (start - em->start);
7300 if (can_nocow_extent(inode, start, &len, &orig_start,
7301 &orig_block_len, &ram_bytes) == 1) {
7302 if (type == BTRFS_ORDERED_PREALLOC) {
7303 free_extent_map(em);
7304 em = create_pinned_em(inode, start, len,
7315 ret = btrfs_add_ordered_extent_dio(inode, start,
7316 block_start, len, len, type);
7318 free_extent_map(em);
7326 * this will cow the extent, reset the len in case we changed
7329 len = bh_result->b_size;
7330 free_extent_map(em);
7331 em = btrfs_new_extent_direct(inode, start, len);
7336 len = min(len, em->len - (start - em->start));
7338 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7340 bh_result->b_size = len;
7341 bh_result->b_bdev = em->bdev;
7342 set_buffer_mapped(bh_result);
7344 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7345 set_buffer_new(bh_result);
7348 * Need to update the i_size under the extent lock so buffered
7349 * readers will get the updated i_size when we unlock.
7351 if (start + len > i_size_read(inode))
7352 i_size_write(inode, start + len);
7354 if (len < orig_len) {
7355 spin_lock(&BTRFS_I(inode)->lock);
7356 BTRFS_I(inode)->outstanding_extents++;
7357 spin_unlock(&BTRFS_I(inode)->lock);
7359 btrfs_free_reserved_data_space(inode, len);
7363 * In the case of write we need to clear and unlock the entire range,
7364 * in the case of read we need to unlock only the end area that we
7365 * aren't using if there is any left over space.
7367 if (lockstart < lockend) {
7368 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7369 lockend, unlock_bits, 1, 0,
7370 &cached_state, GFP_NOFS);
7372 free_extent_state(cached_state);
7375 free_extent_map(em);
7380 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7381 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7385 static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7386 int rw, int mirror_num)
7388 struct btrfs_root *root = BTRFS_I(inode)->root;
7391 BUG_ON(rw & REQ_WRITE);
7395 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7396 BTRFS_WQ_ENDIO_DIO_REPAIR);
7400 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
7406 static int btrfs_check_dio_repairable(struct inode *inode,
7407 struct bio *failed_bio,
7408 struct io_failure_record *failrec,
7413 num_copies = btrfs_num_copies(BTRFS_I(inode)->root->fs_info,
7414 failrec->logical, failrec->len);
7415 if (num_copies == 1) {
7417 * we only have a single copy of the data, so don't bother with
7418 * all the retry and error correction code that follows. no
7419 * matter what the error is, it is very likely to persist.
7421 pr_debug("Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d\n",
7422 num_copies, failrec->this_mirror, failed_mirror);
7426 failrec->failed_mirror = failed_mirror;
7427 failrec->this_mirror++;
7428 if (failrec->this_mirror == failed_mirror)
7429 failrec->this_mirror++;
7431 if (failrec->this_mirror > num_copies) {
7432 pr_debug("Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d\n",
7433 num_copies, failrec->this_mirror, failed_mirror);
7440 static int dio_read_error(struct inode *inode, struct bio *failed_bio,
7441 struct page *page, u64 start, u64 end,
7442 int failed_mirror, bio_end_io_t *repair_endio,
7445 struct io_failure_record *failrec;
7451 BUG_ON(failed_bio->bi_rw & REQ_WRITE);
7453 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7457 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7460 free_io_failure(inode, failrec);
7464 if (failed_bio->bi_vcnt > 1)
7465 read_mode = READ_SYNC | REQ_FAILFAST_DEV;
7467 read_mode = READ_SYNC;
7469 isector = start - btrfs_io_bio(failed_bio)->logical;
7470 isector >>= inode->i_sb->s_blocksize_bits;
7471 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7472 0, isector, repair_endio, repair_arg);
7474 free_io_failure(inode, failrec);
7478 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7479 "Repair DIO Read Error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d\n",
7480 read_mode, failrec->this_mirror, failrec->in_validation);
7482 ret = submit_dio_repair_bio(inode, bio, read_mode,
7483 failrec->this_mirror);
7485 free_io_failure(inode, failrec);
7492 struct btrfs_retry_complete {
7493 struct completion done;
7494 struct inode *inode;
7499 static void btrfs_retry_endio_nocsum(struct bio *bio, int err)
7501 struct btrfs_retry_complete *done = bio->bi_private;
7502 struct bio_vec *bvec;
7509 bio_for_each_segment_all(bvec, bio, i)
7510 clean_io_failure(done->inode, done->start, bvec->bv_page, 0);
7512 complete(&done->done);
7516 static int __btrfs_correct_data_nocsum(struct inode *inode,
7517 struct btrfs_io_bio *io_bio)
7519 struct bio_vec *bvec;
7520 struct btrfs_retry_complete done;
7525 start = io_bio->logical;
7528 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7532 init_completion(&done.done);
7534 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7535 start + bvec->bv_len - 1,
7537 btrfs_retry_endio_nocsum, &done);
7541 wait_for_completion(&done.done);
7543 if (!done.uptodate) {
7544 /* We might have another mirror, so try again */
7548 start += bvec->bv_len;
7554 static void btrfs_retry_endio(struct bio *bio, int err)
7556 struct btrfs_retry_complete *done = bio->bi_private;
7557 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7558 struct bio_vec *bvec;
7567 bio_for_each_segment_all(bvec, bio, i) {
7568 ret = __readpage_endio_check(done->inode, io_bio, i,
7570 done->start, bvec->bv_len);
7572 clean_io_failure(done->inode, done->start,
7578 done->uptodate = uptodate;
7580 complete(&done->done);
7584 static int __btrfs_subio_endio_read(struct inode *inode,
7585 struct btrfs_io_bio *io_bio, int err)
7587 struct bio_vec *bvec;
7588 struct btrfs_retry_complete done;
7595 start = io_bio->logical;
7598 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7599 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7600 0, start, bvec->bv_len);
7606 init_completion(&done.done);
7608 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7609 start + bvec->bv_len - 1,
7611 btrfs_retry_endio, &done);
7617 wait_for_completion(&done.done);
7619 if (!done.uptodate) {
7620 /* We might have another mirror, so try again */
7624 offset += bvec->bv_len;
7625 start += bvec->bv_len;
7631 static int btrfs_subio_endio_read(struct inode *inode,
7632 struct btrfs_io_bio *io_bio, int err)
7634 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7638 return __btrfs_correct_data_nocsum(inode, io_bio);
7642 return __btrfs_subio_endio_read(inode, io_bio, err);
7646 static void btrfs_endio_direct_read(struct bio *bio, int err)
7648 struct btrfs_dio_private *dip = bio->bi_private;
7649 struct inode *inode = dip->inode;
7650 struct bio *dio_bio;
7651 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7653 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
7654 err = btrfs_subio_endio_read(inode, io_bio, err);
7656 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
7657 dip->logical_offset + dip->bytes - 1);
7658 dio_bio = dip->dio_bio;
7662 /* If we had a csum failure make sure to clear the uptodate flag */
7664 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7665 dio_end_io(dio_bio, err);
7668 io_bio->end_io(io_bio, err);
7672 static void btrfs_endio_direct_write(struct bio *bio, int err)
7674 struct btrfs_dio_private *dip = bio->bi_private;
7675 struct inode *inode = dip->inode;
7676 struct btrfs_root *root = BTRFS_I(inode)->root;
7677 struct btrfs_ordered_extent *ordered = NULL;
7678 u64 ordered_offset = dip->logical_offset;
7679 u64 ordered_bytes = dip->bytes;
7680 struct bio *dio_bio;
7686 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7688 ordered_bytes, !err);
7692 btrfs_init_work(&ordered->work, btrfs_endio_write_helper,
7693 finish_ordered_fn, NULL, NULL);
7694 btrfs_queue_work(root->fs_info->endio_write_workers,
7698 * our bio might span multiple ordered extents. If we haven't
7699 * completed the accounting for the whole dio, go back and try again
7701 if (ordered_offset < dip->logical_offset + dip->bytes) {
7702 ordered_bytes = dip->logical_offset + dip->bytes -
7708 dio_bio = dip->dio_bio;
7712 /* If we had an error make sure to clear the uptodate flag */
7714 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7715 dio_end_io(dio_bio, err);
7719 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7720 struct bio *bio, int mirror_num,
7721 unsigned long bio_flags, u64 offset)
7724 struct btrfs_root *root = BTRFS_I(inode)->root;
7725 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7726 BUG_ON(ret); /* -ENOMEM */
7730 static void btrfs_end_dio_bio(struct bio *bio, int err)
7732 struct btrfs_dio_private *dip = bio->bi_private;
7735 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7736 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
7737 btrfs_ino(dip->inode), bio->bi_rw,
7738 (unsigned long long)bio->bi_iter.bi_sector,
7739 bio->bi_iter.bi_size, err);
7741 if (dip->subio_endio)
7742 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
7748 * before atomic variable goto zero, we must make sure
7749 * dip->errors is perceived to be set.
7751 smp_mb__before_atomic();
7754 /* if there are more bios still pending for this dio, just exit */
7755 if (!atomic_dec_and_test(&dip->pending_bios))
7759 bio_io_error(dip->orig_bio);
7761 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
7762 bio_endio(dip->orig_bio, 0);
7768 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7769 u64 first_sector, gfp_t gfp_flags)
7771 int nr_vecs = bio_get_nr_vecs(bdev);
7772 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7775 static inline int btrfs_lookup_and_bind_dio_csum(struct btrfs_root *root,
7776 struct inode *inode,
7777 struct btrfs_dio_private *dip,
7781 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7782 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
7786 * We load all the csum data we need when we submit
7787 * the first bio to reduce the csum tree search and
7790 if (dip->logical_offset == file_offset) {
7791 ret = btrfs_lookup_bio_sums_dio(root, inode, dip->orig_bio,
7797 if (bio == dip->orig_bio)
7800 file_offset -= dip->logical_offset;
7801 file_offset >>= inode->i_sb->s_blocksize_bits;
7802 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
7807 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7808 int rw, u64 file_offset, int skip_sum,
7811 struct btrfs_dio_private *dip = bio->bi_private;
7812 int write = rw & REQ_WRITE;
7813 struct btrfs_root *root = BTRFS_I(inode)->root;
7817 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7822 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7823 BTRFS_WQ_ENDIO_DATA);
7831 if (write && async_submit) {
7832 ret = btrfs_wq_submit_bio(root->fs_info,
7833 inode, rw, bio, 0, 0,
7835 __btrfs_submit_bio_start_direct_io,
7836 __btrfs_submit_bio_done);
7840 * If we aren't doing async submit, calculate the csum of the
7843 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7847 ret = btrfs_lookup_and_bind_dio_csum(root, inode, dip, bio,
7853 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7859 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7862 struct inode *inode = dip->inode;
7863 struct btrfs_root *root = BTRFS_I(inode)->root;
7865 struct bio *orig_bio = dip->orig_bio;
7866 struct bio_vec *bvec = orig_bio->bi_io_vec;
7867 u64 start_sector = orig_bio->bi_iter.bi_sector;
7868 u64 file_offset = dip->logical_offset;
7873 int async_submit = 0;
7875 map_length = orig_bio->bi_iter.bi_size;
7876 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7877 &map_length, NULL, 0);
7881 if (map_length >= orig_bio->bi_iter.bi_size) {
7883 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
7887 /* async crcs make it difficult to collect full stripe writes. */
7888 if (btrfs_get_alloc_profile(root, 1) & BTRFS_BLOCK_GROUP_RAID56_MASK)
7893 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7897 bio->bi_private = dip;
7898 bio->bi_end_io = btrfs_end_dio_bio;
7899 btrfs_io_bio(bio)->logical = file_offset;
7900 atomic_inc(&dip->pending_bios);
7902 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7903 if (map_length < submit_len + bvec->bv_len ||
7904 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7905 bvec->bv_offset) < bvec->bv_len) {
7907 * inc the count before we submit the bio so
7908 * we know the end IO handler won't happen before
7909 * we inc the count. Otherwise, the dip might get freed
7910 * before we're done setting it up
7912 atomic_inc(&dip->pending_bios);
7913 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7914 file_offset, skip_sum,
7918 atomic_dec(&dip->pending_bios);
7922 start_sector += submit_len >> 9;
7923 file_offset += submit_len;
7928 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7929 start_sector, GFP_NOFS);
7932 bio->bi_private = dip;
7933 bio->bi_end_io = btrfs_end_dio_bio;
7934 btrfs_io_bio(bio)->logical = file_offset;
7936 map_length = orig_bio->bi_iter.bi_size;
7937 ret = btrfs_map_block(root->fs_info, rw,
7939 &map_length, NULL, 0);
7945 submit_len += bvec->bv_len;
7952 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7961 * before atomic variable goto zero, we must
7962 * make sure dip->errors is perceived to be set.
7964 smp_mb__before_atomic();
7965 if (atomic_dec_and_test(&dip->pending_bios))
7966 bio_io_error(dip->orig_bio);
7968 /* bio_end_io() will handle error, so we needn't return it */
7972 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7973 struct inode *inode, loff_t file_offset)
7975 struct btrfs_root *root = BTRFS_I(inode)->root;
7976 struct btrfs_dio_private *dip;
7978 struct btrfs_io_bio *btrfs_bio;
7980 int write = rw & REQ_WRITE;
7983 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7985 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7991 dip = kzalloc(sizeof(*dip), GFP_NOFS);
7997 dip->private = dio_bio->bi_private;
7999 dip->logical_offset = file_offset;
8000 dip->bytes = dio_bio->bi_iter.bi_size;
8001 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8002 io_bio->bi_private = dip;
8003 dip->orig_bio = io_bio;
8004 dip->dio_bio = dio_bio;
8005 atomic_set(&dip->pending_bios, 0);
8006 btrfs_bio = btrfs_io_bio(io_bio);
8007 btrfs_bio->logical = file_offset;
8010 io_bio->bi_end_io = btrfs_endio_direct_write;
8012 io_bio->bi_end_io = btrfs_endio_direct_read;
8013 dip->subio_endio = btrfs_subio_endio_read;
8016 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
8020 if (btrfs_bio->end_io)
8021 btrfs_bio->end_io(btrfs_bio, ret);
8027 * If this is a write, we need to clean up the reserved space and kill
8028 * the ordered extent.
8031 struct btrfs_ordered_extent *ordered;
8032 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
8033 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
8034 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
8035 btrfs_free_reserved_extent(root, ordered->start,
8036 ordered->disk_len, 1);
8037 btrfs_put_ordered_extent(ordered);
8038 btrfs_put_ordered_extent(ordered);
8040 bio_endio(dio_bio, ret);
8043 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
8044 const struct iov_iter *iter, loff_t offset)
8048 unsigned blocksize_mask = root->sectorsize - 1;
8049 ssize_t retval = -EINVAL;
8051 if (offset & blocksize_mask)
8054 if (iov_iter_alignment(iter) & blocksize_mask)
8057 /* If this is a write we don't need to check anymore */
8061 * Check to make sure we don't have duplicate iov_base's in this
8062 * iovec, if so return EINVAL, otherwise we'll get csum errors
8063 * when reading back.
8065 for (seg = 0; seg < iter->nr_segs; seg++) {
8066 for (i = seg + 1; i < iter->nr_segs; i++) {
8067 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8076 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
8077 struct iov_iter *iter, loff_t offset)
8079 struct file *file = iocb->ki_filp;
8080 struct inode *inode = file->f_mapping->host;
8084 bool relock = false;
8087 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iter, offset))
8090 atomic_inc(&inode->i_dio_count);
8091 smp_mb__after_atomic();
8094 * The generic stuff only does filemap_write_and_wait_range, which
8095 * isn't enough if we've written compressed pages to this area, so
8096 * we need to flush the dirty pages again to make absolutely sure
8097 * that any outstanding dirty pages are on disk.
8099 count = iov_iter_count(iter);
8100 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8101 &BTRFS_I(inode)->runtime_flags))
8102 filemap_fdatawrite_range(inode->i_mapping, offset,
8103 offset + count - 1);
8107 * If the write DIO is beyond the EOF, we need update
8108 * the isize, but it is protected by i_mutex. So we can
8109 * not unlock the i_mutex at this case.
8111 if (offset + count <= inode->i_size) {
8112 mutex_unlock(&inode->i_mutex);
8115 ret = btrfs_delalloc_reserve_space(inode, count);
8118 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8119 &BTRFS_I(inode)->runtime_flags)) {
8120 inode_dio_done(inode);
8121 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8125 ret = __blockdev_direct_IO(rw, iocb, inode,
8126 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
8127 iter, offset, btrfs_get_blocks_direct, NULL,
8128 btrfs_submit_direct, flags);
8130 if (ret < 0 && ret != -EIOCBQUEUED)
8131 btrfs_delalloc_release_space(inode, count);
8132 else if (ret >= 0 && (size_t)ret < count)
8133 btrfs_delalloc_release_space(inode,
8134 count - (size_t)ret);
8138 inode_dio_done(inode);
8140 mutex_lock(&inode->i_mutex);
8145 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8147 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8148 __u64 start, __u64 len)
8152 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8156 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
8159 int btrfs_readpage(struct file *file, struct page *page)
8161 struct extent_io_tree *tree;
8162 tree = &BTRFS_I(page->mapping->host)->io_tree;
8163 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8166 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8168 struct extent_io_tree *tree;
8171 if (current->flags & PF_MEMALLOC) {
8172 redirty_page_for_writepage(wbc, page);
8176 tree = &BTRFS_I(page->mapping->host)->io_tree;
8177 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
8180 static int btrfs_writepages(struct address_space *mapping,
8181 struct writeback_control *wbc)
8183 struct extent_io_tree *tree;
8185 tree = &BTRFS_I(mapping->host)->io_tree;
8186 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8190 btrfs_readpages(struct file *file, struct address_space *mapping,
8191 struct list_head *pages, unsigned nr_pages)
8193 struct extent_io_tree *tree;
8194 tree = &BTRFS_I(mapping->host)->io_tree;
8195 return extent_readpages(tree, mapping, pages, nr_pages,
8198 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8200 struct extent_io_tree *tree;
8201 struct extent_map_tree *map;
8204 tree = &BTRFS_I(page->mapping->host)->io_tree;
8205 map = &BTRFS_I(page->mapping->host)->extent_tree;
8206 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8208 ClearPagePrivate(page);
8209 set_page_private(page, 0);
8210 page_cache_release(page);
8215 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8217 if (PageWriteback(page) || PageDirty(page))
8219 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
8222 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8223 unsigned int length)
8225 struct inode *inode = page->mapping->host;
8226 struct extent_io_tree *tree;
8227 struct btrfs_ordered_extent *ordered;
8228 struct extent_state *cached_state = NULL;
8229 u64 page_start = page_offset(page);
8230 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
8231 int inode_evicting = inode->i_state & I_FREEING;
8234 * we have the page locked, so new writeback can't start,
8235 * and the dirty bit won't be cleared while we are here.
8237 * Wait for IO on this page so that we can safely clear
8238 * the PagePrivate2 bit and do ordered accounting
8240 wait_on_page_writeback(page);
8242 tree = &BTRFS_I(inode)->io_tree;
8244 btrfs_releasepage(page, GFP_NOFS);
8248 if (!inode_evicting)
8249 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
8250 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8253 * IO on this page will never be started, so we need
8254 * to account for any ordered extents now
8256 if (!inode_evicting)
8257 clear_extent_bit(tree, page_start, page_end,
8258 EXTENT_DIRTY | EXTENT_DELALLOC |
8259 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8260 EXTENT_DEFRAG, 1, 0, &cached_state,
8263 * whoever cleared the private bit is responsible
8264 * for the finish_ordered_io
8266 if (TestClearPagePrivate2(page)) {
8267 struct btrfs_ordered_inode_tree *tree;
8270 tree = &BTRFS_I(inode)->ordered_tree;
8272 spin_lock_irq(&tree->lock);
8273 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8274 new_len = page_start - ordered->file_offset;
8275 if (new_len < ordered->truncated_len)
8276 ordered->truncated_len = new_len;
8277 spin_unlock_irq(&tree->lock);
8279 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8281 PAGE_CACHE_SIZE, 1))
8282 btrfs_finish_ordered_io(ordered);
8284 btrfs_put_ordered_extent(ordered);
8285 if (!inode_evicting) {
8286 cached_state = NULL;
8287 lock_extent_bits(tree, page_start, page_end, 0,
8292 if (!inode_evicting) {
8293 clear_extent_bit(tree, page_start, page_end,
8294 EXTENT_LOCKED | EXTENT_DIRTY |
8295 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8296 EXTENT_DEFRAG, 1, 1,
8297 &cached_state, GFP_NOFS);
8299 __btrfs_releasepage(page, GFP_NOFS);
8302 ClearPageChecked(page);
8303 if (PagePrivate(page)) {
8304 ClearPagePrivate(page);
8305 set_page_private(page, 0);
8306 page_cache_release(page);
8311 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8312 * called from a page fault handler when a page is first dirtied. Hence we must
8313 * be careful to check for EOF conditions here. We set the page up correctly
8314 * for a written page which means we get ENOSPC checking when writing into
8315 * holes and correct delalloc and unwritten extent mapping on filesystems that
8316 * support these features.
8318 * We are not allowed to take the i_mutex here so we have to play games to
8319 * protect against truncate races as the page could now be beyond EOF. Because
8320 * vmtruncate() writes the inode size before removing pages, once we have the
8321 * page lock we can determine safely if the page is beyond EOF. If it is not
8322 * beyond EOF, then the page is guaranteed safe against truncation until we
8325 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
8327 struct page *page = vmf->page;
8328 struct inode *inode = file_inode(vma->vm_file);
8329 struct btrfs_root *root = BTRFS_I(inode)->root;
8330 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8331 struct btrfs_ordered_extent *ordered;
8332 struct extent_state *cached_state = NULL;
8334 unsigned long zero_start;
8341 sb_start_pagefault(inode->i_sb);
8342 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
8344 ret = file_update_time(vma->vm_file);
8350 else /* -ENOSPC, -EIO, etc */
8351 ret = VM_FAULT_SIGBUS;
8357 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8360 size = i_size_read(inode);
8361 page_start = page_offset(page);
8362 page_end = page_start + PAGE_CACHE_SIZE - 1;
8364 if ((page->mapping != inode->i_mapping) ||
8365 (page_start >= size)) {
8366 /* page got truncated out from underneath us */
8369 wait_on_page_writeback(page);
8371 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
8372 set_page_extent_mapped(page);
8375 * we can't set the delalloc bits if there are pending ordered
8376 * extents. Drop our locks and wait for them to finish
8378 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8380 unlock_extent_cached(io_tree, page_start, page_end,
8381 &cached_state, GFP_NOFS);
8383 btrfs_start_ordered_extent(inode, ordered, 1);
8384 btrfs_put_ordered_extent(ordered);
8389 * XXX - page_mkwrite gets called every time the page is dirtied, even
8390 * if it was already dirty, so for space accounting reasons we need to
8391 * clear any delalloc bits for the range we are fixing to save. There
8392 * is probably a better way to do this, but for now keep consistent with
8393 * prepare_pages in the normal write path.
8395 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
8396 EXTENT_DIRTY | EXTENT_DELALLOC |
8397 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8398 0, 0, &cached_state, GFP_NOFS);
8400 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
8403 unlock_extent_cached(io_tree, page_start, page_end,
8404 &cached_state, GFP_NOFS);
8405 ret = VM_FAULT_SIGBUS;
8410 /* page is wholly or partially inside EOF */
8411 if (page_start + PAGE_CACHE_SIZE > size)
8412 zero_start = size & ~PAGE_CACHE_MASK;
8414 zero_start = PAGE_CACHE_SIZE;
8416 if (zero_start != PAGE_CACHE_SIZE) {
8418 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
8419 flush_dcache_page(page);
8422 ClearPageChecked(page);
8423 set_page_dirty(page);
8424 SetPageUptodate(page);
8426 BTRFS_I(inode)->last_trans = root->fs_info->generation;
8427 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8428 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8430 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
8434 sb_end_pagefault(inode->i_sb);
8435 return VM_FAULT_LOCKED;
8439 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
8441 sb_end_pagefault(inode->i_sb);
8445 static int btrfs_truncate(struct inode *inode)
8447 struct btrfs_root *root = BTRFS_I(inode)->root;
8448 struct btrfs_block_rsv *rsv;
8451 struct btrfs_trans_handle *trans;
8452 u64 mask = root->sectorsize - 1;
8453 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
8455 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8461 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
8462 * 3 things going on here
8464 * 1) We need to reserve space for our orphan item and the space to
8465 * delete our orphan item. Lord knows we don't want to have a dangling
8466 * orphan item because we didn't reserve space to remove it.
8468 * 2) We need to reserve space to update our inode.
8470 * 3) We need to have something to cache all the space that is going to
8471 * be free'd up by the truncate operation, but also have some slack
8472 * space reserved in case it uses space during the truncate (thank you
8473 * very much snapshotting).
8475 * And we need these to all be seperate. The fact is we can use alot of
8476 * space doing the truncate, and we have no earthly idea how much space
8477 * we will use, so we need the truncate reservation to be seperate so it
8478 * doesn't end up using space reserved for updating the inode or
8479 * removing the orphan item. We also need to be able to stop the
8480 * transaction and start a new one, which means we need to be able to
8481 * update the inode several times, and we have no idea of knowing how
8482 * many times that will be, so we can't just reserve 1 item for the
8483 * entirety of the opration, so that has to be done seperately as well.
8484 * Then there is the orphan item, which does indeed need to be held on
8485 * to for the whole operation, and we need nobody to touch this reserved
8486 * space except the orphan code.
8488 * So that leaves us with
8490 * 1) root->orphan_block_rsv - for the orphan deletion.
8491 * 2) rsv - for the truncate reservation, which we will steal from the
8492 * transaction reservation.
8493 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
8494 * updating the inode.
8496 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
8499 rsv->size = min_size;
8503 * 1 for the truncate slack space
8504 * 1 for updating the inode.
8506 trans = btrfs_start_transaction(root, 2);
8507 if (IS_ERR(trans)) {
8508 err = PTR_ERR(trans);
8512 /* Migrate the slack space for the truncate to our reserve */
8513 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
8518 * So if we truncate and then write and fsync we normally would just
8519 * write the extents that changed, which is a problem if we need to
8520 * first truncate that entire inode. So set this flag so we write out
8521 * all of the extents in the inode to the sync log so we're completely
8524 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8525 trans->block_rsv = rsv;
8528 ret = btrfs_truncate_inode_items(trans, root, inode,
8530 BTRFS_EXTENT_DATA_KEY);
8531 if (ret != -ENOSPC) {
8536 trans->block_rsv = &root->fs_info->trans_block_rsv;
8537 ret = btrfs_update_inode(trans, root, inode);
8543 btrfs_end_transaction(trans, root);
8544 btrfs_btree_balance_dirty(root);
8546 trans = btrfs_start_transaction(root, 2);
8547 if (IS_ERR(trans)) {
8548 ret = err = PTR_ERR(trans);
8553 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
8555 BUG_ON(ret); /* shouldn't happen */
8556 trans->block_rsv = rsv;
8559 if (ret == 0 && inode->i_nlink > 0) {
8560 trans->block_rsv = root->orphan_block_rsv;
8561 ret = btrfs_orphan_del(trans, inode);
8567 trans->block_rsv = &root->fs_info->trans_block_rsv;
8568 ret = btrfs_update_inode(trans, root, inode);
8572 ret = btrfs_end_transaction(trans, root);
8573 btrfs_btree_balance_dirty(root);
8577 btrfs_free_block_rsv(root, rsv);
8586 * create a new subvolume directory/inode (helper for the ioctl).
8588 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8589 struct btrfs_root *new_root,
8590 struct btrfs_root *parent_root,
8593 struct inode *inode;
8597 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8598 new_dirid, new_dirid,
8599 S_IFDIR | (~current_umask() & S_IRWXUGO),
8602 return PTR_ERR(inode);
8603 inode->i_op = &btrfs_dir_inode_operations;
8604 inode->i_fop = &btrfs_dir_file_operations;
8606 set_nlink(inode, 1);
8607 btrfs_i_size_write(inode, 0);
8608 unlock_new_inode(inode);
8610 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8612 btrfs_err(new_root->fs_info,
8613 "error inheriting subvolume %llu properties: %d",
8614 new_root->root_key.objectid, err);
8616 err = btrfs_update_inode(trans, new_root, inode);
8622 struct inode *btrfs_alloc_inode(struct super_block *sb)
8624 struct btrfs_inode *ei;
8625 struct inode *inode;
8627 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
8634 ei->last_sub_trans = 0;
8635 ei->logged_trans = 0;
8636 ei->delalloc_bytes = 0;
8637 ei->defrag_bytes = 0;
8638 ei->disk_i_size = 0;
8641 ei->index_cnt = (u64)-1;
8643 ei->last_unlink_trans = 0;
8644 ei->last_log_commit = 0;
8646 spin_lock_init(&ei->lock);
8647 ei->outstanding_extents = 0;
8648 ei->reserved_extents = 0;
8650 ei->runtime_flags = 0;
8651 ei->force_compress = BTRFS_COMPRESS_NONE;
8653 ei->delayed_node = NULL;
8655 ei->i_otime.tv_sec = 0;
8656 ei->i_otime.tv_nsec = 0;
8658 inode = &ei->vfs_inode;
8659 extent_map_tree_init(&ei->extent_tree);
8660 extent_io_tree_init(&ei->io_tree, &inode->i_data);
8661 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
8662 ei->io_tree.track_uptodate = 1;
8663 ei->io_failure_tree.track_uptodate = 1;
8664 atomic_set(&ei->sync_writers, 0);
8665 mutex_init(&ei->log_mutex);
8666 mutex_init(&ei->delalloc_mutex);
8667 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8668 INIT_LIST_HEAD(&ei->delalloc_inodes);
8669 RB_CLEAR_NODE(&ei->rb_node);
8674 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8675 void btrfs_test_destroy_inode(struct inode *inode)
8677 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8678 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8682 static void btrfs_i_callback(struct rcu_head *head)
8684 struct inode *inode = container_of(head, struct inode, i_rcu);
8685 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8688 void btrfs_destroy_inode(struct inode *inode)
8690 struct btrfs_ordered_extent *ordered;
8691 struct btrfs_root *root = BTRFS_I(inode)->root;
8693 WARN_ON(!hlist_empty(&inode->i_dentry));
8694 WARN_ON(inode->i_data.nrpages);
8695 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8696 WARN_ON(BTRFS_I(inode)->reserved_extents);
8697 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8698 WARN_ON(BTRFS_I(inode)->csum_bytes);
8699 WARN_ON(BTRFS_I(inode)->defrag_bytes);
8702 * This can happen where we create an inode, but somebody else also
8703 * created the same inode and we need to destroy the one we already
8709 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8710 &BTRFS_I(inode)->runtime_flags)) {
8711 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
8713 atomic_dec(&root->orphan_inodes);
8717 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8721 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
8722 ordered->file_offset, ordered->len);
8723 btrfs_remove_ordered_extent(inode, ordered);
8724 btrfs_put_ordered_extent(ordered);
8725 btrfs_put_ordered_extent(ordered);
8728 inode_tree_del(inode);
8729 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8731 call_rcu(&inode->i_rcu, btrfs_i_callback);
8734 int btrfs_drop_inode(struct inode *inode)
8736 struct btrfs_root *root = BTRFS_I(inode)->root;
8741 /* the snap/subvol tree is on deleting */
8742 if (btrfs_root_refs(&root->root_item) == 0)
8745 return generic_drop_inode(inode);
8748 static void init_once(void *foo)
8750 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8752 inode_init_once(&ei->vfs_inode);
8755 void btrfs_destroy_cachep(void)
8758 * Make sure all delayed rcu free inodes are flushed before we
8762 if (btrfs_inode_cachep)
8763 kmem_cache_destroy(btrfs_inode_cachep);
8764 if (btrfs_trans_handle_cachep)
8765 kmem_cache_destroy(btrfs_trans_handle_cachep);
8766 if (btrfs_transaction_cachep)
8767 kmem_cache_destroy(btrfs_transaction_cachep);
8768 if (btrfs_path_cachep)
8769 kmem_cache_destroy(btrfs_path_cachep);
8770 if (btrfs_free_space_cachep)
8771 kmem_cache_destroy(btrfs_free_space_cachep);
8772 if (btrfs_delalloc_work_cachep)
8773 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8776 int btrfs_init_cachep(void)
8778 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8779 sizeof(struct btrfs_inode), 0,
8780 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8781 if (!btrfs_inode_cachep)
8784 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8785 sizeof(struct btrfs_trans_handle), 0,
8786 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8787 if (!btrfs_trans_handle_cachep)
8790 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8791 sizeof(struct btrfs_transaction), 0,
8792 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8793 if (!btrfs_transaction_cachep)
8796 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8797 sizeof(struct btrfs_path), 0,
8798 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8799 if (!btrfs_path_cachep)
8802 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8803 sizeof(struct btrfs_free_space), 0,
8804 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8805 if (!btrfs_free_space_cachep)
8808 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8809 sizeof(struct btrfs_delalloc_work), 0,
8810 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8812 if (!btrfs_delalloc_work_cachep)
8817 btrfs_destroy_cachep();
8821 static int btrfs_getattr(struct vfsmount *mnt,
8822 struct dentry *dentry, struct kstat *stat)
8825 struct inode *inode = dentry->d_inode;
8826 u32 blocksize = inode->i_sb->s_blocksize;
8828 generic_fillattr(inode, stat);
8829 stat->dev = BTRFS_I(inode)->root->anon_dev;
8830 stat->blksize = PAGE_CACHE_SIZE;
8832 spin_lock(&BTRFS_I(inode)->lock);
8833 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8834 spin_unlock(&BTRFS_I(inode)->lock);
8835 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8836 ALIGN(delalloc_bytes, blocksize)) >> 9;
8840 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8841 struct inode *new_dir, struct dentry *new_dentry)
8843 struct btrfs_trans_handle *trans;
8844 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8845 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8846 struct inode *new_inode = new_dentry->d_inode;
8847 struct inode *old_inode = old_dentry->d_inode;
8848 struct timespec ctime = CURRENT_TIME;
8852 u64 old_ino = btrfs_ino(old_inode);
8854 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8857 /* we only allow rename subvolume link between subvolumes */
8858 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8861 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8862 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8865 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8866 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8870 /* check for collisions, even if the name isn't there */
8871 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8872 new_dentry->d_name.name,
8873 new_dentry->d_name.len);
8876 if (ret == -EEXIST) {
8878 * eexist without a new_inode */
8879 if (WARN_ON(!new_inode)) {
8883 /* maybe -EOVERFLOW */
8890 * we're using rename to replace one file with another. Start IO on it
8891 * now so we don't add too much work to the end of the transaction
8893 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
8894 filemap_flush(old_inode->i_mapping);
8896 /* close the racy window with snapshot create/destroy ioctl */
8897 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8898 down_read(&root->fs_info->subvol_sem);
8900 * We want to reserve the absolute worst case amount of items. So if
8901 * both inodes are subvols and we need to unlink them then that would
8902 * require 4 item modifications, but if they are both normal inodes it
8903 * would require 5 item modifications, so we'll assume their normal
8904 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8905 * should cover the worst case number of items we'll modify.
8907 trans = btrfs_start_transaction(root, 11);
8908 if (IS_ERR(trans)) {
8909 ret = PTR_ERR(trans);
8914 btrfs_record_root_in_trans(trans, dest);
8916 ret = btrfs_set_inode_index(new_dir, &index);
8920 BTRFS_I(old_inode)->dir_index = 0ULL;
8921 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8922 /* force full log commit if subvolume involved. */
8923 btrfs_set_log_full_commit(root->fs_info, trans);
8925 ret = btrfs_insert_inode_ref(trans, dest,
8926 new_dentry->d_name.name,
8927 new_dentry->d_name.len,
8929 btrfs_ino(new_dir), index);
8933 * this is an ugly little race, but the rename is required
8934 * to make sure that if we crash, the inode is either at the
8935 * old name or the new one. pinning the log transaction lets
8936 * us make sure we don't allow a log commit to come in after
8937 * we unlink the name but before we add the new name back in.
8939 btrfs_pin_log_trans(root);
8942 inode_inc_iversion(old_dir);
8943 inode_inc_iversion(new_dir);
8944 inode_inc_iversion(old_inode);
8945 old_dir->i_ctime = old_dir->i_mtime = ctime;
8946 new_dir->i_ctime = new_dir->i_mtime = ctime;
8947 old_inode->i_ctime = ctime;
8949 if (old_dentry->d_parent != new_dentry->d_parent)
8950 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8952 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8953 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8954 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8955 old_dentry->d_name.name,
8956 old_dentry->d_name.len);
8958 ret = __btrfs_unlink_inode(trans, root, old_dir,
8959 old_dentry->d_inode,
8960 old_dentry->d_name.name,
8961 old_dentry->d_name.len);
8963 ret = btrfs_update_inode(trans, root, old_inode);
8966 btrfs_abort_transaction(trans, root, ret);
8971 inode_inc_iversion(new_inode);
8972 new_inode->i_ctime = CURRENT_TIME;
8973 if (unlikely(btrfs_ino(new_inode) ==
8974 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8975 root_objectid = BTRFS_I(new_inode)->location.objectid;
8976 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8978 new_dentry->d_name.name,
8979 new_dentry->d_name.len);
8980 BUG_ON(new_inode->i_nlink == 0);
8982 ret = btrfs_unlink_inode(trans, dest, new_dir,
8983 new_dentry->d_inode,
8984 new_dentry->d_name.name,
8985 new_dentry->d_name.len);
8987 if (!ret && new_inode->i_nlink == 0)
8988 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8990 btrfs_abort_transaction(trans, root, ret);
8995 ret = btrfs_add_link(trans, new_dir, old_inode,
8996 new_dentry->d_name.name,
8997 new_dentry->d_name.len, 0, index);
8999 btrfs_abort_transaction(trans, root, ret);
9003 if (old_inode->i_nlink == 1)
9004 BTRFS_I(old_inode)->dir_index = index;
9006 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
9007 struct dentry *parent = new_dentry->d_parent;
9008 btrfs_log_new_name(trans, old_inode, old_dir, parent);
9009 btrfs_end_log_trans(root);
9012 btrfs_end_transaction(trans, root);
9014 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9015 up_read(&root->fs_info->subvol_sem);
9020 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9021 struct inode *new_dir, struct dentry *new_dentry,
9024 if (flags & ~RENAME_NOREPLACE)
9027 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry);
9030 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9032 struct btrfs_delalloc_work *delalloc_work;
9033 struct inode *inode;
9035 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9037 inode = delalloc_work->inode;
9038 if (delalloc_work->wait) {
9039 btrfs_wait_ordered_range(inode, 0, (u64)-1);
9041 filemap_flush(inode->i_mapping);
9042 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9043 &BTRFS_I(inode)->runtime_flags))
9044 filemap_flush(inode->i_mapping);
9047 if (delalloc_work->delay_iput)
9048 btrfs_add_delayed_iput(inode);
9051 complete(&delalloc_work->completion);
9054 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
9055 int wait, int delay_iput)
9057 struct btrfs_delalloc_work *work;
9059 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
9063 init_completion(&work->completion);
9064 INIT_LIST_HEAD(&work->list);
9065 work->inode = inode;
9067 work->delay_iput = delay_iput;
9068 WARN_ON_ONCE(!inode);
9069 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9070 btrfs_run_delalloc_work, NULL, NULL);
9075 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
9077 wait_for_completion(&work->completion);
9078 kmem_cache_free(btrfs_delalloc_work_cachep, work);
9082 * some fairly slow code that needs optimization. This walks the list
9083 * of all the inodes with pending delalloc and forces them to disk.
9085 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
9088 struct btrfs_inode *binode;
9089 struct inode *inode;
9090 struct btrfs_delalloc_work *work, *next;
9091 struct list_head works;
9092 struct list_head splice;
9095 INIT_LIST_HEAD(&works);
9096 INIT_LIST_HEAD(&splice);
9098 mutex_lock(&root->delalloc_mutex);
9099 spin_lock(&root->delalloc_lock);
9100 list_splice_init(&root->delalloc_inodes, &splice);
9101 while (!list_empty(&splice)) {
9102 binode = list_entry(splice.next, struct btrfs_inode,
9105 list_move_tail(&binode->delalloc_inodes,
9106 &root->delalloc_inodes);
9107 inode = igrab(&binode->vfs_inode);
9109 cond_resched_lock(&root->delalloc_lock);
9112 spin_unlock(&root->delalloc_lock);
9114 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
9117 btrfs_add_delayed_iput(inode);
9123 list_add_tail(&work->list, &works);
9124 btrfs_queue_work(root->fs_info->flush_workers,
9127 if (nr != -1 && ret >= nr)
9130 spin_lock(&root->delalloc_lock);
9132 spin_unlock(&root->delalloc_lock);
9135 list_for_each_entry_safe(work, next, &works, list) {
9136 list_del_init(&work->list);
9137 btrfs_wait_and_free_delalloc_work(work);
9140 if (!list_empty_careful(&splice)) {
9141 spin_lock(&root->delalloc_lock);
9142 list_splice_tail(&splice, &root->delalloc_inodes);
9143 spin_unlock(&root->delalloc_lock);
9145 mutex_unlock(&root->delalloc_mutex);
9149 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
9153 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
9156 ret = __start_delalloc_inodes(root, delay_iput, -1);
9160 * the filemap_flush will queue IO into the worker threads, but
9161 * we have to make sure the IO is actually started and that
9162 * ordered extents get created before we return
9164 atomic_inc(&root->fs_info->async_submit_draining);
9165 while (atomic_read(&root->fs_info->nr_async_submits) ||
9166 atomic_read(&root->fs_info->async_delalloc_pages)) {
9167 wait_event(root->fs_info->async_submit_wait,
9168 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
9169 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
9171 atomic_dec(&root->fs_info->async_submit_draining);
9175 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
9178 struct btrfs_root *root;
9179 struct list_head splice;
9182 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9185 INIT_LIST_HEAD(&splice);
9187 mutex_lock(&fs_info->delalloc_root_mutex);
9188 spin_lock(&fs_info->delalloc_root_lock);
9189 list_splice_init(&fs_info->delalloc_roots, &splice);
9190 while (!list_empty(&splice) && nr) {
9191 root = list_first_entry(&splice, struct btrfs_root,
9193 root = btrfs_grab_fs_root(root);
9195 list_move_tail(&root->delalloc_root,
9196 &fs_info->delalloc_roots);
9197 spin_unlock(&fs_info->delalloc_root_lock);
9199 ret = __start_delalloc_inodes(root, delay_iput, nr);
9200 btrfs_put_fs_root(root);
9208 spin_lock(&fs_info->delalloc_root_lock);
9210 spin_unlock(&fs_info->delalloc_root_lock);
9213 atomic_inc(&fs_info->async_submit_draining);
9214 while (atomic_read(&fs_info->nr_async_submits) ||
9215 atomic_read(&fs_info->async_delalloc_pages)) {
9216 wait_event(fs_info->async_submit_wait,
9217 (atomic_read(&fs_info->nr_async_submits) == 0 &&
9218 atomic_read(&fs_info->async_delalloc_pages) == 0));
9220 atomic_dec(&fs_info->async_submit_draining);
9222 if (!list_empty_careful(&splice)) {
9223 spin_lock(&fs_info->delalloc_root_lock);
9224 list_splice_tail(&splice, &fs_info->delalloc_roots);
9225 spin_unlock(&fs_info->delalloc_root_lock);
9227 mutex_unlock(&fs_info->delalloc_root_mutex);
9231 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9232 const char *symname)
9234 struct btrfs_trans_handle *trans;
9235 struct btrfs_root *root = BTRFS_I(dir)->root;
9236 struct btrfs_path *path;
9237 struct btrfs_key key;
9238 struct inode *inode = NULL;
9246 struct btrfs_file_extent_item *ei;
9247 struct extent_buffer *leaf;
9249 name_len = strlen(symname);
9250 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
9251 return -ENAMETOOLONG;
9254 * 2 items for inode item and ref
9255 * 2 items for dir items
9256 * 1 item for xattr if selinux is on
9258 trans = btrfs_start_transaction(root, 5);
9260 return PTR_ERR(trans);
9262 err = btrfs_find_free_ino(root, &objectid);
9266 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9267 dentry->d_name.len, btrfs_ino(dir), objectid,
9268 S_IFLNK|S_IRWXUGO, &index);
9269 if (IS_ERR(inode)) {
9270 err = PTR_ERR(inode);
9275 * If the active LSM wants to access the inode during
9276 * d_instantiate it needs these. Smack checks to see
9277 * if the filesystem supports xattrs by looking at the
9280 inode->i_fop = &btrfs_file_operations;
9281 inode->i_op = &btrfs_file_inode_operations;
9282 inode->i_mapping->a_ops = &btrfs_aops;
9283 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9284 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9286 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9288 goto out_unlock_inode;
9290 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
9292 goto out_unlock_inode;
9294 path = btrfs_alloc_path();
9297 goto out_unlock_inode;
9299 key.objectid = btrfs_ino(inode);
9301 key.type = BTRFS_EXTENT_DATA_KEY;
9302 datasize = btrfs_file_extent_calc_inline_size(name_len);
9303 err = btrfs_insert_empty_item(trans, root, path, &key,
9306 btrfs_free_path(path);
9307 goto out_unlock_inode;
9309 leaf = path->nodes[0];
9310 ei = btrfs_item_ptr(leaf, path->slots[0],
9311 struct btrfs_file_extent_item);
9312 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9313 btrfs_set_file_extent_type(leaf, ei,
9314 BTRFS_FILE_EXTENT_INLINE);
9315 btrfs_set_file_extent_encryption(leaf, ei, 0);
9316 btrfs_set_file_extent_compression(leaf, ei, 0);
9317 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9318 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9320 ptr = btrfs_file_extent_inline_start(ei);
9321 write_extent_buffer(leaf, symname, ptr, name_len);
9322 btrfs_mark_buffer_dirty(leaf);
9323 btrfs_free_path(path);
9325 inode->i_op = &btrfs_symlink_inode_operations;
9326 inode->i_mapping->a_ops = &btrfs_symlink_aops;
9327 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9328 inode_set_bytes(inode, name_len);
9329 btrfs_i_size_write(inode, name_len);
9330 err = btrfs_update_inode(trans, root, inode);
9333 goto out_unlock_inode;
9336 unlock_new_inode(inode);
9337 d_instantiate(dentry, inode);
9340 btrfs_end_transaction(trans, root);
9342 inode_dec_link_count(inode);
9345 btrfs_btree_balance_dirty(root);
9350 unlock_new_inode(inode);
9354 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9355 u64 start, u64 num_bytes, u64 min_size,
9356 loff_t actual_len, u64 *alloc_hint,
9357 struct btrfs_trans_handle *trans)
9359 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9360 struct extent_map *em;
9361 struct btrfs_root *root = BTRFS_I(inode)->root;
9362 struct btrfs_key ins;
9363 u64 cur_offset = start;
9367 bool own_trans = true;
9371 while (num_bytes > 0) {
9373 trans = btrfs_start_transaction(root, 3);
9374 if (IS_ERR(trans)) {
9375 ret = PTR_ERR(trans);
9380 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
9381 cur_bytes = max(cur_bytes, min_size);
9382 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
9383 *alloc_hint, &ins, 1, 0);
9386 btrfs_end_transaction(trans, root);
9390 ret = insert_reserved_file_extent(trans, inode,
9391 cur_offset, ins.objectid,
9392 ins.offset, ins.offset,
9393 ins.offset, 0, 0, 0,
9394 BTRFS_FILE_EXTENT_PREALLOC);
9396 btrfs_free_reserved_extent(root, ins.objectid,
9398 btrfs_abort_transaction(trans, root, ret);
9400 btrfs_end_transaction(trans, root);
9403 btrfs_drop_extent_cache(inode, cur_offset,
9404 cur_offset + ins.offset -1, 0);
9406 em = alloc_extent_map();
9408 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9409 &BTRFS_I(inode)->runtime_flags);
9413 em->start = cur_offset;
9414 em->orig_start = cur_offset;
9415 em->len = ins.offset;
9416 em->block_start = ins.objectid;
9417 em->block_len = ins.offset;
9418 em->orig_block_len = ins.offset;
9419 em->ram_bytes = ins.offset;
9420 em->bdev = root->fs_info->fs_devices->latest_bdev;
9421 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9422 em->generation = trans->transid;
9425 write_lock(&em_tree->lock);
9426 ret = add_extent_mapping(em_tree, em, 1);
9427 write_unlock(&em_tree->lock);
9430 btrfs_drop_extent_cache(inode, cur_offset,
9431 cur_offset + ins.offset - 1,
9434 free_extent_map(em);
9436 num_bytes -= ins.offset;
9437 cur_offset += ins.offset;
9438 *alloc_hint = ins.objectid + ins.offset;
9440 inode_inc_iversion(inode);
9441 inode->i_ctime = CURRENT_TIME;
9442 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9443 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9444 (actual_len > inode->i_size) &&
9445 (cur_offset > inode->i_size)) {
9446 if (cur_offset > actual_len)
9447 i_size = actual_len;
9449 i_size = cur_offset;
9450 i_size_write(inode, i_size);
9451 btrfs_ordered_update_i_size(inode, i_size, NULL);
9454 ret = btrfs_update_inode(trans, root, inode);
9457 btrfs_abort_transaction(trans, root, ret);
9459 btrfs_end_transaction(trans, root);
9464 btrfs_end_transaction(trans, root);
9469 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9470 u64 start, u64 num_bytes, u64 min_size,
9471 loff_t actual_len, u64 *alloc_hint)
9473 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9474 min_size, actual_len, alloc_hint,
9478 int btrfs_prealloc_file_range_trans(struct inode *inode,
9479 struct btrfs_trans_handle *trans, int mode,
9480 u64 start, u64 num_bytes, u64 min_size,
9481 loff_t actual_len, u64 *alloc_hint)
9483 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9484 min_size, actual_len, alloc_hint, trans);
9487 static int btrfs_set_page_dirty(struct page *page)
9489 return __set_page_dirty_nobuffers(page);
9492 static int btrfs_permission(struct inode *inode, int mask)
9494 struct btrfs_root *root = BTRFS_I(inode)->root;
9495 umode_t mode = inode->i_mode;
9497 if (mask & MAY_WRITE &&
9498 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9499 if (btrfs_root_readonly(root))
9501 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9504 return generic_permission(inode, mask);
9507 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9509 struct btrfs_trans_handle *trans;
9510 struct btrfs_root *root = BTRFS_I(dir)->root;
9511 struct inode *inode = NULL;
9517 * 5 units required for adding orphan entry
9519 trans = btrfs_start_transaction(root, 5);
9521 return PTR_ERR(trans);
9523 ret = btrfs_find_free_ino(root, &objectid);
9527 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9528 btrfs_ino(dir), objectid, mode, &index);
9529 if (IS_ERR(inode)) {
9530 ret = PTR_ERR(inode);
9535 inode->i_fop = &btrfs_file_operations;
9536 inode->i_op = &btrfs_file_inode_operations;
9538 inode->i_mapping->a_ops = &btrfs_aops;
9539 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9540 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9542 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9546 ret = btrfs_update_inode(trans, root, inode);
9549 ret = btrfs_orphan_add(trans, inode);
9554 * We set number of links to 0 in btrfs_new_inode(), and here we set
9555 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9558 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9560 set_nlink(inode, 1);
9561 unlock_new_inode(inode);
9562 d_tmpfile(dentry, inode);
9563 mark_inode_dirty(inode);
9566 btrfs_end_transaction(trans, root);
9569 btrfs_balance_delayed_items(root);
9570 btrfs_btree_balance_dirty(root);
9574 unlock_new_inode(inode);
9579 /* Inspired by filemap_check_errors() */
9580 int btrfs_inode_check_errors(struct inode *inode)
9584 if (test_bit(AS_ENOSPC, &inode->i_mapping->flags) &&
9585 test_and_clear_bit(AS_ENOSPC, &inode->i_mapping->flags))
9587 if (test_bit(AS_EIO, &inode->i_mapping->flags) &&
9588 test_and_clear_bit(AS_EIO, &inode->i_mapping->flags))
9594 static const struct inode_operations btrfs_dir_inode_operations = {
9595 .getattr = btrfs_getattr,
9596 .lookup = btrfs_lookup,
9597 .create = btrfs_create,
9598 .unlink = btrfs_unlink,
9600 .mkdir = btrfs_mkdir,
9601 .rmdir = btrfs_rmdir,
9602 .rename2 = btrfs_rename2,
9603 .symlink = btrfs_symlink,
9604 .setattr = btrfs_setattr,
9605 .mknod = btrfs_mknod,
9606 .setxattr = btrfs_setxattr,
9607 .getxattr = btrfs_getxattr,
9608 .listxattr = btrfs_listxattr,
9609 .removexattr = btrfs_removexattr,
9610 .permission = btrfs_permission,
9611 .get_acl = btrfs_get_acl,
9612 .set_acl = btrfs_set_acl,
9613 .update_time = btrfs_update_time,
9614 .tmpfile = btrfs_tmpfile,
9616 static const struct inode_operations btrfs_dir_ro_inode_operations = {
9617 .lookup = btrfs_lookup,
9618 .permission = btrfs_permission,
9619 .get_acl = btrfs_get_acl,
9620 .set_acl = btrfs_set_acl,
9621 .update_time = btrfs_update_time,
9624 static const struct file_operations btrfs_dir_file_operations = {
9625 .llseek = generic_file_llseek,
9626 .read = generic_read_dir,
9627 .iterate = btrfs_real_readdir,
9628 .unlocked_ioctl = btrfs_ioctl,
9629 #ifdef CONFIG_COMPAT
9630 .compat_ioctl = btrfs_ioctl,
9632 .release = btrfs_release_file,
9633 .fsync = btrfs_sync_file,
9636 static struct extent_io_ops btrfs_extent_io_ops = {
9637 .fill_delalloc = run_delalloc_range,
9638 .submit_bio_hook = btrfs_submit_bio_hook,
9639 .merge_bio_hook = btrfs_merge_bio_hook,
9640 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
9641 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
9642 .writepage_start_hook = btrfs_writepage_start_hook,
9643 .set_bit_hook = btrfs_set_bit_hook,
9644 .clear_bit_hook = btrfs_clear_bit_hook,
9645 .merge_extent_hook = btrfs_merge_extent_hook,
9646 .split_extent_hook = btrfs_split_extent_hook,
9650 * btrfs doesn't support the bmap operation because swapfiles
9651 * use bmap to make a mapping of extents in the file. They assume
9652 * these extents won't change over the life of the file and they
9653 * use the bmap result to do IO directly to the drive.
9655 * the btrfs bmap call would return logical addresses that aren't
9656 * suitable for IO and they also will change frequently as COW
9657 * operations happen. So, swapfile + btrfs == corruption.
9659 * For now we're avoiding this by dropping bmap.
9661 static const struct address_space_operations btrfs_aops = {
9662 .readpage = btrfs_readpage,
9663 .writepage = btrfs_writepage,
9664 .writepages = btrfs_writepages,
9665 .readpages = btrfs_readpages,
9666 .direct_IO = btrfs_direct_IO,
9667 .invalidatepage = btrfs_invalidatepage,
9668 .releasepage = btrfs_releasepage,
9669 .set_page_dirty = btrfs_set_page_dirty,
9670 .error_remove_page = generic_error_remove_page,
9673 static const struct address_space_operations btrfs_symlink_aops = {
9674 .readpage = btrfs_readpage,
9675 .writepage = btrfs_writepage,
9676 .invalidatepage = btrfs_invalidatepage,
9677 .releasepage = btrfs_releasepage,
9680 static const struct inode_operations btrfs_file_inode_operations = {
9681 .getattr = btrfs_getattr,
9682 .setattr = btrfs_setattr,
9683 .setxattr = btrfs_setxattr,
9684 .getxattr = btrfs_getxattr,
9685 .listxattr = btrfs_listxattr,
9686 .removexattr = btrfs_removexattr,
9687 .permission = btrfs_permission,
9688 .fiemap = btrfs_fiemap,
9689 .get_acl = btrfs_get_acl,
9690 .set_acl = btrfs_set_acl,
9691 .update_time = btrfs_update_time,
9693 static const struct inode_operations btrfs_special_inode_operations = {
9694 .getattr = btrfs_getattr,
9695 .setattr = btrfs_setattr,
9696 .permission = btrfs_permission,
9697 .setxattr = btrfs_setxattr,
9698 .getxattr = btrfs_getxattr,
9699 .listxattr = btrfs_listxattr,
9700 .removexattr = btrfs_removexattr,
9701 .get_acl = btrfs_get_acl,
9702 .set_acl = btrfs_set_acl,
9703 .update_time = btrfs_update_time,
9705 static const struct inode_operations btrfs_symlink_inode_operations = {
9706 .readlink = generic_readlink,
9707 .follow_link = page_follow_link_light,
9708 .put_link = page_put_link,
9709 .getattr = btrfs_getattr,
9710 .setattr = btrfs_setattr,
9711 .permission = btrfs_permission,
9712 .setxattr = btrfs_setxattr,
9713 .getxattr = btrfs_getxattr,
9714 .listxattr = btrfs_listxattr,
9715 .removexattr = btrfs_removexattr,
9716 .update_time = btrfs_update_time,
9719 const struct dentry_operations btrfs_dentry_operations = {
9720 .d_delete = btrfs_dentry_delete,
9721 .d_release = btrfs_dentry_release,