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 |
841 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
844 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
845 struct extent_map *em;
848 read_lock(&em_tree->lock);
849 em = search_extent_mapping(em_tree, start, num_bytes);
852 * if block start isn't an actual block number then find the
853 * first block in this inode and use that as a hint. If that
854 * block is also bogus then just don't worry about it.
856 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
858 em = search_extent_mapping(em_tree, 0, 0);
859 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
860 alloc_hint = em->block_start;
864 alloc_hint = em->block_start;
868 read_unlock(&em_tree->lock);
874 * when extent_io.c finds a delayed allocation range in the file,
875 * the call backs end up in this code. The basic idea is to
876 * allocate extents on disk for the range, and create ordered data structs
877 * in ram to track those extents.
879 * locked_page is the page that writepage had locked already. We use
880 * it to make sure we don't do extra locks or unlocks.
882 * *page_started is set to one if we unlock locked_page and do everything
883 * required to start IO on it. It may be clean and already done with
886 static noinline int cow_file_range(struct inode *inode,
887 struct page *locked_page,
888 u64 start, u64 end, int *page_started,
889 unsigned long *nr_written,
892 struct btrfs_root *root = BTRFS_I(inode)->root;
895 unsigned long ram_size;
898 u64 blocksize = root->sectorsize;
899 struct btrfs_key ins;
900 struct extent_map *em;
901 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
904 if (btrfs_is_free_space_inode(inode)) {
910 num_bytes = ALIGN(end - start + 1, blocksize);
911 num_bytes = max(blocksize, num_bytes);
912 disk_num_bytes = num_bytes;
914 /* if this is a small write inside eof, kick off defrag */
915 if (num_bytes < 64 * 1024 &&
916 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
917 btrfs_add_inode_defrag(NULL, inode);
920 /* lets try to make an inline extent */
921 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
924 extent_clear_unlock_delalloc(inode, start, end, NULL,
925 EXTENT_LOCKED | EXTENT_DELALLOC |
926 EXTENT_DEFRAG, PAGE_UNLOCK |
927 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
930 *nr_written = *nr_written +
931 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
934 } else if (ret < 0) {
939 BUG_ON(disk_num_bytes >
940 btrfs_super_total_bytes(root->fs_info->super_copy));
942 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
943 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
945 while (disk_num_bytes > 0) {
948 cur_alloc_size = disk_num_bytes;
949 ret = btrfs_reserve_extent(root, cur_alloc_size,
950 root->sectorsize, 0, alloc_hint,
955 em = alloc_extent_map();
961 em->orig_start = em->start;
962 ram_size = ins.offset;
963 em->len = ins.offset;
964 em->mod_start = em->start;
965 em->mod_len = em->len;
967 em->block_start = ins.objectid;
968 em->block_len = ins.offset;
969 em->orig_block_len = ins.offset;
970 em->ram_bytes = ram_size;
971 em->bdev = root->fs_info->fs_devices->latest_bdev;
972 set_bit(EXTENT_FLAG_PINNED, &em->flags);
976 write_lock(&em_tree->lock);
977 ret = add_extent_mapping(em_tree, em, 1);
978 write_unlock(&em_tree->lock);
979 if (ret != -EEXIST) {
983 btrfs_drop_extent_cache(inode, start,
984 start + ram_size - 1, 0);
989 cur_alloc_size = ins.offset;
990 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
991 ram_size, cur_alloc_size, 0);
993 goto out_drop_extent_cache;
995 if (root->root_key.objectid ==
996 BTRFS_DATA_RELOC_TREE_OBJECTID) {
997 ret = btrfs_reloc_clone_csums(inode, start,
1000 goto out_drop_extent_cache;
1003 if (disk_num_bytes < cur_alloc_size)
1006 /* we're not doing compressed IO, don't unlock the first
1007 * page (which the caller expects to stay locked), don't
1008 * clear any dirty bits and don't set any writeback bits
1010 * Do set the Private2 bit so we know this page was properly
1011 * setup for writepage
1013 op = unlock ? PAGE_UNLOCK : 0;
1014 op |= PAGE_SET_PRIVATE2;
1016 extent_clear_unlock_delalloc(inode, start,
1017 start + ram_size - 1, locked_page,
1018 EXTENT_LOCKED | EXTENT_DELALLOC,
1020 disk_num_bytes -= cur_alloc_size;
1021 num_bytes -= cur_alloc_size;
1022 alloc_hint = ins.objectid + ins.offset;
1023 start += cur_alloc_size;
1028 out_drop_extent_cache:
1029 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1031 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1033 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1034 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1035 EXTENT_DELALLOC | EXTENT_DEFRAG,
1036 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1037 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1042 * work queue call back to started compression on a file and pages
1044 static noinline void async_cow_start(struct btrfs_work *work)
1046 struct async_cow *async_cow;
1048 async_cow = container_of(work, struct async_cow, work);
1050 compress_file_range(async_cow->inode, async_cow->locked_page,
1051 async_cow->start, async_cow->end, async_cow,
1053 if (num_added == 0) {
1054 btrfs_add_delayed_iput(async_cow->inode);
1055 async_cow->inode = NULL;
1060 * work queue call back to submit previously compressed pages
1062 static noinline void async_cow_submit(struct btrfs_work *work)
1064 struct async_cow *async_cow;
1065 struct btrfs_root *root;
1066 unsigned long nr_pages;
1068 async_cow = container_of(work, struct async_cow, work);
1070 root = async_cow->root;
1071 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1074 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1076 waitqueue_active(&root->fs_info->async_submit_wait))
1077 wake_up(&root->fs_info->async_submit_wait);
1079 if (async_cow->inode)
1080 submit_compressed_extents(async_cow->inode, async_cow);
1083 static noinline void async_cow_free(struct btrfs_work *work)
1085 struct async_cow *async_cow;
1086 async_cow = container_of(work, struct async_cow, work);
1087 if (async_cow->inode)
1088 btrfs_add_delayed_iput(async_cow->inode);
1092 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1093 u64 start, u64 end, int *page_started,
1094 unsigned long *nr_written)
1096 struct async_cow *async_cow;
1097 struct btrfs_root *root = BTRFS_I(inode)->root;
1098 unsigned long nr_pages;
1100 int limit = 10 * 1024 * 1024;
1102 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1103 1, 0, NULL, GFP_NOFS);
1104 while (start < end) {
1105 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1106 BUG_ON(!async_cow); /* -ENOMEM */
1107 async_cow->inode = igrab(inode);
1108 async_cow->root = root;
1109 async_cow->locked_page = locked_page;
1110 async_cow->start = start;
1112 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1113 !btrfs_test_opt(root, FORCE_COMPRESS))
1116 cur_end = min(end, start + 512 * 1024 - 1);
1118 async_cow->end = cur_end;
1119 INIT_LIST_HEAD(&async_cow->extents);
1121 btrfs_init_work(&async_cow->work,
1122 btrfs_delalloc_helper,
1123 async_cow_start, async_cow_submit,
1126 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1128 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1130 btrfs_queue_work(root->fs_info->delalloc_workers,
1133 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1134 wait_event(root->fs_info->async_submit_wait,
1135 (atomic_read(&root->fs_info->async_delalloc_pages) <
1139 while (atomic_read(&root->fs_info->async_submit_draining) &&
1140 atomic_read(&root->fs_info->async_delalloc_pages)) {
1141 wait_event(root->fs_info->async_submit_wait,
1142 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1146 *nr_written += nr_pages;
1147 start = cur_end + 1;
1153 static noinline int csum_exist_in_range(struct btrfs_root *root,
1154 u64 bytenr, u64 num_bytes)
1157 struct btrfs_ordered_sum *sums;
1160 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1161 bytenr + num_bytes - 1, &list, 0);
1162 if (ret == 0 && list_empty(&list))
1165 while (!list_empty(&list)) {
1166 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1167 list_del(&sums->list);
1174 * when nowcow writeback call back. This checks for snapshots or COW copies
1175 * of the extents that exist in the file, and COWs the file as required.
1177 * If no cow copies or snapshots exist, we write directly to the existing
1180 static noinline int run_delalloc_nocow(struct inode *inode,
1181 struct page *locked_page,
1182 u64 start, u64 end, int *page_started, int force,
1183 unsigned long *nr_written)
1185 struct btrfs_root *root = BTRFS_I(inode)->root;
1186 struct btrfs_trans_handle *trans;
1187 struct extent_buffer *leaf;
1188 struct btrfs_path *path;
1189 struct btrfs_file_extent_item *fi;
1190 struct btrfs_key found_key;
1205 u64 ino = btrfs_ino(inode);
1207 path = btrfs_alloc_path();
1209 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1210 EXTENT_LOCKED | EXTENT_DELALLOC |
1211 EXTENT_DO_ACCOUNTING |
1212 EXTENT_DEFRAG, PAGE_UNLOCK |
1214 PAGE_SET_WRITEBACK |
1215 PAGE_END_WRITEBACK);
1219 nolock = btrfs_is_free_space_inode(inode);
1222 trans = btrfs_join_transaction_nolock(root);
1224 trans = btrfs_join_transaction(root);
1226 if (IS_ERR(trans)) {
1227 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1228 EXTENT_LOCKED | EXTENT_DELALLOC |
1229 EXTENT_DO_ACCOUNTING |
1230 EXTENT_DEFRAG, PAGE_UNLOCK |
1232 PAGE_SET_WRITEBACK |
1233 PAGE_END_WRITEBACK);
1234 btrfs_free_path(path);
1235 return PTR_ERR(trans);
1238 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1240 cow_start = (u64)-1;
1243 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1247 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1248 leaf = path->nodes[0];
1249 btrfs_item_key_to_cpu(leaf, &found_key,
1250 path->slots[0] - 1);
1251 if (found_key.objectid == ino &&
1252 found_key.type == BTRFS_EXTENT_DATA_KEY)
1257 leaf = path->nodes[0];
1258 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1259 ret = btrfs_next_leaf(root, path);
1264 leaf = path->nodes[0];
1270 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1272 if (found_key.objectid > ino ||
1273 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1274 found_key.offset > end)
1277 if (found_key.offset > cur_offset) {
1278 extent_end = found_key.offset;
1283 fi = btrfs_item_ptr(leaf, path->slots[0],
1284 struct btrfs_file_extent_item);
1285 extent_type = btrfs_file_extent_type(leaf, fi);
1287 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1288 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1289 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1290 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1291 extent_offset = btrfs_file_extent_offset(leaf, fi);
1292 extent_end = found_key.offset +
1293 btrfs_file_extent_num_bytes(leaf, fi);
1295 btrfs_file_extent_disk_num_bytes(leaf, fi);
1296 if (extent_end <= start) {
1300 if (disk_bytenr == 0)
1302 if (btrfs_file_extent_compression(leaf, fi) ||
1303 btrfs_file_extent_encryption(leaf, fi) ||
1304 btrfs_file_extent_other_encoding(leaf, fi))
1306 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1308 if (btrfs_extent_readonly(root, disk_bytenr))
1310 if (btrfs_cross_ref_exist(trans, root, ino,
1312 extent_offset, disk_bytenr))
1314 disk_bytenr += extent_offset;
1315 disk_bytenr += cur_offset - found_key.offset;
1316 num_bytes = min(end + 1, extent_end) - cur_offset;
1318 * if there are pending snapshots for this root,
1319 * we fall into common COW way.
1322 err = btrfs_start_nocow_write(root);
1327 * force cow if csum exists in the range.
1328 * this ensure that csum for a given extent are
1329 * either valid or do not exist.
1331 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1334 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1335 extent_end = found_key.offset +
1336 btrfs_file_extent_inline_len(leaf,
1337 path->slots[0], fi);
1338 extent_end = ALIGN(extent_end, root->sectorsize);
1343 if (extent_end <= start) {
1345 if (!nolock && nocow)
1346 btrfs_end_nocow_write(root);
1350 if (cow_start == (u64)-1)
1351 cow_start = cur_offset;
1352 cur_offset = extent_end;
1353 if (cur_offset > end)
1359 btrfs_release_path(path);
1360 if (cow_start != (u64)-1) {
1361 ret = cow_file_range(inode, locked_page,
1362 cow_start, found_key.offset - 1,
1363 page_started, nr_written, 1);
1365 if (!nolock && nocow)
1366 btrfs_end_nocow_write(root);
1369 cow_start = (u64)-1;
1372 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1373 struct extent_map *em;
1374 struct extent_map_tree *em_tree;
1375 em_tree = &BTRFS_I(inode)->extent_tree;
1376 em = alloc_extent_map();
1377 BUG_ON(!em); /* -ENOMEM */
1378 em->start = cur_offset;
1379 em->orig_start = found_key.offset - extent_offset;
1380 em->len = num_bytes;
1381 em->block_len = num_bytes;
1382 em->block_start = disk_bytenr;
1383 em->orig_block_len = disk_num_bytes;
1384 em->ram_bytes = ram_bytes;
1385 em->bdev = root->fs_info->fs_devices->latest_bdev;
1386 em->mod_start = em->start;
1387 em->mod_len = em->len;
1388 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1389 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1390 em->generation = -1;
1392 write_lock(&em_tree->lock);
1393 ret = add_extent_mapping(em_tree, em, 1);
1394 write_unlock(&em_tree->lock);
1395 if (ret != -EEXIST) {
1396 free_extent_map(em);
1399 btrfs_drop_extent_cache(inode, em->start,
1400 em->start + em->len - 1, 0);
1402 type = BTRFS_ORDERED_PREALLOC;
1404 type = BTRFS_ORDERED_NOCOW;
1407 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1408 num_bytes, num_bytes, type);
1409 BUG_ON(ret); /* -ENOMEM */
1411 if (root->root_key.objectid ==
1412 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1413 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1416 if (!nolock && nocow)
1417 btrfs_end_nocow_write(root);
1422 extent_clear_unlock_delalloc(inode, cur_offset,
1423 cur_offset + num_bytes - 1,
1424 locked_page, EXTENT_LOCKED |
1425 EXTENT_DELALLOC, PAGE_UNLOCK |
1427 if (!nolock && nocow)
1428 btrfs_end_nocow_write(root);
1429 cur_offset = extent_end;
1430 if (cur_offset > end)
1433 btrfs_release_path(path);
1435 if (cur_offset <= end && cow_start == (u64)-1) {
1436 cow_start = cur_offset;
1440 if (cow_start != (u64)-1) {
1441 ret = cow_file_range(inode, locked_page, cow_start, end,
1442 page_started, nr_written, 1);
1448 err = btrfs_end_transaction(trans, root);
1452 if (ret && cur_offset < end)
1453 extent_clear_unlock_delalloc(inode, cur_offset, end,
1454 locked_page, EXTENT_LOCKED |
1455 EXTENT_DELALLOC | EXTENT_DEFRAG |
1456 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1458 PAGE_SET_WRITEBACK |
1459 PAGE_END_WRITEBACK);
1460 btrfs_free_path(path);
1464 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1467 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1468 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1472 * @defrag_bytes is a hint value, no spinlock held here,
1473 * if is not zero, it means the file is defragging.
1474 * Force cow if given extent needs to be defragged.
1476 if (BTRFS_I(inode)->defrag_bytes &&
1477 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1478 EXTENT_DEFRAG, 0, NULL))
1485 * extent_io.c call back to do delayed allocation processing
1487 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1488 u64 start, u64 end, int *page_started,
1489 unsigned long *nr_written)
1492 int force_cow = need_force_cow(inode, start, end);
1494 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1495 ret = run_delalloc_nocow(inode, locked_page, start, end,
1496 page_started, 1, nr_written);
1497 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1498 ret = run_delalloc_nocow(inode, locked_page, start, end,
1499 page_started, 0, nr_written);
1500 } else if (!inode_need_compress(inode)) {
1501 ret = cow_file_range(inode, locked_page, start, end,
1502 page_started, nr_written, 1);
1504 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1505 &BTRFS_I(inode)->runtime_flags);
1506 ret = cow_file_range_async(inode, locked_page, start, end,
1507 page_started, nr_written);
1512 static void btrfs_split_extent_hook(struct inode *inode,
1513 struct extent_state *orig, u64 split)
1515 /* not delalloc, ignore it */
1516 if (!(orig->state & EXTENT_DELALLOC))
1519 spin_lock(&BTRFS_I(inode)->lock);
1520 BTRFS_I(inode)->outstanding_extents++;
1521 spin_unlock(&BTRFS_I(inode)->lock);
1525 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1526 * extents so we can keep track of new extents that are just merged onto old
1527 * extents, such as when we are doing sequential writes, so we can properly
1528 * account for the metadata space we'll need.
1530 static void btrfs_merge_extent_hook(struct inode *inode,
1531 struct extent_state *new,
1532 struct extent_state *other)
1534 /* not delalloc, ignore it */
1535 if (!(other->state & EXTENT_DELALLOC))
1538 spin_lock(&BTRFS_I(inode)->lock);
1539 BTRFS_I(inode)->outstanding_extents--;
1540 spin_unlock(&BTRFS_I(inode)->lock);
1543 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1544 struct inode *inode)
1546 spin_lock(&root->delalloc_lock);
1547 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1548 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1549 &root->delalloc_inodes);
1550 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1551 &BTRFS_I(inode)->runtime_flags);
1552 root->nr_delalloc_inodes++;
1553 if (root->nr_delalloc_inodes == 1) {
1554 spin_lock(&root->fs_info->delalloc_root_lock);
1555 BUG_ON(!list_empty(&root->delalloc_root));
1556 list_add_tail(&root->delalloc_root,
1557 &root->fs_info->delalloc_roots);
1558 spin_unlock(&root->fs_info->delalloc_root_lock);
1561 spin_unlock(&root->delalloc_lock);
1564 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1565 struct inode *inode)
1567 spin_lock(&root->delalloc_lock);
1568 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1569 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1570 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1571 &BTRFS_I(inode)->runtime_flags);
1572 root->nr_delalloc_inodes--;
1573 if (!root->nr_delalloc_inodes) {
1574 spin_lock(&root->fs_info->delalloc_root_lock);
1575 BUG_ON(list_empty(&root->delalloc_root));
1576 list_del_init(&root->delalloc_root);
1577 spin_unlock(&root->fs_info->delalloc_root_lock);
1580 spin_unlock(&root->delalloc_lock);
1584 * extent_io.c set_bit_hook, used to track delayed allocation
1585 * bytes in this file, and to maintain the list of inodes that
1586 * have pending delalloc work to be done.
1588 static void btrfs_set_bit_hook(struct inode *inode,
1589 struct extent_state *state, unsigned long *bits)
1592 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1595 * set_bit and clear bit hooks normally require _irqsave/restore
1596 * but in this case, we are only testing for the DELALLOC
1597 * bit, which is only set or cleared with irqs on
1599 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1600 struct btrfs_root *root = BTRFS_I(inode)->root;
1601 u64 len = state->end + 1 - state->start;
1602 bool do_list = !btrfs_is_free_space_inode(inode);
1604 if (*bits & EXTENT_FIRST_DELALLOC) {
1605 *bits &= ~EXTENT_FIRST_DELALLOC;
1607 spin_lock(&BTRFS_I(inode)->lock);
1608 BTRFS_I(inode)->outstanding_extents++;
1609 spin_unlock(&BTRFS_I(inode)->lock);
1612 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1613 root->fs_info->delalloc_batch);
1614 spin_lock(&BTRFS_I(inode)->lock);
1615 BTRFS_I(inode)->delalloc_bytes += len;
1616 if (*bits & EXTENT_DEFRAG)
1617 BTRFS_I(inode)->defrag_bytes += len;
1618 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1619 &BTRFS_I(inode)->runtime_flags))
1620 btrfs_add_delalloc_inodes(root, inode);
1621 spin_unlock(&BTRFS_I(inode)->lock);
1626 * extent_io.c clear_bit_hook, see set_bit_hook for why
1628 static void btrfs_clear_bit_hook(struct inode *inode,
1629 struct extent_state *state,
1630 unsigned long *bits)
1632 u64 len = state->end + 1 - state->start;
1634 spin_lock(&BTRFS_I(inode)->lock);
1635 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1636 BTRFS_I(inode)->defrag_bytes -= len;
1637 spin_unlock(&BTRFS_I(inode)->lock);
1640 * set_bit and clear bit hooks normally require _irqsave/restore
1641 * but in this case, we are only testing for the DELALLOC
1642 * bit, which is only set or cleared with irqs on
1644 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1645 struct btrfs_root *root = BTRFS_I(inode)->root;
1646 bool do_list = !btrfs_is_free_space_inode(inode);
1648 if (*bits & EXTENT_FIRST_DELALLOC) {
1649 *bits &= ~EXTENT_FIRST_DELALLOC;
1650 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1651 spin_lock(&BTRFS_I(inode)->lock);
1652 BTRFS_I(inode)->outstanding_extents--;
1653 spin_unlock(&BTRFS_I(inode)->lock);
1657 * We don't reserve metadata space for space cache inodes so we
1658 * don't need to call dellalloc_release_metadata if there is an
1661 if (*bits & EXTENT_DO_ACCOUNTING &&
1662 root != root->fs_info->tree_root)
1663 btrfs_delalloc_release_metadata(inode, len);
1665 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1666 && do_list && !(state->state & EXTENT_NORESERVE))
1667 btrfs_free_reserved_data_space(inode, len);
1669 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1670 root->fs_info->delalloc_batch);
1671 spin_lock(&BTRFS_I(inode)->lock);
1672 BTRFS_I(inode)->delalloc_bytes -= len;
1673 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1674 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1675 &BTRFS_I(inode)->runtime_flags))
1676 btrfs_del_delalloc_inode(root, inode);
1677 spin_unlock(&BTRFS_I(inode)->lock);
1682 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1683 * we don't create bios that span stripes or chunks
1685 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1686 size_t size, struct bio *bio,
1687 unsigned long bio_flags)
1689 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1690 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1695 if (bio_flags & EXTENT_BIO_COMPRESSED)
1698 length = bio->bi_iter.bi_size;
1699 map_length = length;
1700 ret = btrfs_map_block(root->fs_info, rw, logical,
1701 &map_length, NULL, 0);
1702 /* Will always return 0 with map_multi == NULL */
1704 if (map_length < length + size)
1710 * in order to insert checksums into the metadata in large chunks,
1711 * we wait until bio submission time. All the pages in the bio are
1712 * checksummed and sums are attached onto the ordered extent record.
1714 * At IO completion time the cums attached on the ordered extent record
1715 * are inserted into the btree
1717 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1718 struct bio *bio, int mirror_num,
1719 unsigned long bio_flags,
1722 struct btrfs_root *root = BTRFS_I(inode)->root;
1725 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1726 BUG_ON(ret); /* -ENOMEM */
1731 * in order to insert checksums into the metadata in large chunks,
1732 * we wait until bio submission time. All the pages in the bio are
1733 * checksummed and sums are attached onto the ordered extent record.
1735 * At IO completion time the cums attached on the ordered extent record
1736 * are inserted into the btree
1738 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1739 int mirror_num, unsigned long bio_flags,
1742 struct btrfs_root *root = BTRFS_I(inode)->root;
1745 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1747 bio_endio(bio, ret);
1752 * extent_io.c submission hook. This does the right thing for csum calculation
1753 * on write, or reading the csums from the tree before a read
1755 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1756 int mirror_num, unsigned long bio_flags,
1759 struct btrfs_root *root = BTRFS_I(inode)->root;
1763 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1765 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1767 if (btrfs_is_free_space_inode(inode))
1770 if (!(rw & REQ_WRITE)) {
1771 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1775 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1776 ret = btrfs_submit_compressed_read(inode, bio,
1780 } else if (!skip_sum) {
1781 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1786 } else if (async && !skip_sum) {
1787 /* csum items have already been cloned */
1788 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1790 /* we're doing a write, do the async checksumming */
1791 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1792 inode, rw, bio, mirror_num,
1793 bio_flags, bio_offset,
1794 __btrfs_submit_bio_start,
1795 __btrfs_submit_bio_done);
1797 } else if (!skip_sum) {
1798 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1804 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1808 bio_endio(bio, ret);
1813 * given a list of ordered sums record them in the inode. This happens
1814 * at IO completion time based on sums calculated at bio submission time.
1816 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1817 struct inode *inode, u64 file_offset,
1818 struct list_head *list)
1820 struct btrfs_ordered_sum *sum;
1822 list_for_each_entry(sum, list, list) {
1823 trans->adding_csums = 1;
1824 btrfs_csum_file_blocks(trans,
1825 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1826 trans->adding_csums = 0;
1831 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1832 struct extent_state **cached_state)
1834 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1835 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1836 cached_state, GFP_NOFS);
1839 /* see btrfs_writepage_start_hook for details on why this is required */
1840 struct btrfs_writepage_fixup {
1842 struct btrfs_work work;
1845 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1847 struct btrfs_writepage_fixup *fixup;
1848 struct btrfs_ordered_extent *ordered;
1849 struct extent_state *cached_state = NULL;
1851 struct inode *inode;
1856 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1860 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1861 ClearPageChecked(page);
1865 inode = page->mapping->host;
1866 page_start = page_offset(page);
1867 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1869 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1872 /* already ordered? We're done */
1873 if (PagePrivate2(page))
1876 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1878 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1879 page_end, &cached_state, GFP_NOFS);
1881 btrfs_start_ordered_extent(inode, ordered, 1);
1882 btrfs_put_ordered_extent(ordered);
1886 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1888 mapping_set_error(page->mapping, ret);
1889 end_extent_writepage(page, ret, page_start, page_end);
1890 ClearPageChecked(page);
1894 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1895 ClearPageChecked(page);
1896 set_page_dirty(page);
1898 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1899 &cached_state, GFP_NOFS);
1902 page_cache_release(page);
1907 * There are a few paths in the higher layers of the kernel that directly
1908 * set the page dirty bit without asking the filesystem if it is a
1909 * good idea. This causes problems because we want to make sure COW
1910 * properly happens and the data=ordered rules are followed.
1912 * In our case any range that doesn't have the ORDERED bit set
1913 * hasn't been properly setup for IO. We kick off an async process
1914 * to fix it up. The async helper will wait for ordered extents, set
1915 * the delalloc bit and make it safe to write the page.
1917 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1919 struct inode *inode = page->mapping->host;
1920 struct btrfs_writepage_fixup *fixup;
1921 struct btrfs_root *root = BTRFS_I(inode)->root;
1923 /* this page is properly in the ordered list */
1924 if (TestClearPagePrivate2(page))
1927 if (PageChecked(page))
1930 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1934 SetPageChecked(page);
1935 page_cache_get(page);
1936 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
1937 btrfs_writepage_fixup_worker, NULL, NULL);
1939 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
1943 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1944 struct inode *inode, u64 file_pos,
1945 u64 disk_bytenr, u64 disk_num_bytes,
1946 u64 num_bytes, u64 ram_bytes,
1947 u8 compression, u8 encryption,
1948 u16 other_encoding, int extent_type)
1950 struct btrfs_root *root = BTRFS_I(inode)->root;
1951 struct btrfs_file_extent_item *fi;
1952 struct btrfs_path *path;
1953 struct extent_buffer *leaf;
1954 struct btrfs_key ins;
1955 int extent_inserted = 0;
1958 path = btrfs_alloc_path();
1963 * we may be replacing one extent in the tree with another.
1964 * The new extent is pinned in the extent map, and we don't want
1965 * to drop it from the cache until it is completely in the btree.
1967 * So, tell btrfs_drop_extents to leave this extent in the cache.
1968 * the caller is expected to unpin it and allow it to be merged
1971 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
1972 file_pos + num_bytes, NULL, 0,
1973 1, sizeof(*fi), &extent_inserted);
1977 if (!extent_inserted) {
1978 ins.objectid = btrfs_ino(inode);
1979 ins.offset = file_pos;
1980 ins.type = BTRFS_EXTENT_DATA_KEY;
1982 path->leave_spinning = 1;
1983 ret = btrfs_insert_empty_item(trans, root, path, &ins,
1988 leaf = path->nodes[0];
1989 fi = btrfs_item_ptr(leaf, path->slots[0],
1990 struct btrfs_file_extent_item);
1991 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1992 btrfs_set_file_extent_type(leaf, fi, extent_type);
1993 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1994 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1995 btrfs_set_file_extent_offset(leaf, fi, 0);
1996 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1997 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1998 btrfs_set_file_extent_compression(leaf, fi, compression);
1999 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2000 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2002 btrfs_mark_buffer_dirty(leaf);
2003 btrfs_release_path(path);
2005 inode_add_bytes(inode, num_bytes);
2007 ins.objectid = disk_bytenr;
2008 ins.offset = disk_num_bytes;
2009 ins.type = BTRFS_EXTENT_ITEM_KEY;
2010 ret = btrfs_alloc_reserved_file_extent(trans, root,
2011 root->root_key.objectid,
2012 btrfs_ino(inode), file_pos, &ins);
2014 btrfs_free_path(path);
2019 /* snapshot-aware defrag */
2020 struct sa_defrag_extent_backref {
2021 struct rb_node node;
2022 struct old_sa_defrag_extent *old;
2031 struct old_sa_defrag_extent {
2032 struct list_head list;
2033 struct new_sa_defrag_extent *new;
2042 struct new_sa_defrag_extent {
2043 struct rb_root root;
2044 struct list_head head;
2045 struct btrfs_path *path;
2046 struct inode *inode;
2054 static int backref_comp(struct sa_defrag_extent_backref *b1,
2055 struct sa_defrag_extent_backref *b2)
2057 if (b1->root_id < b2->root_id)
2059 else if (b1->root_id > b2->root_id)
2062 if (b1->inum < b2->inum)
2064 else if (b1->inum > b2->inum)
2067 if (b1->file_pos < b2->file_pos)
2069 else if (b1->file_pos > b2->file_pos)
2073 * [------------------------------] ===> (a range of space)
2074 * |<--->| |<---->| =============> (fs/file tree A)
2075 * |<---------------------------->| ===> (fs/file tree B)
2077 * A range of space can refer to two file extents in one tree while
2078 * refer to only one file extent in another tree.
2080 * So we may process a disk offset more than one time(two extents in A)
2081 * and locate at the same extent(one extent in B), then insert two same
2082 * backrefs(both refer to the extent in B).
2087 static void backref_insert(struct rb_root *root,
2088 struct sa_defrag_extent_backref *backref)
2090 struct rb_node **p = &root->rb_node;
2091 struct rb_node *parent = NULL;
2092 struct sa_defrag_extent_backref *entry;
2097 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2099 ret = backref_comp(backref, entry);
2103 p = &(*p)->rb_right;
2106 rb_link_node(&backref->node, parent, p);
2107 rb_insert_color(&backref->node, root);
2111 * Note the backref might has changed, and in this case we just return 0.
2113 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2116 struct btrfs_file_extent_item *extent;
2117 struct btrfs_fs_info *fs_info;
2118 struct old_sa_defrag_extent *old = ctx;
2119 struct new_sa_defrag_extent *new = old->new;
2120 struct btrfs_path *path = new->path;
2121 struct btrfs_key key;
2122 struct btrfs_root *root;
2123 struct sa_defrag_extent_backref *backref;
2124 struct extent_buffer *leaf;
2125 struct inode *inode = new->inode;
2131 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2132 inum == btrfs_ino(inode))
2135 key.objectid = root_id;
2136 key.type = BTRFS_ROOT_ITEM_KEY;
2137 key.offset = (u64)-1;
2139 fs_info = BTRFS_I(inode)->root->fs_info;
2140 root = btrfs_read_fs_root_no_name(fs_info, &key);
2142 if (PTR_ERR(root) == -ENOENT)
2145 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2146 inum, offset, root_id);
2147 return PTR_ERR(root);
2150 key.objectid = inum;
2151 key.type = BTRFS_EXTENT_DATA_KEY;
2152 if (offset > (u64)-1 << 32)
2155 key.offset = offset;
2157 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2158 if (WARN_ON(ret < 0))
2165 leaf = path->nodes[0];
2166 slot = path->slots[0];
2168 if (slot >= btrfs_header_nritems(leaf)) {
2169 ret = btrfs_next_leaf(root, path);
2172 } else if (ret > 0) {
2181 btrfs_item_key_to_cpu(leaf, &key, slot);
2183 if (key.objectid > inum)
2186 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2189 extent = btrfs_item_ptr(leaf, slot,
2190 struct btrfs_file_extent_item);
2192 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2196 * 'offset' refers to the exact key.offset,
2197 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2198 * (key.offset - extent_offset).
2200 if (key.offset != offset)
2203 extent_offset = btrfs_file_extent_offset(leaf, extent);
2204 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2206 if (extent_offset >= old->extent_offset + old->offset +
2207 old->len || extent_offset + num_bytes <=
2208 old->extent_offset + old->offset)
2213 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2219 backref->root_id = root_id;
2220 backref->inum = inum;
2221 backref->file_pos = offset;
2222 backref->num_bytes = num_bytes;
2223 backref->extent_offset = extent_offset;
2224 backref->generation = btrfs_file_extent_generation(leaf, extent);
2226 backref_insert(&new->root, backref);
2229 btrfs_release_path(path);
2234 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2235 struct new_sa_defrag_extent *new)
2237 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2238 struct old_sa_defrag_extent *old, *tmp;
2243 list_for_each_entry_safe(old, tmp, &new->head, list) {
2244 ret = iterate_inodes_from_logical(old->bytenr +
2245 old->extent_offset, fs_info,
2246 path, record_one_backref,
2248 if (ret < 0 && ret != -ENOENT)
2251 /* no backref to be processed for this extent */
2253 list_del(&old->list);
2258 if (list_empty(&new->head))
2264 static int relink_is_mergable(struct extent_buffer *leaf,
2265 struct btrfs_file_extent_item *fi,
2266 struct new_sa_defrag_extent *new)
2268 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2271 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2274 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2277 if (btrfs_file_extent_encryption(leaf, fi) ||
2278 btrfs_file_extent_other_encoding(leaf, fi))
2285 * Note the backref might has changed, and in this case we just return 0.
2287 static noinline int relink_extent_backref(struct btrfs_path *path,
2288 struct sa_defrag_extent_backref *prev,
2289 struct sa_defrag_extent_backref *backref)
2291 struct btrfs_file_extent_item *extent;
2292 struct btrfs_file_extent_item *item;
2293 struct btrfs_ordered_extent *ordered;
2294 struct btrfs_trans_handle *trans;
2295 struct btrfs_fs_info *fs_info;
2296 struct btrfs_root *root;
2297 struct btrfs_key key;
2298 struct extent_buffer *leaf;
2299 struct old_sa_defrag_extent *old = backref->old;
2300 struct new_sa_defrag_extent *new = old->new;
2301 struct inode *src_inode = new->inode;
2302 struct inode *inode;
2303 struct extent_state *cached = NULL;
2312 if (prev && prev->root_id == backref->root_id &&
2313 prev->inum == backref->inum &&
2314 prev->file_pos + prev->num_bytes == backref->file_pos)
2317 /* step 1: get root */
2318 key.objectid = backref->root_id;
2319 key.type = BTRFS_ROOT_ITEM_KEY;
2320 key.offset = (u64)-1;
2322 fs_info = BTRFS_I(src_inode)->root->fs_info;
2323 index = srcu_read_lock(&fs_info->subvol_srcu);
2325 root = btrfs_read_fs_root_no_name(fs_info, &key);
2327 srcu_read_unlock(&fs_info->subvol_srcu, index);
2328 if (PTR_ERR(root) == -ENOENT)
2330 return PTR_ERR(root);
2333 if (btrfs_root_readonly(root)) {
2334 srcu_read_unlock(&fs_info->subvol_srcu, index);
2338 /* step 2: get inode */
2339 key.objectid = backref->inum;
2340 key.type = BTRFS_INODE_ITEM_KEY;
2343 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2344 if (IS_ERR(inode)) {
2345 srcu_read_unlock(&fs_info->subvol_srcu, index);
2349 srcu_read_unlock(&fs_info->subvol_srcu, index);
2351 /* step 3: relink backref */
2352 lock_start = backref->file_pos;
2353 lock_end = backref->file_pos + backref->num_bytes - 1;
2354 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2357 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2359 btrfs_put_ordered_extent(ordered);
2363 trans = btrfs_join_transaction(root);
2364 if (IS_ERR(trans)) {
2365 ret = PTR_ERR(trans);
2369 key.objectid = backref->inum;
2370 key.type = BTRFS_EXTENT_DATA_KEY;
2371 key.offset = backref->file_pos;
2373 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2376 } else if (ret > 0) {
2381 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2382 struct btrfs_file_extent_item);
2384 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2385 backref->generation)
2388 btrfs_release_path(path);
2390 start = backref->file_pos;
2391 if (backref->extent_offset < old->extent_offset + old->offset)
2392 start += old->extent_offset + old->offset -
2393 backref->extent_offset;
2395 len = min(backref->extent_offset + backref->num_bytes,
2396 old->extent_offset + old->offset + old->len);
2397 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2399 ret = btrfs_drop_extents(trans, root, inode, start,
2404 key.objectid = btrfs_ino(inode);
2405 key.type = BTRFS_EXTENT_DATA_KEY;
2408 path->leave_spinning = 1;
2410 struct btrfs_file_extent_item *fi;
2412 struct btrfs_key found_key;
2414 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2419 leaf = path->nodes[0];
2420 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2422 fi = btrfs_item_ptr(leaf, path->slots[0],
2423 struct btrfs_file_extent_item);
2424 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2426 if (extent_len + found_key.offset == start &&
2427 relink_is_mergable(leaf, fi, new)) {
2428 btrfs_set_file_extent_num_bytes(leaf, fi,
2430 btrfs_mark_buffer_dirty(leaf);
2431 inode_add_bytes(inode, len);
2437 btrfs_release_path(path);
2442 ret = btrfs_insert_empty_item(trans, root, path, &key,
2445 btrfs_abort_transaction(trans, root, ret);
2449 leaf = path->nodes[0];
2450 item = btrfs_item_ptr(leaf, path->slots[0],
2451 struct btrfs_file_extent_item);
2452 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2453 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2454 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2455 btrfs_set_file_extent_num_bytes(leaf, item, len);
2456 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2457 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2458 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2459 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2460 btrfs_set_file_extent_encryption(leaf, item, 0);
2461 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2463 btrfs_mark_buffer_dirty(leaf);
2464 inode_add_bytes(inode, len);
2465 btrfs_release_path(path);
2467 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2469 backref->root_id, backref->inum,
2470 new->file_pos, 0); /* start - extent_offset */
2472 btrfs_abort_transaction(trans, root, ret);
2478 btrfs_release_path(path);
2479 path->leave_spinning = 0;
2480 btrfs_end_transaction(trans, root);
2482 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2488 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2490 struct old_sa_defrag_extent *old, *tmp;
2495 list_for_each_entry_safe(old, tmp, &new->head, list) {
2496 list_del(&old->list);
2502 static void relink_file_extents(struct new_sa_defrag_extent *new)
2504 struct btrfs_path *path;
2505 struct sa_defrag_extent_backref *backref;
2506 struct sa_defrag_extent_backref *prev = NULL;
2507 struct inode *inode;
2508 struct btrfs_root *root;
2509 struct rb_node *node;
2513 root = BTRFS_I(inode)->root;
2515 path = btrfs_alloc_path();
2519 if (!record_extent_backrefs(path, new)) {
2520 btrfs_free_path(path);
2523 btrfs_release_path(path);
2526 node = rb_first(&new->root);
2529 rb_erase(node, &new->root);
2531 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2533 ret = relink_extent_backref(path, prev, backref);
2546 btrfs_free_path(path);
2548 free_sa_defrag_extent(new);
2550 atomic_dec(&root->fs_info->defrag_running);
2551 wake_up(&root->fs_info->transaction_wait);
2554 static struct new_sa_defrag_extent *
2555 record_old_file_extents(struct inode *inode,
2556 struct btrfs_ordered_extent *ordered)
2558 struct btrfs_root *root = BTRFS_I(inode)->root;
2559 struct btrfs_path *path;
2560 struct btrfs_key key;
2561 struct old_sa_defrag_extent *old;
2562 struct new_sa_defrag_extent *new;
2565 new = kmalloc(sizeof(*new), GFP_NOFS);
2570 new->file_pos = ordered->file_offset;
2571 new->len = ordered->len;
2572 new->bytenr = ordered->start;
2573 new->disk_len = ordered->disk_len;
2574 new->compress_type = ordered->compress_type;
2575 new->root = RB_ROOT;
2576 INIT_LIST_HEAD(&new->head);
2578 path = btrfs_alloc_path();
2582 key.objectid = btrfs_ino(inode);
2583 key.type = BTRFS_EXTENT_DATA_KEY;
2584 key.offset = new->file_pos;
2586 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2589 if (ret > 0 && path->slots[0] > 0)
2592 /* find out all the old extents for the file range */
2594 struct btrfs_file_extent_item *extent;
2595 struct extent_buffer *l;
2604 slot = path->slots[0];
2606 if (slot >= btrfs_header_nritems(l)) {
2607 ret = btrfs_next_leaf(root, path);
2615 btrfs_item_key_to_cpu(l, &key, slot);
2617 if (key.objectid != btrfs_ino(inode))
2619 if (key.type != BTRFS_EXTENT_DATA_KEY)
2621 if (key.offset >= new->file_pos + new->len)
2624 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2626 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2627 if (key.offset + num_bytes < new->file_pos)
2630 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2634 extent_offset = btrfs_file_extent_offset(l, extent);
2636 old = kmalloc(sizeof(*old), GFP_NOFS);
2640 offset = max(new->file_pos, key.offset);
2641 end = min(new->file_pos + new->len, key.offset + num_bytes);
2643 old->bytenr = disk_bytenr;
2644 old->extent_offset = extent_offset;
2645 old->offset = offset - key.offset;
2646 old->len = end - offset;
2649 list_add_tail(&old->list, &new->head);
2655 btrfs_free_path(path);
2656 atomic_inc(&root->fs_info->defrag_running);
2661 btrfs_free_path(path);
2663 free_sa_defrag_extent(new);
2667 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2670 struct btrfs_block_group_cache *cache;
2672 cache = btrfs_lookup_block_group(root->fs_info, start);
2675 spin_lock(&cache->lock);
2676 cache->delalloc_bytes -= len;
2677 spin_unlock(&cache->lock);
2679 btrfs_put_block_group(cache);
2682 /* as ordered data IO finishes, this gets called so we can finish
2683 * an ordered extent if the range of bytes in the file it covers are
2686 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2688 struct inode *inode = ordered_extent->inode;
2689 struct btrfs_root *root = BTRFS_I(inode)->root;
2690 struct btrfs_trans_handle *trans = NULL;
2691 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2692 struct extent_state *cached_state = NULL;
2693 struct new_sa_defrag_extent *new = NULL;
2694 int compress_type = 0;
2696 u64 logical_len = ordered_extent->len;
2698 bool truncated = false;
2700 nolock = btrfs_is_free_space_inode(inode);
2702 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2707 btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2708 ordered_extent->file_offset +
2709 ordered_extent->len - 1);
2711 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2713 logical_len = ordered_extent->truncated_len;
2714 /* Truncated the entire extent, don't bother adding */
2719 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2720 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2721 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2723 trans = btrfs_join_transaction_nolock(root);
2725 trans = btrfs_join_transaction(root);
2726 if (IS_ERR(trans)) {
2727 ret = PTR_ERR(trans);
2731 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2732 ret = btrfs_update_inode_fallback(trans, root, inode);
2733 if (ret) /* -ENOMEM or corruption */
2734 btrfs_abort_transaction(trans, root, ret);
2738 lock_extent_bits(io_tree, ordered_extent->file_offset,
2739 ordered_extent->file_offset + ordered_extent->len - 1,
2742 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2743 ordered_extent->file_offset + ordered_extent->len - 1,
2744 EXTENT_DEFRAG, 1, cached_state);
2746 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2747 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2748 /* the inode is shared */
2749 new = record_old_file_extents(inode, ordered_extent);
2751 clear_extent_bit(io_tree, ordered_extent->file_offset,
2752 ordered_extent->file_offset + ordered_extent->len - 1,
2753 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2757 trans = btrfs_join_transaction_nolock(root);
2759 trans = btrfs_join_transaction(root);
2760 if (IS_ERR(trans)) {
2761 ret = PTR_ERR(trans);
2766 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2768 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2769 compress_type = ordered_extent->compress_type;
2770 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2771 BUG_ON(compress_type);
2772 ret = btrfs_mark_extent_written(trans, inode,
2773 ordered_extent->file_offset,
2774 ordered_extent->file_offset +
2777 BUG_ON(root == root->fs_info->tree_root);
2778 ret = insert_reserved_file_extent(trans, inode,
2779 ordered_extent->file_offset,
2780 ordered_extent->start,
2781 ordered_extent->disk_len,
2782 logical_len, logical_len,
2783 compress_type, 0, 0,
2784 BTRFS_FILE_EXTENT_REG);
2786 btrfs_release_delalloc_bytes(root,
2787 ordered_extent->start,
2788 ordered_extent->disk_len);
2790 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2791 ordered_extent->file_offset, ordered_extent->len,
2794 btrfs_abort_transaction(trans, root, ret);
2798 add_pending_csums(trans, inode, ordered_extent->file_offset,
2799 &ordered_extent->list);
2801 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2802 ret = btrfs_update_inode_fallback(trans, root, inode);
2803 if (ret) { /* -ENOMEM or corruption */
2804 btrfs_abort_transaction(trans, root, ret);
2809 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2810 ordered_extent->file_offset +
2811 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2813 if (root != root->fs_info->tree_root)
2814 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2816 btrfs_end_transaction(trans, root);
2818 if (ret || truncated) {
2822 start = ordered_extent->file_offset + logical_len;
2824 start = ordered_extent->file_offset;
2825 end = ordered_extent->file_offset + ordered_extent->len - 1;
2826 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2828 /* Drop the cache for the part of the extent we didn't write. */
2829 btrfs_drop_extent_cache(inode, start, end, 0);
2832 * If the ordered extent had an IOERR or something else went
2833 * wrong we need to return the space for this ordered extent
2834 * back to the allocator. We only free the extent in the
2835 * truncated case if we didn't write out the extent at all.
2837 if ((ret || !logical_len) &&
2838 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2839 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2840 btrfs_free_reserved_extent(root, ordered_extent->start,
2841 ordered_extent->disk_len, 1);
2846 * This needs to be done to make sure anybody waiting knows we are done
2847 * updating everything for this ordered extent.
2849 btrfs_remove_ordered_extent(inode, ordered_extent);
2851 /* for snapshot-aware defrag */
2854 free_sa_defrag_extent(new);
2855 atomic_dec(&root->fs_info->defrag_running);
2857 relink_file_extents(new);
2862 btrfs_put_ordered_extent(ordered_extent);
2863 /* once for the tree */
2864 btrfs_put_ordered_extent(ordered_extent);
2869 static void finish_ordered_fn(struct btrfs_work *work)
2871 struct btrfs_ordered_extent *ordered_extent;
2872 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2873 btrfs_finish_ordered_io(ordered_extent);
2876 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2877 struct extent_state *state, int uptodate)
2879 struct inode *inode = page->mapping->host;
2880 struct btrfs_root *root = BTRFS_I(inode)->root;
2881 struct btrfs_ordered_extent *ordered_extent = NULL;
2882 struct btrfs_workqueue *wq;
2883 btrfs_work_func_t func;
2885 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2887 ClearPagePrivate2(page);
2888 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2889 end - start + 1, uptodate))
2892 if (btrfs_is_free_space_inode(inode)) {
2893 wq = root->fs_info->endio_freespace_worker;
2894 func = btrfs_freespace_write_helper;
2896 wq = root->fs_info->endio_write_workers;
2897 func = btrfs_endio_write_helper;
2900 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
2902 btrfs_queue_work(wq, &ordered_extent->work);
2907 static int __readpage_endio_check(struct inode *inode,
2908 struct btrfs_io_bio *io_bio,
2909 int icsum, struct page *page,
2910 int pgoff, u64 start, size_t len)
2915 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2916 DEFAULT_RATELIMIT_BURST);
2918 csum_expected = *(((u32 *)io_bio->csum) + icsum);
2920 kaddr = kmap_atomic(page);
2921 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
2922 btrfs_csum_final(csum, (char *)&csum);
2923 if (csum != csum_expected)
2926 kunmap_atomic(kaddr);
2929 if (__ratelimit(&_rs))
2930 btrfs_info(BTRFS_I(inode)->root->fs_info,
2931 "csum failed ino %llu off %llu csum %u expected csum %u",
2932 btrfs_ino(inode), start, csum, csum_expected);
2933 memset(kaddr + pgoff, 1, len);
2934 flush_dcache_page(page);
2935 kunmap_atomic(kaddr);
2936 if (csum_expected == 0)
2942 * when reads are done, we need to check csums to verify the data is correct
2943 * if there's a match, we allow the bio to finish. If not, the code in
2944 * extent_io.c will try to find good copies for us.
2946 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2947 u64 phy_offset, struct page *page,
2948 u64 start, u64 end, int mirror)
2950 size_t offset = start - page_offset(page);
2951 struct inode *inode = page->mapping->host;
2952 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2953 struct btrfs_root *root = BTRFS_I(inode)->root;
2955 if (PageChecked(page)) {
2956 ClearPageChecked(page);
2960 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2963 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2964 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2965 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2970 phy_offset >>= inode->i_sb->s_blocksize_bits;
2971 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
2972 start, (size_t)(end - start + 1));
2975 struct delayed_iput {
2976 struct list_head list;
2977 struct inode *inode;
2980 /* JDM: If this is fs-wide, why can't we add a pointer to
2981 * btrfs_inode instead and avoid the allocation? */
2982 void btrfs_add_delayed_iput(struct inode *inode)
2984 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2985 struct delayed_iput *delayed;
2987 if (atomic_add_unless(&inode->i_count, -1, 1))
2990 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2991 delayed->inode = inode;
2993 spin_lock(&fs_info->delayed_iput_lock);
2994 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2995 spin_unlock(&fs_info->delayed_iput_lock);
2998 void btrfs_run_delayed_iputs(struct btrfs_root *root)
3001 struct btrfs_fs_info *fs_info = root->fs_info;
3002 struct delayed_iput *delayed;
3005 spin_lock(&fs_info->delayed_iput_lock);
3006 empty = list_empty(&fs_info->delayed_iputs);
3007 spin_unlock(&fs_info->delayed_iput_lock);
3011 spin_lock(&fs_info->delayed_iput_lock);
3012 list_splice_init(&fs_info->delayed_iputs, &list);
3013 spin_unlock(&fs_info->delayed_iput_lock);
3015 while (!list_empty(&list)) {
3016 delayed = list_entry(list.next, struct delayed_iput, list);
3017 list_del(&delayed->list);
3018 iput(delayed->inode);
3024 * This is called in transaction commit time. If there are no orphan
3025 * files in the subvolume, it removes orphan item and frees block_rsv
3028 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3029 struct btrfs_root *root)
3031 struct btrfs_block_rsv *block_rsv;
3034 if (atomic_read(&root->orphan_inodes) ||
3035 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3038 spin_lock(&root->orphan_lock);
3039 if (atomic_read(&root->orphan_inodes)) {
3040 spin_unlock(&root->orphan_lock);
3044 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3045 spin_unlock(&root->orphan_lock);
3049 block_rsv = root->orphan_block_rsv;
3050 root->orphan_block_rsv = NULL;
3051 spin_unlock(&root->orphan_lock);
3053 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3054 btrfs_root_refs(&root->root_item) > 0) {
3055 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
3056 root->root_key.objectid);
3058 btrfs_abort_transaction(trans, root, ret);
3060 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3065 WARN_ON(block_rsv->size > 0);
3066 btrfs_free_block_rsv(root, block_rsv);
3071 * This creates an orphan entry for the given inode in case something goes
3072 * wrong in the middle of an unlink/truncate.
3074 * NOTE: caller of this function should reserve 5 units of metadata for
3077 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3079 struct btrfs_root *root = BTRFS_I(inode)->root;
3080 struct btrfs_block_rsv *block_rsv = NULL;
3085 if (!root->orphan_block_rsv) {
3086 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3091 spin_lock(&root->orphan_lock);
3092 if (!root->orphan_block_rsv) {
3093 root->orphan_block_rsv = block_rsv;
3094 } else if (block_rsv) {
3095 btrfs_free_block_rsv(root, block_rsv);
3099 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3100 &BTRFS_I(inode)->runtime_flags)) {
3103 * For proper ENOSPC handling, we should do orphan
3104 * cleanup when mounting. But this introduces backward
3105 * compatibility issue.
3107 if (!xchg(&root->orphan_item_inserted, 1))
3113 atomic_inc(&root->orphan_inodes);
3116 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3117 &BTRFS_I(inode)->runtime_flags))
3119 spin_unlock(&root->orphan_lock);
3121 /* grab metadata reservation from transaction handle */
3123 ret = btrfs_orphan_reserve_metadata(trans, inode);
3124 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3127 /* insert an orphan item to track this unlinked/truncated file */
3129 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3131 atomic_dec(&root->orphan_inodes);
3133 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3134 &BTRFS_I(inode)->runtime_flags);
3135 btrfs_orphan_release_metadata(inode);
3137 if (ret != -EEXIST) {
3138 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3139 &BTRFS_I(inode)->runtime_flags);
3140 btrfs_abort_transaction(trans, root, ret);
3147 /* insert an orphan item to track subvolume contains orphan files */
3149 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3150 root->root_key.objectid);
3151 if (ret && ret != -EEXIST) {
3152 btrfs_abort_transaction(trans, root, ret);
3160 * We have done the truncate/delete so we can go ahead and remove the orphan
3161 * item for this particular inode.
3163 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3164 struct inode *inode)
3166 struct btrfs_root *root = BTRFS_I(inode)->root;
3167 int delete_item = 0;
3168 int release_rsv = 0;
3171 spin_lock(&root->orphan_lock);
3172 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3173 &BTRFS_I(inode)->runtime_flags))
3176 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3177 &BTRFS_I(inode)->runtime_flags))
3179 spin_unlock(&root->orphan_lock);
3182 atomic_dec(&root->orphan_inodes);
3184 ret = btrfs_del_orphan_item(trans, root,
3189 btrfs_orphan_release_metadata(inode);
3195 * this cleans up any orphans that may be left on the list from the last use
3198 int btrfs_orphan_cleanup(struct btrfs_root *root)
3200 struct btrfs_path *path;
3201 struct extent_buffer *leaf;
3202 struct btrfs_key key, found_key;
3203 struct btrfs_trans_handle *trans;
3204 struct inode *inode;
3205 u64 last_objectid = 0;
3206 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3208 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3211 path = btrfs_alloc_path();
3218 key.objectid = BTRFS_ORPHAN_OBJECTID;
3219 key.type = BTRFS_ORPHAN_ITEM_KEY;
3220 key.offset = (u64)-1;
3223 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3228 * if ret == 0 means we found what we were searching for, which
3229 * is weird, but possible, so only screw with path if we didn't
3230 * find the key and see if we have stuff that matches
3234 if (path->slots[0] == 0)
3239 /* pull out the item */
3240 leaf = path->nodes[0];
3241 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3243 /* make sure the item matches what we want */
3244 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3246 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3249 /* release the path since we're done with it */
3250 btrfs_release_path(path);
3253 * this is where we are basically btrfs_lookup, without the
3254 * crossing root thing. we store the inode number in the
3255 * offset of the orphan item.
3258 if (found_key.offset == last_objectid) {
3259 btrfs_err(root->fs_info,
3260 "Error removing orphan entry, stopping orphan cleanup");
3265 last_objectid = found_key.offset;
3267 found_key.objectid = found_key.offset;
3268 found_key.type = BTRFS_INODE_ITEM_KEY;
3269 found_key.offset = 0;
3270 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3271 ret = PTR_ERR_OR_ZERO(inode);
3272 if (ret && ret != -ESTALE)
3275 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3276 struct btrfs_root *dead_root;
3277 struct btrfs_fs_info *fs_info = root->fs_info;
3278 int is_dead_root = 0;
3281 * this is an orphan in the tree root. Currently these
3282 * could come from 2 sources:
3283 * a) a snapshot deletion in progress
3284 * b) a free space cache inode
3285 * We need to distinguish those two, as the snapshot
3286 * orphan must not get deleted.
3287 * find_dead_roots already ran before us, so if this
3288 * is a snapshot deletion, we should find the root
3289 * in the dead_roots list
3291 spin_lock(&fs_info->trans_lock);
3292 list_for_each_entry(dead_root, &fs_info->dead_roots,
3294 if (dead_root->root_key.objectid ==
3295 found_key.objectid) {
3300 spin_unlock(&fs_info->trans_lock);
3302 /* prevent this orphan from being found again */
3303 key.offset = found_key.objectid - 1;
3308 * Inode is already gone but the orphan item is still there,
3309 * kill the orphan item.
3311 if (ret == -ESTALE) {
3312 trans = btrfs_start_transaction(root, 1);
3313 if (IS_ERR(trans)) {
3314 ret = PTR_ERR(trans);
3317 btrfs_debug(root->fs_info, "auto deleting %Lu",
3318 found_key.objectid);
3319 ret = btrfs_del_orphan_item(trans, root,
3320 found_key.objectid);
3321 btrfs_end_transaction(trans, root);
3328 * add this inode to the orphan list so btrfs_orphan_del does
3329 * the proper thing when we hit it
3331 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3332 &BTRFS_I(inode)->runtime_flags);
3333 atomic_inc(&root->orphan_inodes);
3335 /* if we have links, this was a truncate, lets do that */
3336 if (inode->i_nlink) {
3337 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3343 /* 1 for the orphan item deletion. */
3344 trans = btrfs_start_transaction(root, 1);
3345 if (IS_ERR(trans)) {
3347 ret = PTR_ERR(trans);
3350 ret = btrfs_orphan_add(trans, inode);
3351 btrfs_end_transaction(trans, root);
3357 ret = btrfs_truncate(inode);
3359 btrfs_orphan_del(NULL, inode);
3364 /* this will do delete_inode and everything for us */
3369 /* release the path since we're done with it */
3370 btrfs_release_path(path);
3372 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3374 if (root->orphan_block_rsv)
3375 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3378 if (root->orphan_block_rsv ||
3379 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3380 trans = btrfs_join_transaction(root);
3382 btrfs_end_transaction(trans, root);
3386 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3388 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3392 btrfs_crit(root->fs_info,
3393 "could not do orphan cleanup %d", ret);
3394 btrfs_free_path(path);
3399 * very simple check to peek ahead in the leaf looking for xattrs. If we
3400 * don't find any xattrs, we know there can't be any acls.
3402 * slot is the slot the inode is in, objectid is the objectid of the inode
3404 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3405 int slot, u64 objectid,
3406 int *first_xattr_slot)
3408 u32 nritems = btrfs_header_nritems(leaf);
3409 struct btrfs_key found_key;
3410 static u64 xattr_access = 0;
3411 static u64 xattr_default = 0;
3414 if (!xattr_access) {
3415 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3416 strlen(POSIX_ACL_XATTR_ACCESS));
3417 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3418 strlen(POSIX_ACL_XATTR_DEFAULT));
3422 *first_xattr_slot = -1;
3423 while (slot < nritems) {
3424 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3426 /* we found a different objectid, there must not be acls */
3427 if (found_key.objectid != objectid)
3430 /* we found an xattr, assume we've got an acl */
3431 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3432 if (*first_xattr_slot == -1)
3433 *first_xattr_slot = slot;
3434 if (found_key.offset == xattr_access ||
3435 found_key.offset == xattr_default)
3440 * we found a key greater than an xattr key, there can't
3441 * be any acls later on
3443 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3450 * it goes inode, inode backrefs, xattrs, extents,
3451 * so if there are a ton of hard links to an inode there can
3452 * be a lot of backrefs. Don't waste time searching too hard,
3453 * this is just an optimization
3458 /* we hit the end of the leaf before we found an xattr or
3459 * something larger than an xattr. We have to assume the inode
3462 if (*first_xattr_slot == -1)
3463 *first_xattr_slot = slot;
3468 * read an inode from the btree into the in-memory inode
3470 static void btrfs_read_locked_inode(struct inode *inode)
3472 struct btrfs_path *path;
3473 struct extent_buffer *leaf;
3474 struct btrfs_inode_item *inode_item;
3475 struct btrfs_timespec *tspec;
3476 struct btrfs_root *root = BTRFS_I(inode)->root;
3477 struct btrfs_key location;
3482 bool filled = false;
3483 int first_xattr_slot;
3485 ret = btrfs_fill_inode(inode, &rdev);
3489 path = btrfs_alloc_path();
3493 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3495 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3499 leaf = path->nodes[0];
3504 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3505 struct btrfs_inode_item);
3506 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3507 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3508 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3509 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3510 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3512 tspec = btrfs_inode_atime(inode_item);
3513 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3514 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3516 tspec = btrfs_inode_mtime(inode_item);
3517 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3518 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3520 tspec = btrfs_inode_ctime(inode_item);
3521 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3522 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3524 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3525 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3526 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3529 * If we were modified in the current generation and evicted from memory
3530 * and then re-read we need to do a full sync since we don't have any
3531 * idea about which extents were modified before we were evicted from
3534 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3535 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3536 &BTRFS_I(inode)->runtime_flags);
3538 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3539 inode->i_generation = BTRFS_I(inode)->generation;
3541 rdev = btrfs_inode_rdev(leaf, inode_item);
3543 BTRFS_I(inode)->index_cnt = (u64)-1;
3544 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3548 if (inode->i_nlink != 1 ||
3549 path->slots[0] >= btrfs_header_nritems(leaf))
3552 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3553 if (location.objectid != btrfs_ino(inode))
3556 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3557 if (location.type == BTRFS_INODE_REF_KEY) {
3558 struct btrfs_inode_ref *ref;
3560 ref = (struct btrfs_inode_ref *)ptr;
3561 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3562 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3563 struct btrfs_inode_extref *extref;
3565 extref = (struct btrfs_inode_extref *)ptr;
3566 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3571 * try to precache a NULL acl entry for files that don't have
3572 * any xattrs or acls
3574 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3575 btrfs_ino(inode), &first_xattr_slot);
3576 if (first_xattr_slot != -1) {
3577 path->slots[0] = first_xattr_slot;
3578 ret = btrfs_load_inode_props(inode, path);
3580 btrfs_err(root->fs_info,
3581 "error loading props for ino %llu (root %llu): %d",
3583 root->root_key.objectid, ret);
3585 btrfs_free_path(path);
3588 cache_no_acl(inode);
3590 switch (inode->i_mode & S_IFMT) {
3592 inode->i_mapping->a_ops = &btrfs_aops;
3593 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3594 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3595 inode->i_fop = &btrfs_file_operations;
3596 inode->i_op = &btrfs_file_inode_operations;
3599 inode->i_fop = &btrfs_dir_file_operations;
3600 if (root == root->fs_info->tree_root)
3601 inode->i_op = &btrfs_dir_ro_inode_operations;
3603 inode->i_op = &btrfs_dir_inode_operations;
3606 inode->i_op = &btrfs_symlink_inode_operations;
3607 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3608 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3611 inode->i_op = &btrfs_special_inode_operations;
3612 init_special_inode(inode, inode->i_mode, rdev);
3616 btrfs_update_iflags(inode);
3620 btrfs_free_path(path);
3621 make_bad_inode(inode);
3625 * given a leaf and an inode, copy the inode fields into the leaf
3627 static void fill_inode_item(struct btrfs_trans_handle *trans,
3628 struct extent_buffer *leaf,
3629 struct btrfs_inode_item *item,
3630 struct inode *inode)
3632 struct btrfs_map_token token;
3634 btrfs_init_map_token(&token);
3636 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3637 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3638 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3640 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3641 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3643 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3644 inode->i_atime.tv_sec, &token);
3645 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3646 inode->i_atime.tv_nsec, &token);
3648 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3649 inode->i_mtime.tv_sec, &token);
3650 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3651 inode->i_mtime.tv_nsec, &token);
3653 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3654 inode->i_ctime.tv_sec, &token);
3655 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3656 inode->i_ctime.tv_nsec, &token);
3658 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3660 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3662 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3663 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3664 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3665 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3666 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3670 * copy everything in the in-memory inode into the btree.
3672 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3673 struct btrfs_root *root, struct inode *inode)
3675 struct btrfs_inode_item *inode_item;
3676 struct btrfs_path *path;
3677 struct extent_buffer *leaf;
3680 path = btrfs_alloc_path();
3684 path->leave_spinning = 1;
3685 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3693 leaf = path->nodes[0];
3694 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3695 struct btrfs_inode_item);
3697 fill_inode_item(trans, leaf, inode_item, inode);
3698 btrfs_mark_buffer_dirty(leaf);
3699 btrfs_set_inode_last_trans(trans, inode);
3702 btrfs_free_path(path);
3707 * copy everything in the in-memory inode into the btree.
3709 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3710 struct btrfs_root *root, struct inode *inode)
3715 * If the inode is a free space inode, we can deadlock during commit
3716 * if we put it into the delayed code.
3718 * The data relocation inode should also be directly updated
3721 if (!btrfs_is_free_space_inode(inode)
3722 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3723 && !root->fs_info->log_root_recovering) {
3724 btrfs_update_root_times(trans, root);
3726 ret = btrfs_delayed_update_inode(trans, root, inode);
3728 btrfs_set_inode_last_trans(trans, inode);
3732 return btrfs_update_inode_item(trans, root, inode);
3735 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3736 struct btrfs_root *root,
3737 struct inode *inode)
3741 ret = btrfs_update_inode(trans, root, inode);
3743 return btrfs_update_inode_item(trans, root, inode);
3748 * unlink helper that gets used here in inode.c and in the tree logging
3749 * recovery code. It remove a link in a directory with a given name, and
3750 * also drops the back refs in the inode to the directory
3752 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3753 struct btrfs_root *root,
3754 struct inode *dir, struct inode *inode,
3755 const char *name, int name_len)
3757 struct btrfs_path *path;
3759 struct extent_buffer *leaf;
3760 struct btrfs_dir_item *di;
3761 struct btrfs_key key;
3763 u64 ino = btrfs_ino(inode);
3764 u64 dir_ino = btrfs_ino(dir);
3766 path = btrfs_alloc_path();
3772 path->leave_spinning = 1;
3773 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3774 name, name_len, -1);
3783 leaf = path->nodes[0];
3784 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3785 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3788 btrfs_release_path(path);
3791 * If we don't have dir index, we have to get it by looking up
3792 * the inode ref, since we get the inode ref, remove it directly,
3793 * it is unnecessary to do delayed deletion.
3795 * But if we have dir index, needn't search inode ref to get it.
3796 * Since the inode ref is close to the inode item, it is better
3797 * that we delay to delete it, and just do this deletion when
3798 * we update the inode item.
3800 if (BTRFS_I(inode)->dir_index) {
3801 ret = btrfs_delayed_delete_inode_ref(inode);
3803 index = BTRFS_I(inode)->dir_index;
3808 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3811 btrfs_info(root->fs_info,
3812 "failed to delete reference to %.*s, inode %llu parent %llu",
3813 name_len, name, ino, dir_ino);
3814 btrfs_abort_transaction(trans, root, ret);
3818 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3820 btrfs_abort_transaction(trans, root, ret);
3824 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3826 if (ret != 0 && ret != -ENOENT) {
3827 btrfs_abort_transaction(trans, root, ret);
3831 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3836 btrfs_abort_transaction(trans, root, ret);
3838 btrfs_free_path(path);
3842 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3843 inode_inc_iversion(inode);
3844 inode_inc_iversion(dir);
3845 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3846 ret = btrfs_update_inode(trans, root, dir);
3851 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3852 struct btrfs_root *root,
3853 struct inode *dir, struct inode *inode,
3854 const char *name, int name_len)
3857 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3860 ret = btrfs_update_inode(trans, root, inode);
3866 * helper to start transaction for unlink and rmdir.
3868 * unlink and rmdir are special in btrfs, they do not always free space, so
3869 * if we cannot make our reservations the normal way try and see if there is
3870 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3871 * allow the unlink to occur.
3873 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3875 struct btrfs_trans_handle *trans;
3876 struct btrfs_root *root = BTRFS_I(dir)->root;
3880 * 1 for the possible orphan item
3881 * 1 for the dir item
3882 * 1 for the dir index
3883 * 1 for the inode ref
3886 trans = btrfs_start_transaction(root, 5);
3887 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3890 if (PTR_ERR(trans) == -ENOSPC) {
3891 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3893 trans = btrfs_start_transaction(root, 0);
3896 ret = btrfs_cond_migrate_bytes(root->fs_info,
3897 &root->fs_info->trans_block_rsv,
3900 btrfs_end_transaction(trans, root);
3901 return ERR_PTR(ret);
3903 trans->block_rsv = &root->fs_info->trans_block_rsv;
3904 trans->bytes_reserved = num_bytes;
3909 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3911 struct btrfs_root *root = BTRFS_I(dir)->root;
3912 struct btrfs_trans_handle *trans;
3913 struct inode *inode = dentry->d_inode;
3916 trans = __unlink_start_trans(dir);
3918 return PTR_ERR(trans);
3920 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3922 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3923 dentry->d_name.name, dentry->d_name.len);
3927 if (inode->i_nlink == 0) {
3928 ret = btrfs_orphan_add(trans, inode);
3934 btrfs_end_transaction(trans, root);
3935 btrfs_btree_balance_dirty(root);
3939 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3940 struct btrfs_root *root,
3941 struct inode *dir, u64 objectid,
3942 const char *name, int name_len)
3944 struct btrfs_path *path;
3945 struct extent_buffer *leaf;
3946 struct btrfs_dir_item *di;
3947 struct btrfs_key key;
3950 u64 dir_ino = btrfs_ino(dir);
3952 path = btrfs_alloc_path();
3956 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3957 name, name_len, -1);
3958 if (IS_ERR_OR_NULL(di)) {
3966 leaf = path->nodes[0];
3967 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3968 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3969 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3971 btrfs_abort_transaction(trans, root, ret);
3974 btrfs_release_path(path);
3976 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3977 objectid, root->root_key.objectid,
3978 dir_ino, &index, name, name_len);
3980 if (ret != -ENOENT) {
3981 btrfs_abort_transaction(trans, root, ret);
3984 di = btrfs_search_dir_index_item(root, path, dir_ino,
3986 if (IS_ERR_OR_NULL(di)) {
3991 btrfs_abort_transaction(trans, root, ret);
3995 leaf = path->nodes[0];
3996 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3997 btrfs_release_path(path);
4000 btrfs_release_path(path);
4002 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4004 btrfs_abort_transaction(trans, root, ret);
4008 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4009 inode_inc_iversion(dir);
4010 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
4011 ret = btrfs_update_inode_fallback(trans, root, dir);
4013 btrfs_abort_transaction(trans, root, ret);
4015 btrfs_free_path(path);
4019 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4021 struct inode *inode = dentry->d_inode;
4023 struct btrfs_root *root = BTRFS_I(dir)->root;
4024 struct btrfs_trans_handle *trans;
4026 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4028 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
4031 trans = __unlink_start_trans(dir);
4033 return PTR_ERR(trans);
4035 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4036 err = btrfs_unlink_subvol(trans, root, dir,
4037 BTRFS_I(inode)->location.objectid,
4038 dentry->d_name.name,
4039 dentry->d_name.len);
4043 err = btrfs_orphan_add(trans, inode);
4047 /* now the directory is empty */
4048 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
4049 dentry->d_name.name, dentry->d_name.len);
4051 btrfs_i_size_write(inode, 0);
4053 btrfs_end_transaction(trans, root);
4054 btrfs_btree_balance_dirty(root);
4060 * this can truncate away extent items, csum items and directory items.
4061 * It starts at a high offset and removes keys until it can't find
4062 * any higher than new_size
4064 * csum items that cross the new i_size are truncated to the new size
4067 * min_type is the minimum key type to truncate down to. If set to 0, this
4068 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4070 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4071 struct btrfs_root *root,
4072 struct inode *inode,
4073 u64 new_size, u32 min_type)
4075 struct btrfs_path *path;
4076 struct extent_buffer *leaf;
4077 struct btrfs_file_extent_item *fi;
4078 struct btrfs_key key;
4079 struct btrfs_key found_key;
4080 u64 extent_start = 0;
4081 u64 extent_num_bytes = 0;
4082 u64 extent_offset = 0;
4084 u64 last_size = (u64)-1;
4085 u32 found_type = (u8)-1;
4088 int pending_del_nr = 0;
4089 int pending_del_slot = 0;
4090 int extent_type = -1;
4093 u64 ino = btrfs_ino(inode);
4095 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4097 path = btrfs_alloc_path();
4103 * We want to drop from the next block forward in case this new size is
4104 * not block aligned since we will be keeping the last block of the
4105 * extent just the way it is.
4107 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4108 root == root->fs_info->tree_root)
4109 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4110 root->sectorsize), (u64)-1, 0);
4113 * This function is also used to drop the items in the log tree before
4114 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4115 * it is used to drop the loged items. So we shouldn't kill the delayed
4118 if (min_type == 0 && root == BTRFS_I(inode)->root)
4119 btrfs_kill_delayed_inode_items(inode);
4122 key.offset = (u64)-1;
4126 path->leave_spinning = 1;
4127 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4134 /* there are no items in the tree for us to truncate, we're
4137 if (path->slots[0] == 0)
4144 leaf = path->nodes[0];
4145 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4146 found_type = found_key.type;
4148 if (found_key.objectid != ino)
4151 if (found_type < min_type)
4154 item_end = found_key.offset;
4155 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4156 fi = btrfs_item_ptr(leaf, path->slots[0],
4157 struct btrfs_file_extent_item);
4158 extent_type = btrfs_file_extent_type(leaf, fi);
4159 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4161 btrfs_file_extent_num_bytes(leaf, fi);
4162 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4163 item_end += btrfs_file_extent_inline_len(leaf,
4164 path->slots[0], fi);
4168 if (found_type > min_type) {
4171 if (item_end < new_size)
4173 if (found_key.offset >= new_size)
4179 /* FIXME, shrink the extent if the ref count is only 1 */
4180 if (found_type != BTRFS_EXTENT_DATA_KEY)
4184 last_size = found_key.offset;
4186 last_size = new_size;
4188 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4190 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4192 u64 orig_num_bytes =
4193 btrfs_file_extent_num_bytes(leaf, fi);
4194 extent_num_bytes = ALIGN(new_size -
4197 btrfs_set_file_extent_num_bytes(leaf, fi,
4199 num_dec = (orig_num_bytes -
4201 if (test_bit(BTRFS_ROOT_REF_COWS,
4204 inode_sub_bytes(inode, num_dec);
4205 btrfs_mark_buffer_dirty(leaf);
4208 btrfs_file_extent_disk_num_bytes(leaf,
4210 extent_offset = found_key.offset -
4211 btrfs_file_extent_offset(leaf, fi);
4213 /* FIXME blocksize != 4096 */
4214 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4215 if (extent_start != 0) {
4217 if (test_bit(BTRFS_ROOT_REF_COWS,
4219 inode_sub_bytes(inode, num_dec);
4222 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4224 * we can't truncate inline items that have had
4228 btrfs_file_extent_compression(leaf, fi) == 0 &&
4229 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4230 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4231 u32 size = new_size - found_key.offset;
4233 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4234 inode_sub_bytes(inode, item_end + 1 -
4238 * update the ram bytes to properly reflect
4239 * the new size of our item
4241 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4243 btrfs_file_extent_calc_inline_size(size);
4244 btrfs_truncate_item(root, path, size, 1);
4245 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4247 inode_sub_bytes(inode, item_end + 1 -
4253 if (!pending_del_nr) {
4254 /* no pending yet, add ourselves */
4255 pending_del_slot = path->slots[0];
4257 } else if (pending_del_nr &&
4258 path->slots[0] + 1 == pending_del_slot) {
4259 /* hop on the pending chunk */
4261 pending_del_slot = path->slots[0];
4269 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4270 root == root->fs_info->tree_root)) {
4271 btrfs_set_path_blocking(path);
4272 ret = btrfs_free_extent(trans, root, extent_start,
4273 extent_num_bytes, 0,
4274 btrfs_header_owner(leaf),
4275 ino, extent_offset, 0);
4279 if (found_type == BTRFS_INODE_ITEM_KEY)
4282 if (path->slots[0] == 0 ||
4283 path->slots[0] != pending_del_slot) {
4284 if (pending_del_nr) {
4285 ret = btrfs_del_items(trans, root, path,
4289 btrfs_abort_transaction(trans,
4295 btrfs_release_path(path);
4302 if (pending_del_nr) {
4303 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4306 btrfs_abort_transaction(trans, root, ret);
4309 if (last_size != (u64)-1 &&
4310 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4311 btrfs_ordered_update_i_size(inode, last_size, NULL);
4312 btrfs_free_path(path);
4317 * btrfs_truncate_page - read, zero a chunk and write a page
4318 * @inode - inode that we're zeroing
4319 * @from - the offset to start zeroing
4320 * @len - the length to zero, 0 to zero the entire range respective to the
4322 * @front - zero up to the offset instead of from the offset on
4324 * This will find the page for the "from" offset and cow the page and zero the
4325 * part we want to zero. This is used with truncate and hole punching.
4327 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4330 struct address_space *mapping = inode->i_mapping;
4331 struct btrfs_root *root = BTRFS_I(inode)->root;
4332 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4333 struct btrfs_ordered_extent *ordered;
4334 struct extent_state *cached_state = NULL;
4336 u32 blocksize = root->sectorsize;
4337 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4338 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4340 gfp_t mask = btrfs_alloc_write_mask(mapping);
4345 if ((offset & (blocksize - 1)) == 0 &&
4346 (!len || ((len & (blocksize - 1)) == 0)))
4348 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4353 page = find_or_create_page(mapping, index, mask);
4355 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4360 page_start = page_offset(page);
4361 page_end = page_start + PAGE_CACHE_SIZE - 1;
4363 if (!PageUptodate(page)) {
4364 ret = btrfs_readpage(NULL, page);
4366 if (page->mapping != mapping) {
4368 page_cache_release(page);
4371 if (!PageUptodate(page)) {
4376 wait_on_page_writeback(page);
4378 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4379 set_page_extent_mapped(page);
4381 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4383 unlock_extent_cached(io_tree, page_start, page_end,
4384 &cached_state, GFP_NOFS);
4386 page_cache_release(page);
4387 btrfs_start_ordered_extent(inode, ordered, 1);
4388 btrfs_put_ordered_extent(ordered);
4392 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4393 EXTENT_DIRTY | EXTENT_DELALLOC |
4394 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4395 0, 0, &cached_state, GFP_NOFS);
4397 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4400 unlock_extent_cached(io_tree, page_start, page_end,
4401 &cached_state, GFP_NOFS);
4405 if (offset != PAGE_CACHE_SIZE) {
4407 len = PAGE_CACHE_SIZE - offset;
4410 memset(kaddr, 0, offset);
4412 memset(kaddr + offset, 0, len);
4413 flush_dcache_page(page);
4416 ClearPageChecked(page);
4417 set_page_dirty(page);
4418 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4423 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4425 page_cache_release(page);
4430 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4431 u64 offset, u64 len)
4433 struct btrfs_trans_handle *trans;
4437 * Still need to make sure the inode looks like it's been updated so
4438 * that any holes get logged if we fsync.
4440 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4441 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4442 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4443 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4448 * 1 - for the one we're dropping
4449 * 1 - for the one we're adding
4450 * 1 - for updating the inode.
4452 trans = btrfs_start_transaction(root, 3);
4454 return PTR_ERR(trans);
4456 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4458 btrfs_abort_transaction(trans, root, ret);
4459 btrfs_end_transaction(trans, root);
4463 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4464 0, 0, len, 0, len, 0, 0, 0);
4466 btrfs_abort_transaction(trans, root, ret);
4468 btrfs_update_inode(trans, root, inode);
4469 btrfs_end_transaction(trans, root);
4474 * This function puts in dummy file extents for the area we're creating a hole
4475 * for. So if we are truncating this file to a larger size we need to insert
4476 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4477 * the range between oldsize and size
4479 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4481 struct btrfs_root *root = BTRFS_I(inode)->root;
4482 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4483 struct extent_map *em = NULL;
4484 struct extent_state *cached_state = NULL;
4485 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4486 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4487 u64 block_end = ALIGN(size, root->sectorsize);
4494 * If our size started in the middle of a page we need to zero out the
4495 * rest of the page before we expand the i_size, otherwise we could
4496 * expose stale data.
4498 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4502 if (size <= hole_start)
4506 struct btrfs_ordered_extent *ordered;
4508 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4510 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4511 block_end - hole_start);
4514 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4515 &cached_state, GFP_NOFS);
4516 btrfs_start_ordered_extent(inode, ordered, 1);
4517 btrfs_put_ordered_extent(ordered);
4520 cur_offset = hole_start;
4522 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4523 block_end - cur_offset, 0);
4529 last_byte = min(extent_map_end(em), block_end);
4530 last_byte = ALIGN(last_byte , root->sectorsize);
4531 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4532 struct extent_map *hole_em;
4533 hole_size = last_byte - cur_offset;
4535 err = maybe_insert_hole(root, inode, cur_offset,
4539 btrfs_drop_extent_cache(inode, cur_offset,
4540 cur_offset + hole_size - 1, 0);
4541 hole_em = alloc_extent_map();
4543 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4544 &BTRFS_I(inode)->runtime_flags);
4547 hole_em->start = cur_offset;
4548 hole_em->len = hole_size;
4549 hole_em->orig_start = cur_offset;
4551 hole_em->block_start = EXTENT_MAP_HOLE;
4552 hole_em->block_len = 0;
4553 hole_em->orig_block_len = 0;
4554 hole_em->ram_bytes = hole_size;
4555 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4556 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4557 hole_em->generation = root->fs_info->generation;
4560 write_lock(&em_tree->lock);
4561 err = add_extent_mapping(em_tree, hole_em, 1);
4562 write_unlock(&em_tree->lock);
4565 btrfs_drop_extent_cache(inode, cur_offset,
4569 free_extent_map(hole_em);
4572 free_extent_map(em);
4574 cur_offset = last_byte;
4575 if (cur_offset >= block_end)
4578 free_extent_map(em);
4579 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4584 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4586 struct btrfs_root *root = BTRFS_I(inode)->root;
4587 struct btrfs_trans_handle *trans;
4588 loff_t oldsize = i_size_read(inode);
4589 loff_t newsize = attr->ia_size;
4590 int mask = attr->ia_valid;
4594 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4595 * special case where we need to update the times despite not having
4596 * these flags set. For all other operations the VFS set these flags
4597 * explicitly if it wants a timestamp update.
4599 if (newsize != oldsize) {
4600 inode_inc_iversion(inode);
4601 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4602 inode->i_ctime = inode->i_mtime =
4603 current_fs_time(inode->i_sb);
4606 if (newsize > oldsize) {
4607 truncate_pagecache(inode, newsize);
4608 ret = btrfs_cont_expand(inode, oldsize, newsize);
4612 trans = btrfs_start_transaction(root, 1);
4614 return PTR_ERR(trans);
4616 i_size_write(inode, newsize);
4617 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4618 ret = btrfs_update_inode(trans, root, inode);
4619 btrfs_end_transaction(trans, root);
4623 * We're truncating a file that used to have good data down to
4624 * zero. Make sure it gets into the ordered flush list so that
4625 * any new writes get down to disk quickly.
4628 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4629 &BTRFS_I(inode)->runtime_flags);
4632 * 1 for the orphan item we're going to add
4633 * 1 for the orphan item deletion.
4635 trans = btrfs_start_transaction(root, 2);
4637 return PTR_ERR(trans);
4640 * We need to do this in case we fail at _any_ point during the
4641 * actual truncate. Once we do the truncate_setsize we could
4642 * invalidate pages which forces any outstanding ordered io to
4643 * be instantly completed which will give us extents that need
4644 * to be truncated. If we fail to get an orphan inode down we
4645 * could have left over extents that were never meant to live,
4646 * so we need to garuntee from this point on that everything
4647 * will be consistent.
4649 ret = btrfs_orphan_add(trans, inode);
4650 btrfs_end_transaction(trans, root);
4654 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4655 truncate_setsize(inode, newsize);
4657 /* Disable nonlocked read DIO to avoid the end less truncate */
4658 btrfs_inode_block_unlocked_dio(inode);
4659 inode_dio_wait(inode);
4660 btrfs_inode_resume_unlocked_dio(inode);
4662 ret = btrfs_truncate(inode);
4663 if (ret && inode->i_nlink) {
4667 * failed to truncate, disk_i_size is only adjusted down
4668 * as we remove extents, so it should represent the true
4669 * size of the inode, so reset the in memory size and
4670 * delete our orphan entry.
4672 trans = btrfs_join_transaction(root);
4673 if (IS_ERR(trans)) {
4674 btrfs_orphan_del(NULL, inode);
4677 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4678 err = btrfs_orphan_del(trans, inode);
4680 btrfs_abort_transaction(trans, root, err);
4681 btrfs_end_transaction(trans, root);
4688 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4690 struct inode *inode = dentry->d_inode;
4691 struct btrfs_root *root = BTRFS_I(inode)->root;
4694 if (btrfs_root_readonly(root))
4697 err = inode_change_ok(inode, attr);
4701 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4702 err = btrfs_setsize(inode, attr);
4707 if (attr->ia_valid) {
4708 setattr_copy(inode, attr);
4709 inode_inc_iversion(inode);
4710 err = btrfs_dirty_inode(inode);
4712 if (!err && attr->ia_valid & ATTR_MODE)
4713 err = posix_acl_chmod(inode, inode->i_mode);
4720 * While truncating the inode pages during eviction, we get the VFS calling
4721 * btrfs_invalidatepage() against each page of the inode. This is slow because
4722 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4723 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4724 * extent_state structures over and over, wasting lots of time.
4726 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4727 * those expensive operations on a per page basis and do only the ordered io
4728 * finishing, while we release here the extent_map and extent_state structures,
4729 * without the excessive merging and splitting.
4731 static void evict_inode_truncate_pages(struct inode *inode)
4733 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4734 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4735 struct rb_node *node;
4737 ASSERT(inode->i_state & I_FREEING);
4738 truncate_inode_pages_final(&inode->i_data);
4740 write_lock(&map_tree->lock);
4741 while (!RB_EMPTY_ROOT(&map_tree->map)) {
4742 struct extent_map *em;
4744 node = rb_first(&map_tree->map);
4745 em = rb_entry(node, struct extent_map, rb_node);
4746 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4747 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4748 remove_extent_mapping(map_tree, em);
4749 free_extent_map(em);
4750 if (need_resched()) {
4751 write_unlock(&map_tree->lock);
4753 write_lock(&map_tree->lock);
4756 write_unlock(&map_tree->lock);
4758 spin_lock(&io_tree->lock);
4759 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4760 struct extent_state *state;
4761 struct extent_state *cached_state = NULL;
4763 node = rb_first(&io_tree->state);
4764 state = rb_entry(node, struct extent_state, rb_node);
4765 atomic_inc(&state->refs);
4766 spin_unlock(&io_tree->lock);
4768 lock_extent_bits(io_tree, state->start, state->end,
4770 clear_extent_bit(io_tree, state->start, state->end,
4771 EXTENT_LOCKED | EXTENT_DIRTY |
4772 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
4773 EXTENT_DEFRAG, 1, 1,
4774 &cached_state, GFP_NOFS);
4775 free_extent_state(state);
4778 spin_lock(&io_tree->lock);
4780 spin_unlock(&io_tree->lock);
4783 void btrfs_evict_inode(struct inode *inode)
4785 struct btrfs_trans_handle *trans;
4786 struct btrfs_root *root = BTRFS_I(inode)->root;
4787 struct btrfs_block_rsv *rsv, *global_rsv;
4788 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4791 trace_btrfs_inode_evict(inode);
4793 evict_inode_truncate_pages(inode);
4795 if (inode->i_nlink &&
4796 ((btrfs_root_refs(&root->root_item) != 0 &&
4797 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4798 btrfs_is_free_space_inode(inode)))
4801 if (is_bad_inode(inode)) {
4802 btrfs_orphan_del(NULL, inode);
4805 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4806 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4808 btrfs_free_io_failure_record(inode, 0, (u64)-1);
4810 if (root->fs_info->log_root_recovering) {
4811 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4812 &BTRFS_I(inode)->runtime_flags));
4816 if (inode->i_nlink > 0) {
4817 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4818 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4822 ret = btrfs_commit_inode_delayed_inode(inode);
4824 btrfs_orphan_del(NULL, inode);
4828 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4830 btrfs_orphan_del(NULL, inode);
4833 rsv->size = min_size;
4835 global_rsv = &root->fs_info->global_block_rsv;
4837 btrfs_i_size_write(inode, 0);
4840 * This is a bit simpler than btrfs_truncate since we've already
4841 * reserved our space for our orphan item in the unlink, so we just
4842 * need to reserve some slack space in case we add bytes and update
4843 * inode item when doing the truncate.
4846 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4847 BTRFS_RESERVE_FLUSH_LIMIT);
4850 * Try and steal from the global reserve since we will
4851 * likely not use this space anyway, we want to try as
4852 * hard as possible to get this to work.
4855 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4858 btrfs_warn(root->fs_info,
4859 "Could not get space for a delete, will truncate on mount %d",
4861 btrfs_orphan_del(NULL, inode);
4862 btrfs_free_block_rsv(root, rsv);
4866 trans = btrfs_join_transaction(root);
4867 if (IS_ERR(trans)) {
4868 btrfs_orphan_del(NULL, inode);
4869 btrfs_free_block_rsv(root, rsv);
4873 trans->block_rsv = rsv;
4875 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4879 trans->block_rsv = &root->fs_info->trans_block_rsv;
4880 btrfs_end_transaction(trans, root);
4882 btrfs_btree_balance_dirty(root);
4885 btrfs_free_block_rsv(root, rsv);
4888 * Errors here aren't a big deal, it just means we leave orphan items
4889 * in the tree. They will be cleaned up on the next mount.
4892 trans->block_rsv = root->orphan_block_rsv;
4893 btrfs_orphan_del(trans, inode);
4895 btrfs_orphan_del(NULL, inode);
4898 trans->block_rsv = &root->fs_info->trans_block_rsv;
4899 if (!(root == root->fs_info->tree_root ||
4900 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4901 btrfs_return_ino(root, btrfs_ino(inode));
4903 btrfs_end_transaction(trans, root);
4904 btrfs_btree_balance_dirty(root);
4906 btrfs_remove_delayed_node(inode);
4912 * this returns the key found in the dir entry in the location pointer.
4913 * If no dir entries were found, location->objectid is 0.
4915 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4916 struct btrfs_key *location)
4918 const char *name = dentry->d_name.name;
4919 int namelen = dentry->d_name.len;
4920 struct btrfs_dir_item *di;
4921 struct btrfs_path *path;
4922 struct btrfs_root *root = BTRFS_I(dir)->root;
4925 path = btrfs_alloc_path();
4929 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4934 if (IS_ERR_OR_NULL(di))
4937 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4939 btrfs_free_path(path);
4942 location->objectid = 0;
4947 * when we hit a tree root in a directory, the btrfs part of the inode
4948 * needs to be changed to reflect the root directory of the tree root. This
4949 * is kind of like crossing a mount point.
4951 static int fixup_tree_root_location(struct btrfs_root *root,
4953 struct dentry *dentry,
4954 struct btrfs_key *location,
4955 struct btrfs_root **sub_root)
4957 struct btrfs_path *path;
4958 struct btrfs_root *new_root;
4959 struct btrfs_root_ref *ref;
4960 struct extent_buffer *leaf;
4964 path = btrfs_alloc_path();
4971 ret = btrfs_find_item(root->fs_info->tree_root, path,
4972 BTRFS_I(dir)->root->root_key.objectid,
4973 location->objectid, BTRFS_ROOT_REF_KEY, NULL);
4980 leaf = path->nodes[0];
4981 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4982 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4983 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4986 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4987 (unsigned long)(ref + 1),
4988 dentry->d_name.len);
4992 btrfs_release_path(path);
4994 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4995 if (IS_ERR(new_root)) {
4996 err = PTR_ERR(new_root);
5000 *sub_root = new_root;
5001 location->objectid = btrfs_root_dirid(&new_root->root_item);
5002 location->type = BTRFS_INODE_ITEM_KEY;
5003 location->offset = 0;
5006 btrfs_free_path(path);
5010 static void inode_tree_add(struct inode *inode)
5012 struct btrfs_root *root = BTRFS_I(inode)->root;
5013 struct btrfs_inode *entry;
5015 struct rb_node *parent;
5016 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5017 u64 ino = btrfs_ino(inode);
5019 if (inode_unhashed(inode))
5022 spin_lock(&root->inode_lock);
5023 p = &root->inode_tree.rb_node;
5026 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5028 if (ino < btrfs_ino(&entry->vfs_inode))
5029 p = &parent->rb_left;
5030 else if (ino > btrfs_ino(&entry->vfs_inode))
5031 p = &parent->rb_right;
5033 WARN_ON(!(entry->vfs_inode.i_state &
5034 (I_WILL_FREE | I_FREEING)));
5035 rb_replace_node(parent, new, &root->inode_tree);
5036 RB_CLEAR_NODE(parent);
5037 spin_unlock(&root->inode_lock);
5041 rb_link_node(new, parent, p);
5042 rb_insert_color(new, &root->inode_tree);
5043 spin_unlock(&root->inode_lock);
5046 static void inode_tree_del(struct inode *inode)
5048 struct btrfs_root *root = BTRFS_I(inode)->root;
5051 spin_lock(&root->inode_lock);
5052 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5053 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5054 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5055 empty = RB_EMPTY_ROOT(&root->inode_tree);
5057 spin_unlock(&root->inode_lock);
5059 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5060 synchronize_srcu(&root->fs_info->subvol_srcu);
5061 spin_lock(&root->inode_lock);
5062 empty = RB_EMPTY_ROOT(&root->inode_tree);
5063 spin_unlock(&root->inode_lock);
5065 btrfs_add_dead_root(root);
5069 void btrfs_invalidate_inodes(struct btrfs_root *root)
5071 struct rb_node *node;
5072 struct rb_node *prev;
5073 struct btrfs_inode *entry;
5074 struct inode *inode;
5077 if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
5078 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5080 spin_lock(&root->inode_lock);
5082 node = root->inode_tree.rb_node;
5086 entry = rb_entry(node, struct btrfs_inode, rb_node);
5088 if (objectid < btrfs_ino(&entry->vfs_inode))
5089 node = node->rb_left;
5090 else if (objectid > btrfs_ino(&entry->vfs_inode))
5091 node = node->rb_right;
5097 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5098 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
5102 prev = rb_next(prev);
5106 entry = rb_entry(node, struct btrfs_inode, rb_node);
5107 objectid = btrfs_ino(&entry->vfs_inode) + 1;
5108 inode = igrab(&entry->vfs_inode);
5110 spin_unlock(&root->inode_lock);
5111 if (atomic_read(&inode->i_count) > 1)
5112 d_prune_aliases(inode);
5114 * btrfs_drop_inode will have it removed from
5115 * the inode cache when its usage count
5120 spin_lock(&root->inode_lock);
5124 if (cond_resched_lock(&root->inode_lock))
5127 node = rb_next(node);
5129 spin_unlock(&root->inode_lock);
5132 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5134 struct btrfs_iget_args *args = p;
5135 inode->i_ino = args->location->objectid;
5136 memcpy(&BTRFS_I(inode)->location, args->location,
5137 sizeof(*args->location));
5138 BTRFS_I(inode)->root = args->root;
5142 static int btrfs_find_actor(struct inode *inode, void *opaque)
5144 struct btrfs_iget_args *args = opaque;
5145 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5146 args->root == BTRFS_I(inode)->root;
5149 static struct inode *btrfs_iget_locked(struct super_block *s,
5150 struct btrfs_key *location,
5151 struct btrfs_root *root)
5153 struct inode *inode;
5154 struct btrfs_iget_args args;
5155 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5157 args.location = location;
5160 inode = iget5_locked(s, hashval, btrfs_find_actor,
5161 btrfs_init_locked_inode,
5166 /* Get an inode object given its location and corresponding root.
5167 * Returns in *is_new if the inode was read from disk
5169 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5170 struct btrfs_root *root, int *new)
5172 struct inode *inode;
5174 inode = btrfs_iget_locked(s, location, root);
5176 return ERR_PTR(-ENOMEM);
5178 if (inode->i_state & I_NEW) {
5179 btrfs_read_locked_inode(inode);
5180 if (!is_bad_inode(inode)) {
5181 inode_tree_add(inode);
5182 unlock_new_inode(inode);
5186 unlock_new_inode(inode);
5188 inode = ERR_PTR(-ESTALE);
5195 static struct inode *new_simple_dir(struct super_block *s,
5196 struct btrfs_key *key,
5197 struct btrfs_root *root)
5199 struct inode *inode = new_inode(s);
5202 return ERR_PTR(-ENOMEM);
5204 BTRFS_I(inode)->root = root;
5205 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5206 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5208 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5209 inode->i_op = &btrfs_dir_ro_inode_operations;
5210 inode->i_fop = &simple_dir_operations;
5211 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5212 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5217 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5219 struct inode *inode;
5220 struct btrfs_root *root = BTRFS_I(dir)->root;
5221 struct btrfs_root *sub_root = root;
5222 struct btrfs_key location;
5226 if (dentry->d_name.len > BTRFS_NAME_LEN)
5227 return ERR_PTR(-ENAMETOOLONG);
5229 ret = btrfs_inode_by_name(dir, dentry, &location);
5231 return ERR_PTR(ret);
5233 if (location.objectid == 0)
5234 return ERR_PTR(-ENOENT);
5236 if (location.type == BTRFS_INODE_ITEM_KEY) {
5237 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5241 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5243 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5244 ret = fixup_tree_root_location(root, dir, dentry,
5245 &location, &sub_root);
5248 inode = ERR_PTR(ret);
5250 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5252 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5254 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5256 if (!IS_ERR(inode) && root != sub_root) {
5257 down_read(&root->fs_info->cleanup_work_sem);
5258 if (!(inode->i_sb->s_flags & MS_RDONLY))
5259 ret = btrfs_orphan_cleanup(sub_root);
5260 up_read(&root->fs_info->cleanup_work_sem);
5263 inode = ERR_PTR(ret);
5270 static int btrfs_dentry_delete(const struct dentry *dentry)
5272 struct btrfs_root *root;
5273 struct inode *inode = dentry->d_inode;
5275 if (!inode && !IS_ROOT(dentry))
5276 inode = dentry->d_parent->d_inode;
5279 root = BTRFS_I(inode)->root;
5280 if (btrfs_root_refs(&root->root_item) == 0)
5283 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5289 static void btrfs_dentry_release(struct dentry *dentry)
5291 kfree(dentry->d_fsdata);
5294 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5297 struct inode *inode;
5299 inode = btrfs_lookup_dentry(dir, dentry);
5300 if (IS_ERR(inode)) {
5301 if (PTR_ERR(inode) == -ENOENT)
5304 return ERR_CAST(inode);
5307 return d_materialise_unique(dentry, inode);
5310 unsigned char btrfs_filetype_table[] = {
5311 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5314 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5316 struct inode *inode = file_inode(file);
5317 struct btrfs_root *root = BTRFS_I(inode)->root;
5318 struct btrfs_item *item;
5319 struct btrfs_dir_item *di;
5320 struct btrfs_key key;
5321 struct btrfs_key found_key;
5322 struct btrfs_path *path;
5323 struct list_head ins_list;
5324 struct list_head del_list;
5326 struct extent_buffer *leaf;
5328 unsigned char d_type;
5333 int key_type = BTRFS_DIR_INDEX_KEY;
5337 int is_curr = 0; /* ctx->pos points to the current index? */
5339 /* FIXME, use a real flag for deciding about the key type */
5340 if (root->fs_info->tree_root == root)
5341 key_type = BTRFS_DIR_ITEM_KEY;
5343 if (!dir_emit_dots(file, ctx))
5346 path = btrfs_alloc_path();
5352 if (key_type == BTRFS_DIR_INDEX_KEY) {
5353 INIT_LIST_HEAD(&ins_list);
5354 INIT_LIST_HEAD(&del_list);
5355 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5358 key.type = key_type;
5359 key.offset = ctx->pos;
5360 key.objectid = btrfs_ino(inode);
5362 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5367 leaf = path->nodes[0];
5368 slot = path->slots[0];
5369 if (slot >= btrfs_header_nritems(leaf)) {
5370 ret = btrfs_next_leaf(root, path);
5378 item = btrfs_item_nr(slot);
5379 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5381 if (found_key.objectid != key.objectid)
5383 if (found_key.type != key_type)
5385 if (found_key.offset < ctx->pos)
5387 if (key_type == BTRFS_DIR_INDEX_KEY &&
5388 btrfs_should_delete_dir_index(&del_list,
5392 ctx->pos = found_key.offset;
5395 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5397 di_total = btrfs_item_size(leaf, item);
5399 while (di_cur < di_total) {
5400 struct btrfs_key location;
5402 if (verify_dir_item(root, leaf, di))
5405 name_len = btrfs_dir_name_len(leaf, di);
5406 if (name_len <= sizeof(tmp_name)) {
5407 name_ptr = tmp_name;
5409 name_ptr = kmalloc(name_len, GFP_NOFS);
5415 read_extent_buffer(leaf, name_ptr,
5416 (unsigned long)(di + 1), name_len);
5418 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5419 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5422 /* is this a reference to our own snapshot? If so
5425 * In contrast to old kernels, we insert the snapshot's
5426 * dir item and dir index after it has been created, so
5427 * we won't find a reference to our own snapshot. We
5428 * still keep the following code for backward
5431 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5432 location.objectid == root->root_key.objectid) {
5436 over = !dir_emit(ctx, name_ptr, name_len,
5437 location.objectid, d_type);
5440 if (name_ptr != tmp_name)
5445 di_len = btrfs_dir_name_len(leaf, di) +
5446 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5448 di = (struct btrfs_dir_item *)((char *)di + di_len);
5454 if (key_type == BTRFS_DIR_INDEX_KEY) {
5457 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5462 /* Reached end of directory/root. Bump pos past the last item. */
5466 * Stop new entries from being returned after we return the last
5469 * New directory entries are assigned a strictly increasing
5470 * offset. This means that new entries created during readdir
5471 * are *guaranteed* to be seen in the future by that readdir.
5472 * This has broken buggy programs which operate on names as
5473 * they're returned by readdir. Until we re-use freed offsets
5474 * we have this hack to stop new entries from being returned
5475 * under the assumption that they'll never reach this huge
5478 * This is being careful not to overflow 32bit loff_t unless the
5479 * last entry requires it because doing so has broken 32bit apps
5482 if (key_type == BTRFS_DIR_INDEX_KEY) {
5483 if (ctx->pos >= INT_MAX)
5484 ctx->pos = LLONG_MAX;
5491 if (key_type == BTRFS_DIR_INDEX_KEY)
5492 btrfs_put_delayed_items(&ins_list, &del_list);
5493 btrfs_free_path(path);
5497 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5499 struct btrfs_root *root = BTRFS_I(inode)->root;
5500 struct btrfs_trans_handle *trans;
5502 bool nolock = false;
5504 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5507 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5510 if (wbc->sync_mode == WB_SYNC_ALL) {
5512 trans = btrfs_join_transaction_nolock(root);
5514 trans = btrfs_join_transaction(root);
5516 return PTR_ERR(trans);
5517 ret = btrfs_commit_transaction(trans, root);
5523 * This is somewhat expensive, updating the tree every time the
5524 * inode changes. But, it is most likely to find the inode in cache.
5525 * FIXME, needs more benchmarking...there are no reasons other than performance
5526 * to keep or drop this code.
5528 static int btrfs_dirty_inode(struct inode *inode)
5530 struct btrfs_root *root = BTRFS_I(inode)->root;
5531 struct btrfs_trans_handle *trans;
5534 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5537 trans = btrfs_join_transaction(root);
5539 return PTR_ERR(trans);
5541 ret = btrfs_update_inode(trans, root, inode);
5542 if (ret && ret == -ENOSPC) {
5543 /* whoops, lets try again with the full transaction */
5544 btrfs_end_transaction(trans, root);
5545 trans = btrfs_start_transaction(root, 1);
5547 return PTR_ERR(trans);
5549 ret = btrfs_update_inode(trans, root, inode);
5551 btrfs_end_transaction(trans, root);
5552 if (BTRFS_I(inode)->delayed_node)
5553 btrfs_balance_delayed_items(root);
5559 * This is a copy of file_update_time. We need this so we can return error on
5560 * ENOSPC for updating the inode in the case of file write and mmap writes.
5562 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5565 struct btrfs_root *root = BTRFS_I(inode)->root;
5567 if (btrfs_root_readonly(root))
5570 if (flags & S_VERSION)
5571 inode_inc_iversion(inode);
5572 if (flags & S_CTIME)
5573 inode->i_ctime = *now;
5574 if (flags & S_MTIME)
5575 inode->i_mtime = *now;
5576 if (flags & S_ATIME)
5577 inode->i_atime = *now;
5578 return btrfs_dirty_inode(inode);
5582 * find the highest existing sequence number in a directory
5583 * and then set the in-memory index_cnt variable to reflect
5584 * free sequence numbers
5586 static int btrfs_set_inode_index_count(struct inode *inode)
5588 struct btrfs_root *root = BTRFS_I(inode)->root;
5589 struct btrfs_key key, found_key;
5590 struct btrfs_path *path;
5591 struct extent_buffer *leaf;
5594 key.objectid = btrfs_ino(inode);
5595 key.type = BTRFS_DIR_INDEX_KEY;
5596 key.offset = (u64)-1;
5598 path = btrfs_alloc_path();
5602 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5605 /* FIXME: we should be able to handle this */
5611 * MAGIC NUMBER EXPLANATION:
5612 * since we search a directory based on f_pos we have to start at 2
5613 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5614 * else has to start at 2
5616 if (path->slots[0] == 0) {
5617 BTRFS_I(inode)->index_cnt = 2;
5623 leaf = path->nodes[0];
5624 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5626 if (found_key.objectid != btrfs_ino(inode) ||
5627 found_key.type != BTRFS_DIR_INDEX_KEY) {
5628 BTRFS_I(inode)->index_cnt = 2;
5632 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5634 btrfs_free_path(path);
5639 * helper to find a free sequence number in a given directory. This current
5640 * code is very simple, later versions will do smarter things in the btree
5642 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5646 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5647 ret = btrfs_inode_delayed_dir_index_count(dir);
5649 ret = btrfs_set_inode_index_count(dir);
5655 *index = BTRFS_I(dir)->index_cnt;
5656 BTRFS_I(dir)->index_cnt++;
5661 static int btrfs_insert_inode_locked(struct inode *inode)
5663 struct btrfs_iget_args args;
5664 args.location = &BTRFS_I(inode)->location;
5665 args.root = BTRFS_I(inode)->root;
5667 return insert_inode_locked4(inode,
5668 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5669 btrfs_find_actor, &args);
5672 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5673 struct btrfs_root *root,
5675 const char *name, int name_len,
5676 u64 ref_objectid, u64 objectid,
5677 umode_t mode, u64 *index)
5679 struct inode *inode;
5680 struct btrfs_inode_item *inode_item;
5681 struct btrfs_key *location;
5682 struct btrfs_path *path;
5683 struct btrfs_inode_ref *ref;
5684 struct btrfs_key key[2];
5686 int nitems = name ? 2 : 1;
5690 path = btrfs_alloc_path();
5692 return ERR_PTR(-ENOMEM);
5694 inode = new_inode(root->fs_info->sb);
5696 btrfs_free_path(path);
5697 return ERR_PTR(-ENOMEM);
5701 * O_TMPFILE, set link count to 0, so that after this point,
5702 * we fill in an inode item with the correct link count.
5705 set_nlink(inode, 0);
5708 * we have to initialize this early, so we can reclaim the inode
5709 * number if we fail afterwards in this function.
5711 inode->i_ino = objectid;
5714 trace_btrfs_inode_request(dir);
5716 ret = btrfs_set_inode_index(dir, index);
5718 btrfs_free_path(path);
5720 return ERR_PTR(ret);
5726 * index_cnt is ignored for everything but a dir,
5727 * btrfs_get_inode_index_count has an explanation for the magic
5730 BTRFS_I(inode)->index_cnt = 2;
5731 BTRFS_I(inode)->dir_index = *index;
5732 BTRFS_I(inode)->root = root;
5733 BTRFS_I(inode)->generation = trans->transid;
5734 inode->i_generation = BTRFS_I(inode)->generation;
5737 * We could have gotten an inode number from somebody who was fsynced
5738 * and then removed in this same transaction, so let's just set full
5739 * sync since it will be a full sync anyway and this will blow away the
5740 * old info in the log.
5742 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5744 key[0].objectid = objectid;
5745 key[0].type = BTRFS_INODE_ITEM_KEY;
5748 sizes[0] = sizeof(struct btrfs_inode_item);
5752 * Start new inodes with an inode_ref. This is slightly more
5753 * efficient for small numbers of hard links since they will
5754 * be packed into one item. Extended refs will kick in if we
5755 * add more hard links than can fit in the ref item.
5757 key[1].objectid = objectid;
5758 key[1].type = BTRFS_INODE_REF_KEY;
5759 key[1].offset = ref_objectid;
5761 sizes[1] = name_len + sizeof(*ref);
5764 location = &BTRFS_I(inode)->location;
5765 location->objectid = objectid;
5766 location->offset = 0;
5767 location->type = BTRFS_INODE_ITEM_KEY;
5769 ret = btrfs_insert_inode_locked(inode);
5773 path->leave_spinning = 1;
5774 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
5778 inode_init_owner(inode, dir, mode);
5779 inode_set_bytes(inode, 0);
5780 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5781 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5782 struct btrfs_inode_item);
5783 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5784 sizeof(*inode_item));
5785 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5788 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5789 struct btrfs_inode_ref);
5790 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5791 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5792 ptr = (unsigned long)(ref + 1);
5793 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5796 btrfs_mark_buffer_dirty(path->nodes[0]);
5797 btrfs_free_path(path);
5799 btrfs_inherit_iflags(inode, dir);
5801 if (S_ISREG(mode)) {
5802 if (btrfs_test_opt(root, NODATASUM))
5803 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5804 if (btrfs_test_opt(root, NODATACOW))
5805 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5806 BTRFS_INODE_NODATASUM;
5809 inode_tree_add(inode);
5811 trace_btrfs_inode_new(inode);
5812 btrfs_set_inode_last_trans(trans, inode);
5814 btrfs_update_root_times(trans, root);
5816 ret = btrfs_inode_inherit_props(trans, inode, dir);
5818 btrfs_err(root->fs_info,
5819 "error inheriting props for ino %llu (root %llu): %d",
5820 btrfs_ino(inode), root->root_key.objectid, ret);
5825 unlock_new_inode(inode);
5828 BTRFS_I(dir)->index_cnt--;
5829 btrfs_free_path(path);
5831 return ERR_PTR(ret);
5834 static inline u8 btrfs_inode_type(struct inode *inode)
5836 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5840 * utility function to add 'inode' into 'parent_inode' with
5841 * a give name and a given sequence number.
5842 * if 'add_backref' is true, also insert a backref from the
5843 * inode to the parent directory.
5845 int btrfs_add_link(struct btrfs_trans_handle *trans,
5846 struct inode *parent_inode, struct inode *inode,
5847 const char *name, int name_len, int add_backref, u64 index)
5850 struct btrfs_key key;
5851 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5852 u64 ino = btrfs_ino(inode);
5853 u64 parent_ino = btrfs_ino(parent_inode);
5855 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5856 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5859 key.type = BTRFS_INODE_ITEM_KEY;
5863 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5864 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5865 key.objectid, root->root_key.objectid,
5866 parent_ino, index, name, name_len);
5867 } else if (add_backref) {
5868 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5872 /* Nothing to clean up yet */
5876 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5878 btrfs_inode_type(inode), index);
5879 if (ret == -EEXIST || ret == -EOVERFLOW)
5882 btrfs_abort_transaction(trans, root, ret);
5886 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5888 inode_inc_iversion(parent_inode);
5889 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5890 ret = btrfs_update_inode(trans, root, parent_inode);
5892 btrfs_abort_transaction(trans, root, ret);
5896 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5899 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5900 key.objectid, root->root_key.objectid,
5901 parent_ino, &local_index, name, name_len);
5903 } else if (add_backref) {
5907 err = btrfs_del_inode_ref(trans, root, name, name_len,
5908 ino, parent_ino, &local_index);
5913 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5914 struct inode *dir, struct dentry *dentry,
5915 struct inode *inode, int backref, u64 index)
5917 int err = btrfs_add_link(trans, dir, inode,
5918 dentry->d_name.name, dentry->d_name.len,
5925 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5926 umode_t mode, dev_t rdev)
5928 struct btrfs_trans_handle *trans;
5929 struct btrfs_root *root = BTRFS_I(dir)->root;
5930 struct inode *inode = NULL;
5936 if (!new_valid_dev(rdev))
5940 * 2 for inode item and ref
5942 * 1 for xattr if selinux is on
5944 trans = btrfs_start_transaction(root, 5);
5946 return PTR_ERR(trans);
5948 err = btrfs_find_free_ino(root, &objectid);
5952 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5953 dentry->d_name.len, btrfs_ino(dir), objectid,
5955 if (IS_ERR(inode)) {
5956 err = PTR_ERR(inode);
5961 * If the active LSM wants to access the inode during
5962 * d_instantiate it needs these. Smack checks to see
5963 * if the filesystem supports xattrs by looking at the
5966 inode->i_op = &btrfs_special_inode_operations;
5967 init_special_inode(inode, inode->i_mode, rdev);
5969 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5971 goto out_unlock_inode;
5973 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5975 goto out_unlock_inode;
5977 btrfs_update_inode(trans, root, inode);
5978 unlock_new_inode(inode);
5979 d_instantiate(dentry, inode);
5983 btrfs_end_transaction(trans, root);
5984 btrfs_balance_delayed_items(root);
5985 btrfs_btree_balance_dirty(root);
5987 inode_dec_link_count(inode);
5994 unlock_new_inode(inode);
5999 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6000 umode_t mode, bool excl)
6002 struct btrfs_trans_handle *trans;
6003 struct btrfs_root *root = BTRFS_I(dir)->root;
6004 struct inode *inode = NULL;
6005 int drop_inode_on_err = 0;
6011 * 2 for inode item and ref
6013 * 1 for xattr if selinux is on
6015 trans = btrfs_start_transaction(root, 5);
6017 return PTR_ERR(trans);
6019 err = btrfs_find_free_ino(root, &objectid);
6023 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6024 dentry->d_name.len, btrfs_ino(dir), objectid,
6026 if (IS_ERR(inode)) {
6027 err = PTR_ERR(inode);
6030 drop_inode_on_err = 1;
6032 * If the active LSM wants to access the inode during
6033 * d_instantiate it needs these. Smack checks to see
6034 * if the filesystem supports xattrs by looking at the
6037 inode->i_fop = &btrfs_file_operations;
6038 inode->i_op = &btrfs_file_inode_operations;
6039 inode->i_mapping->a_ops = &btrfs_aops;
6040 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
6042 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6044 goto out_unlock_inode;
6046 err = btrfs_update_inode(trans, root, inode);
6048 goto out_unlock_inode;
6050 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6052 goto out_unlock_inode;
6054 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6055 unlock_new_inode(inode);
6056 d_instantiate(dentry, inode);
6059 btrfs_end_transaction(trans, root);
6060 if (err && drop_inode_on_err) {
6061 inode_dec_link_count(inode);
6064 btrfs_balance_delayed_items(root);
6065 btrfs_btree_balance_dirty(root);
6069 unlock_new_inode(inode);
6074 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6075 struct dentry *dentry)
6077 struct btrfs_trans_handle *trans;
6078 struct btrfs_root *root = BTRFS_I(dir)->root;
6079 struct inode *inode = old_dentry->d_inode;
6084 /* do not allow sys_link's with other subvols of the same device */
6085 if (root->objectid != BTRFS_I(inode)->root->objectid)
6088 if (inode->i_nlink >= BTRFS_LINK_MAX)
6091 err = btrfs_set_inode_index(dir, &index);
6096 * 2 items for inode and inode ref
6097 * 2 items for dir items
6098 * 1 item for parent inode
6100 trans = btrfs_start_transaction(root, 5);
6101 if (IS_ERR(trans)) {
6102 err = PTR_ERR(trans);
6106 /* There are several dir indexes for this inode, clear the cache. */
6107 BTRFS_I(inode)->dir_index = 0ULL;
6109 inode_inc_iversion(inode);
6110 inode->i_ctime = CURRENT_TIME;
6112 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6114 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
6119 struct dentry *parent = dentry->d_parent;
6120 err = btrfs_update_inode(trans, root, inode);
6123 if (inode->i_nlink == 1) {
6125 * If new hard link count is 1, it's a file created
6126 * with open(2) O_TMPFILE flag.
6128 err = btrfs_orphan_del(trans, inode);
6132 d_instantiate(dentry, inode);
6133 btrfs_log_new_name(trans, inode, NULL, parent);
6136 btrfs_end_transaction(trans, root);
6137 btrfs_balance_delayed_items(root);
6140 inode_dec_link_count(inode);
6143 btrfs_btree_balance_dirty(root);
6147 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6149 struct inode *inode = NULL;
6150 struct btrfs_trans_handle *trans;
6151 struct btrfs_root *root = BTRFS_I(dir)->root;
6153 int drop_on_err = 0;
6158 * 2 items for inode and ref
6159 * 2 items for dir items
6160 * 1 for xattr if selinux is on
6162 trans = btrfs_start_transaction(root, 5);
6164 return PTR_ERR(trans);
6166 err = btrfs_find_free_ino(root, &objectid);
6170 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6171 dentry->d_name.len, btrfs_ino(dir), objectid,
6172 S_IFDIR | mode, &index);
6173 if (IS_ERR(inode)) {
6174 err = PTR_ERR(inode);
6179 /* these must be set before we unlock the inode */
6180 inode->i_op = &btrfs_dir_inode_operations;
6181 inode->i_fop = &btrfs_dir_file_operations;
6183 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6185 goto out_fail_inode;
6187 btrfs_i_size_write(inode, 0);
6188 err = btrfs_update_inode(trans, root, inode);
6190 goto out_fail_inode;
6192 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6193 dentry->d_name.len, 0, index);
6195 goto out_fail_inode;
6197 d_instantiate(dentry, inode);
6199 * mkdir is special. We're unlocking after we call d_instantiate
6200 * to avoid a race with nfsd calling d_instantiate.
6202 unlock_new_inode(inode);
6206 btrfs_end_transaction(trans, root);
6209 btrfs_balance_delayed_items(root);
6210 btrfs_btree_balance_dirty(root);
6214 unlock_new_inode(inode);
6218 /* Find next extent map of a given extent map, caller needs to ensure locks */
6219 static struct extent_map *next_extent_map(struct extent_map *em)
6221 struct rb_node *next;
6223 next = rb_next(&em->rb_node);
6226 return container_of(next, struct extent_map, rb_node);
6229 static struct extent_map *prev_extent_map(struct extent_map *em)
6231 struct rb_node *prev;
6233 prev = rb_prev(&em->rb_node);
6236 return container_of(prev, struct extent_map, rb_node);
6239 /* helper for btfs_get_extent. Given an existing extent in the tree,
6240 * the existing extent is the nearest extent to map_start,
6241 * and an extent that you want to insert, deal with overlap and insert
6242 * the best fitted new extent into the tree.
6244 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6245 struct extent_map *existing,
6246 struct extent_map *em,
6249 struct extent_map *prev;
6250 struct extent_map *next;
6255 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6257 if (existing->start > map_start) {
6259 prev = prev_extent_map(next);
6262 next = next_extent_map(prev);
6265 start = prev ? extent_map_end(prev) : em->start;
6266 start = max_t(u64, start, em->start);
6267 end = next ? next->start : extent_map_end(em);
6268 end = min_t(u64, end, extent_map_end(em));
6269 start_diff = start - em->start;
6271 em->len = end - start;
6272 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6273 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6274 em->block_start += start_diff;
6275 em->block_len -= start_diff;
6277 return add_extent_mapping(em_tree, em, 0);
6280 static noinline int uncompress_inline(struct btrfs_path *path,
6281 struct inode *inode, struct page *page,
6282 size_t pg_offset, u64 extent_offset,
6283 struct btrfs_file_extent_item *item)
6286 struct extent_buffer *leaf = path->nodes[0];
6289 unsigned long inline_size;
6293 WARN_ON(pg_offset != 0);
6294 compress_type = btrfs_file_extent_compression(leaf, item);
6295 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6296 inline_size = btrfs_file_extent_inline_item_len(leaf,
6297 btrfs_item_nr(path->slots[0]));
6298 tmp = kmalloc(inline_size, GFP_NOFS);
6301 ptr = btrfs_file_extent_inline_start(item);
6303 read_extent_buffer(leaf, tmp, ptr, inline_size);
6305 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6306 ret = btrfs_decompress(compress_type, tmp, page,
6307 extent_offset, inline_size, max_size);
6313 * a bit scary, this does extent mapping from logical file offset to the disk.
6314 * the ugly parts come from merging extents from the disk with the in-ram
6315 * representation. This gets more complex because of the data=ordered code,
6316 * where the in-ram extents might be locked pending data=ordered completion.
6318 * This also copies inline extents directly into the page.
6321 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6322 size_t pg_offset, u64 start, u64 len,
6327 u64 extent_start = 0;
6329 u64 objectid = btrfs_ino(inode);
6331 struct btrfs_path *path = NULL;
6332 struct btrfs_root *root = BTRFS_I(inode)->root;
6333 struct btrfs_file_extent_item *item;
6334 struct extent_buffer *leaf;
6335 struct btrfs_key found_key;
6336 struct extent_map *em = NULL;
6337 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6338 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6339 struct btrfs_trans_handle *trans = NULL;
6340 const bool new_inline = !page || create;
6343 read_lock(&em_tree->lock);
6344 em = lookup_extent_mapping(em_tree, start, len);
6346 em->bdev = root->fs_info->fs_devices->latest_bdev;
6347 read_unlock(&em_tree->lock);
6350 if (em->start > start || em->start + em->len <= start)
6351 free_extent_map(em);
6352 else if (em->block_start == EXTENT_MAP_INLINE && page)
6353 free_extent_map(em);
6357 em = alloc_extent_map();
6362 em->bdev = root->fs_info->fs_devices->latest_bdev;
6363 em->start = EXTENT_MAP_HOLE;
6364 em->orig_start = EXTENT_MAP_HOLE;
6366 em->block_len = (u64)-1;
6369 path = btrfs_alloc_path();
6375 * Chances are we'll be called again, so go ahead and do
6381 ret = btrfs_lookup_file_extent(trans, root, path,
6382 objectid, start, trans != NULL);
6389 if (path->slots[0] == 0)
6394 leaf = path->nodes[0];
6395 item = btrfs_item_ptr(leaf, path->slots[0],
6396 struct btrfs_file_extent_item);
6397 /* are we inside the extent that was found? */
6398 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6399 found_type = found_key.type;
6400 if (found_key.objectid != objectid ||
6401 found_type != BTRFS_EXTENT_DATA_KEY) {
6403 * If we backup past the first extent we want to move forward
6404 * and see if there is an extent in front of us, otherwise we'll
6405 * say there is a hole for our whole search range which can
6412 found_type = btrfs_file_extent_type(leaf, item);
6413 extent_start = found_key.offset;
6414 if (found_type == BTRFS_FILE_EXTENT_REG ||
6415 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6416 extent_end = extent_start +
6417 btrfs_file_extent_num_bytes(leaf, item);
6418 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6420 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6421 extent_end = ALIGN(extent_start + size, root->sectorsize);
6424 if (start >= extent_end) {
6426 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6427 ret = btrfs_next_leaf(root, path);
6434 leaf = path->nodes[0];
6436 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6437 if (found_key.objectid != objectid ||
6438 found_key.type != BTRFS_EXTENT_DATA_KEY)
6440 if (start + len <= found_key.offset)
6442 if (start > found_key.offset)
6445 em->orig_start = start;
6446 em->len = found_key.offset - start;
6450 btrfs_extent_item_to_extent_map(inode, path, item, new_inline, em);
6452 if (found_type == BTRFS_FILE_EXTENT_REG ||
6453 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6455 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6459 size_t extent_offset;
6465 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6466 extent_offset = page_offset(page) + pg_offset - extent_start;
6467 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6468 size - extent_offset);
6469 em->start = extent_start + extent_offset;
6470 em->len = ALIGN(copy_size, root->sectorsize);
6471 em->orig_block_len = em->len;
6472 em->orig_start = em->start;
6473 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6474 if (create == 0 && !PageUptodate(page)) {
6475 if (btrfs_file_extent_compression(leaf, item) !=
6476 BTRFS_COMPRESS_NONE) {
6477 ret = uncompress_inline(path, inode, page,
6479 extent_offset, item);
6486 read_extent_buffer(leaf, map + pg_offset, ptr,
6488 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6489 memset(map + pg_offset + copy_size, 0,
6490 PAGE_CACHE_SIZE - pg_offset -
6495 flush_dcache_page(page);
6496 } else if (create && PageUptodate(page)) {
6500 free_extent_map(em);
6503 btrfs_release_path(path);
6504 trans = btrfs_join_transaction(root);
6507 return ERR_CAST(trans);
6511 write_extent_buffer(leaf, map + pg_offset, ptr,
6514 btrfs_mark_buffer_dirty(leaf);
6516 set_extent_uptodate(io_tree, em->start,
6517 extent_map_end(em) - 1, NULL, GFP_NOFS);
6522 em->orig_start = start;
6525 em->block_start = EXTENT_MAP_HOLE;
6526 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6528 btrfs_release_path(path);
6529 if (em->start > start || extent_map_end(em) <= start) {
6530 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6531 em->start, em->len, start, len);
6537 write_lock(&em_tree->lock);
6538 ret = add_extent_mapping(em_tree, em, 0);
6539 /* it is possible that someone inserted the extent into the tree
6540 * while we had the lock dropped. It is also possible that
6541 * an overlapping map exists in the tree
6543 if (ret == -EEXIST) {
6544 struct extent_map *existing;
6548 existing = search_extent_mapping(em_tree, start, len);
6550 * existing will always be non-NULL, since there must be
6551 * extent causing the -EEXIST.
6553 if (start >= extent_map_end(existing) ||
6554 start <= existing->start) {
6556 * The existing extent map is the one nearest to
6557 * the [start, start + len) range which overlaps
6559 err = merge_extent_mapping(em_tree, existing,
6561 free_extent_map(existing);
6563 free_extent_map(em);
6567 free_extent_map(em);
6572 write_unlock(&em_tree->lock);
6575 trace_btrfs_get_extent(root, em);
6578 btrfs_free_path(path);
6580 ret = btrfs_end_transaction(trans, root);
6585 free_extent_map(em);
6586 return ERR_PTR(err);
6588 BUG_ON(!em); /* Error is always set */
6592 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6593 size_t pg_offset, u64 start, u64 len,
6596 struct extent_map *em;
6597 struct extent_map *hole_em = NULL;
6598 u64 range_start = start;
6604 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6611 * - a pre-alloc extent,
6612 * there might actually be delalloc bytes behind it.
6614 if (em->block_start != EXTENT_MAP_HOLE &&
6615 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6621 /* check to see if we've wrapped (len == -1 or similar) */
6630 /* ok, we didn't find anything, lets look for delalloc */
6631 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6632 end, len, EXTENT_DELALLOC, 1);
6633 found_end = range_start + found;
6634 if (found_end < range_start)
6635 found_end = (u64)-1;
6638 * we didn't find anything useful, return
6639 * the original results from get_extent()
6641 if (range_start > end || found_end <= start) {
6647 /* adjust the range_start to make sure it doesn't
6648 * go backwards from the start they passed in
6650 range_start = max(start, range_start);
6651 found = found_end - range_start;
6654 u64 hole_start = start;
6657 em = alloc_extent_map();
6663 * when btrfs_get_extent can't find anything it
6664 * returns one huge hole
6666 * make sure what it found really fits our range, and
6667 * adjust to make sure it is based on the start from
6671 u64 calc_end = extent_map_end(hole_em);
6673 if (calc_end <= start || (hole_em->start > end)) {
6674 free_extent_map(hole_em);
6677 hole_start = max(hole_em->start, start);
6678 hole_len = calc_end - hole_start;
6682 if (hole_em && range_start > hole_start) {
6683 /* our hole starts before our delalloc, so we
6684 * have to return just the parts of the hole
6685 * that go until the delalloc starts
6687 em->len = min(hole_len,
6688 range_start - hole_start);
6689 em->start = hole_start;
6690 em->orig_start = hole_start;
6692 * don't adjust block start at all,
6693 * it is fixed at EXTENT_MAP_HOLE
6695 em->block_start = hole_em->block_start;
6696 em->block_len = hole_len;
6697 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6698 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6700 em->start = range_start;
6702 em->orig_start = range_start;
6703 em->block_start = EXTENT_MAP_DELALLOC;
6704 em->block_len = found;
6706 } else if (hole_em) {
6711 free_extent_map(hole_em);
6713 free_extent_map(em);
6714 return ERR_PTR(err);
6719 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6722 struct btrfs_root *root = BTRFS_I(inode)->root;
6723 struct extent_map *em;
6724 struct btrfs_key ins;
6728 alloc_hint = get_extent_allocation_hint(inode, start, len);
6729 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
6730 alloc_hint, &ins, 1, 1);
6732 return ERR_PTR(ret);
6734 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6735 ins.offset, ins.offset, ins.offset, 0);
6737 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
6741 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6742 ins.offset, ins.offset, 0);
6744 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
6745 free_extent_map(em);
6746 return ERR_PTR(ret);
6753 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6754 * block must be cow'd
6756 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6757 u64 *orig_start, u64 *orig_block_len,
6760 struct btrfs_trans_handle *trans;
6761 struct btrfs_path *path;
6763 struct extent_buffer *leaf;
6764 struct btrfs_root *root = BTRFS_I(inode)->root;
6765 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6766 struct btrfs_file_extent_item *fi;
6767 struct btrfs_key key;
6774 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6776 path = btrfs_alloc_path();
6780 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
6785 slot = path->slots[0];
6788 /* can't find the item, must cow */
6795 leaf = path->nodes[0];
6796 btrfs_item_key_to_cpu(leaf, &key, slot);
6797 if (key.objectid != btrfs_ino(inode) ||
6798 key.type != BTRFS_EXTENT_DATA_KEY) {
6799 /* not our file or wrong item type, must cow */
6803 if (key.offset > offset) {
6804 /* Wrong offset, must cow */
6808 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6809 found_type = btrfs_file_extent_type(leaf, fi);
6810 if (found_type != BTRFS_FILE_EXTENT_REG &&
6811 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6812 /* not a regular extent, must cow */
6816 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6819 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6820 if (extent_end <= offset)
6823 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6824 if (disk_bytenr == 0)
6827 if (btrfs_file_extent_compression(leaf, fi) ||
6828 btrfs_file_extent_encryption(leaf, fi) ||
6829 btrfs_file_extent_other_encoding(leaf, fi))
6832 backref_offset = btrfs_file_extent_offset(leaf, fi);
6835 *orig_start = key.offset - backref_offset;
6836 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6837 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6840 if (btrfs_extent_readonly(root, disk_bytenr))
6843 num_bytes = min(offset + *len, extent_end) - offset;
6844 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6847 range_end = round_up(offset + num_bytes, root->sectorsize) - 1;
6848 ret = test_range_bit(io_tree, offset, range_end,
6849 EXTENT_DELALLOC, 0, NULL);
6856 btrfs_release_path(path);
6859 * look for other files referencing this extent, if we
6860 * find any we must cow
6862 trans = btrfs_join_transaction(root);
6863 if (IS_ERR(trans)) {
6868 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6869 key.offset - backref_offset, disk_bytenr);
6870 btrfs_end_transaction(trans, root);
6877 * adjust disk_bytenr and num_bytes to cover just the bytes
6878 * in this extent we are about to write. If there
6879 * are any csums in that range we have to cow in order
6880 * to keep the csums correct
6882 disk_bytenr += backref_offset;
6883 disk_bytenr += offset - key.offset;
6884 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6887 * all of the above have passed, it is safe to overwrite this extent
6893 btrfs_free_path(path);
6897 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
6899 struct radix_tree_root *root = &inode->i_mapping->page_tree;
6901 void **pagep = NULL;
6902 struct page *page = NULL;
6906 start_idx = start >> PAGE_CACHE_SHIFT;
6909 * end is the last byte in the last page. end == start is legal
6911 end_idx = end >> PAGE_CACHE_SHIFT;
6915 /* Most of the code in this while loop is lifted from
6916 * find_get_page. It's been modified to begin searching from a
6917 * page and return just the first page found in that range. If the
6918 * found idx is less than or equal to the end idx then we know that
6919 * a page exists. If no pages are found or if those pages are
6920 * outside of the range then we're fine (yay!) */
6921 while (page == NULL &&
6922 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
6923 page = radix_tree_deref_slot(pagep);
6924 if (unlikely(!page))
6927 if (radix_tree_exception(page)) {
6928 if (radix_tree_deref_retry(page)) {
6933 * Otherwise, shmem/tmpfs must be storing a swap entry
6934 * here as an exceptional entry: so return it without
6935 * attempting to raise page count.
6938 break; /* TODO: Is this relevant for this use case? */
6941 if (!page_cache_get_speculative(page)) {
6947 * Has the page moved?
6948 * This is part of the lockless pagecache protocol. See
6949 * include/linux/pagemap.h for details.
6951 if (unlikely(page != *pagep)) {
6952 page_cache_release(page);
6958 if (page->index <= end_idx)
6960 page_cache_release(page);
6967 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6968 struct extent_state **cached_state, int writing)
6970 struct btrfs_ordered_extent *ordered;
6974 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6977 * We're concerned with the entire range that we're going to be
6978 * doing DIO to, so we need to make sure theres no ordered
6979 * extents in this range.
6981 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6982 lockend - lockstart + 1);
6985 * We need to make sure there are no buffered pages in this
6986 * range either, we could have raced between the invalidate in
6987 * generic_file_direct_write and locking the extent. The
6988 * invalidate needs to happen so that reads after a write do not
6993 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
6996 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6997 cached_state, GFP_NOFS);
7000 btrfs_start_ordered_extent(inode, ordered, 1);
7001 btrfs_put_ordered_extent(ordered);
7003 /* Screw you mmap */
7004 ret = filemap_write_and_wait_range(inode->i_mapping,
7011 * If we found a page that couldn't be invalidated just
7012 * fall back to buffered.
7014 ret = invalidate_inode_pages2_range(inode->i_mapping,
7015 lockstart >> PAGE_CACHE_SHIFT,
7016 lockend >> PAGE_CACHE_SHIFT);
7027 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
7028 u64 len, u64 orig_start,
7029 u64 block_start, u64 block_len,
7030 u64 orig_block_len, u64 ram_bytes,
7033 struct extent_map_tree *em_tree;
7034 struct extent_map *em;
7035 struct btrfs_root *root = BTRFS_I(inode)->root;
7038 em_tree = &BTRFS_I(inode)->extent_tree;
7039 em = alloc_extent_map();
7041 return ERR_PTR(-ENOMEM);
7044 em->orig_start = orig_start;
7045 em->mod_start = start;
7048 em->block_len = block_len;
7049 em->block_start = block_start;
7050 em->bdev = root->fs_info->fs_devices->latest_bdev;
7051 em->orig_block_len = orig_block_len;
7052 em->ram_bytes = ram_bytes;
7053 em->generation = -1;
7054 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7055 if (type == BTRFS_ORDERED_PREALLOC)
7056 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7059 btrfs_drop_extent_cache(inode, em->start,
7060 em->start + em->len - 1, 0);
7061 write_lock(&em_tree->lock);
7062 ret = add_extent_mapping(em_tree, em, 1);
7063 write_unlock(&em_tree->lock);
7064 } while (ret == -EEXIST);
7067 free_extent_map(em);
7068 return ERR_PTR(ret);
7075 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7076 struct buffer_head *bh_result, int create)
7078 struct extent_map *em;
7079 struct btrfs_root *root = BTRFS_I(inode)->root;
7080 struct extent_state *cached_state = NULL;
7081 u64 start = iblock << inode->i_blkbits;
7082 u64 lockstart, lockend;
7083 u64 len = bh_result->b_size;
7084 int unlock_bits = EXTENT_LOCKED;
7088 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
7090 len = min_t(u64, len, root->sectorsize);
7093 lockend = start + len - 1;
7096 * If this errors out it's because we couldn't invalidate pagecache for
7097 * this range and we need to fallback to buffered.
7099 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
7102 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7109 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7110 * io. INLINE is special, and we could probably kludge it in here, but
7111 * it's still buffered so for safety lets just fall back to the generic
7114 * For COMPRESSED we _have_ to read the entire extent in so we can
7115 * decompress it, so there will be buffering required no matter what we
7116 * do, so go ahead and fallback to buffered.
7118 * We return -ENOTBLK because thats what makes DIO go ahead and go back
7119 * to buffered IO. Don't blame me, this is the price we pay for using
7122 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7123 em->block_start == EXTENT_MAP_INLINE) {
7124 free_extent_map(em);
7129 /* Just a good old fashioned hole, return */
7130 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7131 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7132 free_extent_map(em);
7137 * We don't allocate a new extent in the following cases
7139 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7141 * 2) The extent is marked as PREALLOC. We're good to go here and can
7142 * just use the extent.
7146 len = min(len, em->len - (start - em->start));
7147 lockstart = start + len;
7151 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7152 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7153 em->block_start != EXTENT_MAP_HOLE)) {
7156 u64 block_start, orig_start, orig_block_len, ram_bytes;
7158 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7159 type = BTRFS_ORDERED_PREALLOC;
7161 type = BTRFS_ORDERED_NOCOW;
7162 len = min(len, em->len - (start - em->start));
7163 block_start = em->block_start + (start - em->start);
7165 if (can_nocow_extent(inode, start, &len, &orig_start,
7166 &orig_block_len, &ram_bytes) == 1) {
7167 if (type == BTRFS_ORDERED_PREALLOC) {
7168 free_extent_map(em);
7169 em = create_pinned_em(inode, start, len,
7180 ret = btrfs_add_ordered_extent_dio(inode, start,
7181 block_start, len, len, type);
7183 free_extent_map(em);
7191 * this will cow the extent, reset the len in case we changed
7194 len = bh_result->b_size;
7195 free_extent_map(em);
7196 em = btrfs_new_extent_direct(inode, start, len);
7201 len = min(len, em->len - (start - em->start));
7203 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7205 bh_result->b_size = len;
7206 bh_result->b_bdev = em->bdev;
7207 set_buffer_mapped(bh_result);
7209 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7210 set_buffer_new(bh_result);
7213 * Need to update the i_size under the extent lock so buffered
7214 * readers will get the updated i_size when we unlock.
7216 if (start + len > i_size_read(inode))
7217 i_size_write(inode, start + len);
7219 spin_lock(&BTRFS_I(inode)->lock);
7220 BTRFS_I(inode)->outstanding_extents++;
7221 spin_unlock(&BTRFS_I(inode)->lock);
7223 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7224 lockstart + len - 1, EXTENT_DELALLOC, NULL,
7225 &cached_state, GFP_NOFS);
7230 * In the case of write we need to clear and unlock the entire range,
7231 * in the case of read we need to unlock only the end area that we
7232 * aren't using if there is any left over space.
7234 if (lockstart < lockend) {
7235 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7236 lockend, unlock_bits, 1, 0,
7237 &cached_state, GFP_NOFS);
7239 free_extent_state(cached_state);
7242 free_extent_map(em);
7247 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7248 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7252 static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7253 int rw, int mirror_num)
7255 struct btrfs_root *root = BTRFS_I(inode)->root;
7258 BUG_ON(rw & REQ_WRITE);
7262 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7263 BTRFS_WQ_ENDIO_DIO_REPAIR);
7267 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
7273 static int btrfs_check_dio_repairable(struct inode *inode,
7274 struct bio *failed_bio,
7275 struct io_failure_record *failrec,
7280 num_copies = btrfs_num_copies(BTRFS_I(inode)->root->fs_info,
7281 failrec->logical, failrec->len);
7282 if (num_copies == 1) {
7284 * we only have a single copy of the data, so don't bother with
7285 * all the retry and error correction code that follows. no
7286 * matter what the error is, it is very likely to persist.
7288 pr_debug("Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d\n",
7289 num_copies, failrec->this_mirror, failed_mirror);
7293 failrec->failed_mirror = failed_mirror;
7294 failrec->this_mirror++;
7295 if (failrec->this_mirror == failed_mirror)
7296 failrec->this_mirror++;
7298 if (failrec->this_mirror > num_copies) {
7299 pr_debug("Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d\n",
7300 num_copies, failrec->this_mirror, failed_mirror);
7307 static int dio_read_error(struct inode *inode, struct bio *failed_bio,
7308 struct page *page, u64 start, u64 end,
7309 int failed_mirror, bio_end_io_t *repair_endio,
7312 struct io_failure_record *failrec;
7318 BUG_ON(failed_bio->bi_rw & REQ_WRITE);
7320 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7324 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7327 free_io_failure(inode, failrec);
7331 if (failed_bio->bi_vcnt > 1)
7332 read_mode = READ_SYNC | REQ_FAILFAST_DEV;
7334 read_mode = READ_SYNC;
7336 isector = start - btrfs_io_bio(failed_bio)->logical;
7337 isector >>= inode->i_sb->s_blocksize_bits;
7338 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7339 0, isector, repair_endio, repair_arg);
7341 free_io_failure(inode, failrec);
7345 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7346 "Repair DIO Read Error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d\n",
7347 read_mode, failrec->this_mirror, failrec->in_validation);
7349 ret = submit_dio_repair_bio(inode, bio, read_mode,
7350 failrec->this_mirror);
7352 free_io_failure(inode, failrec);
7359 struct btrfs_retry_complete {
7360 struct completion done;
7361 struct inode *inode;
7366 static void btrfs_retry_endio_nocsum(struct bio *bio, int err)
7368 struct btrfs_retry_complete *done = bio->bi_private;
7369 struct bio_vec *bvec;
7376 bio_for_each_segment_all(bvec, bio, i)
7377 clean_io_failure(done->inode, done->start, bvec->bv_page, 0);
7379 complete(&done->done);
7383 static int __btrfs_correct_data_nocsum(struct inode *inode,
7384 struct btrfs_io_bio *io_bio)
7386 struct bio_vec *bvec;
7387 struct btrfs_retry_complete done;
7392 start = io_bio->logical;
7395 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7399 init_completion(&done.done);
7401 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7402 start + bvec->bv_len - 1,
7404 btrfs_retry_endio_nocsum, &done);
7408 wait_for_completion(&done.done);
7410 if (!done.uptodate) {
7411 /* We might have another mirror, so try again */
7415 start += bvec->bv_len;
7421 static void btrfs_retry_endio(struct bio *bio, int err)
7423 struct btrfs_retry_complete *done = bio->bi_private;
7424 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7425 struct bio_vec *bvec;
7434 bio_for_each_segment_all(bvec, bio, i) {
7435 ret = __readpage_endio_check(done->inode, io_bio, i,
7437 done->start, bvec->bv_len);
7439 clean_io_failure(done->inode, done->start,
7445 done->uptodate = uptodate;
7447 complete(&done->done);
7451 static int __btrfs_subio_endio_read(struct inode *inode,
7452 struct btrfs_io_bio *io_bio, int err)
7454 struct bio_vec *bvec;
7455 struct btrfs_retry_complete done;
7462 start = io_bio->logical;
7465 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7466 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7467 0, start, bvec->bv_len);
7473 init_completion(&done.done);
7475 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7476 start + bvec->bv_len - 1,
7478 btrfs_retry_endio, &done);
7484 wait_for_completion(&done.done);
7486 if (!done.uptodate) {
7487 /* We might have another mirror, so try again */
7491 offset += bvec->bv_len;
7492 start += bvec->bv_len;
7498 static int btrfs_subio_endio_read(struct inode *inode,
7499 struct btrfs_io_bio *io_bio, int err)
7501 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7505 return __btrfs_correct_data_nocsum(inode, io_bio);
7509 return __btrfs_subio_endio_read(inode, io_bio, err);
7513 static void btrfs_endio_direct_read(struct bio *bio, int err)
7515 struct btrfs_dio_private *dip = bio->bi_private;
7516 struct inode *inode = dip->inode;
7517 struct bio *dio_bio;
7518 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7520 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
7521 err = btrfs_subio_endio_read(inode, io_bio, err);
7523 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
7524 dip->logical_offset + dip->bytes - 1);
7525 dio_bio = dip->dio_bio;
7529 /* If we had a csum failure make sure to clear the uptodate flag */
7531 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7532 dio_end_io(dio_bio, err);
7535 io_bio->end_io(io_bio, err);
7539 static void btrfs_endio_direct_write(struct bio *bio, int err)
7541 struct btrfs_dio_private *dip = bio->bi_private;
7542 struct inode *inode = dip->inode;
7543 struct btrfs_root *root = BTRFS_I(inode)->root;
7544 struct btrfs_ordered_extent *ordered = NULL;
7545 u64 ordered_offset = dip->logical_offset;
7546 u64 ordered_bytes = dip->bytes;
7547 struct bio *dio_bio;
7553 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7555 ordered_bytes, !err);
7559 btrfs_init_work(&ordered->work, btrfs_endio_write_helper,
7560 finish_ordered_fn, NULL, NULL);
7561 btrfs_queue_work(root->fs_info->endio_write_workers,
7565 * our bio might span multiple ordered extents. If we haven't
7566 * completed the accounting for the whole dio, go back and try again
7568 if (ordered_offset < dip->logical_offset + dip->bytes) {
7569 ordered_bytes = dip->logical_offset + dip->bytes -
7575 dio_bio = dip->dio_bio;
7579 /* If we had an error make sure to clear the uptodate flag */
7581 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7582 dio_end_io(dio_bio, err);
7586 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7587 struct bio *bio, int mirror_num,
7588 unsigned long bio_flags, u64 offset)
7591 struct btrfs_root *root = BTRFS_I(inode)->root;
7592 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7593 BUG_ON(ret); /* -ENOMEM */
7597 static void btrfs_end_dio_bio(struct bio *bio, int err)
7599 struct btrfs_dio_private *dip = bio->bi_private;
7602 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7603 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
7604 btrfs_ino(dip->inode), bio->bi_rw,
7605 (unsigned long long)bio->bi_iter.bi_sector,
7606 bio->bi_iter.bi_size, err);
7608 if (dip->subio_endio)
7609 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
7615 * before atomic variable goto zero, we must make sure
7616 * dip->errors is perceived to be set.
7618 smp_mb__before_atomic();
7621 /* if there are more bios still pending for this dio, just exit */
7622 if (!atomic_dec_and_test(&dip->pending_bios))
7626 bio_io_error(dip->orig_bio);
7628 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
7629 bio_endio(dip->orig_bio, 0);
7635 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7636 u64 first_sector, gfp_t gfp_flags)
7638 int nr_vecs = bio_get_nr_vecs(bdev);
7639 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7642 static inline int btrfs_lookup_and_bind_dio_csum(struct btrfs_root *root,
7643 struct inode *inode,
7644 struct btrfs_dio_private *dip,
7648 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7649 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
7653 * We load all the csum data we need when we submit
7654 * the first bio to reduce the csum tree search and
7657 if (dip->logical_offset == file_offset) {
7658 ret = btrfs_lookup_bio_sums_dio(root, inode, dip->orig_bio,
7664 if (bio == dip->orig_bio)
7667 file_offset -= dip->logical_offset;
7668 file_offset >>= inode->i_sb->s_blocksize_bits;
7669 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
7674 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7675 int rw, u64 file_offset, int skip_sum,
7678 struct btrfs_dio_private *dip = bio->bi_private;
7679 int write = rw & REQ_WRITE;
7680 struct btrfs_root *root = BTRFS_I(inode)->root;
7684 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7689 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7690 BTRFS_WQ_ENDIO_DATA);
7698 if (write && async_submit) {
7699 ret = btrfs_wq_submit_bio(root->fs_info,
7700 inode, rw, bio, 0, 0,
7702 __btrfs_submit_bio_start_direct_io,
7703 __btrfs_submit_bio_done);
7707 * If we aren't doing async submit, calculate the csum of the
7710 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7714 ret = btrfs_lookup_and_bind_dio_csum(root, inode, dip, bio,
7720 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7726 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7729 struct inode *inode = dip->inode;
7730 struct btrfs_root *root = BTRFS_I(inode)->root;
7732 struct bio *orig_bio = dip->orig_bio;
7733 struct bio_vec *bvec = orig_bio->bi_io_vec;
7734 u64 start_sector = orig_bio->bi_iter.bi_sector;
7735 u64 file_offset = dip->logical_offset;
7740 int async_submit = 0;
7742 map_length = orig_bio->bi_iter.bi_size;
7743 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7744 &map_length, NULL, 0);
7748 if (map_length >= orig_bio->bi_iter.bi_size) {
7750 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
7754 /* async crcs make it difficult to collect full stripe writes. */
7755 if (btrfs_get_alloc_profile(root, 1) &
7756 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7761 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7765 bio->bi_private = dip;
7766 bio->bi_end_io = btrfs_end_dio_bio;
7767 btrfs_io_bio(bio)->logical = file_offset;
7768 atomic_inc(&dip->pending_bios);
7770 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7771 if (map_length < submit_len + bvec->bv_len ||
7772 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7773 bvec->bv_offset) < bvec->bv_len) {
7775 * inc the count before we submit the bio so
7776 * we know the end IO handler won't happen before
7777 * we inc the count. Otherwise, the dip might get freed
7778 * before we're done setting it up
7780 atomic_inc(&dip->pending_bios);
7781 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7782 file_offset, skip_sum,
7786 atomic_dec(&dip->pending_bios);
7790 start_sector += submit_len >> 9;
7791 file_offset += submit_len;
7796 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7797 start_sector, GFP_NOFS);
7800 bio->bi_private = dip;
7801 bio->bi_end_io = btrfs_end_dio_bio;
7802 btrfs_io_bio(bio)->logical = file_offset;
7804 map_length = orig_bio->bi_iter.bi_size;
7805 ret = btrfs_map_block(root->fs_info, rw,
7807 &map_length, NULL, 0);
7813 submit_len += bvec->bv_len;
7820 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7829 * before atomic variable goto zero, we must
7830 * make sure dip->errors is perceived to be set.
7832 smp_mb__before_atomic();
7833 if (atomic_dec_and_test(&dip->pending_bios))
7834 bio_io_error(dip->orig_bio);
7836 /* bio_end_io() will handle error, so we needn't return it */
7840 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7841 struct inode *inode, loff_t file_offset)
7843 struct btrfs_root *root = BTRFS_I(inode)->root;
7844 struct btrfs_dio_private *dip;
7846 struct btrfs_io_bio *btrfs_bio;
7848 int write = rw & REQ_WRITE;
7851 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7853 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7859 dip = kzalloc(sizeof(*dip), GFP_NOFS);
7865 dip->private = dio_bio->bi_private;
7867 dip->logical_offset = file_offset;
7868 dip->bytes = dio_bio->bi_iter.bi_size;
7869 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7870 io_bio->bi_private = dip;
7871 dip->orig_bio = io_bio;
7872 dip->dio_bio = dio_bio;
7873 atomic_set(&dip->pending_bios, 0);
7874 btrfs_bio = btrfs_io_bio(io_bio);
7875 btrfs_bio->logical = file_offset;
7878 io_bio->bi_end_io = btrfs_endio_direct_write;
7880 io_bio->bi_end_io = btrfs_endio_direct_read;
7881 dip->subio_endio = btrfs_subio_endio_read;
7884 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7888 if (btrfs_bio->end_io)
7889 btrfs_bio->end_io(btrfs_bio, ret);
7895 * If this is a write, we need to clean up the reserved space and kill
7896 * the ordered extent.
7899 struct btrfs_ordered_extent *ordered;
7900 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7901 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7902 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7903 btrfs_free_reserved_extent(root, ordered->start,
7904 ordered->disk_len, 1);
7905 btrfs_put_ordered_extent(ordered);
7906 btrfs_put_ordered_extent(ordered);
7908 bio_endio(dio_bio, ret);
7911 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7912 const struct iov_iter *iter, loff_t offset)
7916 unsigned blocksize_mask = root->sectorsize - 1;
7917 ssize_t retval = -EINVAL;
7919 if (offset & blocksize_mask)
7922 if (iov_iter_alignment(iter) & blocksize_mask)
7925 /* If this is a write we don't need to check anymore */
7929 * Check to make sure we don't have duplicate iov_base's in this
7930 * iovec, if so return EINVAL, otherwise we'll get csum errors
7931 * when reading back.
7933 for (seg = 0; seg < iter->nr_segs; seg++) {
7934 for (i = seg + 1; i < iter->nr_segs; i++) {
7935 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
7944 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7945 struct iov_iter *iter, loff_t offset)
7947 struct file *file = iocb->ki_filp;
7948 struct inode *inode = file->f_mapping->host;
7952 bool relock = false;
7955 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iter, offset))
7958 atomic_inc(&inode->i_dio_count);
7959 smp_mb__after_atomic();
7962 * The generic stuff only does filemap_write_and_wait_range, which
7963 * isn't enough if we've written compressed pages to this area, so
7964 * we need to flush the dirty pages again to make absolutely sure
7965 * that any outstanding dirty pages are on disk.
7967 count = iov_iter_count(iter);
7968 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7969 &BTRFS_I(inode)->runtime_flags))
7970 filemap_fdatawrite_range(inode->i_mapping, offset,
7971 offset + count - 1);
7975 * If the write DIO is beyond the EOF, we need update
7976 * the isize, but it is protected by i_mutex. So we can
7977 * not unlock the i_mutex at this case.
7979 if (offset + count <= inode->i_size) {
7980 mutex_unlock(&inode->i_mutex);
7983 ret = btrfs_delalloc_reserve_space(inode, count);
7986 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7987 &BTRFS_I(inode)->runtime_flags)) {
7988 inode_dio_done(inode);
7989 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7993 ret = __blockdev_direct_IO(rw, iocb, inode,
7994 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7995 iter, offset, btrfs_get_blocks_direct, NULL,
7996 btrfs_submit_direct, flags);
7998 if (ret < 0 && ret != -EIOCBQUEUED)
7999 btrfs_delalloc_release_space(inode, count);
8000 else if (ret >= 0 && (size_t)ret < count)
8001 btrfs_delalloc_release_space(inode,
8002 count - (size_t)ret);
8004 btrfs_delalloc_release_metadata(inode, 0);
8008 inode_dio_done(inode);
8010 mutex_lock(&inode->i_mutex);
8015 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8017 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8018 __u64 start, __u64 len)
8022 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8026 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
8029 int btrfs_readpage(struct file *file, struct page *page)
8031 struct extent_io_tree *tree;
8032 tree = &BTRFS_I(page->mapping->host)->io_tree;
8033 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8036 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8038 struct extent_io_tree *tree;
8041 if (current->flags & PF_MEMALLOC) {
8042 redirty_page_for_writepage(wbc, page);
8046 tree = &BTRFS_I(page->mapping->host)->io_tree;
8047 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
8050 static int btrfs_writepages(struct address_space *mapping,
8051 struct writeback_control *wbc)
8053 struct extent_io_tree *tree;
8055 tree = &BTRFS_I(mapping->host)->io_tree;
8056 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8060 btrfs_readpages(struct file *file, struct address_space *mapping,
8061 struct list_head *pages, unsigned nr_pages)
8063 struct extent_io_tree *tree;
8064 tree = &BTRFS_I(mapping->host)->io_tree;
8065 return extent_readpages(tree, mapping, pages, nr_pages,
8068 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8070 struct extent_io_tree *tree;
8071 struct extent_map_tree *map;
8074 tree = &BTRFS_I(page->mapping->host)->io_tree;
8075 map = &BTRFS_I(page->mapping->host)->extent_tree;
8076 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8078 ClearPagePrivate(page);
8079 set_page_private(page, 0);
8080 page_cache_release(page);
8085 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8087 if (PageWriteback(page) || PageDirty(page))
8089 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
8092 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8093 unsigned int length)
8095 struct inode *inode = page->mapping->host;
8096 struct extent_io_tree *tree;
8097 struct btrfs_ordered_extent *ordered;
8098 struct extent_state *cached_state = NULL;
8099 u64 page_start = page_offset(page);
8100 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
8101 int inode_evicting = inode->i_state & I_FREEING;
8104 * we have the page locked, so new writeback can't start,
8105 * and the dirty bit won't be cleared while we are here.
8107 * Wait for IO on this page so that we can safely clear
8108 * the PagePrivate2 bit and do ordered accounting
8110 wait_on_page_writeback(page);
8112 tree = &BTRFS_I(inode)->io_tree;
8114 btrfs_releasepage(page, GFP_NOFS);
8118 if (!inode_evicting)
8119 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
8120 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8123 * IO on this page will never be started, so we need
8124 * to account for any ordered extents now
8126 if (!inode_evicting)
8127 clear_extent_bit(tree, page_start, page_end,
8128 EXTENT_DIRTY | EXTENT_DELALLOC |
8129 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8130 EXTENT_DEFRAG, 1, 0, &cached_state,
8133 * whoever cleared the private bit is responsible
8134 * for the finish_ordered_io
8136 if (TestClearPagePrivate2(page)) {
8137 struct btrfs_ordered_inode_tree *tree;
8140 tree = &BTRFS_I(inode)->ordered_tree;
8142 spin_lock_irq(&tree->lock);
8143 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8144 new_len = page_start - ordered->file_offset;
8145 if (new_len < ordered->truncated_len)
8146 ordered->truncated_len = new_len;
8147 spin_unlock_irq(&tree->lock);
8149 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8151 PAGE_CACHE_SIZE, 1))
8152 btrfs_finish_ordered_io(ordered);
8154 btrfs_put_ordered_extent(ordered);
8155 if (!inode_evicting) {
8156 cached_state = NULL;
8157 lock_extent_bits(tree, page_start, page_end, 0,
8162 if (!inode_evicting) {
8163 clear_extent_bit(tree, page_start, page_end,
8164 EXTENT_LOCKED | EXTENT_DIRTY |
8165 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8166 EXTENT_DEFRAG, 1, 1,
8167 &cached_state, GFP_NOFS);
8169 __btrfs_releasepage(page, GFP_NOFS);
8172 ClearPageChecked(page);
8173 if (PagePrivate(page)) {
8174 ClearPagePrivate(page);
8175 set_page_private(page, 0);
8176 page_cache_release(page);
8181 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8182 * called from a page fault handler when a page is first dirtied. Hence we must
8183 * be careful to check for EOF conditions here. We set the page up correctly
8184 * for a written page which means we get ENOSPC checking when writing into
8185 * holes and correct delalloc and unwritten extent mapping on filesystems that
8186 * support these features.
8188 * We are not allowed to take the i_mutex here so we have to play games to
8189 * protect against truncate races as the page could now be beyond EOF. Because
8190 * vmtruncate() writes the inode size before removing pages, once we have the
8191 * page lock we can determine safely if the page is beyond EOF. If it is not
8192 * beyond EOF, then the page is guaranteed safe against truncation until we
8195 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
8197 struct page *page = vmf->page;
8198 struct inode *inode = file_inode(vma->vm_file);
8199 struct btrfs_root *root = BTRFS_I(inode)->root;
8200 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8201 struct btrfs_ordered_extent *ordered;
8202 struct extent_state *cached_state = NULL;
8204 unsigned long zero_start;
8211 sb_start_pagefault(inode->i_sb);
8212 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
8214 ret = file_update_time(vma->vm_file);
8220 else /* -ENOSPC, -EIO, etc */
8221 ret = VM_FAULT_SIGBUS;
8227 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8230 size = i_size_read(inode);
8231 page_start = page_offset(page);
8232 page_end = page_start + PAGE_CACHE_SIZE - 1;
8234 if ((page->mapping != inode->i_mapping) ||
8235 (page_start >= size)) {
8236 /* page got truncated out from underneath us */
8239 wait_on_page_writeback(page);
8241 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
8242 set_page_extent_mapped(page);
8245 * we can't set the delalloc bits if there are pending ordered
8246 * extents. Drop our locks and wait for them to finish
8248 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8250 unlock_extent_cached(io_tree, page_start, page_end,
8251 &cached_state, GFP_NOFS);
8253 btrfs_start_ordered_extent(inode, ordered, 1);
8254 btrfs_put_ordered_extent(ordered);
8259 * XXX - page_mkwrite gets called every time the page is dirtied, even
8260 * if it was already dirty, so for space accounting reasons we need to
8261 * clear any delalloc bits for the range we are fixing to save. There
8262 * is probably a better way to do this, but for now keep consistent with
8263 * prepare_pages in the normal write path.
8265 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
8266 EXTENT_DIRTY | EXTENT_DELALLOC |
8267 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8268 0, 0, &cached_state, GFP_NOFS);
8270 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
8273 unlock_extent_cached(io_tree, page_start, page_end,
8274 &cached_state, GFP_NOFS);
8275 ret = VM_FAULT_SIGBUS;
8280 /* page is wholly or partially inside EOF */
8281 if (page_start + PAGE_CACHE_SIZE > size)
8282 zero_start = size & ~PAGE_CACHE_MASK;
8284 zero_start = PAGE_CACHE_SIZE;
8286 if (zero_start != PAGE_CACHE_SIZE) {
8288 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
8289 flush_dcache_page(page);
8292 ClearPageChecked(page);
8293 set_page_dirty(page);
8294 SetPageUptodate(page);
8296 BTRFS_I(inode)->last_trans = root->fs_info->generation;
8297 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8298 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8300 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
8304 sb_end_pagefault(inode->i_sb);
8305 return VM_FAULT_LOCKED;
8309 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
8311 sb_end_pagefault(inode->i_sb);
8315 static int btrfs_truncate(struct inode *inode)
8317 struct btrfs_root *root = BTRFS_I(inode)->root;
8318 struct btrfs_block_rsv *rsv;
8321 struct btrfs_trans_handle *trans;
8322 u64 mask = root->sectorsize - 1;
8323 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
8325 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8331 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
8332 * 3 things going on here
8334 * 1) We need to reserve space for our orphan item and the space to
8335 * delete our orphan item. Lord knows we don't want to have a dangling
8336 * orphan item because we didn't reserve space to remove it.
8338 * 2) We need to reserve space to update our inode.
8340 * 3) We need to have something to cache all the space that is going to
8341 * be free'd up by the truncate operation, but also have some slack
8342 * space reserved in case it uses space during the truncate (thank you
8343 * very much snapshotting).
8345 * And we need these to all be seperate. The fact is we can use alot of
8346 * space doing the truncate, and we have no earthly idea how much space
8347 * we will use, so we need the truncate reservation to be seperate so it
8348 * doesn't end up using space reserved for updating the inode or
8349 * removing the orphan item. We also need to be able to stop the
8350 * transaction and start a new one, which means we need to be able to
8351 * update the inode several times, and we have no idea of knowing how
8352 * many times that will be, so we can't just reserve 1 item for the
8353 * entirety of the opration, so that has to be done seperately as well.
8354 * Then there is the orphan item, which does indeed need to be held on
8355 * to for the whole operation, and we need nobody to touch this reserved
8356 * space except the orphan code.
8358 * So that leaves us with
8360 * 1) root->orphan_block_rsv - for the orphan deletion.
8361 * 2) rsv - for the truncate reservation, which we will steal from the
8362 * transaction reservation.
8363 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
8364 * updating the inode.
8366 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
8369 rsv->size = min_size;
8373 * 1 for the truncate slack space
8374 * 1 for updating the inode.
8376 trans = btrfs_start_transaction(root, 2);
8377 if (IS_ERR(trans)) {
8378 err = PTR_ERR(trans);
8382 /* Migrate the slack space for the truncate to our reserve */
8383 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
8388 * So if we truncate and then write and fsync we normally would just
8389 * write the extents that changed, which is a problem if we need to
8390 * first truncate that entire inode. So set this flag so we write out
8391 * all of the extents in the inode to the sync log so we're completely
8394 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8395 trans->block_rsv = rsv;
8398 ret = btrfs_truncate_inode_items(trans, root, inode,
8400 BTRFS_EXTENT_DATA_KEY);
8401 if (ret != -ENOSPC) {
8406 trans->block_rsv = &root->fs_info->trans_block_rsv;
8407 ret = btrfs_update_inode(trans, root, inode);
8413 btrfs_end_transaction(trans, root);
8414 btrfs_btree_balance_dirty(root);
8416 trans = btrfs_start_transaction(root, 2);
8417 if (IS_ERR(trans)) {
8418 ret = err = PTR_ERR(trans);
8423 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
8425 BUG_ON(ret); /* shouldn't happen */
8426 trans->block_rsv = rsv;
8429 if (ret == 0 && inode->i_nlink > 0) {
8430 trans->block_rsv = root->orphan_block_rsv;
8431 ret = btrfs_orphan_del(trans, inode);
8437 trans->block_rsv = &root->fs_info->trans_block_rsv;
8438 ret = btrfs_update_inode(trans, root, inode);
8442 ret = btrfs_end_transaction(trans, root);
8443 btrfs_btree_balance_dirty(root);
8447 btrfs_free_block_rsv(root, rsv);
8456 * create a new subvolume directory/inode (helper for the ioctl).
8458 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8459 struct btrfs_root *new_root,
8460 struct btrfs_root *parent_root,
8463 struct inode *inode;
8467 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8468 new_dirid, new_dirid,
8469 S_IFDIR | (~current_umask() & S_IRWXUGO),
8472 return PTR_ERR(inode);
8473 inode->i_op = &btrfs_dir_inode_operations;
8474 inode->i_fop = &btrfs_dir_file_operations;
8476 set_nlink(inode, 1);
8477 btrfs_i_size_write(inode, 0);
8478 unlock_new_inode(inode);
8480 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8482 btrfs_err(new_root->fs_info,
8483 "error inheriting subvolume %llu properties: %d",
8484 new_root->root_key.objectid, err);
8486 err = btrfs_update_inode(trans, new_root, inode);
8492 struct inode *btrfs_alloc_inode(struct super_block *sb)
8494 struct btrfs_inode *ei;
8495 struct inode *inode;
8497 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
8504 ei->last_sub_trans = 0;
8505 ei->logged_trans = 0;
8506 ei->delalloc_bytes = 0;
8507 ei->defrag_bytes = 0;
8508 ei->disk_i_size = 0;
8511 ei->index_cnt = (u64)-1;
8513 ei->last_unlink_trans = 0;
8514 ei->last_log_commit = 0;
8516 spin_lock_init(&ei->lock);
8517 ei->outstanding_extents = 0;
8518 ei->reserved_extents = 0;
8520 ei->runtime_flags = 0;
8521 ei->force_compress = BTRFS_COMPRESS_NONE;
8523 ei->delayed_node = NULL;
8525 inode = &ei->vfs_inode;
8526 extent_map_tree_init(&ei->extent_tree);
8527 extent_io_tree_init(&ei->io_tree, &inode->i_data);
8528 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
8529 ei->io_tree.track_uptodate = 1;
8530 ei->io_failure_tree.track_uptodate = 1;
8531 atomic_set(&ei->sync_writers, 0);
8532 mutex_init(&ei->log_mutex);
8533 mutex_init(&ei->delalloc_mutex);
8534 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8535 INIT_LIST_HEAD(&ei->delalloc_inodes);
8536 RB_CLEAR_NODE(&ei->rb_node);
8541 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8542 void btrfs_test_destroy_inode(struct inode *inode)
8544 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8545 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8549 static void btrfs_i_callback(struct rcu_head *head)
8551 struct inode *inode = container_of(head, struct inode, i_rcu);
8552 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8555 void btrfs_destroy_inode(struct inode *inode)
8557 struct btrfs_ordered_extent *ordered;
8558 struct btrfs_root *root = BTRFS_I(inode)->root;
8560 WARN_ON(!hlist_empty(&inode->i_dentry));
8561 WARN_ON(inode->i_data.nrpages);
8562 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8563 WARN_ON(BTRFS_I(inode)->reserved_extents);
8564 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8565 WARN_ON(BTRFS_I(inode)->csum_bytes);
8566 WARN_ON(BTRFS_I(inode)->defrag_bytes);
8569 * This can happen where we create an inode, but somebody else also
8570 * created the same inode and we need to destroy the one we already
8576 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8577 &BTRFS_I(inode)->runtime_flags)) {
8578 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
8580 atomic_dec(&root->orphan_inodes);
8584 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8588 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
8589 ordered->file_offset, ordered->len);
8590 btrfs_remove_ordered_extent(inode, ordered);
8591 btrfs_put_ordered_extent(ordered);
8592 btrfs_put_ordered_extent(ordered);
8595 inode_tree_del(inode);
8596 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8598 call_rcu(&inode->i_rcu, btrfs_i_callback);
8601 int btrfs_drop_inode(struct inode *inode)
8603 struct btrfs_root *root = BTRFS_I(inode)->root;
8608 /* the snap/subvol tree is on deleting */
8609 if (btrfs_root_refs(&root->root_item) == 0)
8612 return generic_drop_inode(inode);
8615 static void init_once(void *foo)
8617 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8619 inode_init_once(&ei->vfs_inode);
8622 void btrfs_destroy_cachep(void)
8625 * Make sure all delayed rcu free inodes are flushed before we
8629 if (btrfs_inode_cachep)
8630 kmem_cache_destroy(btrfs_inode_cachep);
8631 if (btrfs_trans_handle_cachep)
8632 kmem_cache_destroy(btrfs_trans_handle_cachep);
8633 if (btrfs_transaction_cachep)
8634 kmem_cache_destroy(btrfs_transaction_cachep);
8635 if (btrfs_path_cachep)
8636 kmem_cache_destroy(btrfs_path_cachep);
8637 if (btrfs_free_space_cachep)
8638 kmem_cache_destroy(btrfs_free_space_cachep);
8639 if (btrfs_delalloc_work_cachep)
8640 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8643 int btrfs_init_cachep(void)
8645 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8646 sizeof(struct btrfs_inode), 0,
8647 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8648 if (!btrfs_inode_cachep)
8651 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8652 sizeof(struct btrfs_trans_handle), 0,
8653 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8654 if (!btrfs_trans_handle_cachep)
8657 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8658 sizeof(struct btrfs_transaction), 0,
8659 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8660 if (!btrfs_transaction_cachep)
8663 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8664 sizeof(struct btrfs_path), 0,
8665 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8666 if (!btrfs_path_cachep)
8669 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8670 sizeof(struct btrfs_free_space), 0,
8671 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8672 if (!btrfs_free_space_cachep)
8675 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8676 sizeof(struct btrfs_delalloc_work), 0,
8677 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8679 if (!btrfs_delalloc_work_cachep)
8684 btrfs_destroy_cachep();
8688 static int btrfs_getattr(struct vfsmount *mnt,
8689 struct dentry *dentry, struct kstat *stat)
8692 struct inode *inode = dentry->d_inode;
8693 u32 blocksize = inode->i_sb->s_blocksize;
8695 generic_fillattr(inode, stat);
8696 stat->dev = BTRFS_I(inode)->root->anon_dev;
8697 stat->blksize = PAGE_CACHE_SIZE;
8699 spin_lock(&BTRFS_I(inode)->lock);
8700 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8701 spin_unlock(&BTRFS_I(inode)->lock);
8702 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8703 ALIGN(delalloc_bytes, blocksize)) >> 9;
8707 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8708 struct inode *new_dir, struct dentry *new_dentry)
8710 struct btrfs_trans_handle *trans;
8711 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8712 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8713 struct inode *new_inode = new_dentry->d_inode;
8714 struct inode *old_inode = old_dentry->d_inode;
8715 struct timespec ctime = CURRENT_TIME;
8719 u64 old_ino = btrfs_ino(old_inode);
8721 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8724 /* we only allow rename subvolume link between subvolumes */
8725 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8728 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8729 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8732 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8733 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8737 /* check for collisions, even if the name isn't there */
8738 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8739 new_dentry->d_name.name,
8740 new_dentry->d_name.len);
8743 if (ret == -EEXIST) {
8745 * eexist without a new_inode */
8746 if (WARN_ON(!new_inode)) {
8750 /* maybe -EOVERFLOW */
8757 * we're using rename to replace one file with another. Start IO on it
8758 * now so we don't add too much work to the end of the transaction
8760 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
8761 filemap_flush(old_inode->i_mapping);
8763 /* close the racy window with snapshot create/destroy ioctl */
8764 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8765 down_read(&root->fs_info->subvol_sem);
8767 * We want to reserve the absolute worst case amount of items. So if
8768 * both inodes are subvols and we need to unlink them then that would
8769 * require 4 item modifications, but if they are both normal inodes it
8770 * would require 5 item modifications, so we'll assume their normal
8771 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8772 * should cover the worst case number of items we'll modify.
8774 trans = btrfs_start_transaction(root, 11);
8775 if (IS_ERR(trans)) {
8776 ret = PTR_ERR(trans);
8781 btrfs_record_root_in_trans(trans, dest);
8783 ret = btrfs_set_inode_index(new_dir, &index);
8787 BTRFS_I(old_inode)->dir_index = 0ULL;
8788 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8789 /* force full log commit if subvolume involved. */
8790 btrfs_set_log_full_commit(root->fs_info, trans);
8792 ret = btrfs_insert_inode_ref(trans, dest,
8793 new_dentry->d_name.name,
8794 new_dentry->d_name.len,
8796 btrfs_ino(new_dir), index);
8800 * this is an ugly little race, but the rename is required
8801 * to make sure that if we crash, the inode is either at the
8802 * old name or the new one. pinning the log transaction lets
8803 * us make sure we don't allow a log commit to come in after
8804 * we unlink the name but before we add the new name back in.
8806 btrfs_pin_log_trans(root);
8809 inode_inc_iversion(old_dir);
8810 inode_inc_iversion(new_dir);
8811 inode_inc_iversion(old_inode);
8812 old_dir->i_ctime = old_dir->i_mtime = ctime;
8813 new_dir->i_ctime = new_dir->i_mtime = ctime;
8814 old_inode->i_ctime = ctime;
8816 if (old_dentry->d_parent != new_dentry->d_parent)
8817 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8819 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8820 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8821 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8822 old_dentry->d_name.name,
8823 old_dentry->d_name.len);
8825 ret = __btrfs_unlink_inode(trans, root, old_dir,
8826 old_dentry->d_inode,
8827 old_dentry->d_name.name,
8828 old_dentry->d_name.len);
8830 ret = btrfs_update_inode(trans, root, old_inode);
8833 btrfs_abort_transaction(trans, root, ret);
8838 inode_inc_iversion(new_inode);
8839 new_inode->i_ctime = CURRENT_TIME;
8840 if (unlikely(btrfs_ino(new_inode) ==
8841 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8842 root_objectid = BTRFS_I(new_inode)->location.objectid;
8843 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8845 new_dentry->d_name.name,
8846 new_dentry->d_name.len);
8847 BUG_ON(new_inode->i_nlink == 0);
8849 ret = btrfs_unlink_inode(trans, dest, new_dir,
8850 new_dentry->d_inode,
8851 new_dentry->d_name.name,
8852 new_dentry->d_name.len);
8854 if (!ret && new_inode->i_nlink == 0)
8855 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8857 btrfs_abort_transaction(trans, root, ret);
8862 ret = btrfs_add_link(trans, new_dir, old_inode,
8863 new_dentry->d_name.name,
8864 new_dentry->d_name.len, 0, index);
8866 btrfs_abort_transaction(trans, root, ret);
8870 if (old_inode->i_nlink == 1)
8871 BTRFS_I(old_inode)->dir_index = index;
8873 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8874 struct dentry *parent = new_dentry->d_parent;
8875 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8876 btrfs_end_log_trans(root);
8879 btrfs_end_transaction(trans, root);
8881 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8882 up_read(&root->fs_info->subvol_sem);
8887 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
8888 struct inode *new_dir, struct dentry *new_dentry,
8891 if (flags & ~RENAME_NOREPLACE)
8894 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry);
8897 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8899 struct btrfs_delalloc_work *delalloc_work;
8900 struct inode *inode;
8902 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8904 inode = delalloc_work->inode;
8905 if (delalloc_work->wait) {
8906 btrfs_wait_ordered_range(inode, 0, (u64)-1);
8908 filemap_flush(inode->i_mapping);
8909 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8910 &BTRFS_I(inode)->runtime_flags))
8911 filemap_flush(inode->i_mapping);
8914 if (delalloc_work->delay_iput)
8915 btrfs_add_delayed_iput(inode);
8918 complete(&delalloc_work->completion);
8921 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8922 int wait, int delay_iput)
8924 struct btrfs_delalloc_work *work;
8926 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8930 init_completion(&work->completion);
8931 INIT_LIST_HEAD(&work->list);
8932 work->inode = inode;
8934 work->delay_iput = delay_iput;
8935 WARN_ON_ONCE(!inode);
8936 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
8937 btrfs_run_delalloc_work, NULL, NULL);
8942 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8944 wait_for_completion(&work->completion);
8945 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8949 * some fairly slow code that needs optimization. This walks the list
8950 * of all the inodes with pending delalloc and forces them to disk.
8952 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
8955 struct btrfs_inode *binode;
8956 struct inode *inode;
8957 struct btrfs_delalloc_work *work, *next;
8958 struct list_head works;
8959 struct list_head splice;
8962 INIT_LIST_HEAD(&works);
8963 INIT_LIST_HEAD(&splice);
8965 mutex_lock(&root->delalloc_mutex);
8966 spin_lock(&root->delalloc_lock);
8967 list_splice_init(&root->delalloc_inodes, &splice);
8968 while (!list_empty(&splice)) {
8969 binode = list_entry(splice.next, struct btrfs_inode,
8972 list_move_tail(&binode->delalloc_inodes,
8973 &root->delalloc_inodes);
8974 inode = igrab(&binode->vfs_inode);
8976 cond_resched_lock(&root->delalloc_lock);
8979 spin_unlock(&root->delalloc_lock);
8981 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8984 btrfs_add_delayed_iput(inode);
8990 list_add_tail(&work->list, &works);
8991 btrfs_queue_work(root->fs_info->flush_workers,
8994 if (nr != -1 && ret >= nr)
8997 spin_lock(&root->delalloc_lock);
8999 spin_unlock(&root->delalloc_lock);
9002 list_for_each_entry_safe(work, next, &works, list) {
9003 list_del_init(&work->list);
9004 btrfs_wait_and_free_delalloc_work(work);
9007 if (!list_empty_careful(&splice)) {
9008 spin_lock(&root->delalloc_lock);
9009 list_splice_tail(&splice, &root->delalloc_inodes);
9010 spin_unlock(&root->delalloc_lock);
9012 mutex_unlock(&root->delalloc_mutex);
9016 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
9020 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
9023 ret = __start_delalloc_inodes(root, delay_iput, -1);
9027 * the filemap_flush will queue IO into the worker threads, but
9028 * we have to make sure the IO is actually started and that
9029 * ordered extents get created before we return
9031 atomic_inc(&root->fs_info->async_submit_draining);
9032 while (atomic_read(&root->fs_info->nr_async_submits) ||
9033 atomic_read(&root->fs_info->async_delalloc_pages)) {
9034 wait_event(root->fs_info->async_submit_wait,
9035 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
9036 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
9038 atomic_dec(&root->fs_info->async_submit_draining);
9042 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
9045 struct btrfs_root *root;
9046 struct list_head splice;
9049 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9052 INIT_LIST_HEAD(&splice);
9054 mutex_lock(&fs_info->delalloc_root_mutex);
9055 spin_lock(&fs_info->delalloc_root_lock);
9056 list_splice_init(&fs_info->delalloc_roots, &splice);
9057 while (!list_empty(&splice) && nr) {
9058 root = list_first_entry(&splice, struct btrfs_root,
9060 root = btrfs_grab_fs_root(root);
9062 list_move_tail(&root->delalloc_root,
9063 &fs_info->delalloc_roots);
9064 spin_unlock(&fs_info->delalloc_root_lock);
9066 ret = __start_delalloc_inodes(root, delay_iput, nr);
9067 btrfs_put_fs_root(root);
9075 spin_lock(&fs_info->delalloc_root_lock);
9077 spin_unlock(&fs_info->delalloc_root_lock);
9080 atomic_inc(&fs_info->async_submit_draining);
9081 while (atomic_read(&fs_info->nr_async_submits) ||
9082 atomic_read(&fs_info->async_delalloc_pages)) {
9083 wait_event(fs_info->async_submit_wait,
9084 (atomic_read(&fs_info->nr_async_submits) == 0 &&
9085 atomic_read(&fs_info->async_delalloc_pages) == 0));
9087 atomic_dec(&fs_info->async_submit_draining);
9089 if (!list_empty_careful(&splice)) {
9090 spin_lock(&fs_info->delalloc_root_lock);
9091 list_splice_tail(&splice, &fs_info->delalloc_roots);
9092 spin_unlock(&fs_info->delalloc_root_lock);
9094 mutex_unlock(&fs_info->delalloc_root_mutex);
9098 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9099 const char *symname)
9101 struct btrfs_trans_handle *trans;
9102 struct btrfs_root *root = BTRFS_I(dir)->root;
9103 struct btrfs_path *path;
9104 struct btrfs_key key;
9105 struct inode *inode = NULL;
9113 struct btrfs_file_extent_item *ei;
9114 struct extent_buffer *leaf;
9116 name_len = strlen(symname);
9117 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
9118 return -ENAMETOOLONG;
9121 * 2 items for inode item and ref
9122 * 2 items for dir items
9123 * 1 item for xattr if selinux is on
9125 trans = btrfs_start_transaction(root, 5);
9127 return PTR_ERR(trans);
9129 err = btrfs_find_free_ino(root, &objectid);
9133 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9134 dentry->d_name.len, btrfs_ino(dir), objectid,
9135 S_IFLNK|S_IRWXUGO, &index);
9136 if (IS_ERR(inode)) {
9137 err = PTR_ERR(inode);
9142 * If the active LSM wants to access the inode during
9143 * d_instantiate it needs these. Smack checks to see
9144 * if the filesystem supports xattrs by looking at the
9147 inode->i_fop = &btrfs_file_operations;
9148 inode->i_op = &btrfs_file_inode_operations;
9149 inode->i_mapping->a_ops = &btrfs_aops;
9150 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9151 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9153 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9155 goto out_unlock_inode;
9157 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
9159 goto out_unlock_inode;
9161 path = btrfs_alloc_path();
9164 goto out_unlock_inode;
9166 key.objectid = btrfs_ino(inode);
9168 key.type = BTRFS_EXTENT_DATA_KEY;
9169 datasize = btrfs_file_extent_calc_inline_size(name_len);
9170 err = btrfs_insert_empty_item(trans, root, path, &key,
9173 btrfs_free_path(path);
9174 goto out_unlock_inode;
9176 leaf = path->nodes[0];
9177 ei = btrfs_item_ptr(leaf, path->slots[0],
9178 struct btrfs_file_extent_item);
9179 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9180 btrfs_set_file_extent_type(leaf, ei,
9181 BTRFS_FILE_EXTENT_INLINE);
9182 btrfs_set_file_extent_encryption(leaf, ei, 0);
9183 btrfs_set_file_extent_compression(leaf, ei, 0);
9184 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9185 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9187 ptr = btrfs_file_extent_inline_start(ei);
9188 write_extent_buffer(leaf, symname, ptr, name_len);
9189 btrfs_mark_buffer_dirty(leaf);
9190 btrfs_free_path(path);
9192 inode->i_op = &btrfs_symlink_inode_operations;
9193 inode->i_mapping->a_ops = &btrfs_symlink_aops;
9194 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9195 inode_set_bytes(inode, name_len);
9196 btrfs_i_size_write(inode, name_len);
9197 err = btrfs_update_inode(trans, root, inode);
9200 goto out_unlock_inode;
9203 unlock_new_inode(inode);
9204 d_instantiate(dentry, inode);
9207 btrfs_end_transaction(trans, root);
9209 inode_dec_link_count(inode);
9212 btrfs_btree_balance_dirty(root);
9217 unlock_new_inode(inode);
9221 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9222 u64 start, u64 num_bytes, u64 min_size,
9223 loff_t actual_len, u64 *alloc_hint,
9224 struct btrfs_trans_handle *trans)
9226 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9227 struct extent_map *em;
9228 struct btrfs_root *root = BTRFS_I(inode)->root;
9229 struct btrfs_key ins;
9230 u64 cur_offset = start;
9234 bool own_trans = true;
9238 while (num_bytes > 0) {
9240 trans = btrfs_start_transaction(root, 3);
9241 if (IS_ERR(trans)) {
9242 ret = PTR_ERR(trans);
9247 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
9248 cur_bytes = max(cur_bytes, min_size);
9249 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
9250 *alloc_hint, &ins, 1, 0);
9253 btrfs_end_transaction(trans, root);
9257 ret = insert_reserved_file_extent(trans, inode,
9258 cur_offset, ins.objectid,
9259 ins.offset, ins.offset,
9260 ins.offset, 0, 0, 0,
9261 BTRFS_FILE_EXTENT_PREALLOC);
9263 btrfs_free_reserved_extent(root, ins.objectid,
9265 btrfs_abort_transaction(trans, root, ret);
9267 btrfs_end_transaction(trans, root);
9270 btrfs_drop_extent_cache(inode, cur_offset,
9271 cur_offset + ins.offset -1, 0);
9273 em = alloc_extent_map();
9275 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9276 &BTRFS_I(inode)->runtime_flags);
9280 em->start = cur_offset;
9281 em->orig_start = cur_offset;
9282 em->len = ins.offset;
9283 em->block_start = ins.objectid;
9284 em->block_len = ins.offset;
9285 em->orig_block_len = ins.offset;
9286 em->ram_bytes = ins.offset;
9287 em->bdev = root->fs_info->fs_devices->latest_bdev;
9288 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9289 em->generation = trans->transid;
9292 write_lock(&em_tree->lock);
9293 ret = add_extent_mapping(em_tree, em, 1);
9294 write_unlock(&em_tree->lock);
9297 btrfs_drop_extent_cache(inode, cur_offset,
9298 cur_offset + ins.offset - 1,
9301 free_extent_map(em);
9303 num_bytes -= ins.offset;
9304 cur_offset += ins.offset;
9305 *alloc_hint = ins.objectid + ins.offset;
9307 inode_inc_iversion(inode);
9308 inode->i_ctime = CURRENT_TIME;
9309 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9310 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9311 (actual_len > inode->i_size) &&
9312 (cur_offset > inode->i_size)) {
9313 if (cur_offset > actual_len)
9314 i_size = actual_len;
9316 i_size = cur_offset;
9317 i_size_write(inode, i_size);
9318 btrfs_ordered_update_i_size(inode, i_size, NULL);
9321 ret = btrfs_update_inode(trans, root, inode);
9324 btrfs_abort_transaction(trans, root, ret);
9326 btrfs_end_transaction(trans, root);
9331 btrfs_end_transaction(trans, root);
9336 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9337 u64 start, u64 num_bytes, u64 min_size,
9338 loff_t actual_len, u64 *alloc_hint)
9340 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9341 min_size, actual_len, alloc_hint,
9345 int btrfs_prealloc_file_range_trans(struct inode *inode,
9346 struct btrfs_trans_handle *trans, int mode,
9347 u64 start, u64 num_bytes, u64 min_size,
9348 loff_t actual_len, u64 *alloc_hint)
9350 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9351 min_size, actual_len, alloc_hint, trans);
9354 static int btrfs_set_page_dirty(struct page *page)
9356 return __set_page_dirty_nobuffers(page);
9359 static int btrfs_permission(struct inode *inode, int mask)
9361 struct btrfs_root *root = BTRFS_I(inode)->root;
9362 umode_t mode = inode->i_mode;
9364 if (mask & MAY_WRITE &&
9365 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9366 if (btrfs_root_readonly(root))
9368 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9371 return generic_permission(inode, mask);
9374 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9376 struct btrfs_trans_handle *trans;
9377 struct btrfs_root *root = BTRFS_I(dir)->root;
9378 struct inode *inode = NULL;
9384 * 5 units required for adding orphan entry
9386 trans = btrfs_start_transaction(root, 5);
9388 return PTR_ERR(trans);
9390 ret = btrfs_find_free_ino(root, &objectid);
9394 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9395 btrfs_ino(dir), objectid, mode, &index);
9396 if (IS_ERR(inode)) {
9397 ret = PTR_ERR(inode);
9402 inode->i_fop = &btrfs_file_operations;
9403 inode->i_op = &btrfs_file_inode_operations;
9405 inode->i_mapping->a_ops = &btrfs_aops;
9406 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9407 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9409 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9413 ret = btrfs_update_inode(trans, root, inode);
9416 ret = btrfs_orphan_add(trans, inode);
9421 * We set number of links to 0 in btrfs_new_inode(), and here we set
9422 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9425 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9427 set_nlink(inode, 1);
9428 unlock_new_inode(inode);
9429 d_tmpfile(dentry, inode);
9430 mark_inode_dirty(inode);
9433 btrfs_end_transaction(trans, root);
9436 btrfs_balance_delayed_items(root);
9437 btrfs_btree_balance_dirty(root);
9441 unlock_new_inode(inode);
9446 static const struct inode_operations btrfs_dir_inode_operations = {
9447 .getattr = btrfs_getattr,
9448 .lookup = btrfs_lookup,
9449 .create = btrfs_create,
9450 .unlink = btrfs_unlink,
9452 .mkdir = btrfs_mkdir,
9453 .rmdir = btrfs_rmdir,
9454 .rename2 = btrfs_rename2,
9455 .symlink = btrfs_symlink,
9456 .setattr = btrfs_setattr,
9457 .mknod = btrfs_mknod,
9458 .setxattr = btrfs_setxattr,
9459 .getxattr = btrfs_getxattr,
9460 .listxattr = btrfs_listxattr,
9461 .removexattr = btrfs_removexattr,
9462 .permission = btrfs_permission,
9463 .get_acl = btrfs_get_acl,
9464 .set_acl = btrfs_set_acl,
9465 .update_time = btrfs_update_time,
9466 .tmpfile = btrfs_tmpfile,
9468 static const struct inode_operations btrfs_dir_ro_inode_operations = {
9469 .lookup = btrfs_lookup,
9470 .permission = btrfs_permission,
9471 .get_acl = btrfs_get_acl,
9472 .set_acl = btrfs_set_acl,
9473 .update_time = btrfs_update_time,
9476 static const struct file_operations btrfs_dir_file_operations = {
9477 .llseek = generic_file_llseek,
9478 .read = generic_read_dir,
9479 .iterate = btrfs_real_readdir,
9480 .unlocked_ioctl = btrfs_ioctl,
9481 #ifdef CONFIG_COMPAT
9482 .compat_ioctl = btrfs_ioctl,
9484 .release = btrfs_release_file,
9485 .fsync = btrfs_sync_file,
9488 static struct extent_io_ops btrfs_extent_io_ops = {
9489 .fill_delalloc = run_delalloc_range,
9490 .submit_bio_hook = btrfs_submit_bio_hook,
9491 .merge_bio_hook = btrfs_merge_bio_hook,
9492 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
9493 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
9494 .writepage_start_hook = btrfs_writepage_start_hook,
9495 .set_bit_hook = btrfs_set_bit_hook,
9496 .clear_bit_hook = btrfs_clear_bit_hook,
9497 .merge_extent_hook = btrfs_merge_extent_hook,
9498 .split_extent_hook = btrfs_split_extent_hook,
9502 * btrfs doesn't support the bmap operation because swapfiles
9503 * use bmap to make a mapping of extents in the file. They assume
9504 * these extents won't change over the life of the file and they
9505 * use the bmap result to do IO directly to the drive.
9507 * the btrfs bmap call would return logical addresses that aren't
9508 * suitable for IO and they also will change frequently as COW
9509 * operations happen. So, swapfile + btrfs == corruption.
9511 * For now we're avoiding this by dropping bmap.
9513 static const struct address_space_operations btrfs_aops = {
9514 .readpage = btrfs_readpage,
9515 .writepage = btrfs_writepage,
9516 .writepages = btrfs_writepages,
9517 .readpages = btrfs_readpages,
9518 .direct_IO = btrfs_direct_IO,
9519 .invalidatepage = btrfs_invalidatepage,
9520 .releasepage = btrfs_releasepage,
9521 .set_page_dirty = btrfs_set_page_dirty,
9522 .error_remove_page = generic_error_remove_page,
9525 static const struct address_space_operations btrfs_symlink_aops = {
9526 .readpage = btrfs_readpage,
9527 .writepage = btrfs_writepage,
9528 .invalidatepage = btrfs_invalidatepage,
9529 .releasepage = btrfs_releasepage,
9532 static const struct inode_operations btrfs_file_inode_operations = {
9533 .getattr = btrfs_getattr,
9534 .setattr = btrfs_setattr,
9535 .setxattr = btrfs_setxattr,
9536 .getxattr = btrfs_getxattr,
9537 .listxattr = btrfs_listxattr,
9538 .removexattr = btrfs_removexattr,
9539 .permission = btrfs_permission,
9540 .fiemap = btrfs_fiemap,
9541 .get_acl = btrfs_get_acl,
9542 .set_acl = btrfs_set_acl,
9543 .update_time = btrfs_update_time,
9545 static const struct inode_operations btrfs_special_inode_operations = {
9546 .getattr = btrfs_getattr,
9547 .setattr = btrfs_setattr,
9548 .permission = btrfs_permission,
9549 .setxattr = btrfs_setxattr,
9550 .getxattr = btrfs_getxattr,
9551 .listxattr = btrfs_listxattr,
9552 .removexattr = btrfs_removexattr,
9553 .get_acl = btrfs_get_acl,
9554 .set_acl = btrfs_set_acl,
9555 .update_time = btrfs_update_time,
9557 static const struct inode_operations btrfs_symlink_inode_operations = {
9558 .readlink = generic_readlink,
9559 .follow_link = page_follow_link_light,
9560 .put_link = page_put_link,
9561 .getattr = btrfs_getattr,
9562 .setattr = btrfs_setattr,
9563 .permission = btrfs_permission,
9564 .setxattr = btrfs_setxattr,
9565 .getxattr = btrfs_getxattr,
9566 .listxattr = btrfs_listxattr,
9567 .removexattr = btrfs_removexattr,
9568 .update_time = btrfs_update_time,
9571 const struct dentry_operations btrfs_dentry_operations = {
9572 .d_delete = btrfs_dentry_delete,
9573 .d_release = btrfs_dentry_release,