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 int 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);
415 * skip compression for a small file range(<=blocksize) that
416 * isn't an inline extent, since it dosen't save disk space at all.
418 if ((end - start + 1) <= blocksize &&
419 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
420 goto cleanup_and_bail_uncompressed;
422 actual_end = min_t(u64, isize, end + 1);
425 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
426 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
429 * we don't want to send crud past the end of i_size through
430 * compression, that's just a waste of CPU time. So, if the
431 * end of the file is before the start of our current
432 * requested range of bytes, we bail out to the uncompressed
433 * cleanup code that can deal with all of this.
435 * It isn't really the fastest way to fix things, but this is a
436 * very uncommon corner.
438 if (actual_end <= start)
439 goto cleanup_and_bail_uncompressed;
441 total_compressed = actual_end - start;
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 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
533 * inline extent creation worked or returned error,
534 * we don't need to create any more async work items.
535 * Unlock and free up our temp pages.
537 extent_clear_unlock_delalloc(inode, start, end, NULL,
538 clear_flags, PAGE_UNLOCK |
548 * we aren't doing an inline extent round the compressed size
549 * up to a block size boundary so the allocator does sane
552 total_compressed = ALIGN(total_compressed, blocksize);
555 * one last check to make sure the compression is really a
556 * win, compare the page count read with the blocks on disk
558 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
559 if (total_compressed >= total_in) {
562 num_bytes = total_in;
565 if (!will_compress && pages) {
567 * the compression code ran but failed to make things smaller,
568 * free any pages it allocated and our page pointer array
570 for (i = 0; i < nr_pages_ret; i++) {
571 WARN_ON(pages[i]->mapping);
572 page_cache_release(pages[i]);
576 total_compressed = 0;
579 /* flag the file so we don't compress in the future */
580 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
581 !(BTRFS_I(inode)->force_compress)) {
582 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
588 /* the async work queues will take care of doing actual
589 * allocation on disk for these compressed pages,
590 * and will submit them to the elevator.
592 add_async_extent(async_cow, start, num_bytes,
593 total_compressed, pages, nr_pages_ret,
596 if (start + num_bytes < end) {
603 cleanup_and_bail_uncompressed:
605 * No compression, but we still need to write the pages in
606 * the file we've been given so far. redirty the locked
607 * page if it corresponds to our extent and set things up
608 * for the async work queue to run cow_file_range to do
609 * the normal delalloc dance
611 if (page_offset(locked_page) >= start &&
612 page_offset(locked_page) <= end) {
613 __set_page_dirty_nobuffers(locked_page);
614 /* unlocked later on in the async handlers */
617 extent_range_redirty_for_io(inode, start, end);
618 add_async_extent(async_cow, start, end - start + 1,
619 0, NULL, 0, BTRFS_COMPRESS_NONE);
627 for (i = 0; i < nr_pages_ret; i++) {
628 WARN_ON(pages[i]->mapping);
629 page_cache_release(pages[i]);
637 * phase two of compressed writeback. This is the ordered portion
638 * of the code, which only gets called in the order the work was
639 * queued. We walk all the async extents created by compress_file_range
640 * and send them down to the disk.
642 static noinline int submit_compressed_extents(struct inode *inode,
643 struct async_cow *async_cow)
645 struct async_extent *async_extent;
647 struct btrfs_key ins;
648 struct extent_map *em;
649 struct btrfs_root *root = BTRFS_I(inode)->root;
650 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
651 struct extent_io_tree *io_tree;
654 if (list_empty(&async_cow->extents))
658 while (!list_empty(&async_cow->extents)) {
659 async_extent = list_entry(async_cow->extents.next,
660 struct async_extent, list);
661 list_del(&async_extent->list);
663 io_tree = &BTRFS_I(inode)->io_tree;
666 /* did the compression code fall back to uncompressed IO? */
667 if (!async_extent->pages) {
668 int page_started = 0;
669 unsigned long nr_written = 0;
671 lock_extent(io_tree, async_extent->start,
672 async_extent->start +
673 async_extent->ram_size - 1);
675 /* allocate blocks */
676 ret = cow_file_range(inode, async_cow->locked_page,
678 async_extent->start +
679 async_extent->ram_size - 1,
680 &page_started, &nr_written, 0);
685 * if page_started, cow_file_range inserted an
686 * inline extent and took care of all the unlocking
687 * and IO for us. Otherwise, we need to submit
688 * all those pages down to the drive.
690 if (!page_started && !ret)
691 extent_write_locked_range(io_tree,
692 inode, async_extent->start,
693 async_extent->start +
694 async_extent->ram_size - 1,
698 unlock_page(async_cow->locked_page);
704 lock_extent(io_tree, async_extent->start,
705 async_extent->start + async_extent->ram_size - 1);
707 ret = btrfs_reserve_extent(root,
708 async_extent->compressed_size,
709 async_extent->compressed_size,
710 0, alloc_hint, &ins, 1, 1);
714 for (i = 0; i < async_extent->nr_pages; i++) {
715 WARN_ON(async_extent->pages[i]->mapping);
716 page_cache_release(async_extent->pages[i]);
718 kfree(async_extent->pages);
719 async_extent->nr_pages = 0;
720 async_extent->pages = NULL;
722 if (ret == -ENOSPC) {
723 unlock_extent(io_tree, async_extent->start,
724 async_extent->start +
725 async_extent->ram_size - 1);
728 * we need to redirty the pages if we decide to
729 * fallback to uncompressed IO, otherwise we
730 * will not submit these pages down to lower
733 extent_range_redirty_for_io(inode,
735 async_extent->start +
736 async_extent->ram_size - 1);
744 * here we're doing allocation and writeback of the
747 btrfs_drop_extent_cache(inode, async_extent->start,
748 async_extent->start +
749 async_extent->ram_size - 1, 0);
751 em = alloc_extent_map();
754 goto out_free_reserve;
756 em->start = async_extent->start;
757 em->len = async_extent->ram_size;
758 em->orig_start = em->start;
759 em->mod_start = em->start;
760 em->mod_len = em->len;
762 em->block_start = ins.objectid;
763 em->block_len = ins.offset;
764 em->orig_block_len = ins.offset;
765 em->ram_bytes = async_extent->ram_size;
766 em->bdev = root->fs_info->fs_devices->latest_bdev;
767 em->compress_type = async_extent->compress_type;
768 set_bit(EXTENT_FLAG_PINNED, &em->flags);
769 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
773 write_lock(&em_tree->lock);
774 ret = add_extent_mapping(em_tree, em, 1);
775 write_unlock(&em_tree->lock);
776 if (ret != -EEXIST) {
780 btrfs_drop_extent_cache(inode, async_extent->start,
781 async_extent->start +
782 async_extent->ram_size - 1, 0);
786 goto out_free_reserve;
788 ret = btrfs_add_ordered_extent_compress(inode,
791 async_extent->ram_size,
793 BTRFS_ORDERED_COMPRESSED,
794 async_extent->compress_type);
796 btrfs_drop_extent_cache(inode, async_extent->start,
797 async_extent->start +
798 async_extent->ram_size - 1, 0);
799 goto out_free_reserve;
803 * clear dirty, set writeback and unlock the pages.
805 extent_clear_unlock_delalloc(inode, async_extent->start,
806 async_extent->start +
807 async_extent->ram_size - 1,
808 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
809 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
811 ret = btrfs_submit_compressed_write(inode,
813 async_extent->ram_size,
815 ins.offset, async_extent->pages,
816 async_extent->nr_pages);
817 alloc_hint = ins.objectid + ins.offset;
827 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
829 extent_clear_unlock_delalloc(inode, async_extent->start,
830 async_extent->start +
831 async_extent->ram_size - 1,
832 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
833 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
834 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
835 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
840 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
843 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
844 struct extent_map *em;
847 read_lock(&em_tree->lock);
848 em = search_extent_mapping(em_tree, start, num_bytes);
851 * if block start isn't an actual block number then find the
852 * first block in this inode and use that as a hint. If that
853 * block is also bogus then just don't worry about it.
855 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
857 em = search_extent_mapping(em_tree, 0, 0);
858 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
859 alloc_hint = em->block_start;
863 alloc_hint = em->block_start;
867 read_unlock(&em_tree->lock);
873 * when extent_io.c finds a delayed allocation range in the file,
874 * the call backs end up in this code. The basic idea is to
875 * allocate extents on disk for the range, and create ordered data structs
876 * in ram to track those extents.
878 * locked_page is the page that writepage had locked already. We use
879 * it to make sure we don't do extra locks or unlocks.
881 * *page_started is set to one if we unlock locked_page and do everything
882 * required to start IO on it. It may be clean and already done with
885 static noinline int cow_file_range(struct inode *inode,
886 struct page *locked_page,
887 u64 start, u64 end, int *page_started,
888 unsigned long *nr_written,
891 struct btrfs_root *root = BTRFS_I(inode)->root;
894 unsigned long ram_size;
897 u64 blocksize = root->sectorsize;
898 struct btrfs_key ins;
899 struct extent_map *em;
900 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
903 if (btrfs_is_free_space_inode(inode)) {
909 num_bytes = ALIGN(end - start + 1, blocksize);
910 num_bytes = max(blocksize, num_bytes);
911 disk_num_bytes = num_bytes;
913 /* if this is a small write inside eof, kick off defrag */
914 if (num_bytes < 64 * 1024 &&
915 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
916 btrfs_add_inode_defrag(NULL, inode);
919 /* lets try to make an inline extent */
920 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
923 extent_clear_unlock_delalloc(inode, start, end, NULL,
924 EXTENT_LOCKED | EXTENT_DELALLOC |
925 EXTENT_DEFRAG, PAGE_UNLOCK |
926 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
929 *nr_written = *nr_written +
930 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
933 } else if (ret < 0) {
938 BUG_ON(disk_num_bytes >
939 btrfs_super_total_bytes(root->fs_info->super_copy));
941 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
942 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
944 while (disk_num_bytes > 0) {
947 cur_alloc_size = disk_num_bytes;
948 ret = btrfs_reserve_extent(root, cur_alloc_size,
949 root->sectorsize, 0, alloc_hint,
954 em = alloc_extent_map();
960 em->orig_start = em->start;
961 ram_size = ins.offset;
962 em->len = ins.offset;
963 em->mod_start = em->start;
964 em->mod_len = em->len;
966 em->block_start = ins.objectid;
967 em->block_len = ins.offset;
968 em->orig_block_len = ins.offset;
969 em->ram_bytes = ram_size;
970 em->bdev = root->fs_info->fs_devices->latest_bdev;
971 set_bit(EXTENT_FLAG_PINNED, &em->flags);
975 write_lock(&em_tree->lock);
976 ret = add_extent_mapping(em_tree, em, 1);
977 write_unlock(&em_tree->lock);
978 if (ret != -EEXIST) {
982 btrfs_drop_extent_cache(inode, start,
983 start + ram_size - 1, 0);
988 cur_alloc_size = ins.offset;
989 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
990 ram_size, cur_alloc_size, 0);
992 goto out_drop_extent_cache;
994 if (root->root_key.objectid ==
995 BTRFS_DATA_RELOC_TREE_OBJECTID) {
996 ret = btrfs_reloc_clone_csums(inode, start,
999 goto out_drop_extent_cache;
1002 if (disk_num_bytes < cur_alloc_size)
1005 /* we're not doing compressed IO, don't unlock the first
1006 * page (which the caller expects to stay locked), don't
1007 * clear any dirty bits and don't set any writeback bits
1009 * Do set the Private2 bit so we know this page was properly
1010 * setup for writepage
1012 op = unlock ? PAGE_UNLOCK : 0;
1013 op |= PAGE_SET_PRIVATE2;
1015 extent_clear_unlock_delalloc(inode, start,
1016 start + ram_size - 1, locked_page,
1017 EXTENT_LOCKED | EXTENT_DELALLOC,
1019 disk_num_bytes -= cur_alloc_size;
1020 num_bytes -= cur_alloc_size;
1021 alloc_hint = ins.objectid + ins.offset;
1022 start += cur_alloc_size;
1027 out_drop_extent_cache:
1028 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1030 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1032 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1033 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1034 EXTENT_DELALLOC | EXTENT_DEFRAG,
1035 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1036 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1041 * work queue call back to started compression on a file and pages
1043 static noinline void async_cow_start(struct btrfs_work *work)
1045 struct async_cow *async_cow;
1047 async_cow = container_of(work, struct async_cow, work);
1049 compress_file_range(async_cow->inode, async_cow->locked_page,
1050 async_cow->start, async_cow->end, async_cow,
1052 if (num_added == 0) {
1053 btrfs_add_delayed_iput(async_cow->inode);
1054 async_cow->inode = NULL;
1059 * work queue call back to submit previously compressed pages
1061 static noinline void async_cow_submit(struct btrfs_work *work)
1063 struct async_cow *async_cow;
1064 struct btrfs_root *root;
1065 unsigned long nr_pages;
1067 async_cow = container_of(work, struct async_cow, work);
1069 root = async_cow->root;
1070 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1073 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1075 waitqueue_active(&root->fs_info->async_submit_wait))
1076 wake_up(&root->fs_info->async_submit_wait);
1078 if (async_cow->inode)
1079 submit_compressed_extents(async_cow->inode, async_cow);
1082 static noinline void async_cow_free(struct btrfs_work *work)
1084 struct async_cow *async_cow;
1085 async_cow = container_of(work, struct async_cow, work);
1086 if (async_cow->inode)
1087 btrfs_add_delayed_iput(async_cow->inode);
1091 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1092 u64 start, u64 end, int *page_started,
1093 unsigned long *nr_written)
1095 struct async_cow *async_cow;
1096 struct btrfs_root *root = BTRFS_I(inode)->root;
1097 unsigned long nr_pages;
1099 int limit = 10 * 1024 * 1024;
1101 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1102 1, 0, NULL, GFP_NOFS);
1103 while (start < end) {
1104 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1105 BUG_ON(!async_cow); /* -ENOMEM */
1106 async_cow->inode = igrab(inode);
1107 async_cow->root = root;
1108 async_cow->locked_page = locked_page;
1109 async_cow->start = start;
1111 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1112 !btrfs_test_opt(root, FORCE_COMPRESS))
1115 cur_end = min(end, start + 512 * 1024 - 1);
1117 async_cow->end = cur_end;
1118 INIT_LIST_HEAD(&async_cow->extents);
1120 btrfs_init_work(&async_cow->work,
1121 btrfs_delalloc_helper,
1122 async_cow_start, async_cow_submit,
1125 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1127 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1129 btrfs_queue_work(root->fs_info->delalloc_workers,
1132 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1133 wait_event(root->fs_info->async_submit_wait,
1134 (atomic_read(&root->fs_info->async_delalloc_pages) <
1138 while (atomic_read(&root->fs_info->async_submit_draining) &&
1139 atomic_read(&root->fs_info->async_delalloc_pages)) {
1140 wait_event(root->fs_info->async_submit_wait,
1141 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1145 *nr_written += nr_pages;
1146 start = cur_end + 1;
1152 static noinline int csum_exist_in_range(struct btrfs_root *root,
1153 u64 bytenr, u64 num_bytes)
1156 struct btrfs_ordered_sum *sums;
1159 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1160 bytenr + num_bytes - 1, &list, 0);
1161 if (ret == 0 && list_empty(&list))
1164 while (!list_empty(&list)) {
1165 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1166 list_del(&sums->list);
1173 * when nowcow writeback call back. This checks for snapshots or COW copies
1174 * of the extents that exist in the file, and COWs the file as required.
1176 * If no cow copies or snapshots exist, we write directly to the existing
1179 static noinline int run_delalloc_nocow(struct inode *inode,
1180 struct page *locked_page,
1181 u64 start, u64 end, int *page_started, int force,
1182 unsigned long *nr_written)
1184 struct btrfs_root *root = BTRFS_I(inode)->root;
1185 struct btrfs_trans_handle *trans;
1186 struct extent_buffer *leaf;
1187 struct btrfs_path *path;
1188 struct btrfs_file_extent_item *fi;
1189 struct btrfs_key found_key;
1204 u64 ino = btrfs_ino(inode);
1206 path = btrfs_alloc_path();
1208 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1209 EXTENT_LOCKED | EXTENT_DELALLOC |
1210 EXTENT_DO_ACCOUNTING |
1211 EXTENT_DEFRAG, PAGE_UNLOCK |
1213 PAGE_SET_WRITEBACK |
1214 PAGE_END_WRITEBACK);
1218 nolock = btrfs_is_free_space_inode(inode);
1221 trans = btrfs_join_transaction_nolock(root);
1223 trans = btrfs_join_transaction(root);
1225 if (IS_ERR(trans)) {
1226 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1227 EXTENT_LOCKED | EXTENT_DELALLOC |
1228 EXTENT_DO_ACCOUNTING |
1229 EXTENT_DEFRAG, PAGE_UNLOCK |
1231 PAGE_SET_WRITEBACK |
1232 PAGE_END_WRITEBACK);
1233 btrfs_free_path(path);
1234 return PTR_ERR(trans);
1237 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1239 cow_start = (u64)-1;
1242 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1246 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1247 leaf = path->nodes[0];
1248 btrfs_item_key_to_cpu(leaf, &found_key,
1249 path->slots[0] - 1);
1250 if (found_key.objectid == ino &&
1251 found_key.type == BTRFS_EXTENT_DATA_KEY)
1256 leaf = path->nodes[0];
1257 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1258 ret = btrfs_next_leaf(root, path);
1263 leaf = path->nodes[0];
1269 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1271 if (found_key.objectid > ino ||
1272 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1273 found_key.offset > end)
1276 if (found_key.offset > cur_offset) {
1277 extent_end = found_key.offset;
1282 fi = btrfs_item_ptr(leaf, path->slots[0],
1283 struct btrfs_file_extent_item);
1284 extent_type = btrfs_file_extent_type(leaf, fi);
1286 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1287 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1288 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1289 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1290 extent_offset = btrfs_file_extent_offset(leaf, fi);
1291 extent_end = found_key.offset +
1292 btrfs_file_extent_num_bytes(leaf, fi);
1294 btrfs_file_extent_disk_num_bytes(leaf, fi);
1295 if (extent_end <= start) {
1299 if (disk_bytenr == 0)
1301 if (btrfs_file_extent_compression(leaf, fi) ||
1302 btrfs_file_extent_encryption(leaf, fi) ||
1303 btrfs_file_extent_other_encoding(leaf, fi))
1305 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1307 if (btrfs_extent_readonly(root, disk_bytenr))
1309 if (btrfs_cross_ref_exist(trans, root, ino,
1311 extent_offset, disk_bytenr))
1313 disk_bytenr += extent_offset;
1314 disk_bytenr += cur_offset - found_key.offset;
1315 num_bytes = min(end + 1, extent_end) - cur_offset;
1317 * if there are pending snapshots for this root,
1318 * we fall into common COW way.
1321 err = btrfs_start_nocow_write(root);
1326 * force cow if csum exists in the range.
1327 * this ensure that csum for a given extent are
1328 * either valid or do not exist.
1330 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1333 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1334 extent_end = found_key.offset +
1335 btrfs_file_extent_inline_len(leaf,
1336 path->slots[0], fi);
1337 extent_end = ALIGN(extent_end, root->sectorsize);
1342 if (extent_end <= start) {
1344 if (!nolock && nocow)
1345 btrfs_end_nocow_write(root);
1349 if (cow_start == (u64)-1)
1350 cow_start = cur_offset;
1351 cur_offset = extent_end;
1352 if (cur_offset > end)
1358 btrfs_release_path(path);
1359 if (cow_start != (u64)-1) {
1360 ret = cow_file_range(inode, locked_page,
1361 cow_start, found_key.offset - 1,
1362 page_started, nr_written, 1);
1364 if (!nolock && nocow)
1365 btrfs_end_nocow_write(root);
1368 cow_start = (u64)-1;
1371 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1372 struct extent_map *em;
1373 struct extent_map_tree *em_tree;
1374 em_tree = &BTRFS_I(inode)->extent_tree;
1375 em = alloc_extent_map();
1376 BUG_ON(!em); /* -ENOMEM */
1377 em->start = cur_offset;
1378 em->orig_start = found_key.offset - extent_offset;
1379 em->len = num_bytes;
1380 em->block_len = num_bytes;
1381 em->block_start = disk_bytenr;
1382 em->orig_block_len = disk_num_bytes;
1383 em->ram_bytes = ram_bytes;
1384 em->bdev = root->fs_info->fs_devices->latest_bdev;
1385 em->mod_start = em->start;
1386 em->mod_len = em->len;
1387 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1388 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1389 em->generation = -1;
1391 write_lock(&em_tree->lock);
1392 ret = add_extent_mapping(em_tree, em, 1);
1393 write_unlock(&em_tree->lock);
1394 if (ret != -EEXIST) {
1395 free_extent_map(em);
1398 btrfs_drop_extent_cache(inode, em->start,
1399 em->start + em->len - 1, 0);
1401 type = BTRFS_ORDERED_PREALLOC;
1403 type = BTRFS_ORDERED_NOCOW;
1406 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1407 num_bytes, num_bytes, type);
1408 BUG_ON(ret); /* -ENOMEM */
1410 if (root->root_key.objectid ==
1411 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1412 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1415 if (!nolock && nocow)
1416 btrfs_end_nocow_write(root);
1421 extent_clear_unlock_delalloc(inode, cur_offset,
1422 cur_offset + num_bytes - 1,
1423 locked_page, EXTENT_LOCKED |
1424 EXTENT_DELALLOC, PAGE_UNLOCK |
1426 if (!nolock && nocow)
1427 btrfs_end_nocow_write(root);
1428 cur_offset = extent_end;
1429 if (cur_offset > end)
1432 btrfs_release_path(path);
1434 if (cur_offset <= end && cow_start == (u64)-1) {
1435 cow_start = cur_offset;
1439 if (cow_start != (u64)-1) {
1440 ret = cow_file_range(inode, locked_page, cow_start, end,
1441 page_started, nr_written, 1);
1447 err = btrfs_end_transaction(trans, root);
1451 if (ret && cur_offset < end)
1452 extent_clear_unlock_delalloc(inode, cur_offset, end,
1453 locked_page, EXTENT_LOCKED |
1454 EXTENT_DELALLOC | EXTENT_DEFRAG |
1455 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1457 PAGE_SET_WRITEBACK |
1458 PAGE_END_WRITEBACK);
1459 btrfs_free_path(path);
1463 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1466 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1467 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1471 * @defrag_bytes is a hint value, no spinlock held here,
1472 * if is not zero, it means the file is defragging.
1473 * Force cow if given extent needs to be defragged.
1475 if (BTRFS_I(inode)->defrag_bytes &&
1476 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1477 EXTENT_DEFRAG, 0, NULL))
1484 * extent_io.c call back to do delayed allocation processing
1486 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1487 u64 start, u64 end, int *page_started,
1488 unsigned long *nr_written)
1491 int force_cow = need_force_cow(inode, start, end);
1493 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1494 ret = run_delalloc_nocow(inode, locked_page, start, end,
1495 page_started, 1, nr_written);
1496 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1497 ret = run_delalloc_nocow(inode, locked_page, start, end,
1498 page_started, 0, nr_written);
1499 } else if (!inode_need_compress(inode)) {
1500 ret = cow_file_range(inode, locked_page, start, end,
1501 page_started, nr_written, 1);
1503 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1504 &BTRFS_I(inode)->runtime_flags);
1505 ret = cow_file_range_async(inode, locked_page, start, end,
1506 page_started, nr_written);
1511 static void btrfs_split_extent_hook(struct inode *inode,
1512 struct extent_state *orig, u64 split)
1514 /* not delalloc, ignore it */
1515 if (!(orig->state & EXTENT_DELALLOC))
1518 spin_lock(&BTRFS_I(inode)->lock);
1519 BTRFS_I(inode)->outstanding_extents++;
1520 spin_unlock(&BTRFS_I(inode)->lock);
1524 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1525 * extents so we can keep track of new extents that are just merged onto old
1526 * extents, such as when we are doing sequential writes, so we can properly
1527 * account for the metadata space we'll need.
1529 static void btrfs_merge_extent_hook(struct inode *inode,
1530 struct extent_state *new,
1531 struct extent_state *other)
1533 /* not delalloc, ignore it */
1534 if (!(other->state & EXTENT_DELALLOC))
1537 spin_lock(&BTRFS_I(inode)->lock);
1538 BTRFS_I(inode)->outstanding_extents--;
1539 spin_unlock(&BTRFS_I(inode)->lock);
1542 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1543 struct inode *inode)
1545 spin_lock(&root->delalloc_lock);
1546 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1547 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1548 &root->delalloc_inodes);
1549 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1550 &BTRFS_I(inode)->runtime_flags);
1551 root->nr_delalloc_inodes++;
1552 if (root->nr_delalloc_inodes == 1) {
1553 spin_lock(&root->fs_info->delalloc_root_lock);
1554 BUG_ON(!list_empty(&root->delalloc_root));
1555 list_add_tail(&root->delalloc_root,
1556 &root->fs_info->delalloc_roots);
1557 spin_unlock(&root->fs_info->delalloc_root_lock);
1560 spin_unlock(&root->delalloc_lock);
1563 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1564 struct inode *inode)
1566 spin_lock(&root->delalloc_lock);
1567 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1568 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1569 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1570 &BTRFS_I(inode)->runtime_flags);
1571 root->nr_delalloc_inodes--;
1572 if (!root->nr_delalloc_inodes) {
1573 spin_lock(&root->fs_info->delalloc_root_lock);
1574 BUG_ON(list_empty(&root->delalloc_root));
1575 list_del_init(&root->delalloc_root);
1576 spin_unlock(&root->fs_info->delalloc_root_lock);
1579 spin_unlock(&root->delalloc_lock);
1583 * extent_io.c set_bit_hook, used to track delayed allocation
1584 * bytes in this file, and to maintain the list of inodes that
1585 * have pending delalloc work to be done.
1587 static void btrfs_set_bit_hook(struct inode *inode,
1588 struct extent_state *state, unsigned long *bits)
1591 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1594 * set_bit and clear bit hooks normally require _irqsave/restore
1595 * but in this case, we are only testing for the DELALLOC
1596 * bit, which is only set or cleared with irqs on
1598 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1599 struct btrfs_root *root = BTRFS_I(inode)->root;
1600 u64 len = state->end + 1 - state->start;
1601 bool do_list = !btrfs_is_free_space_inode(inode);
1603 if (*bits & EXTENT_FIRST_DELALLOC) {
1604 *bits &= ~EXTENT_FIRST_DELALLOC;
1606 spin_lock(&BTRFS_I(inode)->lock);
1607 BTRFS_I(inode)->outstanding_extents++;
1608 spin_unlock(&BTRFS_I(inode)->lock);
1611 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1612 root->fs_info->delalloc_batch);
1613 spin_lock(&BTRFS_I(inode)->lock);
1614 BTRFS_I(inode)->delalloc_bytes += len;
1615 if (*bits & EXTENT_DEFRAG)
1616 BTRFS_I(inode)->defrag_bytes += len;
1617 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1618 &BTRFS_I(inode)->runtime_flags))
1619 btrfs_add_delalloc_inodes(root, inode);
1620 spin_unlock(&BTRFS_I(inode)->lock);
1625 * extent_io.c clear_bit_hook, see set_bit_hook for why
1627 static void btrfs_clear_bit_hook(struct inode *inode,
1628 struct extent_state *state,
1629 unsigned long *bits)
1631 u64 len = state->end + 1 - state->start;
1633 spin_lock(&BTRFS_I(inode)->lock);
1634 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1635 BTRFS_I(inode)->defrag_bytes -= len;
1636 spin_unlock(&BTRFS_I(inode)->lock);
1639 * set_bit and clear bit hooks normally require _irqsave/restore
1640 * but in this case, we are only testing for the DELALLOC
1641 * bit, which is only set or cleared with irqs on
1643 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1644 struct btrfs_root *root = BTRFS_I(inode)->root;
1645 bool do_list = !btrfs_is_free_space_inode(inode);
1647 if (*bits & EXTENT_FIRST_DELALLOC) {
1648 *bits &= ~EXTENT_FIRST_DELALLOC;
1649 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1650 spin_lock(&BTRFS_I(inode)->lock);
1651 BTRFS_I(inode)->outstanding_extents--;
1652 spin_unlock(&BTRFS_I(inode)->lock);
1656 * We don't reserve metadata space for space cache inodes so we
1657 * don't need to call dellalloc_release_metadata if there is an
1660 if (*bits & EXTENT_DO_ACCOUNTING &&
1661 root != root->fs_info->tree_root)
1662 btrfs_delalloc_release_metadata(inode, len);
1664 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1665 && do_list && !(state->state & EXTENT_NORESERVE))
1666 btrfs_free_reserved_data_space(inode, len);
1668 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1669 root->fs_info->delalloc_batch);
1670 spin_lock(&BTRFS_I(inode)->lock);
1671 BTRFS_I(inode)->delalloc_bytes -= len;
1672 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1673 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1674 &BTRFS_I(inode)->runtime_flags))
1675 btrfs_del_delalloc_inode(root, inode);
1676 spin_unlock(&BTRFS_I(inode)->lock);
1681 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1682 * we don't create bios that span stripes or chunks
1684 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1685 size_t size, struct bio *bio,
1686 unsigned long bio_flags)
1688 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1689 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1694 if (bio_flags & EXTENT_BIO_COMPRESSED)
1697 length = bio->bi_iter.bi_size;
1698 map_length = length;
1699 ret = btrfs_map_block(root->fs_info, rw, logical,
1700 &map_length, NULL, 0);
1701 /* Will always return 0 with map_multi == NULL */
1703 if (map_length < length + size)
1709 * in order to insert checksums into the metadata in large chunks,
1710 * we wait until bio submission time. All the pages in the bio are
1711 * checksummed and sums are attached onto the ordered extent record.
1713 * At IO completion time the cums attached on the ordered extent record
1714 * are inserted into the btree
1716 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1717 struct bio *bio, int mirror_num,
1718 unsigned long bio_flags,
1721 struct btrfs_root *root = BTRFS_I(inode)->root;
1724 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1725 BUG_ON(ret); /* -ENOMEM */
1730 * in order to insert checksums into the metadata in large chunks,
1731 * we wait until bio submission time. All the pages in the bio are
1732 * checksummed and sums are attached onto the ordered extent record.
1734 * At IO completion time the cums attached on the ordered extent record
1735 * are inserted into the btree
1737 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1738 int mirror_num, unsigned long bio_flags,
1741 struct btrfs_root *root = BTRFS_I(inode)->root;
1744 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1746 bio_endio(bio, ret);
1751 * extent_io.c submission hook. This does the right thing for csum calculation
1752 * on write, or reading the csums from the tree before a read
1754 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1755 int mirror_num, unsigned long bio_flags,
1758 struct btrfs_root *root = BTRFS_I(inode)->root;
1762 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1764 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1766 if (btrfs_is_free_space_inode(inode))
1769 if (!(rw & REQ_WRITE)) {
1770 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1774 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1775 ret = btrfs_submit_compressed_read(inode, bio,
1779 } else if (!skip_sum) {
1780 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1785 } else if (async && !skip_sum) {
1786 /* csum items have already been cloned */
1787 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1789 /* we're doing a write, do the async checksumming */
1790 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1791 inode, rw, bio, mirror_num,
1792 bio_flags, bio_offset,
1793 __btrfs_submit_bio_start,
1794 __btrfs_submit_bio_done);
1796 } else if (!skip_sum) {
1797 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1803 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1807 bio_endio(bio, ret);
1812 * given a list of ordered sums record them in the inode. This happens
1813 * at IO completion time based on sums calculated at bio submission time.
1815 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1816 struct inode *inode, u64 file_offset,
1817 struct list_head *list)
1819 struct btrfs_ordered_sum *sum;
1821 list_for_each_entry(sum, list, list) {
1822 trans->adding_csums = 1;
1823 btrfs_csum_file_blocks(trans,
1824 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1825 trans->adding_csums = 0;
1830 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1831 struct extent_state **cached_state)
1833 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1834 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1835 cached_state, GFP_NOFS);
1838 /* see btrfs_writepage_start_hook for details on why this is required */
1839 struct btrfs_writepage_fixup {
1841 struct btrfs_work work;
1844 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1846 struct btrfs_writepage_fixup *fixup;
1847 struct btrfs_ordered_extent *ordered;
1848 struct extent_state *cached_state = NULL;
1850 struct inode *inode;
1855 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1859 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1860 ClearPageChecked(page);
1864 inode = page->mapping->host;
1865 page_start = page_offset(page);
1866 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1868 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1871 /* already ordered? We're done */
1872 if (PagePrivate2(page))
1875 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1877 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1878 page_end, &cached_state, GFP_NOFS);
1880 btrfs_start_ordered_extent(inode, ordered, 1);
1881 btrfs_put_ordered_extent(ordered);
1885 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1887 mapping_set_error(page->mapping, ret);
1888 end_extent_writepage(page, ret, page_start, page_end);
1889 ClearPageChecked(page);
1893 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1894 ClearPageChecked(page);
1895 set_page_dirty(page);
1897 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1898 &cached_state, GFP_NOFS);
1901 page_cache_release(page);
1906 * There are a few paths in the higher layers of the kernel that directly
1907 * set the page dirty bit without asking the filesystem if it is a
1908 * good idea. This causes problems because we want to make sure COW
1909 * properly happens and the data=ordered rules are followed.
1911 * In our case any range that doesn't have the ORDERED bit set
1912 * hasn't been properly setup for IO. We kick off an async process
1913 * to fix it up. The async helper will wait for ordered extents, set
1914 * the delalloc bit and make it safe to write the page.
1916 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1918 struct inode *inode = page->mapping->host;
1919 struct btrfs_writepage_fixup *fixup;
1920 struct btrfs_root *root = BTRFS_I(inode)->root;
1922 /* this page is properly in the ordered list */
1923 if (TestClearPagePrivate2(page))
1926 if (PageChecked(page))
1929 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1933 SetPageChecked(page);
1934 page_cache_get(page);
1935 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
1936 btrfs_writepage_fixup_worker, NULL, NULL);
1938 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
1942 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1943 struct inode *inode, u64 file_pos,
1944 u64 disk_bytenr, u64 disk_num_bytes,
1945 u64 num_bytes, u64 ram_bytes,
1946 u8 compression, u8 encryption,
1947 u16 other_encoding, int extent_type)
1949 struct btrfs_root *root = BTRFS_I(inode)->root;
1950 struct btrfs_file_extent_item *fi;
1951 struct btrfs_path *path;
1952 struct extent_buffer *leaf;
1953 struct btrfs_key ins;
1954 int extent_inserted = 0;
1957 path = btrfs_alloc_path();
1962 * we may be replacing one extent in the tree with another.
1963 * The new extent is pinned in the extent map, and we don't want
1964 * to drop it from the cache until it is completely in the btree.
1966 * So, tell btrfs_drop_extents to leave this extent in the cache.
1967 * the caller is expected to unpin it and allow it to be merged
1970 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
1971 file_pos + num_bytes, NULL, 0,
1972 1, sizeof(*fi), &extent_inserted);
1976 if (!extent_inserted) {
1977 ins.objectid = btrfs_ino(inode);
1978 ins.offset = file_pos;
1979 ins.type = BTRFS_EXTENT_DATA_KEY;
1981 path->leave_spinning = 1;
1982 ret = btrfs_insert_empty_item(trans, root, path, &ins,
1987 leaf = path->nodes[0];
1988 fi = btrfs_item_ptr(leaf, path->slots[0],
1989 struct btrfs_file_extent_item);
1990 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1991 btrfs_set_file_extent_type(leaf, fi, extent_type);
1992 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1993 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1994 btrfs_set_file_extent_offset(leaf, fi, 0);
1995 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1996 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1997 btrfs_set_file_extent_compression(leaf, fi, compression);
1998 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1999 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2001 btrfs_mark_buffer_dirty(leaf);
2002 btrfs_release_path(path);
2004 inode_add_bytes(inode, num_bytes);
2006 ins.objectid = disk_bytenr;
2007 ins.offset = disk_num_bytes;
2008 ins.type = BTRFS_EXTENT_ITEM_KEY;
2009 ret = btrfs_alloc_reserved_file_extent(trans, root,
2010 root->root_key.objectid,
2011 btrfs_ino(inode), file_pos, &ins);
2013 btrfs_free_path(path);
2018 /* snapshot-aware defrag */
2019 struct sa_defrag_extent_backref {
2020 struct rb_node node;
2021 struct old_sa_defrag_extent *old;
2030 struct old_sa_defrag_extent {
2031 struct list_head list;
2032 struct new_sa_defrag_extent *new;
2041 struct new_sa_defrag_extent {
2042 struct rb_root root;
2043 struct list_head head;
2044 struct btrfs_path *path;
2045 struct inode *inode;
2053 static int backref_comp(struct sa_defrag_extent_backref *b1,
2054 struct sa_defrag_extent_backref *b2)
2056 if (b1->root_id < b2->root_id)
2058 else if (b1->root_id > b2->root_id)
2061 if (b1->inum < b2->inum)
2063 else if (b1->inum > b2->inum)
2066 if (b1->file_pos < b2->file_pos)
2068 else if (b1->file_pos > b2->file_pos)
2072 * [------------------------------] ===> (a range of space)
2073 * |<--->| |<---->| =============> (fs/file tree A)
2074 * |<---------------------------->| ===> (fs/file tree B)
2076 * A range of space can refer to two file extents in one tree while
2077 * refer to only one file extent in another tree.
2079 * So we may process a disk offset more than one time(two extents in A)
2080 * and locate at the same extent(one extent in B), then insert two same
2081 * backrefs(both refer to the extent in B).
2086 static void backref_insert(struct rb_root *root,
2087 struct sa_defrag_extent_backref *backref)
2089 struct rb_node **p = &root->rb_node;
2090 struct rb_node *parent = NULL;
2091 struct sa_defrag_extent_backref *entry;
2096 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2098 ret = backref_comp(backref, entry);
2102 p = &(*p)->rb_right;
2105 rb_link_node(&backref->node, parent, p);
2106 rb_insert_color(&backref->node, root);
2110 * Note the backref might has changed, and in this case we just return 0.
2112 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2115 struct btrfs_file_extent_item *extent;
2116 struct btrfs_fs_info *fs_info;
2117 struct old_sa_defrag_extent *old = ctx;
2118 struct new_sa_defrag_extent *new = old->new;
2119 struct btrfs_path *path = new->path;
2120 struct btrfs_key key;
2121 struct btrfs_root *root;
2122 struct sa_defrag_extent_backref *backref;
2123 struct extent_buffer *leaf;
2124 struct inode *inode = new->inode;
2130 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2131 inum == btrfs_ino(inode))
2134 key.objectid = root_id;
2135 key.type = BTRFS_ROOT_ITEM_KEY;
2136 key.offset = (u64)-1;
2138 fs_info = BTRFS_I(inode)->root->fs_info;
2139 root = btrfs_read_fs_root_no_name(fs_info, &key);
2141 if (PTR_ERR(root) == -ENOENT)
2144 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2145 inum, offset, root_id);
2146 return PTR_ERR(root);
2149 key.objectid = inum;
2150 key.type = BTRFS_EXTENT_DATA_KEY;
2151 if (offset > (u64)-1 << 32)
2154 key.offset = offset;
2156 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2157 if (WARN_ON(ret < 0))
2164 leaf = path->nodes[0];
2165 slot = path->slots[0];
2167 if (slot >= btrfs_header_nritems(leaf)) {
2168 ret = btrfs_next_leaf(root, path);
2171 } else if (ret > 0) {
2180 btrfs_item_key_to_cpu(leaf, &key, slot);
2182 if (key.objectid > inum)
2185 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2188 extent = btrfs_item_ptr(leaf, slot,
2189 struct btrfs_file_extent_item);
2191 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2195 * 'offset' refers to the exact key.offset,
2196 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2197 * (key.offset - extent_offset).
2199 if (key.offset != offset)
2202 extent_offset = btrfs_file_extent_offset(leaf, extent);
2203 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2205 if (extent_offset >= old->extent_offset + old->offset +
2206 old->len || extent_offset + num_bytes <=
2207 old->extent_offset + old->offset)
2212 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2218 backref->root_id = root_id;
2219 backref->inum = inum;
2220 backref->file_pos = offset;
2221 backref->num_bytes = num_bytes;
2222 backref->extent_offset = extent_offset;
2223 backref->generation = btrfs_file_extent_generation(leaf, extent);
2225 backref_insert(&new->root, backref);
2228 btrfs_release_path(path);
2233 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2234 struct new_sa_defrag_extent *new)
2236 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2237 struct old_sa_defrag_extent *old, *tmp;
2242 list_for_each_entry_safe(old, tmp, &new->head, list) {
2243 ret = iterate_inodes_from_logical(old->bytenr +
2244 old->extent_offset, fs_info,
2245 path, record_one_backref,
2247 if (ret < 0 && ret != -ENOENT)
2250 /* no backref to be processed for this extent */
2252 list_del(&old->list);
2257 if (list_empty(&new->head))
2263 static int relink_is_mergable(struct extent_buffer *leaf,
2264 struct btrfs_file_extent_item *fi,
2265 struct new_sa_defrag_extent *new)
2267 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2270 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2273 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2276 if (btrfs_file_extent_encryption(leaf, fi) ||
2277 btrfs_file_extent_other_encoding(leaf, fi))
2284 * Note the backref might has changed, and in this case we just return 0.
2286 static noinline int relink_extent_backref(struct btrfs_path *path,
2287 struct sa_defrag_extent_backref *prev,
2288 struct sa_defrag_extent_backref *backref)
2290 struct btrfs_file_extent_item *extent;
2291 struct btrfs_file_extent_item *item;
2292 struct btrfs_ordered_extent *ordered;
2293 struct btrfs_trans_handle *trans;
2294 struct btrfs_fs_info *fs_info;
2295 struct btrfs_root *root;
2296 struct btrfs_key key;
2297 struct extent_buffer *leaf;
2298 struct old_sa_defrag_extent *old = backref->old;
2299 struct new_sa_defrag_extent *new = old->new;
2300 struct inode *src_inode = new->inode;
2301 struct inode *inode;
2302 struct extent_state *cached = NULL;
2311 if (prev && prev->root_id == backref->root_id &&
2312 prev->inum == backref->inum &&
2313 prev->file_pos + prev->num_bytes == backref->file_pos)
2316 /* step 1: get root */
2317 key.objectid = backref->root_id;
2318 key.type = BTRFS_ROOT_ITEM_KEY;
2319 key.offset = (u64)-1;
2321 fs_info = BTRFS_I(src_inode)->root->fs_info;
2322 index = srcu_read_lock(&fs_info->subvol_srcu);
2324 root = btrfs_read_fs_root_no_name(fs_info, &key);
2326 srcu_read_unlock(&fs_info->subvol_srcu, index);
2327 if (PTR_ERR(root) == -ENOENT)
2329 return PTR_ERR(root);
2332 if (btrfs_root_readonly(root)) {
2333 srcu_read_unlock(&fs_info->subvol_srcu, index);
2337 /* step 2: get inode */
2338 key.objectid = backref->inum;
2339 key.type = BTRFS_INODE_ITEM_KEY;
2342 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2343 if (IS_ERR(inode)) {
2344 srcu_read_unlock(&fs_info->subvol_srcu, index);
2348 srcu_read_unlock(&fs_info->subvol_srcu, index);
2350 /* step 3: relink backref */
2351 lock_start = backref->file_pos;
2352 lock_end = backref->file_pos + backref->num_bytes - 1;
2353 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2356 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2358 btrfs_put_ordered_extent(ordered);
2362 trans = btrfs_join_transaction(root);
2363 if (IS_ERR(trans)) {
2364 ret = PTR_ERR(trans);
2368 key.objectid = backref->inum;
2369 key.type = BTRFS_EXTENT_DATA_KEY;
2370 key.offset = backref->file_pos;
2372 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2375 } else if (ret > 0) {
2380 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2381 struct btrfs_file_extent_item);
2383 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2384 backref->generation)
2387 btrfs_release_path(path);
2389 start = backref->file_pos;
2390 if (backref->extent_offset < old->extent_offset + old->offset)
2391 start += old->extent_offset + old->offset -
2392 backref->extent_offset;
2394 len = min(backref->extent_offset + backref->num_bytes,
2395 old->extent_offset + old->offset + old->len);
2396 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2398 ret = btrfs_drop_extents(trans, root, inode, start,
2403 key.objectid = btrfs_ino(inode);
2404 key.type = BTRFS_EXTENT_DATA_KEY;
2407 path->leave_spinning = 1;
2409 struct btrfs_file_extent_item *fi;
2411 struct btrfs_key found_key;
2413 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2418 leaf = path->nodes[0];
2419 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2421 fi = btrfs_item_ptr(leaf, path->slots[0],
2422 struct btrfs_file_extent_item);
2423 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2425 if (extent_len + found_key.offset == start &&
2426 relink_is_mergable(leaf, fi, new)) {
2427 btrfs_set_file_extent_num_bytes(leaf, fi,
2429 btrfs_mark_buffer_dirty(leaf);
2430 inode_add_bytes(inode, len);
2436 btrfs_release_path(path);
2441 ret = btrfs_insert_empty_item(trans, root, path, &key,
2444 btrfs_abort_transaction(trans, root, ret);
2448 leaf = path->nodes[0];
2449 item = btrfs_item_ptr(leaf, path->slots[0],
2450 struct btrfs_file_extent_item);
2451 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2452 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2453 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2454 btrfs_set_file_extent_num_bytes(leaf, item, len);
2455 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2456 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2457 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2458 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2459 btrfs_set_file_extent_encryption(leaf, item, 0);
2460 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2462 btrfs_mark_buffer_dirty(leaf);
2463 inode_add_bytes(inode, len);
2464 btrfs_release_path(path);
2466 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2468 backref->root_id, backref->inum,
2469 new->file_pos, 0); /* start - extent_offset */
2471 btrfs_abort_transaction(trans, root, ret);
2477 btrfs_release_path(path);
2478 path->leave_spinning = 0;
2479 btrfs_end_transaction(trans, root);
2481 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2487 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2489 struct old_sa_defrag_extent *old, *tmp;
2494 list_for_each_entry_safe(old, tmp, &new->head, list) {
2495 list_del(&old->list);
2501 static void relink_file_extents(struct new_sa_defrag_extent *new)
2503 struct btrfs_path *path;
2504 struct sa_defrag_extent_backref *backref;
2505 struct sa_defrag_extent_backref *prev = NULL;
2506 struct inode *inode;
2507 struct btrfs_root *root;
2508 struct rb_node *node;
2512 root = BTRFS_I(inode)->root;
2514 path = btrfs_alloc_path();
2518 if (!record_extent_backrefs(path, new)) {
2519 btrfs_free_path(path);
2522 btrfs_release_path(path);
2525 node = rb_first(&new->root);
2528 rb_erase(node, &new->root);
2530 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2532 ret = relink_extent_backref(path, prev, backref);
2545 btrfs_free_path(path);
2547 free_sa_defrag_extent(new);
2549 atomic_dec(&root->fs_info->defrag_running);
2550 wake_up(&root->fs_info->transaction_wait);
2553 static struct new_sa_defrag_extent *
2554 record_old_file_extents(struct inode *inode,
2555 struct btrfs_ordered_extent *ordered)
2557 struct btrfs_root *root = BTRFS_I(inode)->root;
2558 struct btrfs_path *path;
2559 struct btrfs_key key;
2560 struct old_sa_defrag_extent *old;
2561 struct new_sa_defrag_extent *new;
2564 new = kmalloc(sizeof(*new), GFP_NOFS);
2569 new->file_pos = ordered->file_offset;
2570 new->len = ordered->len;
2571 new->bytenr = ordered->start;
2572 new->disk_len = ordered->disk_len;
2573 new->compress_type = ordered->compress_type;
2574 new->root = RB_ROOT;
2575 INIT_LIST_HEAD(&new->head);
2577 path = btrfs_alloc_path();
2581 key.objectid = btrfs_ino(inode);
2582 key.type = BTRFS_EXTENT_DATA_KEY;
2583 key.offset = new->file_pos;
2585 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2588 if (ret > 0 && path->slots[0] > 0)
2591 /* find out all the old extents for the file range */
2593 struct btrfs_file_extent_item *extent;
2594 struct extent_buffer *l;
2603 slot = path->slots[0];
2605 if (slot >= btrfs_header_nritems(l)) {
2606 ret = btrfs_next_leaf(root, path);
2614 btrfs_item_key_to_cpu(l, &key, slot);
2616 if (key.objectid != btrfs_ino(inode))
2618 if (key.type != BTRFS_EXTENT_DATA_KEY)
2620 if (key.offset >= new->file_pos + new->len)
2623 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2625 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2626 if (key.offset + num_bytes < new->file_pos)
2629 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2633 extent_offset = btrfs_file_extent_offset(l, extent);
2635 old = kmalloc(sizeof(*old), GFP_NOFS);
2639 offset = max(new->file_pos, key.offset);
2640 end = min(new->file_pos + new->len, key.offset + num_bytes);
2642 old->bytenr = disk_bytenr;
2643 old->extent_offset = extent_offset;
2644 old->offset = offset - key.offset;
2645 old->len = end - offset;
2648 list_add_tail(&old->list, &new->head);
2654 btrfs_free_path(path);
2655 atomic_inc(&root->fs_info->defrag_running);
2660 btrfs_free_path(path);
2662 free_sa_defrag_extent(new);
2666 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2669 struct btrfs_block_group_cache *cache;
2671 cache = btrfs_lookup_block_group(root->fs_info, start);
2674 spin_lock(&cache->lock);
2675 cache->delalloc_bytes -= len;
2676 spin_unlock(&cache->lock);
2678 btrfs_put_block_group(cache);
2681 /* as ordered data IO finishes, this gets called so we can finish
2682 * an ordered extent if the range of bytes in the file it covers are
2685 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2687 struct inode *inode = ordered_extent->inode;
2688 struct btrfs_root *root = BTRFS_I(inode)->root;
2689 struct btrfs_trans_handle *trans = NULL;
2690 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2691 struct extent_state *cached_state = NULL;
2692 struct new_sa_defrag_extent *new = NULL;
2693 int compress_type = 0;
2695 u64 logical_len = ordered_extent->len;
2697 bool truncated = false;
2699 nolock = btrfs_is_free_space_inode(inode);
2701 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2706 btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2707 ordered_extent->file_offset +
2708 ordered_extent->len - 1);
2710 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2712 logical_len = ordered_extent->truncated_len;
2713 /* Truncated the entire extent, don't bother adding */
2718 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2719 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2720 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2722 trans = btrfs_join_transaction_nolock(root);
2724 trans = btrfs_join_transaction(root);
2725 if (IS_ERR(trans)) {
2726 ret = PTR_ERR(trans);
2730 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2731 ret = btrfs_update_inode_fallback(trans, root, inode);
2732 if (ret) /* -ENOMEM or corruption */
2733 btrfs_abort_transaction(trans, root, ret);
2737 lock_extent_bits(io_tree, ordered_extent->file_offset,
2738 ordered_extent->file_offset + ordered_extent->len - 1,
2741 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2742 ordered_extent->file_offset + ordered_extent->len - 1,
2743 EXTENT_DEFRAG, 1, cached_state);
2745 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2746 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2747 /* the inode is shared */
2748 new = record_old_file_extents(inode, ordered_extent);
2750 clear_extent_bit(io_tree, ordered_extent->file_offset,
2751 ordered_extent->file_offset + ordered_extent->len - 1,
2752 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2756 trans = btrfs_join_transaction_nolock(root);
2758 trans = btrfs_join_transaction(root);
2759 if (IS_ERR(trans)) {
2760 ret = PTR_ERR(trans);
2765 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2767 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2768 compress_type = ordered_extent->compress_type;
2769 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2770 BUG_ON(compress_type);
2771 ret = btrfs_mark_extent_written(trans, inode,
2772 ordered_extent->file_offset,
2773 ordered_extent->file_offset +
2776 BUG_ON(root == root->fs_info->tree_root);
2777 ret = insert_reserved_file_extent(trans, inode,
2778 ordered_extent->file_offset,
2779 ordered_extent->start,
2780 ordered_extent->disk_len,
2781 logical_len, logical_len,
2782 compress_type, 0, 0,
2783 BTRFS_FILE_EXTENT_REG);
2785 btrfs_release_delalloc_bytes(root,
2786 ordered_extent->start,
2787 ordered_extent->disk_len);
2789 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2790 ordered_extent->file_offset, ordered_extent->len,
2793 btrfs_abort_transaction(trans, root, ret);
2797 add_pending_csums(trans, inode, ordered_extent->file_offset,
2798 &ordered_extent->list);
2800 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2801 ret = btrfs_update_inode_fallback(trans, root, inode);
2802 if (ret) { /* -ENOMEM or corruption */
2803 btrfs_abort_transaction(trans, root, ret);
2808 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2809 ordered_extent->file_offset +
2810 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2812 if (root != root->fs_info->tree_root)
2813 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2815 btrfs_end_transaction(trans, root);
2817 if (ret || truncated) {
2821 start = ordered_extent->file_offset + logical_len;
2823 start = ordered_extent->file_offset;
2824 end = ordered_extent->file_offset + ordered_extent->len - 1;
2825 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2827 /* Drop the cache for the part of the extent we didn't write. */
2828 btrfs_drop_extent_cache(inode, start, end, 0);
2831 * If the ordered extent had an IOERR or something else went
2832 * wrong we need to return the space for this ordered extent
2833 * back to the allocator. We only free the extent in the
2834 * truncated case if we didn't write out the extent at all.
2836 if ((ret || !logical_len) &&
2837 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2838 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2839 btrfs_free_reserved_extent(root, ordered_extent->start,
2840 ordered_extent->disk_len, 1);
2845 * This needs to be done to make sure anybody waiting knows we are done
2846 * updating everything for this ordered extent.
2848 btrfs_remove_ordered_extent(inode, ordered_extent);
2850 /* for snapshot-aware defrag */
2853 free_sa_defrag_extent(new);
2854 atomic_dec(&root->fs_info->defrag_running);
2856 relink_file_extents(new);
2861 btrfs_put_ordered_extent(ordered_extent);
2862 /* once for the tree */
2863 btrfs_put_ordered_extent(ordered_extent);
2868 static void finish_ordered_fn(struct btrfs_work *work)
2870 struct btrfs_ordered_extent *ordered_extent;
2871 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2872 btrfs_finish_ordered_io(ordered_extent);
2875 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2876 struct extent_state *state, int uptodate)
2878 struct inode *inode = page->mapping->host;
2879 struct btrfs_root *root = BTRFS_I(inode)->root;
2880 struct btrfs_ordered_extent *ordered_extent = NULL;
2881 struct btrfs_workqueue *wq;
2882 btrfs_work_func_t func;
2884 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2886 ClearPagePrivate2(page);
2887 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2888 end - start + 1, uptodate))
2891 if (btrfs_is_free_space_inode(inode)) {
2892 wq = root->fs_info->endio_freespace_worker;
2893 func = btrfs_freespace_write_helper;
2895 wq = root->fs_info->endio_write_workers;
2896 func = btrfs_endio_write_helper;
2899 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
2901 btrfs_queue_work(wq, &ordered_extent->work);
2906 static int __readpage_endio_check(struct inode *inode,
2907 struct btrfs_io_bio *io_bio,
2908 int icsum, struct page *page,
2909 int pgoff, u64 start, size_t len)
2914 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2915 DEFAULT_RATELIMIT_BURST);
2917 csum_expected = *(((u32 *)io_bio->csum) + icsum);
2919 kaddr = kmap_atomic(page);
2920 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
2921 btrfs_csum_final(csum, (char *)&csum);
2922 if (csum != csum_expected)
2925 kunmap_atomic(kaddr);
2928 if (__ratelimit(&_rs))
2929 btrfs_info(BTRFS_I(inode)->root->fs_info,
2930 "csum failed ino %llu off %llu csum %u expected csum %u",
2931 btrfs_ino(inode), start, csum, csum_expected);
2932 memset(kaddr + pgoff, 1, len);
2933 flush_dcache_page(page);
2934 kunmap_atomic(kaddr);
2935 if (csum_expected == 0)
2941 * when reads are done, we need to check csums to verify the data is correct
2942 * if there's a match, we allow the bio to finish. If not, the code in
2943 * extent_io.c will try to find good copies for us.
2945 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2946 u64 phy_offset, struct page *page,
2947 u64 start, u64 end, int mirror)
2949 size_t offset = start - page_offset(page);
2950 struct inode *inode = page->mapping->host;
2951 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2952 struct btrfs_root *root = BTRFS_I(inode)->root;
2954 if (PageChecked(page)) {
2955 ClearPageChecked(page);
2959 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2962 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2963 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2964 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2969 phy_offset >>= inode->i_sb->s_blocksize_bits;
2970 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
2971 start, (size_t)(end - start + 1));
2974 struct delayed_iput {
2975 struct list_head list;
2976 struct inode *inode;
2979 /* JDM: If this is fs-wide, why can't we add a pointer to
2980 * btrfs_inode instead and avoid the allocation? */
2981 void btrfs_add_delayed_iput(struct inode *inode)
2983 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2984 struct delayed_iput *delayed;
2986 if (atomic_add_unless(&inode->i_count, -1, 1))
2989 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2990 delayed->inode = inode;
2992 spin_lock(&fs_info->delayed_iput_lock);
2993 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2994 spin_unlock(&fs_info->delayed_iput_lock);
2997 void btrfs_run_delayed_iputs(struct btrfs_root *root)
3000 struct btrfs_fs_info *fs_info = root->fs_info;
3001 struct delayed_iput *delayed;
3004 spin_lock(&fs_info->delayed_iput_lock);
3005 empty = list_empty(&fs_info->delayed_iputs);
3006 spin_unlock(&fs_info->delayed_iput_lock);
3010 spin_lock(&fs_info->delayed_iput_lock);
3011 list_splice_init(&fs_info->delayed_iputs, &list);
3012 spin_unlock(&fs_info->delayed_iput_lock);
3014 while (!list_empty(&list)) {
3015 delayed = list_entry(list.next, struct delayed_iput, list);
3016 list_del(&delayed->list);
3017 iput(delayed->inode);
3023 * This is called in transaction commit time. If there are no orphan
3024 * files in the subvolume, it removes orphan item and frees block_rsv
3027 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3028 struct btrfs_root *root)
3030 struct btrfs_block_rsv *block_rsv;
3033 if (atomic_read(&root->orphan_inodes) ||
3034 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3037 spin_lock(&root->orphan_lock);
3038 if (atomic_read(&root->orphan_inodes)) {
3039 spin_unlock(&root->orphan_lock);
3043 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3044 spin_unlock(&root->orphan_lock);
3048 block_rsv = root->orphan_block_rsv;
3049 root->orphan_block_rsv = NULL;
3050 spin_unlock(&root->orphan_lock);
3052 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3053 btrfs_root_refs(&root->root_item) > 0) {
3054 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
3055 root->root_key.objectid);
3057 btrfs_abort_transaction(trans, root, ret);
3059 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3064 WARN_ON(block_rsv->size > 0);
3065 btrfs_free_block_rsv(root, block_rsv);
3070 * This creates an orphan entry for the given inode in case something goes
3071 * wrong in the middle of an unlink/truncate.
3073 * NOTE: caller of this function should reserve 5 units of metadata for
3076 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3078 struct btrfs_root *root = BTRFS_I(inode)->root;
3079 struct btrfs_block_rsv *block_rsv = NULL;
3084 if (!root->orphan_block_rsv) {
3085 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3090 spin_lock(&root->orphan_lock);
3091 if (!root->orphan_block_rsv) {
3092 root->orphan_block_rsv = block_rsv;
3093 } else if (block_rsv) {
3094 btrfs_free_block_rsv(root, block_rsv);
3098 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3099 &BTRFS_I(inode)->runtime_flags)) {
3102 * For proper ENOSPC handling, we should do orphan
3103 * cleanup when mounting. But this introduces backward
3104 * compatibility issue.
3106 if (!xchg(&root->orphan_item_inserted, 1))
3112 atomic_inc(&root->orphan_inodes);
3115 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3116 &BTRFS_I(inode)->runtime_flags))
3118 spin_unlock(&root->orphan_lock);
3120 /* grab metadata reservation from transaction handle */
3122 ret = btrfs_orphan_reserve_metadata(trans, inode);
3123 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3126 /* insert an orphan item to track this unlinked/truncated file */
3128 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3130 atomic_dec(&root->orphan_inodes);
3132 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3133 &BTRFS_I(inode)->runtime_flags);
3134 btrfs_orphan_release_metadata(inode);
3136 if (ret != -EEXIST) {
3137 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3138 &BTRFS_I(inode)->runtime_flags);
3139 btrfs_abort_transaction(trans, root, ret);
3146 /* insert an orphan item to track subvolume contains orphan files */
3148 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3149 root->root_key.objectid);
3150 if (ret && ret != -EEXIST) {
3151 btrfs_abort_transaction(trans, root, ret);
3159 * We have done the truncate/delete so we can go ahead and remove the orphan
3160 * item for this particular inode.
3162 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3163 struct inode *inode)
3165 struct btrfs_root *root = BTRFS_I(inode)->root;
3166 int delete_item = 0;
3167 int release_rsv = 0;
3170 spin_lock(&root->orphan_lock);
3171 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3172 &BTRFS_I(inode)->runtime_flags))
3175 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3176 &BTRFS_I(inode)->runtime_flags))
3178 spin_unlock(&root->orphan_lock);
3181 atomic_dec(&root->orphan_inodes);
3183 ret = btrfs_del_orphan_item(trans, root,
3188 btrfs_orphan_release_metadata(inode);
3194 * this cleans up any orphans that may be left on the list from the last use
3197 int btrfs_orphan_cleanup(struct btrfs_root *root)
3199 struct btrfs_path *path;
3200 struct extent_buffer *leaf;
3201 struct btrfs_key key, found_key;
3202 struct btrfs_trans_handle *trans;
3203 struct inode *inode;
3204 u64 last_objectid = 0;
3205 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3207 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3210 path = btrfs_alloc_path();
3217 key.objectid = BTRFS_ORPHAN_OBJECTID;
3218 key.type = BTRFS_ORPHAN_ITEM_KEY;
3219 key.offset = (u64)-1;
3222 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3227 * if ret == 0 means we found what we were searching for, which
3228 * is weird, but possible, so only screw with path if we didn't
3229 * find the key and see if we have stuff that matches
3233 if (path->slots[0] == 0)
3238 /* pull out the item */
3239 leaf = path->nodes[0];
3240 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3242 /* make sure the item matches what we want */
3243 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3245 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3248 /* release the path since we're done with it */
3249 btrfs_release_path(path);
3252 * this is where we are basically btrfs_lookup, without the
3253 * crossing root thing. we store the inode number in the
3254 * offset of the orphan item.
3257 if (found_key.offset == last_objectid) {
3258 btrfs_err(root->fs_info,
3259 "Error removing orphan entry, stopping orphan cleanup");
3264 last_objectid = found_key.offset;
3266 found_key.objectid = found_key.offset;
3267 found_key.type = BTRFS_INODE_ITEM_KEY;
3268 found_key.offset = 0;
3269 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3270 ret = PTR_ERR_OR_ZERO(inode);
3271 if (ret && ret != -ESTALE)
3274 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3275 struct btrfs_root *dead_root;
3276 struct btrfs_fs_info *fs_info = root->fs_info;
3277 int is_dead_root = 0;
3280 * this is an orphan in the tree root. Currently these
3281 * could come from 2 sources:
3282 * a) a snapshot deletion in progress
3283 * b) a free space cache inode
3284 * We need to distinguish those two, as the snapshot
3285 * orphan must not get deleted.
3286 * find_dead_roots already ran before us, so if this
3287 * is a snapshot deletion, we should find the root
3288 * in the dead_roots list
3290 spin_lock(&fs_info->trans_lock);
3291 list_for_each_entry(dead_root, &fs_info->dead_roots,
3293 if (dead_root->root_key.objectid ==
3294 found_key.objectid) {
3299 spin_unlock(&fs_info->trans_lock);
3301 /* prevent this orphan from being found again */
3302 key.offset = found_key.objectid - 1;
3307 * Inode is already gone but the orphan item is still there,
3308 * kill the orphan item.
3310 if (ret == -ESTALE) {
3311 trans = btrfs_start_transaction(root, 1);
3312 if (IS_ERR(trans)) {
3313 ret = PTR_ERR(trans);
3316 btrfs_debug(root->fs_info, "auto deleting %Lu",
3317 found_key.objectid);
3318 ret = btrfs_del_orphan_item(trans, root,
3319 found_key.objectid);
3320 btrfs_end_transaction(trans, root);
3327 * add this inode to the orphan list so btrfs_orphan_del does
3328 * the proper thing when we hit it
3330 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3331 &BTRFS_I(inode)->runtime_flags);
3332 atomic_inc(&root->orphan_inodes);
3334 /* if we have links, this was a truncate, lets do that */
3335 if (inode->i_nlink) {
3336 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3342 /* 1 for the orphan item deletion. */
3343 trans = btrfs_start_transaction(root, 1);
3344 if (IS_ERR(trans)) {
3346 ret = PTR_ERR(trans);
3349 ret = btrfs_orphan_add(trans, inode);
3350 btrfs_end_transaction(trans, root);
3356 ret = btrfs_truncate(inode);
3358 btrfs_orphan_del(NULL, inode);
3363 /* this will do delete_inode and everything for us */
3368 /* release the path since we're done with it */
3369 btrfs_release_path(path);
3371 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3373 if (root->orphan_block_rsv)
3374 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3377 if (root->orphan_block_rsv ||
3378 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3379 trans = btrfs_join_transaction(root);
3381 btrfs_end_transaction(trans, root);
3385 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3387 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3391 btrfs_crit(root->fs_info,
3392 "could not do orphan cleanup %d", ret);
3393 btrfs_free_path(path);
3398 * very simple check to peek ahead in the leaf looking for xattrs. If we
3399 * don't find any xattrs, we know there can't be any acls.
3401 * slot is the slot the inode is in, objectid is the objectid of the inode
3403 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3404 int slot, u64 objectid,
3405 int *first_xattr_slot)
3407 u32 nritems = btrfs_header_nritems(leaf);
3408 struct btrfs_key found_key;
3409 static u64 xattr_access = 0;
3410 static u64 xattr_default = 0;
3413 if (!xattr_access) {
3414 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3415 strlen(POSIX_ACL_XATTR_ACCESS));
3416 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3417 strlen(POSIX_ACL_XATTR_DEFAULT));
3421 *first_xattr_slot = -1;
3422 while (slot < nritems) {
3423 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3425 /* we found a different objectid, there must not be acls */
3426 if (found_key.objectid != objectid)
3429 /* we found an xattr, assume we've got an acl */
3430 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3431 if (*first_xattr_slot == -1)
3432 *first_xattr_slot = slot;
3433 if (found_key.offset == xattr_access ||
3434 found_key.offset == xattr_default)
3439 * we found a key greater than an xattr key, there can't
3440 * be any acls later on
3442 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3449 * it goes inode, inode backrefs, xattrs, extents,
3450 * so if there are a ton of hard links to an inode there can
3451 * be a lot of backrefs. Don't waste time searching too hard,
3452 * this is just an optimization
3457 /* we hit the end of the leaf before we found an xattr or
3458 * something larger than an xattr. We have to assume the inode
3461 if (*first_xattr_slot == -1)
3462 *first_xattr_slot = slot;
3467 * read an inode from the btree into the in-memory inode
3469 static void btrfs_read_locked_inode(struct inode *inode)
3471 struct btrfs_path *path;
3472 struct extent_buffer *leaf;
3473 struct btrfs_inode_item *inode_item;
3474 struct btrfs_timespec *tspec;
3475 struct btrfs_root *root = BTRFS_I(inode)->root;
3476 struct btrfs_key location;
3481 bool filled = false;
3482 int first_xattr_slot;
3484 ret = btrfs_fill_inode(inode, &rdev);
3488 path = btrfs_alloc_path();
3492 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3494 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3498 leaf = path->nodes[0];
3503 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3504 struct btrfs_inode_item);
3505 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3506 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3507 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3508 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3509 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3511 tspec = btrfs_inode_atime(inode_item);
3512 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3513 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3515 tspec = btrfs_inode_mtime(inode_item);
3516 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3517 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3519 tspec = btrfs_inode_ctime(inode_item);
3520 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3521 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3523 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3524 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3525 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3528 * If we were modified in the current generation and evicted from memory
3529 * and then re-read we need to do a full sync since we don't have any
3530 * idea about which extents were modified before we were evicted from
3533 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3534 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3535 &BTRFS_I(inode)->runtime_flags);
3537 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3538 inode->i_generation = BTRFS_I(inode)->generation;
3540 rdev = btrfs_inode_rdev(leaf, inode_item);
3542 BTRFS_I(inode)->index_cnt = (u64)-1;
3543 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3547 if (inode->i_nlink != 1 ||
3548 path->slots[0] >= btrfs_header_nritems(leaf))
3551 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3552 if (location.objectid != btrfs_ino(inode))
3555 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3556 if (location.type == BTRFS_INODE_REF_KEY) {
3557 struct btrfs_inode_ref *ref;
3559 ref = (struct btrfs_inode_ref *)ptr;
3560 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3561 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3562 struct btrfs_inode_extref *extref;
3564 extref = (struct btrfs_inode_extref *)ptr;
3565 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3570 * try to precache a NULL acl entry for files that don't have
3571 * any xattrs or acls
3573 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3574 btrfs_ino(inode), &first_xattr_slot);
3575 if (first_xattr_slot != -1) {
3576 path->slots[0] = first_xattr_slot;
3577 ret = btrfs_load_inode_props(inode, path);
3579 btrfs_err(root->fs_info,
3580 "error loading props for ino %llu (root %llu): %d",
3582 root->root_key.objectid, ret);
3584 btrfs_free_path(path);
3587 cache_no_acl(inode);
3589 switch (inode->i_mode & S_IFMT) {
3591 inode->i_mapping->a_ops = &btrfs_aops;
3592 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3593 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3594 inode->i_fop = &btrfs_file_operations;
3595 inode->i_op = &btrfs_file_inode_operations;
3598 inode->i_fop = &btrfs_dir_file_operations;
3599 if (root == root->fs_info->tree_root)
3600 inode->i_op = &btrfs_dir_ro_inode_operations;
3602 inode->i_op = &btrfs_dir_inode_operations;
3605 inode->i_op = &btrfs_symlink_inode_operations;
3606 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3607 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3610 inode->i_op = &btrfs_special_inode_operations;
3611 init_special_inode(inode, inode->i_mode, rdev);
3615 btrfs_update_iflags(inode);
3619 btrfs_free_path(path);
3620 make_bad_inode(inode);
3624 * given a leaf and an inode, copy the inode fields into the leaf
3626 static void fill_inode_item(struct btrfs_trans_handle *trans,
3627 struct extent_buffer *leaf,
3628 struct btrfs_inode_item *item,
3629 struct inode *inode)
3631 struct btrfs_map_token token;
3633 btrfs_init_map_token(&token);
3635 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3636 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3637 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3639 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3640 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3642 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3643 inode->i_atime.tv_sec, &token);
3644 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3645 inode->i_atime.tv_nsec, &token);
3647 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3648 inode->i_mtime.tv_sec, &token);
3649 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3650 inode->i_mtime.tv_nsec, &token);
3652 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3653 inode->i_ctime.tv_sec, &token);
3654 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3655 inode->i_ctime.tv_nsec, &token);
3657 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3659 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3661 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3662 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3663 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3664 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3665 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3669 * copy everything in the in-memory inode into the btree.
3671 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3672 struct btrfs_root *root, struct inode *inode)
3674 struct btrfs_inode_item *inode_item;
3675 struct btrfs_path *path;
3676 struct extent_buffer *leaf;
3679 path = btrfs_alloc_path();
3683 path->leave_spinning = 1;
3684 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3692 leaf = path->nodes[0];
3693 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3694 struct btrfs_inode_item);
3696 fill_inode_item(trans, leaf, inode_item, inode);
3697 btrfs_mark_buffer_dirty(leaf);
3698 btrfs_set_inode_last_trans(trans, inode);
3701 btrfs_free_path(path);
3706 * copy everything in the in-memory inode into the btree.
3708 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3709 struct btrfs_root *root, struct inode *inode)
3714 * If the inode is a free space inode, we can deadlock during commit
3715 * if we put it into the delayed code.
3717 * The data relocation inode should also be directly updated
3720 if (!btrfs_is_free_space_inode(inode)
3721 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3722 && !root->fs_info->log_root_recovering) {
3723 btrfs_update_root_times(trans, root);
3725 ret = btrfs_delayed_update_inode(trans, root, inode);
3727 btrfs_set_inode_last_trans(trans, inode);
3731 return btrfs_update_inode_item(trans, root, inode);
3734 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3735 struct btrfs_root *root,
3736 struct inode *inode)
3740 ret = btrfs_update_inode(trans, root, inode);
3742 return btrfs_update_inode_item(trans, root, inode);
3747 * unlink helper that gets used here in inode.c and in the tree logging
3748 * recovery code. It remove a link in a directory with a given name, and
3749 * also drops the back refs in the inode to the directory
3751 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3752 struct btrfs_root *root,
3753 struct inode *dir, struct inode *inode,
3754 const char *name, int name_len)
3756 struct btrfs_path *path;
3758 struct extent_buffer *leaf;
3759 struct btrfs_dir_item *di;
3760 struct btrfs_key key;
3762 u64 ino = btrfs_ino(inode);
3763 u64 dir_ino = btrfs_ino(dir);
3765 path = btrfs_alloc_path();
3771 path->leave_spinning = 1;
3772 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3773 name, name_len, -1);
3782 leaf = path->nodes[0];
3783 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3784 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3787 btrfs_release_path(path);
3790 * If we don't have dir index, we have to get it by looking up
3791 * the inode ref, since we get the inode ref, remove it directly,
3792 * it is unnecessary to do delayed deletion.
3794 * But if we have dir index, needn't search inode ref to get it.
3795 * Since the inode ref is close to the inode item, it is better
3796 * that we delay to delete it, and just do this deletion when
3797 * we update the inode item.
3799 if (BTRFS_I(inode)->dir_index) {
3800 ret = btrfs_delayed_delete_inode_ref(inode);
3802 index = BTRFS_I(inode)->dir_index;
3807 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3810 btrfs_info(root->fs_info,
3811 "failed to delete reference to %.*s, inode %llu parent %llu",
3812 name_len, name, ino, dir_ino);
3813 btrfs_abort_transaction(trans, root, ret);
3817 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3819 btrfs_abort_transaction(trans, root, ret);
3823 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3825 if (ret != 0 && ret != -ENOENT) {
3826 btrfs_abort_transaction(trans, root, ret);
3830 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3835 btrfs_abort_transaction(trans, root, ret);
3837 btrfs_free_path(path);
3841 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3842 inode_inc_iversion(inode);
3843 inode_inc_iversion(dir);
3844 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3845 ret = btrfs_update_inode(trans, root, dir);
3850 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3851 struct btrfs_root *root,
3852 struct inode *dir, struct inode *inode,
3853 const char *name, int name_len)
3856 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3859 ret = btrfs_update_inode(trans, root, inode);
3865 * helper to start transaction for unlink and rmdir.
3867 * unlink and rmdir are special in btrfs, they do not always free space, so
3868 * if we cannot make our reservations the normal way try and see if there is
3869 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3870 * allow the unlink to occur.
3872 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3874 struct btrfs_trans_handle *trans;
3875 struct btrfs_root *root = BTRFS_I(dir)->root;
3879 * 1 for the possible orphan item
3880 * 1 for the dir item
3881 * 1 for the dir index
3882 * 1 for the inode ref
3885 trans = btrfs_start_transaction(root, 5);
3886 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3889 if (PTR_ERR(trans) == -ENOSPC) {
3890 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3892 trans = btrfs_start_transaction(root, 0);
3895 ret = btrfs_cond_migrate_bytes(root->fs_info,
3896 &root->fs_info->trans_block_rsv,
3899 btrfs_end_transaction(trans, root);
3900 return ERR_PTR(ret);
3902 trans->block_rsv = &root->fs_info->trans_block_rsv;
3903 trans->bytes_reserved = num_bytes;
3908 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3910 struct btrfs_root *root = BTRFS_I(dir)->root;
3911 struct btrfs_trans_handle *trans;
3912 struct inode *inode = dentry->d_inode;
3915 trans = __unlink_start_trans(dir);
3917 return PTR_ERR(trans);
3919 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3921 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3922 dentry->d_name.name, dentry->d_name.len);
3926 if (inode->i_nlink == 0) {
3927 ret = btrfs_orphan_add(trans, inode);
3933 btrfs_end_transaction(trans, root);
3934 btrfs_btree_balance_dirty(root);
3938 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3939 struct btrfs_root *root,
3940 struct inode *dir, u64 objectid,
3941 const char *name, int name_len)
3943 struct btrfs_path *path;
3944 struct extent_buffer *leaf;
3945 struct btrfs_dir_item *di;
3946 struct btrfs_key key;
3949 u64 dir_ino = btrfs_ino(dir);
3951 path = btrfs_alloc_path();
3955 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3956 name, name_len, -1);
3957 if (IS_ERR_OR_NULL(di)) {
3965 leaf = path->nodes[0];
3966 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3967 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3968 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3970 btrfs_abort_transaction(trans, root, ret);
3973 btrfs_release_path(path);
3975 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3976 objectid, root->root_key.objectid,
3977 dir_ino, &index, name, name_len);
3979 if (ret != -ENOENT) {
3980 btrfs_abort_transaction(trans, root, ret);
3983 di = btrfs_search_dir_index_item(root, path, dir_ino,
3985 if (IS_ERR_OR_NULL(di)) {
3990 btrfs_abort_transaction(trans, root, ret);
3994 leaf = path->nodes[0];
3995 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3996 btrfs_release_path(path);
3999 btrfs_release_path(path);
4001 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4003 btrfs_abort_transaction(trans, root, ret);
4007 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4008 inode_inc_iversion(dir);
4009 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
4010 ret = btrfs_update_inode_fallback(trans, root, dir);
4012 btrfs_abort_transaction(trans, root, ret);
4014 btrfs_free_path(path);
4018 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4020 struct inode *inode = dentry->d_inode;
4022 struct btrfs_root *root = BTRFS_I(dir)->root;
4023 struct btrfs_trans_handle *trans;
4025 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4027 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
4030 trans = __unlink_start_trans(dir);
4032 return PTR_ERR(trans);
4034 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4035 err = btrfs_unlink_subvol(trans, root, dir,
4036 BTRFS_I(inode)->location.objectid,
4037 dentry->d_name.name,
4038 dentry->d_name.len);
4042 err = btrfs_orphan_add(trans, inode);
4046 /* now the directory is empty */
4047 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
4048 dentry->d_name.name, dentry->d_name.len);
4050 btrfs_i_size_write(inode, 0);
4052 btrfs_end_transaction(trans, root);
4053 btrfs_btree_balance_dirty(root);
4059 * this can truncate away extent items, csum items and directory items.
4060 * It starts at a high offset and removes keys until it can't find
4061 * any higher than new_size
4063 * csum items that cross the new i_size are truncated to the new size
4066 * min_type is the minimum key type to truncate down to. If set to 0, this
4067 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4069 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4070 struct btrfs_root *root,
4071 struct inode *inode,
4072 u64 new_size, u32 min_type)
4074 struct btrfs_path *path;
4075 struct extent_buffer *leaf;
4076 struct btrfs_file_extent_item *fi;
4077 struct btrfs_key key;
4078 struct btrfs_key found_key;
4079 u64 extent_start = 0;
4080 u64 extent_num_bytes = 0;
4081 u64 extent_offset = 0;
4083 u64 last_size = (u64)-1;
4084 u32 found_type = (u8)-1;
4087 int pending_del_nr = 0;
4088 int pending_del_slot = 0;
4089 int extent_type = -1;
4092 u64 ino = btrfs_ino(inode);
4094 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4096 path = btrfs_alloc_path();
4102 * We want to drop from the next block forward in case this new size is
4103 * not block aligned since we will be keeping the last block of the
4104 * extent just the way it is.
4106 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4107 root == root->fs_info->tree_root)
4108 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4109 root->sectorsize), (u64)-1, 0);
4112 * This function is also used to drop the items in the log tree before
4113 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4114 * it is used to drop the loged items. So we shouldn't kill the delayed
4117 if (min_type == 0 && root == BTRFS_I(inode)->root)
4118 btrfs_kill_delayed_inode_items(inode);
4121 key.offset = (u64)-1;
4125 path->leave_spinning = 1;
4126 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4133 /* there are no items in the tree for us to truncate, we're
4136 if (path->slots[0] == 0)
4143 leaf = path->nodes[0];
4144 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4145 found_type = found_key.type;
4147 if (found_key.objectid != ino)
4150 if (found_type < min_type)
4153 item_end = found_key.offset;
4154 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4155 fi = btrfs_item_ptr(leaf, path->slots[0],
4156 struct btrfs_file_extent_item);
4157 extent_type = btrfs_file_extent_type(leaf, fi);
4158 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4160 btrfs_file_extent_num_bytes(leaf, fi);
4161 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4162 item_end += btrfs_file_extent_inline_len(leaf,
4163 path->slots[0], fi);
4167 if (found_type > min_type) {
4170 if (item_end < new_size)
4172 if (found_key.offset >= new_size)
4178 /* FIXME, shrink the extent if the ref count is only 1 */
4179 if (found_type != BTRFS_EXTENT_DATA_KEY)
4183 last_size = found_key.offset;
4185 last_size = new_size;
4187 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4189 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4191 u64 orig_num_bytes =
4192 btrfs_file_extent_num_bytes(leaf, fi);
4193 extent_num_bytes = ALIGN(new_size -
4196 btrfs_set_file_extent_num_bytes(leaf, fi,
4198 num_dec = (orig_num_bytes -
4200 if (test_bit(BTRFS_ROOT_REF_COWS,
4203 inode_sub_bytes(inode, num_dec);
4204 btrfs_mark_buffer_dirty(leaf);
4207 btrfs_file_extent_disk_num_bytes(leaf,
4209 extent_offset = found_key.offset -
4210 btrfs_file_extent_offset(leaf, fi);
4212 /* FIXME blocksize != 4096 */
4213 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4214 if (extent_start != 0) {
4216 if (test_bit(BTRFS_ROOT_REF_COWS,
4218 inode_sub_bytes(inode, num_dec);
4221 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4223 * we can't truncate inline items that have had
4227 btrfs_file_extent_compression(leaf, fi) == 0 &&
4228 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4229 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4230 u32 size = new_size - found_key.offset;
4232 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4233 inode_sub_bytes(inode, item_end + 1 -
4237 * update the ram bytes to properly reflect
4238 * the new size of our item
4240 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4242 btrfs_file_extent_calc_inline_size(size);
4243 btrfs_truncate_item(root, path, size, 1);
4244 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4246 inode_sub_bytes(inode, item_end + 1 -
4252 if (!pending_del_nr) {
4253 /* no pending yet, add ourselves */
4254 pending_del_slot = path->slots[0];
4256 } else if (pending_del_nr &&
4257 path->slots[0] + 1 == pending_del_slot) {
4258 /* hop on the pending chunk */
4260 pending_del_slot = path->slots[0];
4268 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4269 root == root->fs_info->tree_root)) {
4270 btrfs_set_path_blocking(path);
4271 ret = btrfs_free_extent(trans, root, extent_start,
4272 extent_num_bytes, 0,
4273 btrfs_header_owner(leaf),
4274 ino, extent_offset, 0);
4278 if (found_type == BTRFS_INODE_ITEM_KEY)
4281 if (path->slots[0] == 0 ||
4282 path->slots[0] != pending_del_slot) {
4283 if (pending_del_nr) {
4284 ret = btrfs_del_items(trans, root, path,
4288 btrfs_abort_transaction(trans,
4294 btrfs_release_path(path);
4301 if (pending_del_nr) {
4302 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4305 btrfs_abort_transaction(trans, root, ret);
4308 if (last_size != (u64)-1 &&
4309 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4310 btrfs_ordered_update_i_size(inode, last_size, NULL);
4311 btrfs_free_path(path);
4316 * btrfs_truncate_page - read, zero a chunk and write a page
4317 * @inode - inode that we're zeroing
4318 * @from - the offset to start zeroing
4319 * @len - the length to zero, 0 to zero the entire range respective to the
4321 * @front - zero up to the offset instead of from the offset on
4323 * This will find the page for the "from" offset and cow the page and zero the
4324 * part we want to zero. This is used with truncate and hole punching.
4326 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4329 struct address_space *mapping = inode->i_mapping;
4330 struct btrfs_root *root = BTRFS_I(inode)->root;
4331 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4332 struct btrfs_ordered_extent *ordered;
4333 struct extent_state *cached_state = NULL;
4335 u32 blocksize = root->sectorsize;
4336 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4337 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4339 gfp_t mask = btrfs_alloc_write_mask(mapping);
4344 if ((offset & (blocksize - 1)) == 0 &&
4345 (!len || ((len & (blocksize - 1)) == 0)))
4347 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4352 page = find_or_create_page(mapping, index, mask);
4354 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4359 page_start = page_offset(page);
4360 page_end = page_start + PAGE_CACHE_SIZE - 1;
4362 if (!PageUptodate(page)) {
4363 ret = btrfs_readpage(NULL, page);
4365 if (page->mapping != mapping) {
4367 page_cache_release(page);
4370 if (!PageUptodate(page)) {
4375 wait_on_page_writeback(page);
4377 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4378 set_page_extent_mapped(page);
4380 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4382 unlock_extent_cached(io_tree, page_start, page_end,
4383 &cached_state, GFP_NOFS);
4385 page_cache_release(page);
4386 btrfs_start_ordered_extent(inode, ordered, 1);
4387 btrfs_put_ordered_extent(ordered);
4391 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4392 EXTENT_DIRTY | EXTENT_DELALLOC |
4393 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4394 0, 0, &cached_state, GFP_NOFS);
4396 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4399 unlock_extent_cached(io_tree, page_start, page_end,
4400 &cached_state, GFP_NOFS);
4404 if (offset != PAGE_CACHE_SIZE) {
4406 len = PAGE_CACHE_SIZE - offset;
4409 memset(kaddr, 0, offset);
4411 memset(kaddr + offset, 0, len);
4412 flush_dcache_page(page);
4415 ClearPageChecked(page);
4416 set_page_dirty(page);
4417 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4422 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4424 page_cache_release(page);
4429 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4430 u64 offset, u64 len)
4432 struct btrfs_trans_handle *trans;
4436 * Still need to make sure the inode looks like it's been updated so
4437 * that any holes get logged if we fsync.
4439 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4440 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4441 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4442 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4447 * 1 - for the one we're dropping
4448 * 1 - for the one we're adding
4449 * 1 - for updating the inode.
4451 trans = btrfs_start_transaction(root, 3);
4453 return PTR_ERR(trans);
4455 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4457 btrfs_abort_transaction(trans, root, ret);
4458 btrfs_end_transaction(trans, root);
4462 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4463 0, 0, len, 0, len, 0, 0, 0);
4465 btrfs_abort_transaction(trans, root, ret);
4467 btrfs_update_inode(trans, root, inode);
4468 btrfs_end_transaction(trans, root);
4473 * This function puts in dummy file extents for the area we're creating a hole
4474 * for. So if we are truncating this file to a larger size we need to insert
4475 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4476 * the range between oldsize and size
4478 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4480 struct btrfs_root *root = BTRFS_I(inode)->root;
4481 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4482 struct extent_map *em = NULL;
4483 struct extent_state *cached_state = NULL;
4484 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4485 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4486 u64 block_end = ALIGN(size, root->sectorsize);
4493 * If our size started in the middle of a page we need to zero out the
4494 * rest of the page before we expand the i_size, otherwise we could
4495 * expose stale data.
4497 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4501 if (size <= hole_start)
4505 struct btrfs_ordered_extent *ordered;
4507 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4509 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4510 block_end - hole_start);
4513 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4514 &cached_state, GFP_NOFS);
4515 btrfs_start_ordered_extent(inode, ordered, 1);
4516 btrfs_put_ordered_extent(ordered);
4519 cur_offset = hole_start;
4521 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4522 block_end - cur_offset, 0);
4528 last_byte = min(extent_map_end(em), block_end);
4529 last_byte = ALIGN(last_byte , root->sectorsize);
4530 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4531 struct extent_map *hole_em;
4532 hole_size = last_byte - cur_offset;
4534 err = maybe_insert_hole(root, inode, cur_offset,
4538 btrfs_drop_extent_cache(inode, cur_offset,
4539 cur_offset + hole_size - 1, 0);
4540 hole_em = alloc_extent_map();
4542 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4543 &BTRFS_I(inode)->runtime_flags);
4546 hole_em->start = cur_offset;
4547 hole_em->len = hole_size;
4548 hole_em->orig_start = cur_offset;
4550 hole_em->block_start = EXTENT_MAP_HOLE;
4551 hole_em->block_len = 0;
4552 hole_em->orig_block_len = 0;
4553 hole_em->ram_bytes = hole_size;
4554 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4555 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4556 hole_em->generation = root->fs_info->generation;
4559 write_lock(&em_tree->lock);
4560 err = add_extent_mapping(em_tree, hole_em, 1);
4561 write_unlock(&em_tree->lock);
4564 btrfs_drop_extent_cache(inode, cur_offset,
4568 free_extent_map(hole_em);
4571 free_extent_map(em);
4573 cur_offset = last_byte;
4574 if (cur_offset >= block_end)
4577 free_extent_map(em);
4578 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4583 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4585 struct btrfs_root *root = BTRFS_I(inode)->root;
4586 struct btrfs_trans_handle *trans;
4587 loff_t oldsize = i_size_read(inode);
4588 loff_t newsize = attr->ia_size;
4589 int mask = attr->ia_valid;
4593 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4594 * special case where we need to update the times despite not having
4595 * these flags set. For all other operations the VFS set these flags
4596 * explicitly if it wants a timestamp update.
4598 if (newsize != oldsize) {
4599 inode_inc_iversion(inode);
4600 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4601 inode->i_ctime = inode->i_mtime =
4602 current_fs_time(inode->i_sb);
4605 if (newsize > oldsize) {
4606 truncate_pagecache(inode, newsize);
4607 ret = btrfs_cont_expand(inode, oldsize, newsize);
4611 trans = btrfs_start_transaction(root, 1);
4613 return PTR_ERR(trans);
4615 i_size_write(inode, newsize);
4616 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4617 ret = btrfs_update_inode(trans, root, inode);
4618 btrfs_end_transaction(trans, root);
4622 * We're truncating a file that used to have good data down to
4623 * zero. Make sure it gets into the ordered flush list so that
4624 * any new writes get down to disk quickly.
4627 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4628 &BTRFS_I(inode)->runtime_flags);
4631 * 1 for the orphan item we're going to add
4632 * 1 for the orphan item deletion.
4634 trans = btrfs_start_transaction(root, 2);
4636 return PTR_ERR(trans);
4639 * We need to do this in case we fail at _any_ point during the
4640 * actual truncate. Once we do the truncate_setsize we could
4641 * invalidate pages which forces any outstanding ordered io to
4642 * be instantly completed which will give us extents that need
4643 * to be truncated. If we fail to get an orphan inode down we
4644 * could have left over extents that were never meant to live,
4645 * so we need to garuntee from this point on that everything
4646 * will be consistent.
4648 ret = btrfs_orphan_add(trans, inode);
4649 btrfs_end_transaction(trans, root);
4653 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4654 truncate_setsize(inode, newsize);
4656 /* Disable nonlocked read DIO to avoid the end less truncate */
4657 btrfs_inode_block_unlocked_dio(inode);
4658 inode_dio_wait(inode);
4659 btrfs_inode_resume_unlocked_dio(inode);
4661 ret = btrfs_truncate(inode);
4662 if (ret && inode->i_nlink) {
4666 * failed to truncate, disk_i_size is only adjusted down
4667 * as we remove extents, so it should represent the true
4668 * size of the inode, so reset the in memory size and
4669 * delete our orphan entry.
4671 trans = btrfs_join_transaction(root);
4672 if (IS_ERR(trans)) {
4673 btrfs_orphan_del(NULL, inode);
4676 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4677 err = btrfs_orphan_del(trans, inode);
4679 btrfs_abort_transaction(trans, root, err);
4680 btrfs_end_transaction(trans, root);
4687 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4689 struct inode *inode = dentry->d_inode;
4690 struct btrfs_root *root = BTRFS_I(inode)->root;
4693 if (btrfs_root_readonly(root))
4696 err = inode_change_ok(inode, attr);
4700 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4701 err = btrfs_setsize(inode, attr);
4706 if (attr->ia_valid) {
4707 setattr_copy(inode, attr);
4708 inode_inc_iversion(inode);
4709 err = btrfs_dirty_inode(inode);
4711 if (!err && attr->ia_valid & ATTR_MODE)
4712 err = posix_acl_chmod(inode, inode->i_mode);
4719 * While truncating the inode pages during eviction, we get the VFS calling
4720 * btrfs_invalidatepage() against each page of the inode. This is slow because
4721 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4722 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4723 * extent_state structures over and over, wasting lots of time.
4725 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4726 * those expensive operations on a per page basis and do only the ordered io
4727 * finishing, while we release here the extent_map and extent_state structures,
4728 * without the excessive merging and splitting.
4730 static void evict_inode_truncate_pages(struct inode *inode)
4732 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4733 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4734 struct rb_node *node;
4736 ASSERT(inode->i_state & I_FREEING);
4737 truncate_inode_pages_final(&inode->i_data);
4739 write_lock(&map_tree->lock);
4740 while (!RB_EMPTY_ROOT(&map_tree->map)) {
4741 struct extent_map *em;
4743 node = rb_first(&map_tree->map);
4744 em = rb_entry(node, struct extent_map, rb_node);
4745 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4746 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4747 remove_extent_mapping(map_tree, em);
4748 free_extent_map(em);
4749 if (need_resched()) {
4750 write_unlock(&map_tree->lock);
4752 write_lock(&map_tree->lock);
4755 write_unlock(&map_tree->lock);
4757 spin_lock(&io_tree->lock);
4758 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4759 struct extent_state *state;
4760 struct extent_state *cached_state = NULL;
4762 node = rb_first(&io_tree->state);
4763 state = rb_entry(node, struct extent_state, rb_node);
4764 atomic_inc(&state->refs);
4765 spin_unlock(&io_tree->lock);
4767 lock_extent_bits(io_tree, state->start, state->end,
4769 clear_extent_bit(io_tree, state->start, state->end,
4770 EXTENT_LOCKED | EXTENT_DIRTY |
4771 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
4772 EXTENT_DEFRAG, 1, 1,
4773 &cached_state, GFP_NOFS);
4774 free_extent_state(state);
4777 spin_lock(&io_tree->lock);
4779 spin_unlock(&io_tree->lock);
4782 void btrfs_evict_inode(struct inode *inode)
4784 struct btrfs_trans_handle *trans;
4785 struct btrfs_root *root = BTRFS_I(inode)->root;
4786 struct btrfs_block_rsv *rsv, *global_rsv;
4787 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4790 trace_btrfs_inode_evict(inode);
4792 evict_inode_truncate_pages(inode);
4794 if (inode->i_nlink &&
4795 ((btrfs_root_refs(&root->root_item) != 0 &&
4796 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4797 btrfs_is_free_space_inode(inode)))
4800 if (is_bad_inode(inode)) {
4801 btrfs_orphan_del(NULL, inode);
4804 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4805 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4807 btrfs_free_io_failure_record(inode, 0, (u64)-1);
4809 if (root->fs_info->log_root_recovering) {
4810 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4811 &BTRFS_I(inode)->runtime_flags));
4815 if (inode->i_nlink > 0) {
4816 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4817 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4821 ret = btrfs_commit_inode_delayed_inode(inode);
4823 btrfs_orphan_del(NULL, inode);
4827 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4829 btrfs_orphan_del(NULL, inode);
4832 rsv->size = min_size;
4834 global_rsv = &root->fs_info->global_block_rsv;
4836 btrfs_i_size_write(inode, 0);
4839 * This is a bit simpler than btrfs_truncate since we've already
4840 * reserved our space for our orphan item in the unlink, so we just
4841 * need to reserve some slack space in case we add bytes and update
4842 * inode item when doing the truncate.
4845 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4846 BTRFS_RESERVE_FLUSH_LIMIT);
4849 * Try and steal from the global reserve since we will
4850 * likely not use this space anyway, we want to try as
4851 * hard as possible to get this to work.
4854 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4857 btrfs_warn(root->fs_info,
4858 "Could not get space for a delete, will truncate on mount %d",
4860 btrfs_orphan_del(NULL, inode);
4861 btrfs_free_block_rsv(root, rsv);
4865 trans = btrfs_join_transaction(root);
4866 if (IS_ERR(trans)) {
4867 btrfs_orphan_del(NULL, inode);
4868 btrfs_free_block_rsv(root, rsv);
4872 trans->block_rsv = rsv;
4874 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4878 trans->block_rsv = &root->fs_info->trans_block_rsv;
4879 btrfs_end_transaction(trans, root);
4881 btrfs_btree_balance_dirty(root);
4884 btrfs_free_block_rsv(root, rsv);
4887 * Errors here aren't a big deal, it just means we leave orphan items
4888 * in the tree. They will be cleaned up on the next mount.
4891 trans->block_rsv = root->orphan_block_rsv;
4892 btrfs_orphan_del(trans, inode);
4894 btrfs_orphan_del(NULL, inode);
4897 trans->block_rsv = &root->fs_info->trans_block_rsv;
4898 if (!(root == root->fs_info->tree_root ||
4899 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4900 btrfs_return_ino(root, btrfs_ino(inode));
4902 btrfs_end_transaction(trans, root);
4903 btrfs_btree_balance_dirty(root);
4905 btrfs_remove_delayed_node(inode);
4911 * this returns the key found in the dir entry in the location pointer.
4912 * If no dir entries were found, location->objectid is 0.
4914 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4915 struct btrfs_key *location)
4917 const char *name = dentry->d_name.name;
4918 int namelen = dentry->d_name.len;
4919 struct btrfs_dir_item *di;
4920 struct btrfs_path *path;
4921 struct btrfs_root *root = BTRFS_I(dir)->root;
4924 path = btrfs_alloc_path();
4928 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4933 if (IS_ERR_OR_NULL(di))
4936 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4938 btrfs_free_path(path);
4941 location->objectid = 0;
4946 * when we hit a tree root in a directory, the btrfs part of the inode
4947 * needs to be changed to reflect the root directory of the tree root. This
4948 * is kind of like crossing a mount point.
4950 static int fixup_tree_root_location(struct btrfs_root *root,
4952 struct dentry *dentry,
4953 struct btrfs_key *location,
4954 struct btrfs_root **sub_root)
4956 struct btrfs_path *path;
4957 struct btrfs_root *new_root;
4958 struct btrfs_root_ref *ref;
4959 struct extent_buffer *leaf;
4963 path = btrfs_alloc_path();
4970 ret = btrfs_find_item(root->fs_info->tree_root, path,
4971 BTRFS_I(dir)->root->root_key.objectid,
4972 location->objectid, BTRFS_ROOT_REF_KEY, NULL);
4979 leaf = path->nodes[0];
4980 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4981 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4982 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4985 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4986 (unsigned long)(ref + 1),
4987 dentry->d_name.len);
4991 btrfs_release_path(path);
4993 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4994 if (IS_ERR(new_root)) {
4995 err = PTR_ERR(new_root);
4999 *sub_root = new_root;
5000 location->objectid = btrfs_root_dirid(&new_root->root_item);
5001 location->type = BTRFS_INODE_ITEM_KEY;
5002 location->offset = 0;
5005 btrfs_free_path(path);
5009 static void inode_tree_add(struct inode *inode)
5011 struct btrfs_root *root = BTRFS_I(inode)->root;
5012 struct btrfs_inode *entry;
5014 struct rb_node *parent;
5015 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5016 u64 ino = btrfs_ino(inode);
5018 if (inode_unhashed(inode))
5021 spin_lock(&root->inode_lock);
5022 p = &root->inode_tree.rb_node;
5025 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5027 if (ino < btrfs_ino(&entry->vfs_inode))
5028 p = &parent->rb_left;
5029 else if (ino > btrfs_ino(&entry->vfs_inode))
5030 p = &parent->rb_right;
5032 WARN_ON(!(entry->vfs_inode.i_state &
5033 (I_WILL_FREE | I_FREEING)));
5034 rb_replace_node(parent, new, &root->inode_tree);
5035 RB_CLEAR_NODE(parent);
5036 spin_unlock(&root->inode_lock);
5040 rb_link_node(new, parent, p);
5041 rb_insert_color(new, &root->inode_tree);
5042 spin_unlock(&root->inode_lock);
5045 static void inode_tree_del(struct inode *inode)
5047 struct btrfs_root *root = BTRFS_I(inode)->root;
5050 spin_lock(&root->inode_lock);
5051 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5052 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5053 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5054 empty = RB_EMPTY_ROOT(&root->inode_tree);
5056 spin_unlock(&root->inode_lock);
5058 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5059 synchronize_srcu(&root->fs_info->subvol_srcu);
5060 spin_lock(&root->inode_lock);
5061 empty = RB_EMPTY_ROOT(&root->inode_tree);
5062 spin_unlock(&root->inode_lock);
5064 btrfs_add_dead_root(root);
5068 void btrfs_invalidate_inodes(struct btrfs_root *root)
5070 struct rb_node *node;
5071 struct rb_node *prev;
5072 struct btrfs_inode *entry;
5073 struct inode *inode;
5076 if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
5077 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5079 spin_lock(&root->inode_lock);
5081 node = root->inode_tree.rb_node;
5085 entry = rb_entry(node, struct btrfs_inode, rb_node);
5087 if (objectid < btrfs_ino(&entry->vfs_inode))
5088 node = node->rb_left;
5089 else if (objectid > btrfs_ino(&entry->vfs_inode))
5090 node = node->rb_right;
5096 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5097 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
5101 prev = rb_next(prev);
5105 entry = rb_entry(node, struct btrfs_inode, rb_node);
5106 objectid = btrfs_ino(&entry->vfs_inode) + 1;
5107 inode = igrab(&entry->vfs_inode);
5109 spin_unlock(&root->inode_lock);
5110 if (atomic_read(&inode->i_count) > 1)
5111 d_prune_aliases(inode);
5113 * btrfs_drop_inode will have it removed from
5114 * the inode cache when its usage count
5119 spin_lock(&root->inode_lock);
5123 if (cond_resched_lock(&root->inode_lock))
5126 node = rb_next(node);
5128 spin_unlock(&root->inode_lock);
5131 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5133 struct btrfs_iget_args *args = p;
5134 inode->i_ino = args->location->objectid;
5135 memcpy(&BTRFS_I(inode)->location, args->location,
5136 sizeof(*args->location));
5137 BTRFS_I(inode)->root = args->root;
5141 static int btrfs_find_actor(struct inode *inode, void *opaque)
5143 struct btrfs_iget_args *args = opaque;
5144 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5145 args->root == BTRFS_I(inode)->root;
5148 static struct inode *btrfs_iget_locked(struct super_block *s,
5149 struct btrfs_key *location,
5150 struct btrfs_root *root)
5152 struct inode *inode;
5153 struct btrfs_iget_args args;
5154 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5156 args.location = location;
5159 inode = iget5_locked(s, hashval, btrfs_find_actor,
5160 btrfs_init_locked_inode,
5165 /* Get an inode object given its location and corresponding root.
5166 * Returns in *is_new if the inode was read from disk
5168 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5169 struct btrfs_root *root, int *new)
5171 struct inode *inode;
5173 inode = btrfs_iget_locked(s, location, root);
5175 return ERR_PTR(-ENOMEM);
5177 if (inode->i_state & I_NEW) {
5178 btrfs_read_locked_inode(inode);
5179 if (!is_bad_inode(inode)) {
5180 inode_tree_add(inode);
5181 unlock_new_inode(inode);
5185 unlock_new_inode(inode);
5187 inode = ERR_PTR(-ESTALE);
5194 static struct inode *new_simple_dir(struct super_block *s,
5195 struct btrfs_key *key,
5196 struct btrfs_root *root)
5198 struct inode *inode = new_inode(s);
5201 return ERR_PTR(-ENOMEM);
5203 BTRFS_I(inode)->root = root;
5204 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5205 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5207 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5208 inode->i_op = &btrfs_dir_ro_inode_operations;
5209 inode->i_fop = &simple_dir_operations;
5210 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5211 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5216 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5218 struct inode *inode;
5219 struct btrfs_root *root = BTRFS_I(dir)->root;
5220 struct btrfs_root *sub_root = root;
5221 struct btrfs_key location;
5225 if (dentry->d_name.len > BTRFS_NAME_LEN)
5226 return ERR_PTR(-ENAMETOOLONG);
5228 ret = btrfs_inode_by_name(dir, dentry, &location);
5230 return ERR_PTR(ret);
5232 if (location.objectid == 0)
5233 return ERR_PTR(-ENOENT);
5235 if (location.type == BTRFS_INODE_ITEM_KEY) {
5236 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5240 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5242 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5243 ret = fixup_tree_root_location(root, dir, dentry,
5244 &location, &sub_root);
5247 inode = ERR_PTR(ret);
5249 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5251 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5253 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5255 if (!IS_ERR(inode) && root != sub_root) {
5256 down_read(&root->fs_info->cleanup_work_sem);
5257 if (!(inode->i_sb->s_flags & MS_RDONLY))
5258 ret = btrfs_orphan_cleanup(sub_root);
5259 up_read(&root->fs_info->cleanup_work_sem);
5262 inode = ERR_PTR(ret);
5265 * If orphan cleanup did remove any orphans, it means the tree
5266 * was modified and therefore the commit root is not the same as
5267 * the current root anymore. This is a problem, because send
5268 * uses the commit root and therefore can see inode items that
5269 * don't exist in the current root anymore, and for example make
5270 * calls to btrfs_iget, which will do tree lookups based on the
5271 * current root and not on the commit root. Those lookups will
5272 * fail, returning a -ESTALE error, and making send fail with
5273 * that error. So make sure a send does not see any orphans we
5274 * have just removed, and that it will see the same inodes
5275 * regardless of whether a transaction commit happened before
5276 * it started (meaning that the commit root will be the same as
5277 * the current root) or not.
5279 if (sub_root->node != sub_root->commit_root) {
5280 u64 sub_flags = btrfs_root_flags(&sub_root->root_item);
5282 if (sub_flags & BTRFS_ROOT_SUBVOL_RDONLY) {
5283 struct extent_buffer *eb;
5286 * Assert we can't have races between dentry
5287 * lookup called through the snapshot creation
5288 * ioctl and the VFS.
5290 ASSERT(mutex_is_locked(&dir->i_mutex));
5292 down_write(&root->fs_info->commit_root_sem);
5293 eb = sub_root->commit_root;
5294 sub_root->commit_root =
5295 btrfs_root_node(sub_root);
5296 up_write(&root->fs_info->commit_root_sem);
5297 free_extent_buffer(eb);
5305 static int btrfs_dentry_delete(const struct dentry *dentry)
5307 struct btrfs_root *root;
5308 struct inode *inode = dentry->d_inode;
5310 if (!inode && !IS_ROOT(dentry))
5311 inode = dentry->d_parent->d_inode;
5314 root = BTRFS_I(inode)->root;
5315 if (btrfs_root_refs(&root->root_item) == 0)
5318 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5324 static void btrfs_dentry_release(struct dentry *dentry)
5326 kfree(dentry->d_fsdata);
5329 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5332 struct inode *inode;
5334 inode = btrfs_lookup_dentry(dir, dentry);
5335 if (IS_ERR(inode)) {
5336 if (PTR_ERR(inode) == -ENOENT)
5339 return ERR_CAST(inode);
5342 return d_materialise_unique(dentry, inode);
5345 unsigned char btrfs_filetype_table[] = {
5346 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5349 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5351 struct inode *inode = file_inode(file);
5352 struct btrfs_root *root = BTRFS_I(inode)->root;
5353 struct btrfs_item *item;
5354 struct btrfs_dir_item *di;
5355 struct btrfs_key key;
5356 struct btrfs_key found_key;
5357 struct btrfs_path *path;
5358 struct list_head ins_list;
5359 struct list_head del_list;
5361 struct extent_buffer *leaf;
5363 unsigned char d_type;
5368 int key_type = BTRFS_DIR_INDEX_KEY;
5372 int is_curr = 0; /* ctx->pos points to the current index? */
5374 /* FIXME, use a real flag for deciding about the key type */
5375 if (root->fs_info->tree_root == root)
5376 key_type = BTRFS_DIR_ITEM_KEY;
5378 if (!dir_emit_dots(file, ctx))
5381 path = btrfs_alloc_path();
5387 if (key_type == BTRFS_DIR_INDEX_KEY) {
5388 INIT_LIST_HEAD(&ins_list);
5389 INIT_LIST_HEAD(&del_list);
5390 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5393 key.type = key_type;
5394 key.offset = ctx->pos;
5395 key.objectid = btrfs_ino(inode);
5397 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5402 leaf = path->nodes[0];
5403 slot = path->slots[0];
5404 if (slot >= btrfs_header_nritems(leaf)) {
5405 ret = btrfs_next_leaf(root, path);
5413 item = btrfs_item_nr(slot);
5414 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5416 if (found_key.objectid != key.objectid)
5418 if (found_key.type != key_type)
5420 if (found_key.offset < ctx->pos)
5422 if (key_type == BTRFS_DIR_INDEX_KEY &&
5423 btrfs_should_delete_dir_index(&del_list,
5427 ctx->pos = found_key.offset;
5430 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5432 di_total = btrfs_item_size(leaf, item);
5434 while (di_cur < di_total) {
5435 struct btrfs_key location;
5437 if (verify_dir_item(root, leaf, di))
5440 name_len = btrfs_dir_name_len(leaf, di);
5441 if (name_len <= sizeof(tmp_name)) {
5442 name_ptr = tmp_name;
5444 name_ptr = kmalloc(name_len, GFP_NOFS);
5450 read_extent_buffer(leaf, name_ptr,
5451 (unsigned long)(di + 1), name_len);
5453 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5454 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5457 /* is this a reference to our own snapshot? If so
5460 * In contrast to old kernels, we insert the snapshot's
5461 * dir item and dir index after it has been created, so
5462 * we won't find a reference to our own snapshot. We
5463 * still keep the following code for backward
5466 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5467 location.objectid == root->root_key.objectid) {
5471 over = !dir_emit(ctx, name_ptr, name_len,
5472 location.objectid, d_type);
5475 if (name_ptr != tmp_name)
5480 di_len = btrfs_dir_name_len(leaf, di) +
5481 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5483 di = (struct btrfs_dir_item *)((char *)di + di_len);
5489 if (key_type == BTRFS_DIR_INDEX_KEY) {
5492 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5497 /* Reached end of directory/root. Bump pos past the last item. */
5501 * Stop new entries from being returned after we return the last
5504 * New directory entries are assigned a strictly increasing
5505 * offset. This means that new entries created during readdir
5506 * are *guaranteed* to be seen in the future by that readdir.
5507 * This has broken buggy programs which operate on names as
5508 * they're returned by readdir. Until we re-use freed offsets
5509 * we have this hack to stop new entries from being returned
5510 * under the assumption that they'll never reach this huge
5513 * This is being careful not to overflow 32bit loff_t unless the
5514 * last entry requires it because doing so has broken 32bit apps
5517 if (key_type == BTRFS_DIR_INDEX_KEY) {
5518 if (ctx->pos >= INT_MAX)
5519 ctx->pos = LLONG_MAX;
5526 if (key_type == BTRFS_DIR_INDEX_KEY)
5527 btrfs_put_delayed_items(&ins_list, &del_list);
5528 btrfs_free_path(path);
5532 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5534 struct btrfs_root *root = BTRFS_I(inode)->root;
5535 struct btrfs_trans_handle *trans;
5537 bool nolock = false;
5539 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5542 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5545 if (wbc->sync_mode == WB_SYNC_ALL) {
5547 trans = btrfs_join_transaction_nolock(root);
5549 trans = btrfs_join_transaction(root);
5551 return PTR_ERR(trans);
5552 ret = btrfs_commit_transaction(trans, root);
5558 * This is somewhat expensive, updating the tree every time the
5559 * inode changes. But, it is most likely to find the inode in cache.
5560 * FIXME, needs more benchmarking...there are no reasons other than performance
5561 * to keep or drop this code.
5563 static int btrfs_dirty_inode(struct inode *inode)
5565 struct btrfs_root *root = BTRFS_I(inode)->root;
5566 struct btrfs_trans_handle *trans;
5569 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5572 trans = btrfs_join_transaction(root);
5574 return PTR_ERR(trans);
5576 ret = btrfs_update_inode(trans, root, inode);
5577 if (ret && ret == -ENOSPC) {
5578 /* whoops, lets try again with the full transaction */
5579 btrfs_end_transaction(trans, root);
5580 trans = btrfs_start_transaction(root, 1);
5582 return PTR_ERR(trans);
5584 ret = btrfs_update_inode(trans, root, inode);
5586 btrfs_end_transaction(trans, root);
5587 if (BTRFS_I(inode)->delayed_node)
5588 btrfs_balance_delayed_items(root);
5594 * This is a copy of file_update_time. We need this so we can return error on
5595 * ENOSPC for updating the inode in the case of file write and mmap writes.
5597 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5600 struct btrfs_root *root = BTRFS_I(inode)->root;
5602 if (btrfs_root_readonly(root))
5605 if (flags & S_VERSION)
5606 inode_inc_iversion(inode);
5607 if (flags & S_CTIME)
5608 inode->i_ctime = *now;
5609 if (flags & S_MTIME)
5610 inode->i_mtime = *now;
5611 if (flags & S_ATIME)
5612 inode->i_atime = *now;
5613 return btrfs_dirty_inode(inode);
5617 * find the highest existing sequence number in a directory
5618 * and then set the in-memory index_cnt variable to reflect
5619 * free sequence numbers
5621 static int btrfs_set_inode_index_count(struct inode *inode)
5623 struct btrfs_root *root = BTRFS_I(inode)->root;
5624 struct btrfs_key key, found_key;
5625 struct btrfs_path *path;
5626 struct extent_buffer *leaf;
5629 key.objectid = btrfs_ino(inode);
5630 key.type = BTRFS_DIR_INDEX_KEY;
5631 key.offset = (u64)-1;
5633 path = btrfs_alloc_path();
5637 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5640 /* FIXME: we should be able to handle this */
5646 * MAGIC NUMBER EXPLANATION:
5647 * since we search a directory based on f_pos we have to start at 2
5648 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5649 * else has to start at 2
5651 if (path->slots[0] == 0) {
5652 BTRFS_I(inode)->index_cnt = 2;
5658 leaf = path->nodes[0];
5659 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5661 if (found_key.objectid != btrfs_ino(inode) ||
5662 found_key.type != BTRFS_DIR_INDEX_KEY) {
5663 BTRFS_I(inode)->index_cnt = 2;
5667 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5669 btrfs_free_path(path);
5674 * helper to find a free sequence number in a given directory. This current
5675 * code is very simple, later versions will do smarter things in the btree
5677 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5681 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5682 ret = btrfs_inode_delayed_dir_index_count(dir);
5684 ret = btrfs_set_inode_index_count(dir);
5690 *index = BTRFS_I(dir)->index_cnt;
5691 BTRFS_I(dir)->index_cnt++;
5696 static int btrfs_insert_inode_locked(struct inode *inode)
5698 struct btrfs_iget_args args;
5699 args.location = &BTRFS_I(inode)->location;
5700 args.root = BTRFS_I(inode)->root;
5702 return insert_inode_locked4(inode,
5703 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5704 btrfs_find_actor, &args);
5707 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5708 struct btrfs_root *root,
5710 const char *name, int name_len,
5711 u64 ref_objectid, u64 objectid,
5712 umode_t mode, u64 *index)
5714 struct inode *inode;
5715 struct btrfs_inode_item *inode_item;
5716 struct btrfs_key *location;
5717 struct btrfs_path *path;
5718 struct btrfs_inode_ref *ref;
5719 struct btrfs_key key[2];
5721 int nitems = name ? 2 : 1;
5725 path = btrfs_alloc_path();
5727 return ERR_PTR(-ENOMEM);
5729 inode = new_inode(root->fs_info->sb);
5731 btrfs_free_path(path);
5732 return ERR_PTR(-ENOMEM);
5736 * O_TMPFILE, set link count to 0, so that after this point,
5737 * we fill in an inode item with the correct link count.
5740 set_nlink(inode, 0);
5743 * we have to initialize this early, so we can reclaim the inode
5744 * number if we fail afterwards in this function.
5746 inode->i_ino = objectid;
5749 trace_btrfs_inode_request(dir);
5751 ret = btrfs_set_inode_index(dir, index);
5753 btrfs_free_path(path);
5755 return ERR_PTR(ret);
5761 * index_cnt is ignored for everything but a dir,
5762 * btrfs_get_inode_index_count has an explanation for the magic
5765 BTRFS_I(inode)->index_cnt = 2;
5766 BTRFS_I(inode)->dir_index = *index;
5767 BTRFS_I(inode)->root = root;
5768 BTRFS_I(inode)->generation = trans->transid;
5769 inode->i_generation = BTRFS_I(inode)->generation;
5772 * We could have gotten an inode number from somebody who was fsynced
5773 * and then removed in this same transaction, so let's just set full
5774 * sync since it will be a full sync anyway and this will blow away the
5775 * old info in the log.
5777 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5779 key[0].objectid = objectid;
5780 key[0].type = BTRFS_INODE_ITEM_KEY;
5783 sizes[0] = sizeof(struct btrfs_inode_item);
5787 * Start new inodes with an inode_ref. This is slightly more
5788 * efficient for small numbers of hard links since they will
5789 * be packed into one item. Extended refs will kick in if we
5790 * add more hard links than can fit in the ref item.
5792 key[1].objectid = objectid;
5793 key[1].type = BTRFS_INODE_REF_KEY;
5794 key[1].offset = ref_objectid;
5796 sizes[1] = name_len + sizeof(*ref);
5799 location = &BTRFS_I(inode)->location;
5800 location->objectid = objectid;
5801 location->offset = 0;
5802 location->type = BTRFS_INODE_ITEM_KEY;
5804 ret = btrfs_insert_inode_locked(inode);
5808 path->leave_spinning = 1;
5809 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
5813 inode_init_owner(inode, dir, mode);
5814 inode_set_bytes(inode, 0);
5815 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5816 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5817 struct btrfs_inode_item);
5818 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5819 sizeof(*inode_item));
5820 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5823 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5824 struct btrfs_inode_ref);
5825 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5826 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5827 ptr = (unsigned long)(ref + 1);
5828 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5831 btrfs_mark_buffer_dirty(path->nodes[0]);
5832 btrfs_free_path(path);
5834 btrfs_inherit_iflags(inode, dir);
5836 if (S_ISREG(mode)) {
5837 if (btrfs_test_opt(root, NODATASUM))
5838 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5839 if (btrfs_test_opt(root, NODATACOW))
5840 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5841 BTRFS_INODE_NODATASUM;
5844 inode_tree_add(inode);
5846 trace_btrfs_inode_new(inode);
5847 btrfs_set_inode_last_trans(trans, inode);
5849 btrfs_update_root_times(trans, root);
5851 ret = btrfs_inode_inherit_props(trans, inode, dir);
5853 btrfs_err(root->fs_info,
5854 "error inheriting props for ino %llu (root %llu): %d",
5855 btrfs_ino(inode), root->root_key.objectid, ret);
5860 unlock_new_inode(inode);
5863 BTRFS_I(dir)->index_cnt--;
5864 btrfs_free_path(path);
5866 return ERR_PTR(ret);
5869 static inline u8 btrfs_inode_type(struct inode *inode)
5871 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5875 * utility function to add 'inode' into 'parent_inode' with
5876 * a give name and a given sequence number.
5877 * if 'add_backref' is true, also insert a backref from the
5878 * inode to the parent directory.
5880 int btrfs_add_link(struct btrfs_trans_handle *trans,
5881 struct inode *parent_inode, struct inode *inode,
5882 const char *name, int name_len, int add_backref, u64 index)
5885 struct btrfs_key key;
5886 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5887 u64 ino = btrfs_ino(inode);
5888 u64 parent_ino = btrfs_ino(parent_inode);
5890 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5891 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5894 key.type = BTRFS_INODE_ITEM_KEY;
5898 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5899 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5900 key.objectid, root->root_key.objectid,
5901 parent_ino, index, name, name_len);
5902 } else if (add_backref) {
5903 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5907 /* Nothing to clean up yet */
5911 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5913 btrfs_inode_type(inode), index);
5914 if (ret == -EEXIST || ret == -EOVERFLOW)
5917 btrfs_abort_transaction(trans, root, ret);
5921 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5923 inode_inc_iversion(parent_inode);
5924 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5925 ret = btrfs_update_inode(trans, root, parent_inode);
5927 btrfs_abort_transaction(trans, root, ret);
5931 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5934 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5935 key.objectid, root->root_key.objectid,
5936 parent_ino, &local_index, name, name_len);
5938 } else if (add_backref) {
5942 err = btrfs_del_inode_ref(trans, root, name, name_len,
5943 ino, parent_ino, &local_index);
5948 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5949 struct inode *dir, struct dentry *dentry,
5950 struct inode *inode, int backref, u64 index)
5952 int err = btrfs_add_link(trans, dir, inode,
5953 dentry->d_name.name, dentry->d_name.len,
5960 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5961 umode_t mode, dev_t rdev)
5963 struct btrfs_trans_handle *trans;
5964 struct btrfs_root *root = BTRFS_I(dir)->root;
5965 struct inode *inode = NULL;
5971 if (!new_valid_dev(rdev))
5975 * 2 for inode item and ref
5977 * 1 for xattr if selinux is on
5979 trans = btrfs_start_transaction(root, 5);
5981 return PTR_ERR(trans);
5983 err = btrfs_find_free_ino(root, &objectid);
5987 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5988 dentry->d_name.len, btrfs_ino(dir), objectid,
5990 if (IS_ERR(inode)) {
5991 err = PTR_ERR(inode);
5996 * If the active LSM wants to access the inode during
5997 * d_instantiate it needs these. Smack checks to see
5998 * if the filesystem supports xattrs by looking at the
6001 inode->i_op = &btrfs_special_inode_operations;
6002 init_special_inode(inode, inode->i_mode, rdev);
6004 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6006 goto out_unlock_inode;
6008 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6010 goto out_unlock_inode;
6012 btrfs_update_inode(trans, root, inode);
6013 unlock_new_inode(inode);
6014 d_instantiate(dentry, inode);
6018 btrfs_end_transaction(trans, root);
6019 btrfs_balance_delayed_items(root);
6020 btrfs_btree_balance_dirty(root);
6022 inode_dec_link_count(inode);
6029 unlock_new_inode(inode);
6034 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6035 umode_t mode, bool excl)
6037 struct btrfs_trans_handle *trans;
6038 struct btrfs_root *root = BTRFS_I(dir)->root;
6039 struct inode *inode = NULL;
6040 int drop_inode_on_err = 0;
6046 * 2 for inode item and ref
6048 * 1 for xattr if selinux is on
6050 trans = btrfs_start_transaction(root, 5);
6052 return PTR_ERR(trans);
6054 err = btrfs_find_free_ino(root, &objectid);
6058 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6059 dentry->d_name.len, btrfs_ino(dir), objectid,
6061 if (IS_ERR(inode)) {
6062 err = PTR_ERR(inode);
6065 drop_inode_on_err = 1;
6067 * If the active LSM wants to access the inode during
6068 * d_instantiate it needs these. Smack checks to see
6069 * if the filesystem supports xattrs by looking at the
6072 inode->i_fop = &btrfs_file_operations;
6073 inode->i_op = &btrfs_file_inode_operations;
6074 inode->i_mapping->a_ops = &btrfs_aops;
6075 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
6077 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6079 goto out_unlock_inode;
6081 err = btrfs_update_inode(trans, root, inode);
6083 goto out_unlock_inode;
6085 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6087 goto out_unlock_inode;
6089 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6090 unlock_new_inode(inode);
6091 d_instantiate(dentry, inode);
6094 btrfs_end_transaction(trans, root);
6095 if (err && drop_inode_on_err) {
6096 inode_dec_link_count(inode);
6099 btrfs_balance_delayed_items(root);
6100 btrfs_btree_balance_dirty(root);
6104 unlock_new_inode(inode);
6109 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6110 struct dentry *dentry)
6112 struct btrfs_trans_handle *trans;
6113 struct btrfs_root *root = BTRFS_I(dir)->root;
6114 struct inode *inode = old_dentry->d_inode;
6119 /* do not allow sys_link's with other subvols of the same device */
6120 if (root->objectid != BTRFS_I(inode)->root->objectid)
6123 if (inode->i_nlink >= BTRFS_LINK_MAX)
6126 err = btrfs_set_inode_index(dir, &index);
6131 * 2 items for inode and inode ref
6132 * 2 items for dir items
6133 * 1 item for parent inode
6135 trans = btrfs_start_transaction(root, 5);
6136 if (IS_ERR(trans)) {
6137 err = PTR_ERR(trans);
6141 /* There are several dir indexes for this inode, clear the cache. */
6142 BTRFS_I(inode)->dir_index = 0ULL;
6144 inode_inc_iversion(inode);
6145 inode->i_ctime = CURRENT_TIME;
6147 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6149 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
6154 struct dentry *parent = dentry->d_parent;
6155 err = btrfs_update_inode(trans, root, inode);
6158 if (inode->i_nlink == 1) {
6160 * If new hard link count is 1, it's a file created
6161 * with open(2) O_TMPFILE flag.
6163 err = btrfs_orphan_del(trans, inode);
6167 d_instantiate(dentry, inode);
6168 btrfs_log_new_name(trans, inode, NULL, parent);
6171 btrfs_end_transaction(trans, root);
6172 btrfs_balance_delayed_items(root);
6175 inode_dec_link_count(inode);
6178 btrfs_btree_balance_dirty(root);
6182 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6184 struct inode *inode = NULL;
6185 struct btrfs_trans_handle *trans;
6186 struct btrfs_root *root = BTRFS_I(dir)->root;
6188 int drop_on_err = 0;
6193 * 2 items for inode and ref
6194 * 2 items for dir items
6195 * 1 for xattr if selinux is on
6197 trans = btrfs_start_transaction(root, 5);
6199 return PTR_ERR(trans);
6201 err = btrfs_find_free_ino(root, &objectid);
6205 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6206 dentry->d_name.len, btrfs_ino(dir), objectid,
6207 S_IFDIR | mode, &index);
6208 if (IS_ERR(inode)) {
6209 err = PTR_ERR(inode);
6214 /* these must be set before we unlock the inode */
6215 inode->i_op = &btrfs_dir_inode_operations;
6216 inode->i_fop = &btrfs_dir_file_operations;
6218 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6220 goto out_fail_inode;
6222 btrfs_i_size_write(inode, 0);
6223 err = btrfs_update_inode(trans, root, inode);
6225 goto out_fail_inode;
6227 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6228 dentry->d_name.len, 0, index);
6230 goto out_fail_inode;
6232 d_instantiate(dentry, inode);
6234 * mkdir is special. We're unlocking after we call d_instantiate
6235 * to avoid a race with nfsd calling d_instantiate.
6237 unlock_new_inode(inode);
6241 btrfs_end_transaction(trans, root);
6244 btrfs_balance_delayed_items(root);
6245 btrfs_btree_balance_dirty(root);
6249 unlock_new_inode(inode);
6253 /* Find next extent map of a given extent map, caller needs to ensure locks */
6254 static struct extent_map *next_extent_map(struct extent_map *em)
6256 struct rb_node *next;
6258 next = rb_next(&em->rb_node);
6261 return container_of(next, struct extent_map, rb_node);
6264 static struct extent_map *prev_extent_map(struct extent_map *em)
6266 struct rb_node *prev;
6268 prev = rb_prev(&em->rb_node);
6271 return container_of(prev, struct extent_map, rb_node);
6274 /* helper for btfs_get_extent. Given an existing extent in the tree,
6275 * the existing extent is the nearest extent to map_start,
6276 * and an extent that you want to insert, deal with overlap and insert
6277 * the best fitted new extent into the tree.
6279 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6280 struct extent_map *existing,
6281 struct extent_map *em,
6284 struct extent_map *prev;
6285 struct extent_map *next;
6290 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6292 if (existing->start > map_start) {
6294 prev = prev_extent_map(next);
6297 next = next_extent_map(prev);
6300 start = prev ? extent_map_end(prev) : em->start;
6301 start = max_t(u64, start, em->start);
6302 end = next ? next->start : extent_map_end(em);
6303 end = min_t(u64, end, extent_map_end(em));
6304 start_diff = start - em->start;
6306 em->len = end - start;
6307 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6308 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6309 em->block_start += start_diff;
6310 em->block_len -= start_diff;
6312 return add_extent_mapping(em_tree, em, 0);
6315 static noinline int uncompress_inline(struct btrfs_path *path,
6316 struct inode *inode, struct page *page,
6317 size_t pg_offset, u64 extent_offset,
6318 struct btrfs_file_extent_item *item)
6321 struct extent_buffer *leaf = path->nodes[0];
6324 unsigned long inline_size;
6328 WARN_ON(pg_offset != 0);
6329 compress_type = btrfs_file_extent_compression(leaf, item);
6330 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6331 inline_size = btrfs_file_extent_inline_item_len(leaf,
6332 btrfs_item_nr(path->slots[0]));
6333 tmp = kmalloc(inline_size, GFP_NOFS);
6336 ptr = btrfs_file_extent_inline_start(item);
6338 read_extent_buffer(leaf, tmp, ptr, inline_size);
6340 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6341 ret = btrfs_decompress(compress_type, tmp, page,
6342 extent_offset, inline_size, max_size);
6348 * a bit scary, this does extent mapping from logical file offset to the disk.
6349 * the ugly parts come from merging extents from the disk with the in-ram
6350 * representation. This gets more complex because of the data=ordered code,
6351 * where the in-ram extents might be locked pending data=ordered completion.
6353 * This also copies inline extents directly into the page.
6356 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6357 size_t pg_offset, u64 start, u64 len,
6362 u64 extent_start = 0;
6364 u64 objectid = btrfs_ino(inode);
6366 struct btrfs_path *path = NULL;
6367 struct btrfs_root *root = BTRFS_I(inode)->root;
6368 struct btrfs_file_extent_item *item;
6369 struct extent_buffer *leaf;
6370 struct btrfs_key found_key;
6371 struct extent_map *em = NULL;
6372 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6373 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6374 struct btrfs_trans_handle *trans = NULL;
6375 const bool new_inline = !page || create;
6378 read_lock(&em_tree->lock);
6379 em = lookup_extent_mapping(em_tree, start, len);
6381 em->bdev = root->fs_info->fs_devices->latest_bdev;
6382 read_unlock(&em_tree->lock);
6385 if (em->start > start || em->start + em->len <= start)
6386 free_extent_map(em);
6387 else if (em->block_start == EXTENT_MAP_INLINE && page)
6388 free_extent_map(em);
6392 em = alloc_extent_map();
6397 em->bdev = root->fs_info->fs_devices->latest_bdev;
6398 em->start = EXTENT_MAP_HOLE;
6399 em->orig_start = EXTENT_MAP_HOLE;
6401 em->block_len = (u64)-1;
6404 path = btrfs_alloc_path();
6410 * Chances are we'll be called again, so go ahead and do
6416 ret = btrfs_lookup_file_extent(trans, root, path,
6417 objectid, start, trans != NULL);
6424 if (path->slots[0] == 0)
6429 leaf = path->nodes[0];
6430 item = btrfs_item_ptr(leaf, path->slots[0],
6431 struct btrfs_file_extent_item);
6432 /* are we inside the extent that was found? */
6433 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6434 found_type = found_key.type;
6435 if (found_key.objectid != objectid ||
6436 found_type != BTRFS_EXTENT_DATA_KEY) {
6438 * If we backup past the first extent we want to move forward
6439 * and see if there is an extent in front of us, otherwise we'll
6440 * say there is a hole for our whole search range which can
6447 found_type = btrfs_file_extent_type(leaf, item);
6448 extent_start = found_key.offset;
6449 if (found_type == BTRFS_FILE_EXTENT_REG ||
6450 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6451 extent_end = extent_start +
6452 btrfs_file_extent_num_bytes(leaf, item);
6453 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6455 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6456 extent_end = ALIGN(extent_start + size, root->sectorsize);
6459 if (start >= extent_end) {
6461 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6462 ret = btrfs_next_leaf(root, path);
6469 leaf = path->nodes[0];
6471 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6472 if (found_key.objectid != objectid ||
6473 found_key.type != BTRFS_EXTENT_DATA_KEY)
6475 if (start + len <= found_key.offset)
6477 if (start > found_key.offset)
6480 em->orig_start = start;
6481 em->len = found_key.offset - start;
6485 btrfs_extent_item_to_extent_map(inode, path, item, new_inline, em);
6487 if (found_type == BTRFS_FILE_EXTENT_REG ||
6488 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6490 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6494 size_t extent_offset;
6500 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6501 extent_offset = page_offset(page) + pg_offset - extent_start;
6502 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6503 size - extent_offset);
6504 em->start = extent_start + extent_offset;
6505 em->len = ALIGN(copy_size, root->sectorsize);
6506 em->orig_block_len = em->len;
6507 em->orig_start = em->start;
6508 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6509 if (create == 0 && !PageUptodate(page)) {
6510 if (btrfs_file_extent_compression(leaf, item) !=
6511 BTRFS_COMPRESS_NONE) {
6512 ret = uncompress_inline(path, inode, page,
6514 extent_offset, item);
6521 read_extent_buffer(leaf, map + pg_offset, ptr,
6523 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6524 memset(map + pg_offset + copy_size, 0,
6525 PAGE_CACHE_SIZE - pg_offset -
6530 flush_dcache_page(page);
6531 } else if (create && PageUptodate(page)) {
6535 free_extent_map(em);
6538 btrfs_release_path(path);
6539 trans = btrfs_join_transaction(root);
6542 return ERR_CAST(trans);
6546 write_extent_buffer(leaf, map + pg_offset, ptr,
6549 btrfs_mark_buffer_dirty(leaf);
6551 set_extent_uptodate(io_tree, em->start,
6552 extent_map_end(em) - 1, NULL, GFP_NOFS);
6557 em->orig_start = start;
6560 em->block_start = EXTENT_MAP_HOLE;
6561 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6563 btrfs_release_path(path);
6564 if (em->start > start || extent_map_end(em) <= start) {
6565 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6566 em->start, em->len, start, len);
6572 write_lock(&em_tree->lock);
6573 ret = add_extent_mapping(em_tree, em, 0);
6574 /* it is possible that someone inserted the extent into the tree
6575 * while we had the lock dropped. It is also possible that
6576 * an overlapping map exists in the tree
6578 if (ret == -EEXIST) {
6579 struct extent_map *existing;
6583 existing = search_extent_mapping(em_tree, start, len);
6585 * existing will always be non-NULL, since there must be
6586 * extent causing the -EEXIST.
6588 if (start >= extent_map_end(existing) ||
6589 start + len <= existing->start) {
6591 * The existing extent map is the one nearest to
6592 * the [start, start + len) range which overlaps
6594 err = merge_extent_mapping(em_tree, existing,
6596 free_extent_map(existing);
6598 free_extent_map(em);
6602 free_extent_map(em);
6607 write_unlock(&em_tree->lock);
6610 trace_btrfs_get_extent(root, em);
6613 btrfs_free_path(path);
6615 ret = btrfs_end_transaction(trans, root);
6620 free_extent_map(em);
6621 return ERR_PTR(err);
6623 BUG_ON(!em); /* Error is always set */
6627 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6628 size_t pg_offset, u64 start, u64 len,
6631 struct extent_map *em;
6632 struct extent_map *hole_em = NULL;
6633 u64 range_start = start;
6639 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6646 * - a pre-alloc extent,
6647 * there might actually be delalloc bytes behind it.
6649 if (em->block_start != EXTENT_MAP_HOLE &&
6650 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6656 /* check to see if we've wrapped (len == -1 or similar) */
6665 /* ok, we didn't find anything, lets look for delalloc */
6666 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6667 end, len, EXTENT_DELALLOC, 1);
6668 found_end = range_start + found;
6669 if (found_end < range_start)
6670 found_end = (u64)-1;
6673 * we didn't find anything useful, return
6674 * the original results from get_extent()
6676 if (range_start > end || found_end <= start) {
6682 /* adjust the range_start to make sure it doesn't
6683 * go backwards from the start they passed in
6685 range_start = max(start, range_start);
6686 found = found_end - range_start;
6689 u64 hole_start = start;
6692 em = alloc_extent_map();
6698 * when btrfs_get_extent can't find anything it
6699 * returns one huge hole
6701 * make sure what it found really fits our range, and
6702 * adjust to make sure it is based on the start from
6706 u64 calc_end = extent_map_end(hole_em);
6708 if (calc_end <= start || (hole_em->start > end)) {
6709 free_extent_map(hole_em);
6712 hole_start = max(hole_em->start, start);
6713 hole_len = calc_end - hole_start;
6717 if (hole_em && range_start > hole_start) {
6718 /* our hole starts before our delalloc, so we
6719 * have to return just the parts of the hole
6720 * that go until the delalloc starts
6722 em->len = min(hole_len,
6723 range_start - hole_start);
6724 em->start = hole_start;
6725 em->orig_start = hole_start;
6727 * don't adjust block start at all,
6728 * it is fixed at EXTENT_MAP_HOLE
6730 em->block_start = hole_em->block_start;
6731 em->block_len = hole_len;
6732 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6733 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6735 em->start = range_start;
6737 em->orig_start = range_start;
6738 em->block_start = EXTENT_MAP_DELALLOC;
6739 em->block_len = found;
6741 } else if (hole_em) {
6746 free_extent_map(hole_em);
6748 free_extent_map(em);
6749 return ERR_PTR(err);
6754 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6757 struct btrfs_root *root = BTRFS_I(inode)->root;
6758 struct extent_map *em;
6759 struct btrfs_key ins;
6763 alloc_hint = get_extent_allocation_hint(inode, start, len);
6764 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
6765 alloc_hint, &ins, 1, 1);
6767 return ERR_PTR(ret);
6769 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6770 ins.offset, ins.offset, ins.offset, 0);
6772 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
6776 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6777 ins.offset, ins.offset, 0);
6779 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
6780 free_extent_map(em);
6781 return ERR_PTR(ret);
6788 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6789 * block must be cow'd
6791 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6792 u64 *orig_start, u64 *orig_block_len,
6795 struct btrfs_trans_handle *trans;
6796 struct btrfs_path *path;
6798 struct extent_buffer *leaf;
6799 struct btrfs_root *root = BTRFS_I(inode)->root;
6800 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6801 struct btrfs_file_extent_item *fi;
6802 struct btrfs_key key;
6809 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6811 path = btrfs_alloc_path();
6815 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
6820 slot = path->slots[0];
6823 /* can't find the item, must cow */
6830 leaf = path->nodes[0];
6831 btrfs_item_key_to_cpu(leaf, &key, slot);
6832 if (key.objectid != btrfs_ino(inode) ||
6833 key.type != BTRFS_EXTENT_DATA_KEY) {
6834 /* not our file or wrong item type, must cow */
6838 if (key.offset > offset) {
6839 /* Wrong offset, must cow */
6843 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6844 found_type = btrfs_file_extent_type(leaf, fi);
6845 if (found_type != BTRFS_FILE_EXTENT_REG &&
6846 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6847 /* not a regular extent, must cow */
6851 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6854 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6855 if (extent_end <= offset)
6858 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6859 if (disk_bytenr == 0)
6862 if (btrfs_file_extent_compression(leaf, fi) ||
6863 btrfs_file_extent_encryption(leaf, fi) ||
6864 btrfs_file_extent_other_encoding(leaf, fi))
6867 backref_offset = btrfs_file_extent_offset(leaf, fi);
6870 *orig_start = key.offset - backref_offset;
6871 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6872 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6875 if (btrfs_extent_readonly(root, disk_bytenr))
6878 num_bytes = min(offset + *len, extent_end) - offset;
6879 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6882 range_end = round_up(offset + num_bytes, root->sectorsize) - 1;
6883 ret = test_range_bit(io_tree, offset, range_end,
6884 EXTENT_DELALLOC, 0, NULL);
6891 btrfs_release_path(path);
6894 * look for other files referencing this extent, if we
6895 * find any we must cow
6897 trans = btrfs_join_transaction(root);
6898 if (IS_ERR(trans)) {
6903 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6904 key.offset - backref_offset, disk_bytenr);
6905 btrfs_end_transaction(trans, root);
6912 * adjust disk_bytenr and num_bytes to cover just the bytes
6913 * in this extent we are about to write. If there
6914 * are any csums in that range we have to cow in order
6915 * to keep the csums correct
6917 disk_bytenr += backref_offset;
6918 disk_bytenr += offset - key.offset;
6919 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6922 * all of the above have passed, it is safe to overwrite this extent
6928 btrfs_free_path(path);
6932 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
6934 struct radix_tree_root *root = &inode->i_mapping->page_tree;
6936 void **pagep = NULL;
6937 struct page *page = NULL;
6941 start_idx = start >> PAGE_CACHE_SHIFT;
6944 * end is the last byte in the last page. end == start is legal
6946 end_idx = end >> PAGE_CACHE_SHIFT;
6950 /* Most of the code in this while loop is lifted from
6951 * find_get_page. It's been modified to begin searching from a
6952 * page and return just the first page found in that range. If the
6953 * found idx is less than or equal to the end idx then we know that
6954 * a page exists. If no pages are found or if those pages are
6955 * outside of the range then we're fine (yay!) */
6956 while (page == NULL &&
6957 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
6958 page = radix_tree_deref_slot(pagep);
6959 if (unlikely(!page))
6962 if (radix_tree_exception(page)) {
6963 if (radix_tree_deref_retry(page)) {
6968 * Otherwise, shmem/tmpfs must be storing a swap entry
6969 * here as an exceptional entry: so return it without
6970 * attempting to raise page count.
6973 break; /* TODO: Is this relevant for this use case? */
6976 if (!page_cache_get_speculative(page)) {
6982 * Has the page moved?
6983 * This is part of the lockless pagecache protocol. See
6984 * include/linux/pagemap.h for details.
6986 if (unlikely(page != *pagep)) {
6987 page_cache_release(page);
6993 if (page->index <= end_idx)
6995 page_cache_release(page);
7002 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7003 struct extent_state **cached_state, int writing)
7005 struct btrfs_ordered_extent *ordered;
7009 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7012 * We're concerned with the entire range that we're going to be
7013 * doing DIO to, so we need to make sure theres no ordered
7014 * extents in this range.
7016 ordered = btrfs_lookup_ordered_range(inode, lockstart,
7017 lockend - lockstart + 1);
7020 * We need to make sure there are no buffered pages in this
7021 * range either, we could have raced between the invalidate in
7022 * generic_file_direct_write and locking the extent. The
7023 * invalidate needs to happen so that reads after a write do not
7028 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7031 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7032 cached_state, GFP_NOFS);
7035 btrfs_start_ordered_extent(inode, ordered, 1);
7036 btrfs_put_ordered_extent(ordered);
7038 /* Screw you mmap */
7039 ret = filemap_write_and_wait_range(inode->i_mapping,
7046 * If we found a page that couldn't be invalidated just
7047 * fall back to buffered.
7049 ret = invalidate_inode_pages2_range(inode->i_mapping,
7050 lockstart >> PAGE_CACHE_SHIFT,
7051 lockend >> PAGE_CACHE_SHIFT);
7062 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
7063 u64 len, u64 orig_start,
7064 u64 block_start, u64 block_len,
7065 u64 orig_block_len, u64 ram_bytes,
7068 struct extent_map_tree *em_tree;
7069 struct extent_map *em;
7070 struct btrfs_root *root = BTRFS_I(inode)->root;
7073 em_tree = &BTRFS_I(inode)->extent_tree;
7074 em = alloc_extent_map();
7076 return ERR_PTR(-ENOMEM);
7079 em->orig_start = orig_start;
7080 em->mod_start = start;
7083 em->block_len = block_len;
7084 em->block_start = block_start;
7085 em->bdev = root->fs_info->fs_devices->latest_bdev;
7086 em->orig_block_len = orig_block_len;
7087 em->ram_bytes = ram_bytes;
7088 em->generation = -1;
7089 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7090 if (type == BTRFS_ORDERED_PREALLOC)
7091 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7094 btrfs_drop_extent_cache(inode, em->start,
7095 em->start + em->len - 1, 0);
7096 write_lock(&em_tree->lock);
7097 ret = add_extent_mapping(em_tree, em, 1);
7098 write_unlock(&em_tree->lock);
7099 } while (ret == -EEXIST);
7102 free_extent_map(em);
7103 return ERR_PTR(ret);
7110 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7111 struct buffer_head *bh_result, int create)
7113 struct extent_map *em;
7114 struct btrfs_root *root = BTRFS_I(inode)->root;
7115 struct extent_state *cached_state = NULL;
7116 u64 start = iblock << inode->i_blkbits;
7117 u64 lockstart, lockend;
7118 u64 len = bh_result->b_size;
7119 int unlock_bits = EXTENT_LOCKED;
7123 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
7125 len = min_t(u64, len, root->sectorsize);
7128 lockend = start + len - 1;
7131 * If this errors out it's because we couldn't invalidate pagecache for
7132 * this range and we need to fallback to buffered.
7134 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
7137 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7144 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7145 * io. INLINE is special, and we could probably kludge it in here, but
7146 * it's still buffered so for safety lets just fall back to the generic
7149 * For COMPRESSED we _have_ to read the entire extent in so we can
7150 * decompress it, so there will be buffering required no matter what we
7151 * do, so go ahead and fallback to buffered.
7153 * We return -ENOTBLK because thats what makes DIO go ahead and go back
7154 * to buffered IO. Don't blame me, this is the price we pay for using
7157 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7158 em->block_start == EXTENT_MAP_INLINE) {
7159 free_extent_map(em);
7164 /* Just a good old fashioned hole, return */
7165 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7166 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7167 free_extent_map(em);
7172 * We don't allocate a new extent in the following cases
7174 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7176 * 2) The extent is marked as PREALLOC. We're good to go here and can
7177 * just use the extent.
7181 len = min(len, em->len - (start - em->start));
7182 lockstart = start + len;
7186 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7187 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7188 em->block_start != EXTENT_MAP_HOLE)) {
7191 u64 block_start, orig_start, orig_block_len, ram_bytes;
7193 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7194 type = BTRFS_ORDERED_PREALLOC;
7196 type = BTRFS_ORDERED_NOCOW;
7197 len = min(len, em->len - (start - em->start));
7198 block_start = em->block_start + (start - em->start);
7200 if (can_nocow_extent(inode, start, &len, &orig_start,
7201 &orig_block_len, &ram_bytes) == 1) {
7202 if (type == BTRFS_ORDERED_PREALLOC) {
7203 free_extent_map(em);
7204 em = create_pinned_em(inode, start, len,
7215 ret = btrfs_add_ordered_extent_dio(inode, start,
7216 block_start, len, len, type);
7218 free_extent_map(em);
7226 * this will cow the extent, reset the len in case we changed
7229 len = bh_result->b_size;
7230 free_extent_map(em);
7231 em = btrfs_new_extent_direct(inode, start, len);
7236 len = min(len, em->len - (start - em->start));
7238 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7240 bh_result->b_size = len;
7241 bh_result->b_bdev = em->bdev;
7242 set_buffer_mapped(bh_result);
7244 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7245 set_buffer_new(bh_result);
7248 * Need to update the i_size under the extent lock so buffered
7249 * readers will get the updated i_size when we unlock.
7251 if (start + len > i_size_read(inode))
7252 i_size_write(inode, start + len);
7254 spin_lock(&BTRFS_I(inode)->lock);
7255 BTRFS_I(inode)->outstanding_extents++;
7256 spin_unlock(&BTRFS_I(inode)->lock);
7258 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7259 lockstart + len - 1, EXTENT_DELALLOC, NULL,
7260 &cached_state, GFP_NOFS);
7265 * In the case of write we need to clear and unlock the entire range,
7266 * in the case of read we need to unlock only the end area that we
7267 * aren't using if there is any left over space.
7269 if (lockstart < lockend) {
7270 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7271 lockend, unlock_bits, 1, 0,
7272 &cached_state, GFP_NOFS);
7274 free_extent_state(cached_state);
7277 free_extent_map(em);
7282 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7283 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7287 static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7288 int rw, int mirror_num)
7290 struct btrfs_root *root = BTRFS_I(inode)->root;
7293 BUG_ON(rw & REQ_WRITE);
7297 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7298 BTRFS_WQ_ENDIO_DIO_REPAIR);
7302 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
7308 static int btrfs_check_dio_repairable(struct inode *inode,
7309 struct bio *failed_bio,
7310 struct io_failure_record *failrec,
7315 num_copies = btrfs_num_copies(BTRFS_I(inode)->root->fs_info,
7316 failrec->logical, failrec->len);
7317 if (num_copies == 1) {
7319 * we only have a single copy of the data, so don't bother with
7320 * all the retry and error correction code that follows. no
7321 * matter what the error is, it is very likely to persist.
7323 pr_debug("Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d\n",
7324 num_copies, failrec->this_mirror, failed_mirror);
7328 failrec->failed_mirror = failed_mirror;
7329 failrec->this_mirror++;
7330 if (failrec->this_mirror == failed_mirror)
7331 failrec->this_mirror++;
7333 if (failrec->this_mirror > num_copies) {
7334 pr_debug("Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d\n",
7335 num_copies, failrec->this_mirror, failed_mirror);
7342 static int dio_read_error(struct inode *inode, struct bio *failed_bio,
7343 struct page *page, u64 start, u64 end,
7344 int failed_mirror, bio_end_io_t *repair_endio,
7347 struct io_failure_record *failrec;
7353 BUG_ON(failed_bio->bi_rw & REQ_WRITE);
7355 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7359 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7362 free_io_failure(inode, failrec);
7366 if (failed_bio->bi_vcnt > 1)
7367 read_mode = READ_SYNC | REQ_FAILFAST_DEV;
7369 read_mode = READ_SYNC;
7371 isector = start - btrfs_io_bio(failed_bio)->logical;
7372 isector >>= inode->i_sb->s_blocksize_bits;
7373 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7374 0, isector, repair_endio, repair_arg);
7376 free_io_failure(inode, failrec);
7380 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7381 "Repair DIO Read Error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d\n",
7382 read_mode, failrec->this_mirror, failrec->in_validation);
7384 ret = submit_dio_repair_bio(inode, bio, read_mode,
7385 failrec->this_mirror);
7387 free_io_failure(inode, failrec);
7394 struct btrfs_retry_complete {
7395 struct completion done;
7396 struct inode *inode;
7401 static void btrfs_retry_endio_nocsum(struct bio *bio, int err)
7403 struct btrfs_retry_complete *done = bio->bi_private;
7404 struct bio_vec *bvec;
7411 bio_for_each_segment_all(bvec, bio, i)
7412 clean_io_failure(done->inode, done->start, bvec->bv_page, 0);
7414 complete(&done->done);
7418 static int __btrfs_correct_data_nocsum(struct inode *inode,
7419 struct btrfs_io_bio *io_bio)
7421 struct bio_vec *bvec;
7422 struct btrfs_retry_complete done;
7427 start = io_bio->logical;
7430 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7434 init_completion(&done.done);
7436 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7437 start + bvec->bv_len - 1,
7439 btrfs_retry_endio_nocsum, &done);
7443 wait_for_completion(&done.done);
7445 if (!done.uptodate) {
7446 /* We might have another mirror, so try again */
7450 start += bvec->bv_len;
7456 static void btrfs_retry_endio(struct bio *bio, int err)
7458 struct btrfs_retry_complete *done = bio->bi_private;
7459 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7460 struct bio_vec *bvec;
7469 bio_for_each_segment_all(bvec, bio, i) {
7470 ret = __readpage_endio_check(done->inode, io_bio, i,
7472 done->start, bvec->bv_len);
7474 clean_io_failure(done->inode, done->start,
7480 done->uptodate = uptodate;
7482 complete(&done->done);
7486 static int __btrfs_subio_endio_read(struct inode *inode,
7487 struct btrfs_io_bio *io_bio, int err)
7489 struct bio_vec *bvec;
7490 struct btrfs_retry_complete done;
7497 start = io_bio->logical;
7500 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7501 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7502 0, start, bvec->bv_len);
7508 init_completion(&done.done);
7510 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7511 start + bvec->bv_len - 1,
7513 btrfs_retry_endio, &done);
7519 wait_for_completion(&done.done);
7521 if (!done.uptodate) {
7522 /* We might have another mirror, so try again */
7526 offset += bvec->bv_len;
7527 start += bvec->bv_len;
7533 static int btrfs_subio_endio_read(struct inode *inode,
7534 struct btrfs_io_bio *io_bio, int err)
7536 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7540 return __btrfs_correct_data_nocsum(inode, io_bio);
7544 return __btrfs_subio_endio_read(inode, io_bio, err);
7548 static void btrfs_endio_direct_read(struct bio *bio, int err)
7550 struct btrfs_dio_private *dip = bio->bi_private;
7551 struct inode *inode = dip->inode;
7552 struct bio *dio_bio;
7553 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7555 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
7556 err = btrfs_subio_endio_read(inode, io_bio, err);
7558 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
7559 dip->logical_offset + dip->bytes - 1);
7560 dio_bio = dip->dio_bio;
7564 /* If we had a csum failure make sure to clear the uptodate flag */
7566 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7567 dio_end_io(dio_bio, err);
7570 io_bio->end_io(io_bio, err);
7574 static void btrfs_endio_direct_write(struct bio *bio, int err)
7576 struct btrfs_dio_private *dip = bio->bi_private;
7577 struct inode *inode = dip->inode;
7578 struct btrfs_root *root = BTRFS_I(inode)->root;
7579 struct btrfs_ordered_extent *ordered = NULL;
7580 u64 ordered_offset = dip->logical_offset;
7581 u64 ordered_bytes = dip->bytes;
7582 struct bio *dio_bio;
7588 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7590 ordered_bytes, !err);
7594 btrfs_init_work(&ordered->work, btrfs_endio_write_helper,
7595 finish_ordered_fn, NULL, NULL);
7596 btrfs_queue_work(root->fs_info->endio_write_workers,
7600 * our bio might span multiple ordered extents. If we haven't
7601 * completed the accounting for the whole dio, go back and try again
7603 if (ordered_offset < dip->logical_offset + dip->bytes) {
7604 ordered_bytes = dip->logical_offset + dip->bytes -
7610 dio_bio = dip->dio_bio;
7614 /* If we had an error make sure to clear the uptodate flag */
7616 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7617 dio_end_io(dio_bio, err);
7621 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7622 struct bio *bio, int mirror_num,
7623 unsigned long bio_flags, u64 offset)
7626 struct btrfs_root *root = BTRFS_I(inode)->root;
7627 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7628 BUG_ON(ret); /* -ENOMEM */
7632 static void btrfs_end_dio_bio(struct bio *bio, int err)
7634 struct btrfs_dio_private *dip = bio->bi_private;
7637 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7638 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
7639 btrfs_ino(dip->inode), bio->bi_rw,
7640 (unsigned long long)bio->bi_iter.bi_sector,
7641 bio->bi_iter.bi_size, err);
7643 if (dip->subio_endio)
7644 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
7650 * before atomic variable goto zero, we must make sure
7651 * dip->errors is perceived to be set.
7653 smp_mb__before_atomic();
7656 /* if there are more bios still pending for this dio, just exit */
7657 if (!atomic_dec_and_test(&dip->pending_bios))
7661 bio_io_error(dip->orig_bio);
7663 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
7664 bio_endio(dip->orig_bio, 0);
7670 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7671 u64 first_sector, gfp_t gfp_flags)
7673 int nr_vecs = bio_get_nr_vecs(bdev);
7674 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7677 static inline int btrfs_lookup_and_bind_dio_csum(struct btrfs_root *root,
7678 struct inode *inode,
7679 struct btrfs_dio_private *dip,
7683 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7684 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
7688 * We load all the csum data we need when we submit
7689 * the first bio to reduce the csum tree search and
7692 if (dip->logical_offset == file_offset) {
7693 ret = btrfs_lookup_bio_sums_dio(root, inode, dip->orig_bio,
7699 if (bio == dip->orig_bio)
7702 file_offset -= dip->logical_offset;
7703 file_offset >>= inode->i_sb->s_blocksize_bits;
7704 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
7709 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7710 int rw, u64 file_offset, int skip_sum,
7713 struct btrfs_dio_private *dip = bio->bi_private;
7714 int write = rw & REQ_WRITE;
7715 struct btrfs_root *root = BTRFS_I(inode)->root;
7719 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7724 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
7732 if (write && async_submit) {
7733 ret = btrfs_wq_submit_bio(root->fs_info,
7734 inode, rw, bio, 0, 0,
7736 __btrfs_submit_bio_start_direct_io,
7737 __btrfs_submit_bio_done);
7741 * If we aren't doing async submit, calculate the csum of the
7744 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7748 ret = btrfs_lookup_and_bind_dio_csum(root, inode, dip, bio,
7754 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7760 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7763 struct inode *inode = dip->inode;
7764 struct btrfs_root *root = BTRFS_I(inode)->root;
7766 struct bio *orig_bio = dip->orig_bio;
7767 struct bio_vec *bvec = orig_bio->bi_io_vec;
7768 u64 start_sector = orig_bio->bi_iter.bi_sector;
7769 u64 file_offset = dip->logical_offset;
7774 int async_submit = 0;
7776 map_length = orig_bio->bi_iter.bi_size;
7777 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7778 &map_length, NULL, 0);
7782 if (map_length >= orig_bio->bi_iter.bi_size) {
7784 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
7788 /* async crcs make it difficult to collect full stripe writes. */
7789 if (btrfs_get_alloc_profile(root, 1) &
7790 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7795 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7799 bio->bi_private = dip;
7800 bio->bi_end_io = btrfs_end_dio_bio;
7801 btrfs_io_bio(bio)->logical = file_offset;
7802 atomic_inc(&dip->pending_bios);
7804 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7805 if (unlikely(map_length < submit_len + bvec->bv_len ||
7806 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7807 bvec->bv_offset) < bvec->bv_len)) {
7809 * inc the count before we submit the bio so
7810 * we know the end IO handler won't happen before
7811 * we inc the count. Otherwise, the dip might get freed
7812 * before we're done setting it up
7814 atomic_inc(&dip->pending_bios);
7815 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7816 file_offset, skip_sum,
7820 atomic_dec(&dip->pending_bios);
7824 start_sector += submit_len >> 9;
7825 file_offset += submit_len;
7830 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7831 start_sector, GFP_NOFS);
7834 bio->bi_private = dip;
7835 bio->bi_end_io = btrfs_end_dio_bio;
7836 btrfs_io_bio(bio)->logical = file_offset;
7838 map_length = orig_bio->bi_iter.bi_size;
7839 ret = btrfs_map_block(root->fs_info, rw,
7841 &map_length, NULL, 0);
7847 submit_len += bvec->bv_len;
7854 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7863 * before atomic variable goto zero, we must
7864 * make sure dip->errors is perceived to be set.
7866 smp_mb__before_atomic();
7867 if (atomic_dec_and_test(&dip->pending_bios))
7868 bio_io_error(dip->orig_bio);
7870 /* bio_end_io() will handle error, so we needn't return it */
7874 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7875 struct inode *inode, loff_t file_offset)
7877 struct btrfs_root *root = BTRFS_I(inode)->root;
7878 struct btrfs_dio_private *dip;
7880 struct btrfs_io_bio *btrfs_bio;
7882 int write = rw & REQ_WRITE;
7885 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7887 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7893 dip = kzalloc(sizeof(*dip), GFP_NOFS);
7899 dip->private = dio_bio->bi_private;
7901 dip->logical_offset = file_offset;
7902 dip->bytes = dio_bio->bi_iter.bi_size;
7903 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7904 io_bio->bi_private = dip;
7905 dip->orig_bio = io_bio;
7906 dip->dio_bio = dio_bio;
7907 atomic_set(&dip->pending_bios, 0);
7908 btrfs_bio = btrfs_io_bio(io_bio);
7909 btrfs_bio->logical = file_offset;
7912 io_bio->bi_end_io = btrfs_endio_direct_write;
7914 io_bio->bi_end_io = btrfs_endio_direct_read;
7915 dip->subio_endio = btrfs_subio_endio_read;
7918 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7922 if (btrfs_bio->end_io)
7923 btrfs_bio->end_io(btrfs_bio, ret);
7929 * If this is a write, we need to clean up the reserved space and kill
7930 * the ordered extent.
7933 struct btrfs_ordered_extent *ordered;
7934 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7935 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7936 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7937 btrfs_free_reserved_extent(root, ordered->start,
7938 ordered->disk_len, 1);
7939 btrfs_put_ordered_extent(ordered);
7940 btrfs_put_ordered_extent(ordered);
7942 bio_endio(dio_bio, ret);
7945 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7946 const struct iov_iter *iter, loff_t offset)
7950 unsigned blocksize_mask = root->sectorsize - 1;
7951 ssize_t retval = -EINVAL;
7953 if (offset & blocksize_mask)
7956 if (iov_iter_alignment(iter) & blocksize_mask)
7959 /* If this is a write we don't need to check anymore */
7963 * Check to make sure we don't have duplicate iov_base's in this
7964 * iovec, if so return EINVAL, otherwise we'll get csum errors
7965 * when reading back.
7967 for (seg = 0; seg < iter->nr_segs; seg++) {
7968 for (i = seg + 1; i < iter->nr_segs; i++) {
7969 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
7978 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7979 struct iov_iter *iter, loff_t offset)
7981 struct file *file = iocb->ki_filp;
7982 struct inode *inode = file->f_mapping->host;
7986 bool relock = false;
7989 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iter, offset))
7992 atomic_inc(&inode->i_dio_count);
7993 smp_mb__after_atomic();
7996 * The generic stuff only does filemap_write_and_wait_range, which
7997 * isn't enough if we've written compressed pages to this area, so
7998 * we need to flush the dirty pages again to make absolutely sure
7999 * that any outstanding dirty pages are on disk.
8001 count = iov_iter_count(iter);
8002 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8003 &BTRFS_I(inode)->runtime_flags))
8004 filemap_fdatawrite_range(inode->i_mapping, offset,
8005 offset + count - 1);
8009 * If the write DIO is beyond the EOF, we need update
8010 * the isize, but it is protected by i_mutex. So we can
8011 * not unlock the i_mutex at this case.
8013 if (offset + count <= inode->i_size) {
8014 mutex_unlock(&inode->i_mutex);
8017 ret = btrfs_delalloc_reserve_space(inode, count);
8020 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8021 &BTRFS_I(inode)->runtime_flags))) {
8022 inode_dio_done(inode);
8023 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8027 ret = __blockdev_direct_IO(rw, iocb, inode,
8028 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
8029 iter, offset, btrfs_get_blocks_direct, NULL,
8030 btrfs_submit_direct, flags);
8032 if (ret < 0 && ret != -EIOCBQUEUED)
8033 btrfs_delalloc_release_space(inode, count);
8034 else if (ret >= 0 && (size_t)ret < count)
8035 btrfs_delalloc_release_space(inode,
8036 count - (size_t)ret);
8038 btrfs_delalloc_release_metadata(inode, 0);
8042 inode_dio_done(inode);
8044 mutex_lock(&inode->i_mutex);
8049 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8051 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8052 __u64 start, __u64 len)
8056 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8060 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
8063 int btrfs_readpage(struct file *file, struct page *page)
8065 struct extent_io_tree *tree;
8066 tree = &BTRFS_I(page->mapping->host)->io_tree;
8067 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8070 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8072 struct extent_io_tree *tree;
8075 if (current->flags & PF_MEMALLOC) {
8076 redirty_page_for_writepage(wbc, page);
8080 tree = &BTRFS_I(page->mapping->host)->io_tree;
8081 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
8084 static int btrfs_writepages(struct address_space *mapping,
8085 struct writeback_control *wbc)
8087 struct extent_io_tree *tree;
8089 tree = &BTRFS_I(mapping->host)->io_tree;
8090 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8094 btrfs_readpages(struct file *file, struct address_space *mapping,
8095 struct list_head *pages, unsigned nr_pages)
8097 struct extent_io_tree *tree;
8098 tree = &BTRFS_I(mapping->host)->io_tree;
8099 return extent_readpages(tree, mapping, pages, nr_pages,
8102 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8104 struct extent_io_tree *tree;
8105 struct extent_map_tree *map;
8108 tree = &BTRFS_I(page->mapping->host)->io_tree;
8109 map = &BTRFS_I(page->mapping->host)->extent_tree;
8110 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8112 ClearPagePrivate(page);
8113 set_page_private(page, 0);
8114 page_cache_release(page);
8119 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8121 if (PageWriteback(page) || PageDirty(page))
8123 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
8126 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8127 unsigned int length)
8129 struct inode *inode = page->mapping->host;
8130 struct extent_io_tree *tree;
8131 struct btrfs_ordered_extent *ordered;
8132 struct extent_state *cached_state = NULL;
8133 u64 page_start = page_offset(page);
8134 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
8135 int inode_evicting = inode->i_state & I_FREEING;
8138 * we have the page locked, so new writeback can't start,
8139 * and the dirty bit won't be cleared while we are here.
8141 * Wait for IO on this page so that we can safely clear
8142 * the PagePrivate2 bit and do ordered accounting
8144 wait_on_page_writeback(page);
8146 tree = &BTRFS_I(inode)->io_tree;
8148 btrfs_releasepage(page, GFP_NOFS);
8152 if (!inode_evicting)
8153 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
8154 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8157 * IO on this page will never be started, so we need
8158 * to account for any ordered extents now
8160 if (!inode_evicting)
8161 clear_extent_bit(tree, page_start, page_end,
8162 EXTENT_DIRTY | EXTENT_DELALLOC |
8163 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8164 EXTENT_DEFRAG, 1, 0, &cached_state,
8167 * whoever cleared the private bit is responsible
8168 * for the finish_ordered_io
8170 if (TestClearPagePrivate2(page)) {
8171 struct btrfs_ordered_inode_tree *tree;
8174 tree = &BTRFS_I(inode)->ordered_tree;
8176 spin_lock_irq(&tree->lock);
8177 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8178 new_len = page_start - ordered->file_offset;
8179 if (new_len < ordered->truncated_len)
8180 ordered->truncated_len = new_len;
8181 spin_unlock_irq(&tree->lock);
8183 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8185 PAGE_CACHE_SIZE, 1))
8186 btrfs_finish_ordered_io(ordered);
8188 btrfs_put_ordered_extent(ordered);
8189 if (!inode_evicting) {
8190 cached_state = NULL;
8191 lock_extent_bits(tree, page_start, page_end, 0,
8196 if (!inode_evicting) {
8197 clear_extent_bit(tree, page_start, page_end,
8198 EXTENT_LOCKED | EXTENT_DIRTY |
8199 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8200 EXTENT_DEFRAG, 1, 1,
8201 &cached_state, GFP_NOFS);
8203 __btrfs_releasepage(page, GFP_NOFS);
8206 ClearPageChecked(page);
8207 if (PagePrivate(page)) {
8208 ClearPagePrivate(page);
8209 set_page_private(page, 0);
8210 page_cache_release(page);
8215 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8216 * called from a page fault handler when a page is first dirtied. Hence we must
8217 * be careful to check for EOF conditions here. We set the page up correctly
8218 * for a written page which means we get ENOSPC checking when writing into
8219 * holes and correct delalloc and unwritten extent mapping on filesystems that
8220 * support these features.
8222 * We are not allowed to take the i_mutex here so we have to play games to
8223 * protect against truncate races as the page could now be beyond EOF. Because
8224 * vmtruncate() writes the inode size before removing pages, once we have the
8225 * page lock we can determine safely if the page is beyond EOF. If it is not
8226 * beyond EOF, then the page is guaranteed safe against truncation until we
8229 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
8231 struct page *page = vmf->page;
8232 struct inode *inode = file_inode(vma->vm_file);
8233 struct btrfs_root *root = BTRFS_I(inode)->root;
8234 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8235 struct btrfs_ordered_extent *ordered;
8236 struct extent_state *cached_state = NULL;
8238 unsigned long zero_start;
8245 sb_start_pagefault(inode->i_sb);
8246 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
8248 ret = file_update_time(vma->vm_file);
8254 else /* -ENOSPC, -EIO, etc */
8255 ret = VM_FAULT_SIGBUS;
8261 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8264 size = i_size_read(inode);
8265 page_start = page_offset(page);
8266 page_end = page_start + PAGE_CACHE_SIZE - 1;
8268 if ((page->mapping != inode->i_mapping) ||
8269 (page_start >= size)) {
8270 /* page got truncated out from underneath us */
8273 wait_on_page_writeback(page);
8275 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
8276 set_page_extent_mapped(page);
8279 * we can't set the delalloc bits if there are pending ordered
8280 * extents. Drop our locks and wait for them to finish
8282 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8284 unlock_extent_cached(io_tree, page_start, page_end,
8285 &cached_state, GFP_NOFS);
8287 btrfs_start_ordered_extent(inode, ordered, 1);
8288 btrfs_put_ordered_extent(ordered);
8293 * XXX - page_mkwrite gets called every time the page is dirtied, even
8294 * if it was already dirty, so for space accounting reasons we need to
8295 * clear any delalloc bits for the range we are fixing to save. There
8296 * is probably a better way to do this, but for now keep consistent with
8297 * prepare_pages in the normal write path.
8299 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
8300 EXTENT_DIRTY | EXTENT_DELALLOC |
8301 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8302 0, 0, &cached_state, GFP_NOFS);
8304 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
8307 unlock_extent_cached(io_tree, page_start, page_end,
8308 &cached_state, GFP_NOFS);
8309 ret = VM_FAULT_SIGBUS;
8314 /* page is wholly or partially inside EOF */
8315 if (page_start + PAGE_CACHE_SIZE > size)
8316 zero_start = size & ~PAGE_CACHE_MASK;
8318 zero_start = PAGE_CACHE_SIZE;
8320 if (zero_start != PAGE_CACHE_SIZE) {
8322 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
8323 flush_dcache_page(page);
8326 ClearPageChecked(page);
8327 set_page_dirty(page);
8328 SetPageUptodate(page);
8330 BTRFS_I(inode)->last_trans = root->fs_info->generation;
8331 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8332 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8334 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
8338 sb_end_pagefault(inode->i_sb);
8339 return VM_FAULT_LOCKED;
8343 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
8345 sb_end_pagefault(inode->i_sb);
8349 static int btrfs_truncate(struct inode *inode)
8351 struct btrfs_root *root = BTRFS_I(inode)->root;
8352 struct btrfs_block_rsv *rsv;
8355 struct btrfs_trans_handle *trans;
8356 u64 mask = root->sectorsize - 1;
8357 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
8359 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8365 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
8366 * 3 things going on here
8368 * 1) We need to reserve space for our orphan item and the space to
8369 * delete our orphan item. Lord knows we don't want to have a dangling
8370 * orphan item because we didn't reserve space to remove it.
8372 * 2) We need to reserve space to update our inode.
8374 * 3) We need to have something to cache all the space that is going to
8375 * be free'd up by the truncate operation, but also have some slack
8376 * space reserved in case it uses space during the truncate (thank you
8377 * very much snapshotting).
8379 * And we need these to all be seperate. The fact is we can use alot of
8380 * space doing the truncate, and we have no earthly idea how much space
8381 * we will use, so we need the truncate reservation to be seperate so it
8382 * doesn't end up using space reserved for updating the inode or
8383 * removing the orphan item. We also need to be able to stop the
8384 * transaction and start a new one, which means we need to be able to
8385 * update the inode several times, and we have no idea of knowing how
8386 * many times that will be, so we can't just reserve 1 item for the
8387 * entirety of the opration, so that has to be done seperately as well.
8388 * Then there is the orphan item, which does indeed need to be held on
8389 * to for the whole operation, and we need nobody to touch this reserved
8390 * space except the orphan code.
8392 * So that leaves us with
8394 * 1) root->orphan_block_rsv - for the orphan deletion.
8395 * 2) rsv - for the truncate reservation, which we will steal from the
8396 * transaction reservation.
8397 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
8398 * updating the inode.
8400 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
8403 rsv->size = min_size;
8407 * 1 for the truncate slack space
8408 * 1 for updating the inode.
8410 trans = btrfs_start_transaction(root, 2);
8411 if (IS_ERR(trans)) {
8412 err = PTR_ERR(trans);
8416 /* Migrate the slack space for the truncate to our reserve */
8417 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
8422 * So if we truncate and then write and fsync we normally would just
8423 * write the extents that changed, which is a problem if we need to
8424 * first truncate that entire inode. So set this flag so we write out
8425 * all of the extents in the inode to the sync log so we're completely
8428 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8429 trans->block_rsv = rsv;
8432 ret = btrfs_truncate_inode_items(trans, root, inode,
8434 BTRFS_EXTENT_DATA_KEY);
8435 if (ret != -ENOSPC) {
8440 trans->block_rsv = &root->fs_info->trans_block_rsv;
8441 ret = btrfs_update_inode(trans, root, inode);
8447 btrfs_end_transaction(trans, root);
8448 btrfs_btree_balance_dirty(root);
8450 trans = btrfs_start_transaction(root, 2);
8451 if (IS_ERR(trans)) {
8452 ret = err = PTR_ERR(trans);
8457 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
8459 BUG_ON(ret); /* shouldn't happen */
8460 trans->block_rsv = rsv;
8463 if (ret == 0 && inode->i_nlink > 0) {
8464 trans->block_rsv = root->orphan_block_rsv;
8465 ret = btrfs_orphan_del(trans, inode);
8471 trans->block_rsv = &root->fs_info->trans_block_rsv;
8472 ret = btrfs_update_inode(trans, root, inode);
8476 ret = btrfs_end_transaction(trans, root);
8477 btrfs_btree_balance_dirty(root);
8481 btrfs_free_block_rsv(root, rsv);
8490 * create a new subvolume directory/inode (helper for the ioctl).
8492 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8493 struct btrfs_root *new_root,
8494 struct btrfs_root *parent_root,
8497 struct inode *inode;
8501 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8502 new_dirid, new_dirid,
8503 S_IFDIR | (~current_umask() & S_IRWXUGO),
8506 return PTR_ERR(inode);
8507 inode->i_op = &btrfs_dir_inode_operations;
8508 inode->i_fop = &btrfs_dir_file_operations;
8510 set_nlink(inode, 1);
8511 btrfs_i_size_write(inode, 0);
8512 unlock_new_inode(inode);
8514 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8516 btrfs_err(new_root->fs_info,
8517 "error inheriting subvolume %llu properties: %d",
8518 new_root->root_key.objectid, err);
8520 err = btrfs_update_inode(trans, new_root, inode);
8526 struct inode *btrfs_alloc_inode(struct super_block *sb)
8528 struct btrfs_inode *ei;
8529 struct inode *inode;
8531 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
8538 ei->last_sub_trans = 0;
8539 ei->logged_trans = 0;
8540 ei->delalloc_bytes = 0;
8541 ei->defrag_bytes = 0;
8542 ei->disk_i_size = 0;
8545 ei->index_cnt = (u64)-1;
8547 ei->last_unlink_trans = 0;
8548 ei->last_log_commit = 0;
8550 spin_lock_init(&ei->lock);
8551 ei->outstanding_extents = 0;
8552 ei->reserved_extents = 0;
8554 ei->runtime_flags = 0;
8555 ei->force_compress = BTRFS_COMPRESS_NONE;
8557 ei->delayed_node = NULL;
8559 inode = &ei->vfs_inode;
8560 extent_map_tree_init(&ei->extent_tree);
8561 extent_io_tree_init(&ei->io_tree, &inode->i_data);
8562 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
8563 ei->io_tree.track_uptodate = 1;
8564 ei->io_failure_tree.track_uptodate = 1;
8565 atomic_set(&ei->sync_writers, 0);
8566 mutex_init(&ei->log_mutex);
8567 mutex_init(&ei->delalloc_mutex);
8568 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8569 INIT_LIST_HEAD(&ei->delalloc_inodes);
8570 RB_CLEAR_NODE(&ei->rb_node);
8575 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8576 void btrfs_test_destroy_inode(struct inode *inode)
8578 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8579 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8583 static void btrfs_i_callback(struct rcu_head *head)
8585 struct inode *inode = container_of(head, struct inode, i_rcu);
8586 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8589 void btrfs_destroy_inode(struct inode *inode)
8591 struct btrfs_ordered_extent *ordered;
8592 struct btrfs_root *root = BTRFS_I(inode)->root;
8594 WARN_ON(!hlist_empty(&inode->i_dentry));
8595 WARN_ON(inode->i_data.nrpages);
8596 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8597 WARN_ON(BTRFS_I(inode)->reserved_extents);
8598 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8599 WARN_ON(BTRFS_I(inode)->csum_bytes);
8600 WARN_ON(BTRFS_I(inode)->defrag_bytes);
8603 * This can happen where we create an inode, but somebody else also
8604 * created the same inode and we need to destroy the one we already
8610 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8611 &BTRFS_I(inode)->runtime_flags)) {
8612 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
8614 atomic_dec(&root->orphan_inodes);
8618 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8622 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
8623 ordered->file_offset, ordered->len);
8624 btrfs_remove_ordered_extent(inode, ordered);
8625 btrfs_put_ordered_extent(ordered);
8626 btrfs_put_ordered_extent(ordered);
8629 inode_tree_del(inode);
8630 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8632 call_rcu(&inode->i_rcu, btrfs_i_callback);
8635 int btrfs_drop_inode(struct inode *inode)
8637 struct btrfs_root *root = BTRFS_I(inode)->root;
8642 /* the snap/subvol tree is on deleting */
8643 if (btrfs_root_refs(&root->root_item) == 0)
8646 return generic_drop_inode(inode);
8649 static void init_once(void *foo)
8651 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8653 inode_init_once(&ei->vfs_inode);
8656 void btrfs_destroy_cachep(void)
8659 * Make sure all delayed rcu free inodes are flushed before we
8663 if (btrfs_inode_cachep)
8664 kmem_cache_destroy(btrfs_inode_cachep);
8665 if (btrfs_trans_handle_cachep)
8666 kmem_cache_destroy(btrfs_trans_handle_cachep);
8667 if (btrfs_transaction_cachep)
8668 kmem_cache_destroy(btrfs_transaction_cachep);
8669 if (btrfs_path_cachep)
8670 kmem_cache_destroy(btrfs_path_cachep);
8671 if (btrfs_free_space_cachep)
8672 kmem_cache_destroy(btrfs_free_space_cachep);
8673 if (btrfs_delalloc_work_cachep)
8674 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8677 int btrfs_init_cachep(void)
8679 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8680 sizeof(struct btrfs_inode), 0,
8681 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8682 if (!btrfs_inode_cachep)
8685 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8686 sizeof(struct btrfs_trans_handle), 0,
8687 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8688 if (!btrfs_trans_handle_cachep)
8691 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8692 sizeof(struct btrfs_transaction), 0,
8693 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8694 if (!btrfs_transaction_cachep)
8697 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8698 sizeof(struct btrfs_path), 0,
8699 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8700 if (!btrfs_path_cachep)
8703 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8704 sizeof(struct btrfs_free_space), 0,
8705 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8706 if (!btrfs_free_space_cachep)
8709 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8710 sizeof(struct btrfs_delalloc_work), 0,
8711 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8713 if (!btrfs_delalloc_work_cachep)
8718 btrfs_destroy_cachep();
8722 static int btrfs_getattr(struct vfsmount *mnt,
8723 struct dentry *dentry, struct kstat *stat)
8726 struct inode *inode = dentry->d_inode;
8727 u32 blocksize = inode->i_sb->s_blocksize;
8729 generic_fillattr(inode, stat);
8730 stat->dev = BTRFS_I(inode)->root->anon_dev;
8731 stat->blksize = PAGE_CACHE_SIZE;
8733 spin_lock(&BTRFS_I(inode)->lock);
8734 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8735 spin_unlock(&BTRFS_I(inode)->lock);
8736 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8737 ALIGN(delalloc_bytes, blocksize)) >> 9;
8741 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8742 struct inode *new_dir, struct dentry *new_dentry)
8744 struct btrfs_trans_handle *trans;
8745 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8746 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8747 struct inode *new_inode = new_dentry->d_inode;
8748 struct inode *old_inode = old_dentry->d_inode;
8749 struct timespec ctime = CURRENT_TIME;
8753 u64 old_ino = btrfs_ino(old_inode);
8755 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8758 /* we only allow rename subvolume link between subvolumes */
8759 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8762 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8763 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8766 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8767 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8771 /* check for collisions, even if the name isn't there */
8772 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8773 new_dentry->d_name.name,
8774 new_dentry->d_name.len);
8777 if (ret == -EEXIST) {
8779 * eexist without a new_inode */
8780 if (WARN_ON(!new_inode)) {
8784 /* maybe -EOVERFLOW */
8791 * we're using rename to replace one file with another. Start IO on it
8792 * now so we don't add too much work to the end of the transaction
8794 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
8795 filemap_flush(old_inode->i_mapping);
8797 /* close the racy window with snapshot create/destroy ioctl */
8798 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8799 down_read(&root->fs_info->subvol_sem);
8801 * We want to reserve the absolute worst case amount of items. So if
8802 * both inodes are subvols and we need to unlink them then that would
8803 * require 4 item modifications, but if they are both normal inodes it
8804 * would require 5 item modifications, so we'll assume their normal
8805 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8806 * should cover the worst case number of items we'll modify.
8808 trans = btrfs_start_transaction(root, 11);
8809 if (IS_ERR(trans)) {
8810 ret = PTR_ERR(trans);
8815 btrfs_record_root_in_trans(trans, dest);
8817 ret = btrfs_set_inode_index(new_dir, &index);
8821 BTRFS_I(old_inode)->dir_index = 0ULL;
8822 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8823 /* force full log commit if subvolume involved. */
8824 btrfs_set_log_full_commit(root->fs_info, trans);
8826 ret = btrfs_insert_inode_ref(trans, dest,
8827 new_dentry->d_name.name,
8828 new_dentry->d_name.len,
8830 btrfs_ino(new_dir), index);
8834 * this is an ugly little race, but the rename is required
8835 * to make sure that if we crash, the inode is either at the
8836 * old name or the new one. pinning the log transaction lets
8837 * us make sure we don't allow a log commit to come in after
8838 * we unlink the name but before we add the new name back in.
8840 btrfs_pin_log_trans(root);
8843 inode_inc_iversion(old_dir);
8844 inode_inc_iversion(new_dir);
8845 inode_inc_iversion(old_inode);
8846 old_dir->i_ctime = old_dir->i_mtime = ctime;
8847 new_dir->i_ctime = new_dir->i_mtime = ctime;
8848 old_inode->i_ctime = ctime;
8850 if (old_dentry->d_parent != new_dentry->d_parent)
8851 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8853 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8854 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8855 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8856 old_dentry->d_name.name,
8857 old_dentry->d_name.len);
8859 ret = __btrfs_unlink_inode(trans, root, old_dir,
8860 old_dentry->d_inode,
8861 old_dentry->d_name.name,
8862 old_dentry->d_name.len);
8864 ret = btrfs_update_inode(trans, root, old_inode);
8867 btrfs_abort_transaction(trans, root, ret);
8872 inode_inc_iversion(new_inode);
8873 new_inode->i_ctime = CURRENT_TIME;
8874 if (unlikely(btrfs_ino(new_inode) ==
8875 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8876 root_objectid = BTRFS_I(new_inode)->location.objectid;
8877 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8879 new_dentry->d_name.name,
8880 new_dentry->d_name.len);
8881 BUG_ON(new_inode->i_nlink == 0);
8883 ret = btrfs_unlink_inode(trans, dest, new_dir,
8884 new_dentry->d_inode,
8885 new_dentry->d_name.name,
8886 new_dentry->d_name.len);
8888 if (!ret && new_inode->i_nlink == 0)
8889 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8891 btrfs_abort_transaction(trans, root, ret);
8896 ret = btrfs_add_link(trans, new_dir, old_inode,
8897 new_dentry->d_name.name,
8898 new_dentry->d_name.len, 0, index);
8900 btrfs_abort_transaction(trans, root, ret);
8904 if (old_inode->i_nlink == 1)
8905 BTRFS_I(old_inode)->dir_index = index;
8907 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8908 struct dentry *parent = new_dentry->d_parent;
8909 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8910 btrfs_end_log_trans(root);
8913 btrfs_end_transaction(trans, root);
8915 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8916 up_read(&root->fs_info->subvol_sem);
8921 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
8922 struct inode *new_dir, struct dentry *new_dentry,
8925 if (flags & ~RENAME_NOREPLACE)
8928 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry);
8931 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8933 struct btrfs_delalloc_work *delalloc_work;
8934 struct inode *inode;
8936 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8938 inode = delalloc_work->inode;
8939 if (delalloc_work->wait) {
8940 btrfs_wait_ordered_range(inode, 0, (u64)-1);
8942 filemap_flush(inode->i_mapping);
8943 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8944 &BTRFS_I(inode)->runtime_flags))
8945 filemap_flush(inode->i_mapping);
8948 if (delalloc_work->delay_iput)
8949 btrfs_add_delayed_iput(inode);
8952 complete(&delalloc_work->completion);
8955 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8956 int wait, int delay_iput)
8958 struct btrfs_delalloc_work *work;
8960 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8964 init_completion(&work->completion);
8965 INIT_LIST_HEAD(&work->list);
8966 work->inode = inode;
8968 work->delay_iput = delay_iput;
8969 WARN_ON_ONCE(!inode);
8970 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
8971 btrfs_run_delalloc_work, NULL, NULL);
8976 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8978 wait_for_completion(&work->completion);
8979 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8983 * some fairly slow code that needs optimization. This walks the list
8984 * of all the inodes with pending delalloc and forces them to disk.
8986 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
8989 struct btrfs_inode *binode;
8990 struct inode *inode;
8991 struct btrfs_delalloc_work *work, *next;
8992 struct list_head works;
8993 struct list_head splice;
8996 INIT_LIST_HEAD(&works);
8997 INIT_LIST_HEAD(&splice);
8999 mutex_lock(&root->delalloc_mutex);
9000 spin_lock(&root->delalloc_lock);
9001 list_splice_init(&root->delalloc_inodes, &splice);
9002 while (!list_empty(&splice)) {
9003 binode = list_entry(splice.next, struct btrfs_inode,
9006 list_move_tail(&binode->delalloc_inodes,
9007 &root->delalloc_inodes);
9008 inode = igrab(&binode->vfs_inode);
9010 cond_resched_lock(&root->delalloc_lock);
9013 spin_unlock(&root->delalloc_lock);
9015 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
9016 if (unlikely(!work)) {
9018 btrfs_add_delayed_iput(inode);
9024 list_add_tail(&work->list, &works);
9025 btrfs_queue_work(root->fs_info->flush_workers,
9028 if (nr != -1 && ret >= nr)
9031 spin_lock(&root->delalloc_lock);
9033 spin_unlock(&root->delalloc_lock);
9036 list_for_each_entry_safe(work, next, &works, list) {
9037 list_del_init(&work->list);
9038 btrfs_wait_and_free_delalloc_work(work);
9041 if (!list_empty_careful(&splice)) {
9042 spin_lock(&root->delalloc_lock);
9043 list_splice_tail(&splice, &root->delalloc_inodes);
9044 spin_unlock(&root->delalloc_lock);
9046 mutex_unlock(&root->delalloc_mutex);
9050 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
9054 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
9057 ret = __start_delalloc_inodes(root, delay_iput, -1);
9061 * the filemap_flush will queue IO into the worker threads, but
9062 * we have to make sure the IO is actually started and that
9063 * ordered extents get created before we return
9065 atomic_inc(&root->fs_info->async_submit_draining);
9066 while (atomic_read(&root->fs_info->nr_async_submits) ||
9067 atomic_read(&root->fs_info->async_delalloc_pages)) {
9068 wait_event(root->fs_info->async_submit_wait,
9069 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
9070 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
9072 atomic_dec(&root->fs_info->async_submit_draining);
9076 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
9079 struct btrfs_root *root;
9080 struct list_head splice;
9083 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9086 INIT_LIST_HEAD(&splice);
9088 mutex_lock(&fs_info->delalloc_root_mutex);
9089 spin_lock(&fs_info->delalloc_root_lock);
9090 list_splice_init(&fs_info->delalloc_roots, &splice);
9091 while (!list_empty(&splice) && nr) {
9092 root = list_first_entry(&splice, struct btrfs_root,
9094 root = btrfs_grab_fs_root(root);
9096 list_move_tail(&root->delalloc_root,
9097 &fs_info->delalloc_roots);
9098 spin_unlock(&fs_info->delalloc_root_lock);
9100 ret = __start_delalloc_inodes(root, delay_iput, nr);
9101 btrfs_put_fs_root(root);
9109 spin_lock(&fs_info->delalloc_root_lock);
9111 spin_unlock(&fs_info->delalloc_root_lock);
9114 atomic_inc(&fs_info->async_submit_draining);
9115 while (atomic_read(&fs_info->nr_async_submits) ||
9116 atomic_read(&fs_info->async_delalloc_pages)) {
9117 wait_event(fs_info->async_submit_wait,
9118 (atomic_read(&fs_info->nr_async_submits) == 0 &&
9119 atomic_read(&fs_info->async_delalloc_pages) == 0));
9121 atomic_dec(&fs_info->async_submit_draining);
9123 if (!list_empty_careful(&splice)) {
9124 spin_lock(&fs_info->delalloc_root_lock);
9125 list_splice_tail(&splice, &fs_info->delalloc_roots);
9126 spin_unlock(&fs_info->delalloc_root_lock);
9128 mutex_unlock(&fs_info->delalloc_root_mutex);
9132 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9133 const char *symname)
9135 struct btrfs_trans_handle *trans;
9136 struct btrfs_root *root = BTRFS_I(dir)->root;
9137 struct btrfs_path *path;
9138 struct btrfs_key key;
9139 struct inode *inode = NULL;
9147 struct btrfs_file_extent_item *ei;
9148 struct extent_buffer *leaf;
9150 name_len = strlen(symname);
9151 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
9152 return -ENAMETOOLONG;
9155 * 2 items for inode item and ref
9156 * 2 items for dir items
9157 * 1 item for xattr if selinux is on
9159 trans = btrfs_start_transaction(root, 5);
9161 return PTR_ERR(trans);
9163 err = btrfs_find_free_ino(root, &objectid);
9167 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9168 dentry->d_name.len, btrfs_ino(dir), objectid,
9169 S_IFLNK|S_IRWXUGO, &index);
9170 if (IS_ERR(inode)) {
9171 err = PTR_ERR(inode);
9176 * If the active LSM wants to access the inode during
9177 * d_instantiate it needs these. Smack checks to see
9178 * if the filesystem supports xattrs by looking at the
9181 inode->i_fop = &btrfs_file_operations;
9182 inode->i_op = &btrfs_file_inode_operations;
9183 inode->i_mapping->a_ops = &btrfs_aops;
9184 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9185 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9187 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9189 goto out_unlock_inode;
9191 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
9193 goto out_unlock_inode;
9195 path = btrfs_alloc_path();
9198 goto out_unlock_inode;
9200 key.objectid = btrfs_ino(inode);
9202 key.type = BTRFS_EXTENT_DATA_KEY;
9203 datasize = btrfs_file_extent_calc_inline_size(name_len);
9204 err = btrfs_insert_empty_item(trans, root, path, &key,
9207 btrfs_free_path(path);
9208 goto out_unlock_inode;
9210 leaf = path->nodes[0];
9211 ei = btrfs_item_ptr(leaf, path->slots[0],
9212 struct btrfs_file_extent_item);
9213 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9214 btrfs_set_file_extent_type(leaf, ei,
9215 BTRFS_FILE_EXTENT_INLINE);
9216 btrfs_set_file_extent_encryption(leaf, ei, 0);
9217 btrfs_set_file_extent_compression(leaf, ei, 0);
9218 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9219 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9221 ptr = btrfs_file_extent_inline_start(ei);
9222 write_extent_buffer(leaf, symname, ptr, name_len);
9223 btrfs_mark_buffer_dirty(leaf);
9224 btrfs_free_path(path);
9226 inode->i_op = &btrfs_symlink_inode_operations;
9227 inode->i_mapping->a_ops = &btrfs_symlink_aops;
9228 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9229 inode_set_bytes(inode, name_len);
9230 btrfs_i_size_write(inode, name_len);
9231 err = btrfs_update_inode(trans, root, inode);
9234 goto out_unlock_inode;
9237 unlock_new_inode(inode);
9238 d_instantiate(dentry, inode);
9241 btrfs_end_transaction(trans, root);
9243 inode_dec_link_count(inode);
9246 btrfs_btree_balance_dirty(root);
9251 unlock_new_inode(inode);
9255 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9256 u64 start, u64 num_bytes, u64 min_size,
9257 loff_t actual_len, u64 *alloc_hint,
9258 struct btrfs_trans_handle *trans)
9260 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9261 struct extent_map *em;
9262 struct btrfs_root *root = BTRFS_I(inode)->root;
9263 struct btrfs_key ins;
9264 u64 cur_offset = start;
9268 bool own_trans = true;
9272 while (num_bytes > 0) {
9274 trans = btrfs_start_transaction(root, 3);
9275 if (IS_ERR(trans)) {
9276 ret = PTR_ERR(trans);
9281 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
9282 cur_bytes = max(cur_bytes, min_size);
9283 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
9284 *alloc_hint, &ins, 1, 0);
9287 btrfs_end_transaction(trans, root);
9291 ret = insert_reserved_file_extent(trans, inode,
9292 cur_offset, ins.objectid,
9293 ins.offset, ins.offset,
9294 ins.offset, 0, 0, 0,
9295 BTRFS_FILE_EXTENT_PREALLOC);
9297 btrfs_free_reserved_extent(root, ins.objectid,
9299 btrfs_abort_transaction(trans, root, ret);
9301 btrfs_end_transaction(trans, root);
9304 btrfs_drop_extent_cache(inode, cur_offset,
9305 cur_offset + ins.offset -1, 0);
9307 em = alloc_extent_map();
9309 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9310 &BTRFS_I(inode)->runtime_flags);
9314 em->start = cur_offset;
9315 em->orig_start = cur_offset;
9316 em->len = ins.offset;
9317 em->block_start = ins.objectid;
9318 em->block_len = ins.offset;
9319 em->orig_block_len = ins.offset;
9320 em->ram_bytes = ins.offset;
9321 em->bdev = root->fs_info->fs_devices->latest_bdev;
9322 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9323 em->generation = trans->transid;
9326 write_lock(&em_tree->lock);
9327 ret = add_extent_mapping(em_tree, em, 1);
9328 write_unlock(&em_tree->lock);
9331 btrfs_drop_extent_cache(inode, cur_offset,
9332 cur_offset + ins.offset - 1,
9335 free_extent_map(em);
9337 num_bytes -= ins.offset;
9338 cur_offset += ins.offset;
9339 *alloc_hint = ins.objectid + ins.offset;
9341 inode_inc_iversion(inode);
9342 inode->i_ctime = CURRENT_TIME;
9343 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9344 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9345 (actual_len > inode->i_size) &&
9346 (cur_offset > inode->i_size)) {
9347 if (cur_offset > actual_len)
9348 i_size = actual_len;
9350 i_size = cur_offset;
9351 i_size_write(inode, i_size);
9352 btrfs_ordered_update_i_size(inode, i_size, NULL);
9355 ret = btrfs_update_inode(trans, root, inode);
9358 btrfs_abort_transaction(trans, root, ret);
9360 btrfs_end_transaction(trans, root);
9365 btrfs_end_transaction(trans, root);
9370 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9371 u64 start, u64 num_bytes, u64 min_size,
9372 loff_t actual_len, u64 *alloc_hint)
9374 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9375 min_size, actual_len, alloc_hint,
9379 int btrfs_prealloc_file_range_trans(struct inode *inode,
9380 struct btrfs_trans_handle *trans, int mode,
9381 u64 start, u64 num_bytes, u64 min_size,
9382 loff_t actual_len, u64 *alloc_hint)
9384 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9385 min_size, actual_len, alloc_hint, trans);
9388 static int btrfs_set_page_dirty(struct page *page)
9390 return __set_page_dirty_nobuffers(page);
9393 static int btrfs_permission(struct inode *inode, int mask)
9395 struct btrfs_root *root = BTRFS_I(inode)->root;
9396 umode_t mode = inode->i_mode;
9398 if (mask & MAY_WRITE &&
9399 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9400 if (btrfs_root_readonly(root))
9402 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9405 return generic_permission(inode, mask);
9408 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9410 struct btrfs_trans_handle *trans;
9411 struct btrfs_root *root = BTRFS_I(dir)->root;
9412 struct inode *inode = NULL;
9418 * 5 units required for adding orphan entry
9420 trans = btrfs_start_transaction(root, 5);
9422 return PTR_ERR(trans);
9424 ret = btrfs_find_free_ino(root, &objectid);
9428 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9429 btrfs_ino(dir), objectid, mode, &index);
9430 if (IS_ERR(inode)) {
9431 ret = PTR_ERR(inode);
9436 inode->i_fop = &btrfs_file_operations;
9437 inode->i_op = &btrfs_file_inode_operations;
9439 inode->i_mapping->a_ops = &btrfs_aops;
9440 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9441 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9443 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9447 ret = btrfs_update_inode(trans, root, inode);
9450 ret = btrfs_orphan_add(trans, inode);
9455 * We set number of links to 0 in btrfs_new_inode(), and here we set
9456 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9459 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9461 set_nlink(inode, 1);
9462 unlock_new_inode(inode);
9463 d_tmpfile(dentry, inode);
9464 mark_inode_dirty(inode);
9467 btrfs_end_transaction(trans, root);
9470 btrfs_balance_delayed_items(root);
9471 btrfs_btree_balance_dirty(root);
9475 unlock_new_inode(inode);
9480 static const struct inode_operations btrfs_dir_inode_operations = {
9481 .getattr = btrfs_getattr,
9482 .lookup = btrfs_lookup,
9483 .create = btrfs_create,
9484 .unlink = btrfs_unlink,
9486 .mkdir = btrfs_mkdir,
9487 .rmdir = btrfs_rmdir,
9488 .rename2 = btrfs_rename2,
9489 .symlink = btrfs_symlink,
9490 .setattr = btrfs_setattr,
9491 .mknod = btrfs_mknod,
9492 .setxattr = btrfs_setxattr,
9493 .getxattr = btrfs_getxattr,
9494 .listxattr = btrfs_listxattr,
9495 .removexattr = btrfs_removexattr,
9496 .permission = btrfs_permission,
9497 .get_acl = btrfs_get_acl,
9498 .set_acl = btrfs_set_acl,
9499 .update_time = btrfs_update_time,
9500 .tmpfile = btrfs_tmpfile,
9502 static const struct inode_operations btrfs_dir_ro_inode_operations = {
9503 .lookup = btrfs_lookup,
9504 .permission = btrfs_permission,
9505 .get_acl = btrfs_get_acl,
9506 .set_acl = btrfs_set_acl,
9507 .update_time = btrfs_update_time,
9510 static const struct file_operations btrfs_dir_file_operations = {
9511 .llseek = generic_file_llseek,
9512 .read = generic_read_dir,
9513 .iterate = btrfs_real_readdir,
9514 .unlocked_ioctl = btrfs_ioctl,
9515 #ifdef CONFIG_COMPAT
9516 .compat_ioctl = btrfs_ioctl,
9518 .release = btrfs_release_file,
9519 .fsync = btrfs_sync_file,
9522 static struct extent_io_ops btrfs_extent_io_ops = {
9523 .fill_delalloc = run_delalloc_range,
9524 .submit_bio_hook = btrfs_submit_bio_hook,
9525 .merge_bio_hook = btrfs_merge_bio_hook,
9526 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
9527 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
9528 .writepage_start_hook = btrfs_writepage_start_hook,
9529 .set_bit_hook = btrfs_set_bit_hook,
9530 .clear_bit_hook = btrfs_clear_bit_hook,
9531 .merge_extent_hook = btrfs_merge_extent_hook,
9532 .split_extent_hook = btrfs_split_extent_hook,
9536 * btrfs doesn't support the bmap operation because swapfiles
9537 * use bmap to make a mapping of extents in the file. They assume
9538 * these extents won't change over the life of the file and they
9539 * use the bmap result to do IO directly to the drive.
9541 * the btrfs bmap call would return logical addresses that aren't
9542 * suitable for IO and they also will change frequently as COW
9543 * operations happen. So, swapfile + btrfs == corruption.
9545 * For now we're avoiding this by dropping bmap.
9547 static const struct address_space_operations btrfs_aops = {
9548 .readpage = btrfs_readpage,
9549 .writepage = btrfs_writepage,
9550 .writepages = btrfs_writepages,
9551 .readpages = btrfs_readpages,
9552 .direct_IO = btrfs_direct_IO,
9553 .invalidatepage = btrfs_invalidatepage,
9554 .releasepage = btrfs_releasepage,
9555 .set_page_dirty = btrfs_set_page_dirty,
9556 .error_remove_page = generic_error_remove_page,
9559 static const struct address_space_operations btrfs_symlink_aops = {
9560 .readpage = btrfs_readpage,
9561 .writepage = btrfs_writepage,
9562 .invalidatepage = btrfs_invalidatepage,
9563 .releasepage = btrfs_releasepage,
9566 static const struct inode_operations btrfs_file_inode_operations = {
9567 .getattr = btrfs_getattr,
9568 .setattr = btrfs_setattr,
9569 .setxattr = btrfs_setxattr,
9570 .getxattr = btrfs_getxattr,
9571 .listxattr = btrfs_listxattr,
9572 .removexattr = btrfs_removexattr,
9573 .permission = btrfs_permission,
9574 .fiemap = btrfs_fiemap,
9575 .get_acl = btrfs_get_acl,
9576 .set_acl = btrfs_set_acl,
9577 .update_time = btrfs_update_time,
9579 static const struct inode_operations btrfs_special_inode_operations = {
9580 .getattr = btrfs_getattr,
9581 .setattr = btrfs_setattr,
9582 .permission = btrfs_permission,
9583 .setxattr = btrfs_setxattr,
9584 .getxattr = btrfs_getxattr,
9585 .listxattr = btrfs_listxattr,
9586 .removexattr = btrfs_removexattr,
9587 .get_acl = btrfs_get_acl,
9588 .set_acl = btrfs_set_acl,
9589 .update_time = btrfs_update_time,
9591 static const struct inode_operations btrfs_symlink_inode_operations = {
9592 .readlink = generic_readlink,
9593 .follow_link = page_follow_link_light,
9594 .put_link = page_put_link,
9595 .getattr = btrfs_getattr,
9596 .setattr = btrfs_setattr,
9597 .permission = btrfs_permission,
9598 .setxattr = btrfs_setxattr,
9599 .getxattr = btrfs_getxattr,
9600 .listxattr = btrfs_listxattr,
9601 .removexattr = btrfs_removexattr,
9602 .update_time = btrfs_update_time,
9605 const struct dentry_operations btrfs_dentry_operations = {
9606 .d_delete = btrfs_dentry_delete,
9607 .d_release = btrfs_dentry_release,