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/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
41 #include <linux/mount.h>
42 #include <linux/btrfs.h>
43 #include <linux/blkdev.h>
44 #include <linux/posix_acl_xattr.h>
45 #include <linux/uio.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"
65 struct btrfs_iget_args {
66 struct btrfs_key *location;
67 struct btrfs_root *root;
70 struct btrfs_dio_data {
71 u64 outstanding_extents;
73 u64 unsubmitted_oe_range_start;
74 u64 unsubmitted_oe_range_end;
77 static const struct inode_operations btrfs_dir_inode_operations;
78 static const struct inode_operations btrfs_symlink_inode_operations;
79 static const struct inode_operations btrfs_dir_ro_inode_operations;
80 static const struct inode_operations btrfs_special_inode_operations;
81 static const struct inode_operations btrfs_file_inode_operations;
82 static const struct address_space_operations btrfs_aops;
83 static const struct address_space_operations btrfs_symlink_aops;
84 static const struct file_operations btrfs_dir_file_operations;
85 static const struct extent_io_ops btrfs_extent_io_ops;
87 static struct kmem_cache *btrfs_inode_cachep;
88 struct kmem_cache *btrfs_trans_handle_cachep;
89 struct kmem_cache *btrfs_transaction_cachep;
90 struct kmem_cache *btrfs_path_cachep;
91 struct kmem_cache *btrfs_free_space_cachep;
94 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
95 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
96 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
97 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
98 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
99 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
100 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
101 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
104 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
105 static int btrfs_truncate(struct inode *inode);
106 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
107 static noinline int cow_file_range(struct inode *inode,
108 struct page *locked_page,
109 u64 start, u64 end, u64 delalloc_end,
110 int *page_started, unsigned long *nr_written,
111 int unlock, struct btrfs_dedupe_hash *hash);
112 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
113 u64 len, u64 orig_start,
114 u64 block_start, u64 block_len,
115 u64 orig_block_len, u64 ram_bytes,
118 static int btrfs_dirty_inode(struct inode *inode);
120 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
121 void btrfs_test_inode_set_ops(struct inode *inode)
123 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
127 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
128 struct inode *inode, struct inode *dir,
129 const struct qstr *qstr)
133 err = btrfs_init_acl(trans, inode, dir);
135 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
140 * this does all the hard work for inserting an inline extent into
141 * the btree. The caller should have done a btrfs_drop_extents so that
142 * no overlapping inline items exist in the btree
144 static int insert_inline_extent(struct btrfs_trans_handle *trans,
145 struct btrfs_path *path, int extent_inserted,
146 struct btrfs_root *root, struct inode *inode,
147 u64 start, size_t size, size_t compressed_size,
149 struct page **compressed_pages)
151 struct extent_buffer *leaf;
152 struct page *page = NULL;
155 struct btrfs_file_extent_item *ei;
158 size_t cur_size = size;
159 unsigned long offset;
161 if (compressed_size && compressed_pages)
162 cur_size = compressed_size;
164 inode_add_bytes(inode, size);
166 if (!extent_inserted) {
167 struct btrfs_key key;
170 key.objectid = btrfs_ino(inode);
172 key.type = BTRFS_EXTENT_DATA_KEY;
174 datasize = btrfs_file_extent_calc_inline_size(cur_size);
175 path->leave_spinning = 1;
176 ret = btrfs_insert_empty_item(trans, root, path, &key,
183 leaf = path->nodes[0];
184 ei = btrfs_item_ptr(leaf, path->slots[0],
185 struct btrfs_file_extent_item);
186 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
187 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
188 btrfs_set_file_extent_encryption(leaf, ei, 0);
189 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
190 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
191 ptr = btrfs_file_extent_inline_start(ei);
193 if (compress_type != BTRFS_COMPRESS_NONE) {
196 while (compressed_size > 0) {
197 cpage = compressed_pages[i];
198 cur_size = min_t(unsigned long, compressed_size,
201 kaddr = kmap_atomic(cpage);
202 write_extent_buffer(leaf, kaddr, ptr, cur_size);
203 kunmap_atomic(kaddr);
207 compressed_size -= cur_size;
209 btrfs_set_file_extent_compression(leaf, ei,
212 page = find_get_page(inode->i_mapping,
213 start >> PAGE_SHIFT);
214 btrfs_set_file_extent_compression(leaf, ei, 0);
215 kaddr = kmap_atomic(page);
216 offset = start & (PAGE_SIZE - 1);
217 write_extent_buffer(leaf, kaddr + offset, ptr, size);
218 kunmap_atomic(kaddr);
221 btrfs_mark_buffer_dirty(leaf);
222 btrfs_release_path(path);
225 * we're an inline extent, so nobody can
226 * extend the file past i_size without locking
227 * a page we already have locked.
229 * We must do any isize and inode updates
230 * before we unlock the pages. Otherwise we
231 * could end up racing with unlink.
233 BTRFS_I(inode)->disk_i_size = inode->i_size;
234 ret = btrfs_update_inode(trans, root, inode);
243 * conditionally insert an inline extent into the file. This
244 * does the checks required to make sure the data is small enough
245 * to fit as an inline extent.
247 static noinline int cow_file_range_inline(struct btrfs_root *root,
248 struct inode *inode, u64 start,
249 u64 end, size_t compressed_size,
251 struct page **compressed_pages)
253 struct btrfs_trans_handle *trans;
254 u64 isize = i_size_read(inode);
255 u64 actual_end = min(end + 1, isize);
256 u64 inline_len = actual_end - start;
257 u64 aligned_end = ALIGN(end, root->sectorsize);
258 u64 data_len = inline_len;
260 struct btrfs_path *path;
261 int extent_inserted = 0;
262 u32 extent_item_size;
265 data_len = compressed_size;
268 actual_end > root->sectorsize ||
269 data_len > BTRFS_MAX_INLINE_DATA_SIZE(root) ||
271 (actual_end & (root->sectorsize - 1)) == 0) ||
273 data_len > root->fs_info->max_inline) {
277 path = btrfs_alloc_path();
281 trans = btrfs_join_transaction(root);
283 btrfs_free_path(path);
284 return PTR_ERR(trans);
286 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
288 if (compressed_size && compressed_pages)
289 extent_item_size = btrfs_file_extent_calc_inline_size(
292 extent_item_size = btrfs_file_extent_calc_inline_size(
295 ret = __btrfs_drop_extents(trans, root, inode, path,
296 start, aligned_end, NULL,
297 1, 1, extent_item_size, &extent_inserted);
299 btrfs_abort_transaction(trans, ret);
303 if (isize > actual_end)
304 inline_len = min_t(u64, isize, actual_end);
305 ret = insert_inline_extent(trans, path, extent_inserted,
307 inline_len, compressed_size,
308 compress_type, compressed_pages);
309 if (ret && ret != -ENOSPC) {
310 btrfs_abort_transaction(trans, ret);
312 } else if (ret == -ENOSPC) {
317 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
318 btrfs_delalloc_release_metadata(inode, end + 1 - start);
319 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
322 * Don't forget to free the reserved space, as for inlined extent
323 * it won't count as data extent, free them directly here.
324 * And at reserve time, it's always aligned to page size, so
325 * just free one page here.
327 btrfs_qgroup_free_data(inode, 0, PAGE_SIZE);
328 btrfs_free_path(path);
329 btrfs_end_transaction(trans, root);
333 struct async_extent {
338 unsigned long nr_pages;
340 struct list_head list;
345 struct btrfs_root *root;
346 struct page *locked_page;
349 struct list_head extents;
350 struct btrfs_work work;
353 static noinline int add_async_extent(struct async_cow *cow,
354 u64 start, u64 ram_size,
357 unsigned long nr_pages,
360 struct async_extent *async_extent;
362 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
363 BUG_ON(!async_extent); /* -ENOMEM */
364 async_extent->start = start;
365 async_extent->ram_size = ram_size;
366 async_extent->compressed_size = compressed_size;
367 async_extent->pages = pages;
368 async_extent->nr_pages = nr_pages;
369 async_extent->compress_type = compress_type;
370 list_add_tail(&async_extent->list, &cow->extents);
374 static inline int inode_need_compress(struct inode *inode)
376 struct btrfs_root *root = BTRFS_I(inode)->root;
379 if (btrfs_test_opt(root->fs_info, FORCE_COMPRESS))
381 /* bad compression ratios */
382 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
384 if (btrfs_test_opt(root->fs_info, COMPRESS) ||
385 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
386 BTRFS_I(inode)->force_compress)
392 * we create compressed extents in two phases. The first
393 * phase compresses a range of pages that have already been
394 * locked (both pages and state bits are locked).
396 * This is done inside an ordered work queue, and the compression
397 * is spread across many cpus. The actual IO submission is step
398 * two, and the ordered work queue takes care of making sure that
399 * happens in the same order things were put onto the queue by
400 * writepages and friends.
402 * If this code finds it can't get good compression, it puts an
403 * entry onto the work queue to write the uncompressed bytes. This
404 * makes sure that both compressed inodes and uncompressed inodes
405 * are written in the same order that the flusher thread sent them
408 static noinline void compress_file_range(struct inode *inode,
409 struct page *locked_page,
411 struct async_cow *async_cow,
414 struct btrfs_root *root = BTRFS_I(inode)->root;
416 u64 blocksize = root->sectorsize;
418 u64 isize = i_size_read(inode);
420 struct page **pages = NULL;
421 unsigned long nr_pages;
422 unsigned long nr_pages_ret = 0;
423 unsigned long total_compressed = 0;
424 unsigned long total_in = 0;
425 unsigned long max_compressed = SZ_128K;
426 unsigned long max_uncompressed = SZ_128K;
429 int compress_type = root->fs_info->compress_type;
432 /* if this is a small write inside eof, kick off a defrag */
433 if ((end - start + 1) < SZ_16K &&
434 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
435 btrfs_add_inode_defrag(NULL, inode);
437 actual_end = min_t(u64, isize, end + 1);
440 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
441 nr_pages = min_t(unsigned long, nr_pages, SZ_128K / PAGE_SIZE);
444 * we don't want to send crud past the end of i_size through
445 * compression, that's just a waste of CPU time. So, if the
446 * end of the file is before the start of our current
447 * requested range of bytes, we bail out to the uncompressed
448 * cleanup code that can deal with all of this.
450 * It isn't really the fastest way to fix things, but this is a
451 * very uncommon corner.
453 if (actual_end <= start)
454 goto cleanup_and_bail_uncompressed;
456 total_compressed = actual_end - start;
459 * skip compression for a small file range(<=blocksize) that
460 * isn't an inline extent, since it doesn't save disk space at all.
462 if (total_compressed <= blocksize &&
463 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
464 goto cleanup_and_bail_uncompressed;
466 /* we want to make sure that amount of ram required to uncompress
467 * an extent is reasonable, so we limit the total size in ram
468 * of a compressed extent to 128k. This is a crucial number
469 * because it also controls how easily we can spread reads across
470 * cpus for decompression.
472 * We also want to make sure the amount of IO required to do
473 * a random read is reasonably small, so we limit the size of
474 * a compressed extent to 128k.
476 total_compressed = min(total_compressed, max_uncompressed);
477 num_bytes = ALIGN(end - start + 1, blocksize);
478 num_bytes = max(blocksize, num_bytes);
483 * we do compression for mount -o compress and when the
484 * inode has not been flagged as nocompress. This flag can
485 * change at any time if we discover bad compression ratios.
487 if (inode_need_compress(inode)) {
489 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
491 /* just bail out to the uncompressed code */
495 if (BTRFS_I(inode)->force_compress)
496 compress_type = BTRFS_I(inode)->force_compress;
499 * we need to call clear_page_dirty_for_io on each
500 * page in the range. Otherwise applications with the file
501 * mmap'd can wander in and change the page contents while
502 * we are compressing them.
504 * If the compression fails for any reason, we set the pages
505 * dirty again later on.
507 extent_range_clear_dirty_for_io(inode, start, end);
509 ret = btrfs_compress_pages(compress_type,
510 inode->i_mapping, start,
511 total_compressed, pages,
512 nr_pages, &nr_pages_ret,
518 unsigned long offset = total_compressed &
520 struct page *page = pages[nr_pages_ret - 1];
523 /* zero the tail end of the last page, we might be
524 * sending it down to disk
527 kaddr = kmap_atomic(page);
528 memset(kaddr + offset, 0,
530 kunmap_atomic(kaddr);
537 /* lets try to make an inline extent */
538 if (ret || total_in < (actual_end - start)) {
539 /* we didn't compress the entire range, try
540 * to make an uncompressed inline extent.
542 ret = cow_file_range_inline(root, inode, start, end,
545 /* try making a compressed inline extent */
546 ret = cow_file_range_inline(root, inode, start, end,
548 compress_type, pages);
551 unsigned long clear_flags = EXTENT_DELALLOC |
553 unsigned long page_error_op;
555 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
556 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
559 * inline extent creation worked or returned error,
560 * we don't need to create any more async work items.
561 * Unlock and free up our temp pages.
563 extent_clear_unlock_delalloc(inode, start, end, NULL,
564 clear_flags, PAGE_UNLOCK |
569 btrfs_free_reserved_data_space_noquota(inode, start,
577 * we aren't doing an inline extent round the compressed size
578 * up to a block size boundary so the allocator does sane
581 total_compressed = ALIGN(total_compressed, blocksize);
584 * one last check to make sure the compression is really a
585 * win, compare the page count read with the blocks on disk
587 total_in = ALIGN(total_in, PAGE_SIZE);
588 if (total_compressed >= total_in) {
591 num_bytes = total_in;
595 * The async work queues will take care of doing actual
596 * allocation on disk for these compressed pages, and
597 * will submit them to the elevator.
599 add_async_extent(async_cow, start, num_bytes,
600 total_compressed, pages, nr_pages_ret,
603 if (start + num_bytes < end) {
614 * the compression code ran but failed to make things smaller,
615 * free any pages it allocated and our page pointer array
617 for (i = 0; i < nr_pages_ret; i++) {
618 WARN_ON(pages[i]->mapping);
623 total_compressed = 0;
626 /* flag the file so we don't compress in the future */
627 if (!btrfs_test_opt(root->fs_info, FORCE_COMPRESS) &&
628 !(BTRFS_I(inode)->force_compress)) {
629 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
632 cleanup_and_bail_uncompressed:
634 * No compression, but we still need to write the pages in the file
635 * we've been given so far. redirty the locked page if it corresponds
636 * to our extent and set things up for the async work queue to run
637 * cow_file_range to do the normal delalloc dance.
639 if (page_offset(locked_page) >= start &&
640 page_offset(locked_page) <= end)
641 __set_page_dirty_nobuffers(locked_page);
642 /* unlocked later on in the async handlers */
645 extent_range_redirty_for_io(inode, start, end);
646 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
647 BTRFS_COMPRESS_NONE);
653 for (i = 0; i < nr_pages_ret; i++) {
654 WARN_ON(pages[i]->mapping);
660 static void free_async_extent_pages(struct async_extent *async_extent)
664 if (!async_extent->pages)
667 for (i = 0; i < async_extent->nr_pages; i++) {
668 WARN_ON(async_extent->pages[i]->mapping);
669 put_page(async_extent->pages[i]);
671 kfree(async_extent->pages);
672 async_extent->nr_pages = 0;
673 async_extent->pages = NULL;
677 * phase two of compressed writeback. This is the ordered portion
678 * of the code, which only gets called in the order the work was
679 * queued. We walk all the async extents created by compress_file_range
680 * and send them down to the disk.
682 static noinline void submit_compressed_extents(struct inode *inode,
683 struct async_cow *async_cow)
685 struct async_extent *async_extent;
687 struct btrfs_key ins;
688 struct extent_map *em;
689 struct btrfs_root *root = BTRFS_I(inode)->root;
690 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
691 struct extent_io_tree *io_tree;
695 while (!list_empty(&async_cow->extents)) {
696 async_extent = list_entry(async_cow->extents.next,
697 struct async_extent, list);
698 list_del(&async_extent->list);
700 io_tree = &BTRFS_I(inode)->io_tree;
703 /* did the compression code fall back to uncompressed IO? */
704 if (!async_extent->pages) {
705 int page_started = 0;
706 unsigned long nr_written = 0;
708 lock_extent(io_tree, async_extent->start,
709 async_extent->start +
710 async_extent->ram_size - 1);
712 /* allocate blocks */
713 ret = cow_file_range(inode, async_cow->locked_page,
715 async_extent->start +
716 async_extent->ram_size - 1,
717 async_extent->start +
718 async_extent->ram_size - 1,
719 &page_started, &nr_written, 0,
725 * if page_started, cow_file_range inserted an
726 * inline extent and took care of all the unlocking
727 * and IO for us. Otherwise, we need to submit
728 * all those pages down to the drive.
730 if (!page_started && !ret)
731 extent_write_locked_range(io_tree,
732 inode, async_extent->start,
733 async_extent->start +
734 async_extent->ram_size - 1,
738 unlock_page(async_cow->locked_page);
744 lock_extent(io_tree, async_extent->start,
745 async_extent->start + async_extent->ram_size - 1);
747 ret = btrfs_reserve_extent(root, async_extent->ram_size,
748 async_extent->compressed_size,
749 async_extent->compressed_size,
750 0, alloc_hint, &ins, 1, 1);
752 free_async_extent_pages(async_extent);
754 if (ret == -ENOSPC) {
755 unlock_extent(io_tree, async_extent->start,
756 async_extent->start +
757 async_extent->ram_size - 1);
760 * we need to redirty the pages if we decide to
761 * fallback to uncompressed IO, otherwise we
762 * will not submit these pages down to lower
765 extent_range_redirty_for_io(inode,
767 async_extent->start +
768 async_extent->ram_size - 1);
775 * here we're doing allocation and writeback of the
778 btrfs_drop_extent_cache(inode, async_extent->start,
779 async_extent->start +
780 async_extent->ram_size - 1, 0);
782 em = alloc_extent_map();
785 goto out_free_reserve;
787 em->start = async_extent->start;
788 em->len = async_extent->ram_size;
789 em->orig_start = em->start;
790 em->mod_start = em->start;
791 em->mod_len = em->len;
793 em->block_start = ins.objectid;
794 em->block_len = ins.offset;
795 em->orig_block_len = ins.offset;
796 em->ram_bytes = async_extent->ram_size;
797 em->bdev = root->fs_info->fs_devices->latest_bdev;
798 em->compress_type = async_extent->compress_type;
799 set_bit(EXTENT_FLAG_PINNED, &em->flags);
800 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
804 write_lock(&em_tree->lock);
805 ret = add_extent_mapping(em_tree, em, 1);
806 write_unlock(&em_tree->lock);
807 if (ret != -EEXIST) {
811 btrfs_drop_extent_cache(inode, async_extent->start,
812 async_extent->start +
813 async_extent->ram_size - 1, 0);
817 goto out_free_reserve;
819 ret = btrfs_add_ordered_extent_compress(inode,
822 async_extent->ram_size,
824 BTRFS_ORDERED_COMPRESSED,
825 async_extent->compress_type);
827 btrfs_drop_extent_cache(inode, async_extent->start,
828 async_extent->start +
829 async_extent->ram_size - 1, 0);
830 goto out_free_reserve;
832 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
835 * clear dirty, set writeback and unlock the pages.
837 extent_clear_unlock_delalloc(inode, async_extent->start,
838 async_extent->start +
839 async_extent->ram_size - 1,
840 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
841 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
843 ret = btrfs_submit_compressed_write(inode,
845 async_extent->ram_size,
847 ins.offset, async_extent->pages,
848 async_extent->nr_pages);
850 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
851 struct page *p = async_extent->pages[0];
852 const u64 start = async_extent->start;
853 const u64 end = start + async_extent->ram_size - 1;
855 p->mapping = inode->i_mapping;
856 tree->ops->writepage_end_io_hook(p, start, end,
859 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
862 free_async_extent_pages(async_extent);
864 alloc_hint = ins.objectid + ins.offset;
870 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
871 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
873 extent_clear_unlock_delalloc(inode, async_extent->start,
874 async_extent->start +
875 async_extent->ram_size - 1,
876 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
877 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
878 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
879 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
881 free_async_extent_pages(async_extent);
886 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
889 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
890 struct extent_map *em;
893 read_lock(&em_tree->lock);
894 em = search_extent_mapping(em_tree, start, num_bytes);
897 * if block start isn't an actual block number then find the
898 * first block in this inode and use that as a hint. If that
899 * block is also bogus then just don't worry about it.
901 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
903 em = search_extent_mapping(em_tree, 0, 0);
904 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
905 alloc_hint = em->block_start;
909 alloc_hint = em->block_start;
913 read_unlock(&em_tree->lock);
919 * when extent_io.c finds a delayed allocation range in the file,
920 * the call backs end up in this code. The basic idea is to
921 * allocate extents on disk for the range, and create ordered data structs
922 * in ram to track those extents.
924 * locked_page is the page that writepage had locked already. We use
925 * it to make sure we don't do extra locks or unlocks.
927 * *page_started is set to one if we unlock locked_page and do everything
928 * required to start IO on it. It may be clean and already done with
931 static noinline int cow_file_range(struct inode *inode,
932 struct page *locked_page,
933 u64 start, u64 end, u64 delalloc_end,
934 int *page_started, unsigned long *nr_written,
935 int unlock, struct btrfs_dedupe_hash *hash)
937 struct btrfs_root *root = BTRFS_I(inode)->root;
940 unsigned long ram_size;
943 u64 blocksize = root->sectorsize;
944 struct btrfs_key ins;
945 struct extent_map *em;
946 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
949 if (btrfs_is_free_space_inode(inode)) {
955 num_bytes = ALIGN(end - start + 1, blocksize);
956 num_bytes = max(blocksize, num_bytes);
957 disk_num_bytes = num_bytes;
959 /* if this is a small write inside eof, kick off defrag */
960 if (num_bytes < SZ_64K &&
961 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
962 btrfs_add_inode_defrag(NULL, inode);
965 /* lets try to make an inline extent */
966 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
969 extent_clear_unlock_delalloc(inode, start, end, NULL,
970 EXTENT_LOCKED | EXTENT_DELALLOC |
971 EXTENT_DEFRAG, PAGE_UNLOCK |
972 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
974 btrfs_free_reserved_data_space_noquota(inode, start,
976 *nr_written = *nr_written +
977 (end - start + PAGE_SIZE) / PAGE_SIZE;
980 } else if (ret < 0) {
985 BUG_ON(disk_num_bytes >
986 btrfs_super_total_bytes(root->fs_info->super_copy));
988 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
989 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
991 while (disk_num_bytes > 0) {
994 cur_alloc_size = disk_num_bytes;
995 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
996 root->sectorsize, 0, alloc_hint,
1001 em = alloc_extent_map();
1007 em->orig_start = em->start;
1008 ram_size = ins.offset;
1009 em->len = ins.offset;
1010 em->mod_start = em->start;
1011 em->mod_len = em->len;
1013 em->block_start = ins.objectid;
1014 em->block_len = ins.offset;
1015 em->orig_block_len = ins.offset;
1016 em->ram_bytes = ram_size;
1017 em->bdev = root->fs_info->fs_devices->latest_bdev;
1018 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1019 em->generation = -1;
1022 write_lock(&em_tree->lock);
1023 ret = add_extent_mapping(em_tree, em, 1);
1024 write_unlock(&em_tree->lock);
1025 if (ret != -EEXIST) {
1026 free_extent_map(em);
1029 btrfs_drop_extent_cache(inode, start,
1030 start + ram_size - 1, 0);
1035 cur_alloc_size = ins.offset;
1036 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1037 ram_size, cur_alloc_size, 0);
1039 goto out_drop_extent_cache;
1041 if (root->root_key.objectid ==
1042 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1043 ret = btrfs_reloc_clone_csums(inode, start,
1046 goto out_drop_extent_cache;
1049 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
1051 if (disk_num_bytes < cur_alloc_size)
1054 /* we're not doing compressed IO, don't unlock the first
1055 * page (which the caller expects to stay locked), don't
1056 * clear any dirty bits and don't set any writeback bits
1058 * Do set the Private2 bit so we know this page was properly
1059 * setup for writepage
1061 op = unlock ? PAGE_UNLOCK : 0;
1062 op |= PAGE_SET_PRIVATE2;
1064 extent_clear_unlock_delalloc(inode, start,
1065 start + ram_size - 1, locked_page,
1066 EXTENT_LOCKED | EXTENT_DELALLOC,
1068 disk_num_bytes -= cur_alloc_size;
1069 num_bytes -= cur_alloc_size;
1070 alloc_hint = ins.objectid + ins.offset;
1071 start += cur_alloc_size;
1076 out_drop_extent_cache:
1077 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1079 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
1080 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1082 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1083 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1084 EXTENT_DELALLOC | EXTENT_DEFRAG,
1085 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1086 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1091 * work queue call back to started compression on a file and pages
1093 static noinline void async_cow_start(struct btrfs_work *work)
1095 struct async_cow *async_cow;
1097 async_cow = container_of(work, struct async_cow, work);
1099 compress_file_range(async_cow->inode, async_cow->locked_page,
1100 async_cow->start, async_cow->end, async_cow,
1102 if (num_added == 0) {
1103 btrfs_add_delayed_iput(async_cow->inode);
1104 async_cow->inode = NULL;
1109 * work queue call back to submit previously compressed pages
1111 static noinline void async_cow_submit(struct btrfs_work *work)
1113 struct async_cow *async_cow;
1114 struct btrfs_root *root;
1115 unsigned long nr_pages;
1117 async_cow = container_of(work, struct async_cow, work);
1119 root = async_cow->root;
1120 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1124 * atomic_sub_return implies a barrier for waitqueue_active
1126 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1128 waitqueue_active(&root->fs_info->async_submit_wait))
1129 wake_up(&root->fs_info->async_submit_wait);
1131 if (async_cow->inode)
1132 submit_compressed_extents(async_cow->inode, async_cow);
1135 static noinline void async_cow_free(struct btrfs_work *work)
1137 struct async_cow *async_cow;
1138 async_cow = container_of(work, struct async_cow, work);
1139 if (async_cow->inode)
1140 btrfs_add_delayed_iput(async_cow->inode);
1144 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1145 u64 start, u64 end, int *page_started,
1146 unsigned long *nr_written)
1148 struct async_cow *async_cow;
1149 struct btrfs_root *root = BTRFS_I(inode)->root;
1150 unsigned long nr_pages;
1152 int limit = 10 * SZ_1M;
1154 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1155 1, 0, NULL, GFP_NOFS);
1156 while (start < end) {
1157 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1158 BUG_ON(!async_cow); /* -ENOMEM */
1159 async_cow->inode = igrab(inode);
1160 async_cow->root = root;
1161 async_cow->locked_page = locked_page;
1162 async_cow->start = start;
1164 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1165 !btrfs_test_opt(root->fs_info, FORCE_COMPRESS))
1168 cur_end = min(end, start + SZ_512K - 1);
1170 async_cow->end = cur_end;
1171 INIT_LIST_HEAD(&async_cow->extents);
1173 btrfs_init_work(&async_cow->work,
1174 btrfs_delalloc_helper,
1175 async_cow_start, async_cow_submit,
1178 nr_pages = (cur_end - start + PAGE_SIZE) >>
1180 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1182 btrfs_queue_work(root->fs_info->delalloc_workers,
1185 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1186 wait_event(root->fs_info->async_submit_wait,
1187 (atomic_read(&root->fs_info->async_delalloc_pages) <
1191 while (atomic_read(&root->fs_info->async_submit_draining) &&
1192 atomic_read(&root->fs_info->async_delalloc_pages)) {
1193 wait_event(root->fs_info->async_submit_wait,
1194 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1198 *nr_written += nr_pages;
1199 start = cur_end + 1;
1205 static noinline int csum_exist_in_range(struct btrfs_root *root,
1206 u64 bytenr, u64 num_bytes)
1209 struct btrfs_ordered_sum *sums;
1212 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1213 bytenr + num_bytes - 1, &list, 0);
1214 if (ret == 0 && list_empty(&list))
1217 while (!list_empty(&list)) {
1218 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1219 list_del(&sums->list);
1226 * when nowcow writeback call back. This checks for snapshots or COW copies
1227 * of the extents that exist in the file, and COWs the file as required.
1229 * If no cow copies or snapshots exist, we write directly to the existing
1232 static noinline int run_delalloc_nocow(struct inode *inode,
1233 struct page *locked_page,
1234 u64 start, u64 end, int *page_started, int force,
1235 unsigned long *nr_written)
1237 struct btrfs_root *root = BTRFS_I(inode)->root;
1238 struct btrfs_trans_handle *trans;
1239 struct extent_buffer *leaf;
1240 struct btrfs_path *path;
1241 struct btrfs_file_extent_item *fi;
1242 struct btrfs_key found_key;
1257 u64 ino = btrfs_ino(inode);
1259 path = btrfs_alloc_path();
1261 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1262 EXTENT_LOCKED | EXTENT_DELALLOC |
1263 EXTENT_DO_ACCOUNTING |
1264 EXTENT_DEFRAG, PAGE_UNLOCK |
1266 PAGE_SET_WRITEBACK |
1267 PAGE_END_WRITEBACK);
1271 nolock = btrfs_is_free_space_inode(inode);
1274 trans = btrfs_join_transaction_nolock(root);
1276 trans = btrfs_join_transaction(root);
1278 if (IS_ERR(trans)) {
1279 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1280 EXTENT_LOCKED | EXTENT_DELALLOC |
1281 EXTENT_DO_ACCOUNTING |
1282 EXTENT_DEFRAG, PAGE_UNLOCK |
1284 PAGE_SET_WRITEBACK |
1285 PAGE_END_WRITEBACK);
1286 btrfs_free_path(path);
1287 return PTR_ERR(trans);
1290 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1292 cow_start = (u64)-1;
1295 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1299 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1300 leaf = path->nodes[0];
1301 btrfs_item_key_to_cpu(leaf, &found_key,
1302 path->slots[0] - 1);
1303 if (found_key.objectid == ino &&
1304 found_key.type == BTRFS_EXTENT_DATA_KEY)
1309 leaf = path->nodes[0];
1310 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1311 ret = btrfs_next_leaf(root, path);
1316 leaf = path->nodes[0];
1322 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1324 if (found_key.objectid > ino)
1326 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1327 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1331 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1332 found_key.offset > end)
1335 if (found_key.offset > cur_offset) {
1336 extent_end = found_key.offset;
1341 fi = btrfs_item_ptr(leaf, path->slots[0],
1342 struct btrfs_file_extent_item);
1343 extent_type = btrfs_file_extent_type(leaf, fi);
1345 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1346 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1347 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1348 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1349 extent_offset = btrfs_file_extent_offset(leaf, fi);
1350 extent_end = found_key.offset +
1351 btrfs_file_extent_num_bytes(leaf, fi);
1353 btrfs_file_extent_disk_num_bytes(leaf, fi);
1354 if (extent_end <= start) {
1358 if (disk_bytenr == 0)
1360 if (btrfs_file_extent_compression(leaf, fi) ||
1361 btrfs_file_extent_encryption(leaf, fi) ||
1362 btrfs_file_extent_other_encoding(leaf, fi))
1364 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1366 if (btrfs_extent_readonly(root, disk_bytenr))
1368 if (btrfs_cross_ref_exist(trans, root, ino,
1370 extent_offset, disk_bytenr))
1372 disk_bytenr += extent_offset;
1373 disk_bytenr += cur_offset - found_key.offset;
1374 num_bytes = min(end + 1, extent_end) - cur_offset;
1376 * if there are pending snapshots for this root,
1377 * we fall into common COW way.
1380 err = btrfs_start_write_no_snapshoting(root);
1385 * force cow if csum exists in the range.
1386 * this ensure that csum for a given extent are
1387 * either valid or do not exist.
1389 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1391 if (!btrfs_inc_nocow_writers(root->fs_info,
1395 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1396 extent_end = found_key.offset +
1397 btrfs_file_extent_inline_len(leaf,
1398 path->slots[0], fi);
1399 extent_end = ALIGN(extent_end, root->sectorsize);
1404 if (extent_end <= start) {
1406 if (!nolock && nocow)
1407 btrfs_end_write_no_snapshoting(root);
1409 btrfs_dec_nocow_writers(root->fs_info,
1414 if (cow_start == (u64)-1)
1415 cow_start = cur_offset;
1416 cur_offset = extent_end;
1417 if (cur_offset > end)
1423 btrfs_release_path(path);
1424 if (cow_start != (u64)-1) {
1425 ret = cow_file_range(inode, locked_page,
1426 cow_start, found_key.offset - 1,
1427 end, page_started, nr_written, 1,
1430 if (!nolock && nocow)
1431 btrfs_end_write_no_snapshoting(root);
1433 btrfs_dec_nocow_writers(root->fs_info,
1437 cow_start = (u64)-1;
1440 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1441 struct extent_map *em;
1442 struct extent_map_tree *em_tree;
1443 em_tree = &BTRFS_I(inode)->extent_tree;
1444 em = alloc_extent_map();
1445 BUG_ON(!em); /* -ENOMEM */
1446 em->start = cur_offset;
1447 em->orig_start = found_key.offset - extent_offset;
1448 em->len = num_bytes;
1449 em->block_len = num_bytes;
1450 em->block_start = disk_bytenr;
1451 em->orig_block_len = disk_num_bytes;
1452 em->ram_bytes = ram_bytes;
1453 em->bdev = root->fs_info->fs_devices->latest_bdev;
1454 em->mod_start = em->start;
1455 em->mod_len = em->len;
1456 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1457 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1458 em->generation = -1;
1460 write_lock(&em_tree->lock);
1461 ret = add_extent_mapping(em_tree, em, 1);
1462 write_unlock(&em_tree->lock);
1463 if (ret != -EEXIST) {
1464 free_extent_map(em);
1467 btrfs_drop_extent_cache(inode, em->start,
1468 em->start + em->len - 1, 0);
1470 type = BTRFS_ORDERED_PREALLOC;
1472 type = BTRFS_ORDERED_NOCOW;
1475 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1476 num_bytes, num_bytes, type);
1478 btrfs_dec_nocow_writers(root->fs_info, disk_bytenr);
1479 BUG_ON(ret); /* -ENOMEM */
1481 if (root->root_key.objectid ==
1482 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1483 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1486 if (!nolock && nocow)
1487 btrfs_end_write_no_snapshoting(root);
1492 extent_clear_unlock_delalloc(inode, cur_offset,
1493 cur_offset + num_bytes - 1,
1494 locked_page, EXTENT_LOCKED |
1496 EXTENT_CLEAR_DATA_RESV,
1497 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1499 if (!nolock && nocow)
1500 btrfs_end_write_no_snapshoting(root);
1501 cur_offset = extent_end;
1502 if (cur_offset > end)
1505 btrfs_release_path(path);
1507 if (cur_offset <= end && cow_start == (u64)-1) {
1508 cow_start = cur_offset;
1512 if (cow_start != (u64)-1) {
1513 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1514 page_started, nr_written, 1, NULL);
1520 err = btrfs_end_transaction(trans, root);
1524 if (ret && cur_offset < end)
1525 extent_clear_unlock_delalloc(inode, cur_offset, end,
1526 locked_page, EXTENT_LOCKED |
1527 EXTENT_DELALLOC | EXTENT_DEFRAG |
1528 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1530 PAGE_SET_WRITEBACK |
1531 PAGE_END_WRITEBACK);
1532 btrfs_free_path(path);
1536 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1539 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1540 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1544 * @defrag_bytes is a hint value, no spinlock held here,
1545 * if is not zero, it means the file is defragging.
1546 * Force cow if given extent needs to be defragged.
1548 if (BTRFS_I(inode)->defrag_bytes &&
1549 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1550 EXTENT_DEFRAG, 0, NULL))
1557 * extent_io.c call back to do delayed allocation processing
1559 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1560 u64 start, u64 end, int *page_started,
1561 unsigned long *nr_written)
1564 int force_cow = need_force_cow(inode, start, end);
1566 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1567 ret = run_delalloc_nocow(inode, locked_page, start, end,
1568 page_started, 1, nr_written);
1569 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1570 ret = run_delalloc_nocow(inode, locked_page, start, end,
1571 page_started, 0, nr_written);
1572 } else if (!inode_need_compress(inode)) {
1573 ret = cow_file_range(inode, locked_page, start, end, end,
1574 page_started, nr_written, 1, NULL);
1576 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1577 &BTRFS_I(inode)->runtime_flags);
1578 ret = cow_file_range_async(inode, locked_page, start, end,
1579 page_started, nr_written);
1584 static void btrfs_split_extent_hook(struct inode *inode,
1585 struct extent_state *orig, u64 split)
1589 /* not delalloc, ignore it */
1590 if (!(orig->state & EXTENT_DELALLOC))
1593 size = orig->end - orig->start + 1;
1594 if (size > BTRFS_MAX_EXTENT_SIZE) {
1599 * See the explanation in btrfs_merge_extent_hook, the same
1600 * applies here, just in reverse.
1602 new_size = orig->end - split + 1;
1603 num_extents = div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1604 BTRFS_MAX_EXTENT_SIZE);
1605 new_size = split - orig->start;
1606 num_extents += div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1607 BTRFS_MAX_EXTENT_SIZE);
1608 if (div64_u64(size + BTRFS_MAX_EXTENT_SIZE - 1,
1609 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1613 spin_lock(&BTRFS_I(inode)->lock);
1614 BTRFS_I(inode)->outstanding_extents++;
1615 spin_unlock(&BTRFS_I(inode)->lock);
1619 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1620 * extents so we can keep track of new extents that are just merged onto old
1621 * extents, such as when we are doing sequential writes, so we can properly
1622 * account for the metadata space we'll need.
1624 static void btrfs_merge_extent_hook(struct inode *inode,
1625 struct extent_state *new,
1626 struct extent_state *other)
1628 u64 new_size, old_size;
1631 /* not delalloc, ignore it */
1632 if (!(other->state & EXTENT_DELALLOC))
1635 if (new->start > other->start)
1636 new_size = new->end - other->start + 1;
1638 new_size = other->end - new->start + 1;
1640 /* we're not bigger than the max, unreserve the space and go */
1641 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1642 spin_lock(&BTRFS_I(inode)->lock);
1643 BTRFS_I(inode)->outstanding_extents--;
1644 spin_unlock(&BTRFS_I(inode)->lock);
1649 * We have to add up either side to figure out how many extents were
1650 * accounted for before we merged into one big extent. If the number of
1651 * extents we accounted for is <= the amount we need for the new range
1652 * then we can return, otherwise drop. Think of it like this
1656 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1657 * need 2 outstanding extents, on one side we have 1 and the other side
1658 * we have 1 so they are == and we can return. But in this case
1660 * [MAX_SIZE+4k][MAX_SIZE+4k]
1662 * Each range on their own accounts for 2 extents, but merged together
1663 * they are only 3 extents worth of accounting, so we need to drop in
1666 old_size = other->end - other->start + 1;
1667 num_extents = div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1668 BTRFS_MAX_EXTENT_SIZE);
1669 old_size = new->end - new->start + 1;
1670 num_extents += div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1671 BTRFS_MAX_EXTENT_SIZE);
1673 if (div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1674 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1677 spin_lock(&BTRFS_I(inode)->lock);
1678 BTRFS_I(inode)->outstanding_extents--;
1679 spin_unlock(&BTRFS_I(inode)->lock);
1682 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1683 struct inode *inode)
1685 spin_lock(&root->delalloc_lock);
1686 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1687 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1688 &root->delalloc_inodes);
1689 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1690 &BTRFS_I(inode)->runtime_flags);
1691 root->nr_delalloc_inodes++;
1692 if (root->nr_delalloc_inodes == 1) {
1693 spin_lock(&root->fs_info->delalloc_root_lock);
1694 BUG_ON(!list_empty(&root->delalloc_root));
1695 list_add_tail(&root->delalloc_root,
1696 &root->fs_info->delalloc_roots);
1697 spin_unlock(&root->fs_info->delalloc_root_lock);
1700 spin_unlock(&root->delalloc_lock);
1703 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1704 struct inode *inode)
1706 spin_lock(&root->delalloc_lock);
1707 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1708 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1709 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1710 &BTRFS_I(inode)->runtime_flags);
1711 root->nr_delalloc_inodes--;
1712 if (!root->nr_delalloc_inodes) {
1713 spin_lock(&root->fs_info->delalloc_root_lock);
1714 BUG_ON(list_empty(&root->delalloc_root));
1715 list_del_init(&root->delalloc_root);
1716 spin_unlock(&root->fs_info->delalloc_root_lock);
1719 spin_unlock(&root->delalloc_lock);
1723 * extent_io.c set_bit_hook, used to track delayed allocation
1724 * bytes in this file, and to maintain the list of inodes that
1725 * have pending delalloc work to be done.
1727 static void btrfs_set_bit_hook(struct inode *inode,
1728 struct extent_state *state, unsigned *bits)
1731 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1734 * set_bit and clear bit hooks normally require _irqsave/restore
1735 * but in this case, we are only testing for the DELALLOC
1736 * bit, which is only set or cleared with irqs on
1738 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1739 struct btrfs_root *root = BTRFS_I(inode)->root;
1740 u64 len = state->end + 1 - state->start;
1741 bool do_list = !btrfs_is_free_space_inode(inode);
1743 if (*bits & EXTENT_FIRST_DELALLOC) {
1744 *bits &= ~EXTENT_FIRST_DELALLOC;
1746 spin_lock(&BTRFS_I(inode)->lock);
1747 BTRFS_I(inode)->outstanding_extents++;
1748 spin_unlock(&BTRFS_I(inode)->lock);
1751 /* For sanity tests */
1752 if (btrfs_is_testing(root->fs_info))
1755 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1756 root->fs_info->delalloc_batch);
1757 spin_lock(&BTRFS_I(inode)->lock);
1758 BTRFS_I(inode)->delalloc_bytes += len;
1759 if (*bits & EXTENT_DEFRAG)
1760 BTRFS_I(inode)->defrag_bytes += len;
1761 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1762 &BTRFS_I(inode)->runtime_flags))
1763 btrfs_add_delalloc_inodes(root, inode);
1764 spin_unlock(&BTRFS_I(inode)->lock);
1769 * extent_io.c clear_bit_hook, see set_bit_hook for why
1771 static void btrfs_clear_bit_hook(struct inode *inode,
1772 struct extent_state *state,
1775 u64 len = state->end + 1 - state->start;
1776 u64 num_extents = div64_u64(len + BTRFS_MAX_EXTENT_SIZE -1,
1777 BTRFS_MAX_EXTENT_SIZE);
1779 spin_lock(&BTRFS_I(inode)->lock);
1780 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1781 BTRFS_I(inode)->defrag_bytes -= len;
1782 spin_unlock(&BTRFS_I(inode)->lock);
1785 * set_bit and clear bit hooks normally require _irqsave/restore
1786 * but in this case, we are only testing for the DELALLOC
1787 * bit, which is only set or cleared with irqs on
1789 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1790 struct btrfs_root *root = BTRFS_I(inode)->root;
1791 bool do_list = !btrfs_is_free_space_inode(inode);
1793 if (*bits & EXTENT_FIRST_DELALLOC) {
1794 *bits &= ~EXTENT_FIRST_DELALLOC;
1795 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1796 spin_lock(&BTRFS_I(inode)->lock);
1797 BTRFS_I(inode)->outstanding_extents -= num_extents;
1798 spin_unlock(&BTRFS_I(inode)->lock);
1802 * We don't reserve metadata space for space cache inodes so we
1803 * don't need to call dellalloc_release_metadata if there is an
1806 if (*bits & EXTENT_DO_ACCOUNTING &&
1807 root != root->fs_info->tree_root)
1808 btrfs_delalloc_release_metadata(inode, len);
1810 /* For sanity tests. */
1811 if (btrfs_is_testing(root->fs_info))
1814 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1815 && do_list && !(state->state & EXTENT_NORESERVE)
1816 && (*bits & (EXTENT_DO_ACCOUNTING |
1817 EXTENT_CLEAR_DATA_RESV)))
1818 btrfs_free_reserved_data_space_noquota(inode,
1821 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1822 root->fs_info->delalloc_batch);
1823 spin_lock(&BTRFS_I(inode)->lock);
1824 BTRFS_I(inode)->delalloc_bytes -= len;
1825 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1826 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1827 &BTRFS_I(inode)->runtime_flags))
1828 btrfs_del_delalloc_inode(root, inode);
1829 spin_unlock(&BTRFS_I(inode)->lock);
1834 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1835 * we don't create bios that span stripes or chunks
1837 * return 1 if page cannot be merged to bio
1838 * return 0 if page can be merged to bio
1839 * return error otherwise
1841 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1842 size_t size, struct bio *bio,
1843 unsigned long bio_flags)
1845 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1846 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1851 if (bio_flags & EXTENT_BIO_COMPRESSED)
1854 length = bio->bi_iter.bi_size;
1855 map_length = length;
1856 ret = btrfs_map_block(root->fs_info, rw, logical,
1857 &map_length, NULL, 0);
1860 if (map_length < length + size)
1866 * in order to insert checksums into the metadata in large chunks,
1867 * we wait until bio submission time. All the pages in the bio are
1868 * checksummed and sums are attached onto the ordered extent record.
1870 * At IO completion time the cums attached on the ordered extent record
1871 * are inserted into the btree
1873 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1874 struct bio *bio, int mirror_num,
1875 unsigned long bio_flags,
1878 struct btrfs_root *root = BTRFS_I(inode)->root;
1881 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1882 BUG_ON(ret); /* -ENOMEM */
1887 * in order to insert checksums into the metadata in large chunks,
1888 * we wait until bio submission time. All the pages in the bio are
1889 * checksummed and sums are attached onto the ordered extent record.
1891 * At IO completion time the cums attached on the ordered extent record
1892 * are inserted into the btree
1894 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1895 int mirror_num, unsigned long bio_flags,
1898 struct btrfs_root *root = BTRFS_I(inode)->root;
1901 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1903 bio->bi_error = ret;
1910 * extent_io.c submission hook. This does the right thing for csum calculation
1911 * on write, or reading the csums from the tree before a read
1913 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1914 int mirror_num, unsigned long bio_flags,
1917 struct btrfs_root *root = BTRFS_I(inode)->root;
1918 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1921 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1923 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1925 if (btrfs_is_free_space_inode(inode))
1926 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1928 if (!(rw & REQ_WRITE)) {
1929 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1933 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1934 ret = btrfs_submit_compressed_read(inode, bio,
1938 } else if (!skip_sum) {
1939 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1944 } else if (async && !skip_sum) {
1945 /* csum items have already been cloned */
1946 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1948 /* we're doing a write, do the async checksumming */
1949 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1950 inode, rw, bio, mirror_num,
1951 bio_flags, bio_offset,
1952 __btrfs_submit_bio_start,
1953 __btrfs_submit_bio_done);
1955 } else if (!skip_sum) {
1956 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1962 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1966 bio->bi_error = ret;
1973 * given a list of ordered sums record them in the inode. This happens
1974 * at IO completion time based on sums calculated at bio submission time.
1976 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1977 struct inode *inode, u64 file_offset,
1978 struct list_head *list)
1980 struct btrfs_ordered_sum *sum;
1982 list_for_each_entry(sum, list, list) {
1983 trans->adding_csums = 1;
1984 btrfs_csum_file_blocks(trans,
1985 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1986 trans->adding_csums = 0;
1991 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1992 struct extent_state **cached_state)
1994 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
1995 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1999 /* see btrfs_writepage_start_hook for details on why this is required */
2000 struct btrfs_writepage_fixup {
2002 struct btrfs_work work;
2005 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2007 struct btrfs_writepage_fixup *fixup;
2008 struct btrfs_ordered_extent *ordered;
2009 struct extent_state *cached_state = NULL;
2011 struct inode *inode;
2016 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2020 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2021 ClearPageChecked(page);
2025 inode = page->mapping->host;
2026 page_start = page_offset(page);
2027 page_end = page_offset(page) + PAGE_SIZE - 1;
2029 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2032 /* already ordered? We're done */
2033 if (PagePrivate2(page))
2036 ordered = btrfs_lookup_ordered_range(inode, page_start,
2039 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2040 page_end, &cached_state, GFP_NOFS);
2042 btrfs_start_ordered_extent(inode, ordered, 1);
2043 btrfs_put_ordered_extent(ordered);
2047 ret = btrfs_delalloc_reserve_space(inode, page_start,
2050 mapping_set_error(page->mapping, ret);
2051 end_extent_writepage(page, ret, page_start, page_end);
2052 ClearPageChecked(page);
2056 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
2057 ClearPageChecked(page);
2058 set_page_dirty(page);
2060 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2061 &cached_state, GFP_NOFS);
2069 * There are a few paths in the higher layers of the kernel that directly
2070 * set the page dirty bit without asking the filesystem if it is a
2071 * good idea. This causes problems because we want to make sure COW
2072 * properly happens and the data=ordered rules are followed.
2074 * In our case any range that doesn't have the ORDERED bit set
2075 * hasn't been properly setup for IO. We kick off an async process
2076 * to fix it up. The async helper will wait for ordered extents, set
2077 * the delalloc bit and make it safe to write the page.
2079 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2081 struct inode *inode = page->mapping->host;
2082 struct btrfs_writepage_fixup *fixup;
2083 struct btrfs_root *root = BTRFS_I(inode)->root;
2085 /* this page is properly in the ordered list */
2086 if (TestClearPagePrivate2(page))
2089 if (PageChecked(page))
2092 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2096 SetPageChecked(page);
2098 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2099 btrfs_writepage_fixup_worker, NULL, NULL);
2101 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
2105 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2106 struct inode *inode, u64 file_pos,
2107 u64 disk_bytenr, u64 disk_num_bytes,
2108 u64 num_bytes, u64 ram_bytes,
2109 u8 compression, u8 encryption,
2110 u16 other_encoding, int extent_type)
2112 struct btrfs_root *root = BTRFS_I(inode)->root;
2113 struct btrfs_file_extent_item *fi;
2114 struct btrfs_path *path;
2115 struct extent_buffer *leaf;
2116 struct btrfs_key ins;
2117 int extent_inserted = 0;
2120 path = btrfs_alloc_path();
2125 * we may be replacing one extent in the tree with another.
2126 * The new extent is pinned in the extent map, and we don't want
2127 * to drop it from the cache until it is completely in the btree.
2129 * So, tell btrfs_drop_extents to leave this extent in the cache.
2130 * the caller is expected to unpin it and allow it to be merged
2133 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2134 file_pos + num_bytes, NULL, 0,
2135 1, sizeof(*fi), &extent_inserted);
2139 if (!extent_inserted) {
2140 ins.objectid = btrfs_ino(inode);
2141 ins.offset = file_pos;
2142 ins.type = BTRFS_EXTENT_DATA_KEY;
2144 path->leave_spinning = 1;
2145 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2150 leaf = path->nodes[0];
2151 fi = btrfs_item_ptr(leaf, path->slots[0],
2152 struct btrfs_file_extent_item);
2153 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2154 btrfs_set_file_extent_type(leaf, fi, extent_type);
2155 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2156 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2157 btrfs_set_file_extent_offset(leaf, fi, 0);
2158 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2159 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2160 btrfs_set_file_extent_compression(leaf, fi, compression);
2161 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2162 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2164 btrfs_mark_buffer_dirty(leaf);
2165 btrfs_release_path(path);
2167 inode_add_bytes(inode, num_bytes);
2169 ins.objectid = disk_bytenr;
2170 ins.offset = disk_num_bytes;
2171 ins.type = BTRFS_EXTENT_ITEM_KEY;
2172 ret = btrfs_alloc_reserved_file_extent(trans, root,
2173 root->root_key.objectid,
2174 btrfs_ino(inode), file_pos,
2177 * Release the reserved range from inode dirty range map, as it is
2178 * already moved into delayed_ref_head
2180 btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2182 btrfs_free_path(path);
2187 /* snapshot-aware defrag */
2188 struct sa_defrag_extent_backref {
2189 struct rb_node node;
2190 struct old_sa_defrag_extent *old;
2199 struct old_sa_defrag_extent {
2200 struct list_head list;
2201 struct new_sa_defrag_extent *new;
2210 struct new_sa_defrag_extent {
2211 struct rb_root root;
2212 struct list_head head;
2213 struct btrfs_path *path;
2214 struct inode *inode;
2222 static int backref_comp(struct sa_defrag_extent_backref *b1,
2223 struct sa_defrag_extent_backref *b2)
2225 if (b1->root_id < b2->root_id)
2227 else if (b1->root_id > b2->root_id)
2230 if (b1->inum < b2->inum)
2232 else if (b1->inum > b2->inum)
2235 if (b1->file_pos < b2->file_pos)
2237 else if (b1->file_pos > b2->file_pos)
2241 * [------------------------------] ===> (a range of space)
2242 * |<--->| |<---->| =============> (fs/file tree A)
2243 * |<---------------------------->| ===> (fs/file tree B)
2245 * A range of space can refer to two file extents in one tree while
2246 * refer to only one file extent in another tree.
2248 * So we may process a disk offset more than one time(two extents in A)
2249 * and locate at the same extent(one extent in B), then insert two same
2250 * backrefs(both refer to the extent in B).
2255 static void backref_insert(struct rb_root *root,
2256 struct sa_defrag_extent_backref *backref)
2258 struct rb_node **p = &root->rb_node;
2259 struct rb_node *parent = NULL;
2260 struct sa_defrag_extent_backref *entry;
2265 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2267 ret = backref_comp(backref, entry);
2271 p = &(*p)->rb_right;
2274 rb_link_node(&backref->node, parent, p);
2275 rb_insert_color(&backref->node, root);
2279 * Note the backref might has changed, and in this case we just return 0.
2281 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2284 struct btrfs_file_extent_item *extent;
2285 struct btrfs_fs_info *fs_info;
2286 struct old_sa_defrag_extent *old = ctx;
2287 struct new_sa_defrag_extent *new = old->new;
2288 struct btrfs_path *path = new->path;
2289 struct btrfs_key key;
2290 struct btrfs_root *root;
2291 struct sa_defrag_extent_backref *backref;
2292 struct extent_buffer *leaf;
2293 struct inode *inode = new->inode;
2299 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2300 inum == btrfs_ino(inode))
2303 key.objectid = root_id;
2304 key.type = BTRFS_ROOT_ITEM_KEY;
2305 key.offset = (u64)-1;
2307 fs_info = BTRFS_I(inode)->root->fs_info;
2308 root = btrfs_read_fs_root_no_name(fs_info, &key);
2310 if (PTR_ERR(root) == -ENOENT)
2313 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2314 inum, offset, root_id);
2315 return PTR_ERR(root);
2318 key.objectid = inum;
2319 key.type = BTRFS_EXTENT_DATA_KEY;
2320 if (offset > (u64)-1 << 32)
2323 key.offset = offset;
2325 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2326 if (WARN_ON(ret < 0))
2333 leaf = path->nodes[0];
2334 slot = path->slots[0];
2336 if (slot >= btrfs_header_nritems(leaf)) {
2337 ret = btrfs_next_leaf(root, path);
2340 } else if (ret > 0) {
2349 btrfs_item_key_to_cpu(leaf, &key, slot);
2351 if (key.objectid > inum)
2354 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2357 extent = btrfs_item_ptr(leaf, slot,
2358 struct btrfs_file_extent_item);
2360 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2364 * 'offset' refers to the exact key.offset,
2365 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2366 * (key.offset - extent_offset).
2368 if (key.offset != offset)
2371 extent_offset = btrfs_file_extent_offset(leaf, extent);
2372 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2374 if (extent_offset >= old->extent_offset + old->offset +
2375 old->len || extent_offset + num_bytes <=
2376 old->extent_offset + old->offset)
2381 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2387 backref->root_id = root_id;
2388 backref->inum = inum;
2389 backref->file_pos = offset;
2390 backref->num_bytes = num_bytes;
2391 backref->extent_offset = extent_offset;
2392 backref->generation = btrfs_file_extent_generation(leaf, extent);
2394 backref_insert(&new->root, backref);
2397 btrfs_release_path(path);
2402 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2403 struct new_sa_defrag_extent *new)
2405 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2406 struct old_sa_defrag_extent *old, *tmp;
2411 list_for_each_entry_safe(old, tmp, &new->head, list) {
2412 ret = iterate_inodes_from_logical(old->bytenr +
2413 old->extent_offset, fs_info,
2414 path, record_one_backref,
2416 if (ret < 0 && ret != -ENOENT)
2419 /* no backref to be processed for this extent */
2421 list_del(&old->list);
2426 if (list_empty(&new->head))
2432 static int relink_is_mergable(struct extent_buffer *leaf,
2433 struct btrfs_file_extent_item *fi,
2434 struct new_sa_defrag_extent *new)
2436 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2439 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2442 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2445 if (btrfs_file_extent_encryption(leaf, fi) ||
2446 btrfs_file_extent_other_encoding(leaf, fi))
2453 * Note the backref might has changed, and in this case we just return 0.
2455 static noinline int relink_extent_backref(struct btrfs_path *path,
2456 struct sa_defrag_extent_backref *prev,
2457 struct sa_defrag_extent_backref *backref)
2459 struct btrfs_file_extent_item *extent;
2460 struct btrfs_file_extent_item *item;
2461 struct btrfs_ordered_extent *ordered;
2462 struct btrfs_trans_handle *trans;
2463 struct btrfs_fs_info *fs_info;
2464 struct btrfs_root *root;
2465 struct btrfs_key key;
2466 struct extent_buffer *leaf;
2467 struct old_sa_defrag_extent *old = backref->old;
2468 struct new_sa_defrag_extent *new = old->new;
2469 struct inode *src_inode = new->inode;
2470 struct inode *inode;
2471 struct extent_state *cached = NULL;
2480 if (prev && prev->root_id == backref->root_id &&
2481 prev->inum == backref->inum &&
2482 prev->file_pos + prev->num_bytes == backref->file_pos)
2485 /* step 1: get root */
2486 key.objectid = backref->root_id;
2487 key.type = BTRFS_ROOT_ITEM_KEY;
2488 key.offset = (u64)-1;
2490 fs_info = BTRFS_I(src_inode)->root->fs_info;
2491 index = srcu_read_lock(&fs_info->subvol_srcu);
2493 root = btrfs_read_fs_root_no_name(fs_info, &key);
2495 srcu_read_unlock(&fs_info->subvol_srcu, index);
2496 if (PTR_ERR(root) == -ENOENT)
2498 return PTR_ERR(root);
2501 if (btrfs_root_readonly(root)) {
2502 srcu_read_unlock(&fs_info->subvol_srcu, index);
2506 /* step 2: get inode */
2507 key.objectid = backref->inum;
2508 key.type = BTRFS_INODE_ITEM_KEY;
2511 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2512 if (IS_ERR(inode)) {
2513 srcu_read_unlock(&fs_info->subvol_srcu, index);
2517 srcu_read_unlock(&fs_info->subvol_srcu, index);
2519 /* step 3: relink backref */
2520 lock_start = backref->file_pos;
2521 lock_end = backref->file_pos + backref->num_bytes - 1;
2522 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2525 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2527 btrfs_put_ordered_extent(ordered);
2531 trans = btrfs_join_transaction(root);
2532 if (IS_ERR(trans)) {
2533 ret = PTR_ERR(trans);
2537 key.objectid = backref->inum;
2538 key.type = BTRFS_EXTENT_DATA_KEY;
2539 key.offset = backref->file_pos;
2541 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2544 } else if (ret > 0) {
2549 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2550 struct btrfs_file_extent_item);
2552 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2553 backref->generation)
2556 btrfs_release_path(path);
2558 start = backref->file_pos;
2559 if (backref->extent_offset < old->extent_offset + old->offset)
2560 start += old->extent_offset + old->offset -
2561 backref->extent_offset;
2563 len = min(backref->extent_offset + backref->num_bytes,
2564 old->extent_offset + old->offset + old->len);
2565 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2567 ret = btrfs_drop_extents(trans, root, inode, start,
2572 key.objectid = btrfs_ino(inode);
2573 key.type = BTRFS_EXTENT_DATA_KEY;
2576 path->leave_spinning = 1;
2578 struct btrfs_file_extent_item *fi;
2580 struct btrfs_key found_key;
2582 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2587 leaf = path->nodes[0];
2588 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2590 fi = btrfs_item_ptr(leaf, path->slots[0],
2591 struct btrfs_file_extent_item);
2592 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2594 if (extent_len + found_key.offset == start &&
2595 relink_is_mergable(leaf, fi, new)) {
2596 btrfs_set_file_extent_num_bytes(leaf, fi,
2598 btrfs_mark_buffer_dirty(leaf);
2599 inode_add_bytes(inode, len);
2605 btrfs_release_path(path);
2610 ret = btrfs_insert_empty_item(trans, root, path, &key,
2613 btrfs_abort_transaction(trans, ret);
2617 leaf = path->nodes[0];
2618 item = btrfs_item_ptr(leaf, path->slots[0],
2619 struct btrfs_file_extent_item);
2620 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2621 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2622 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2623 btrfs_set_file_extent_num_bytes(leaf, item, len);
2624 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2625 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2626 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2627 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2628 btrfs_set_file_extent_encryption(leaf, item, 0);
2629 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2631 btrfs_mark_buffer_dirty(leaf);
2632 inode_add_bytes(inode, len);
2633 btrfs_release_path(path);
2635 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2637 backref->root_id, backref->inum,
2638 new->file_pos); /* start - extent_offset */
2640 btrfs_abort_transaction(trans, ret);
2646 btrfs_release_path(path);
2647 path->leave_spinning = 0;
2648 btrfs_end_transaction(trans, root);
2650 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2656 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2658 struct old_sa_defrag_extent *old, *tmp;
2663 list_for_each_entry_safe(old, tmp, &new->head, list) {
2669 static void relink_file_extents(struct new_sa_defrag_extent *new)
2671 struct btrfs_path *path;
2672 struct sa_defrag_extent_backref *backref;
2673 struct sa_defrag_extent_backref *prev = NULL;
2674 struct inode *inode;
2675 struct btrfs_root *root;
2676 struct rb_node *node;
2680 root = BTRFS_I(inode)->root;
2682 path = btrfs_alloc_path();
2686 if (!record_extent_backrefs(path, new)) {
2687 btrfs_free_path(path);
2690 btrfs_release_path(path);
2693 node = rb_first(&new->root);
2696 rb_erase(node, &new->root);
2698 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2700 ret = relink_extent_backref(path, prev, backref);
2713 btrfs_free_path(path);
2715 free_sa_defrag_extent(new);
2717 atomic_dec(&root->fs_info->defrag_running);
2718 wake_up(&root->fs_info->transaction_wait);
2721 static struct new_sa_defrag_extent *
2722 record_old_file_extents(struct inode *inode,
2723 struct btrfs_ordered_extent *ordered)
2725 struct btrfs_root *root = BTRFS_I(inode)->root;
2726 struct btrfs_path *path;
2727 struct btrfs_key key;
2728 struct old_sa_defrag_extent *old;
2729 struct new_sa_defrag_extent *new;
2732 new = kmalloc(sizeof(*new), GFP_NOFS);
2737 new->file_pos = ordered->file_offset;
2738 new->len = ordered->len;
2739 new->bytenr = ordered->start;
2740 new->disk_len = ordered->disk_len;
2741 new->compress_type = ordered->compress_type;
2742 new->root = RB_ROOT;
2743 INIT_LIST_HEAD(&new->head);
2745 path = btrfs_alloc_path();
2749 key.objectid = btrfs_ino(inode);
2750 key.type = BTRFS_EXTENT_DATA_KEY;
2751 key.offset = new->file_pos;
2753 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2756 if (ret > 0 && path->slots[0] > 0)
2759 /* find out all the old extents for the file range */
2761 struct btrfs_file_extent_item *extent;
2762 struct extent_buffer *l;
2771 slot = path->slots[0];
2773 if (slot >= btrfs_header_nritems(l)) {
2774 ret = btrfs_next_leaf(root, path);
2782 btrfs_item_key_to_cpu(l, &key, slot);
2784 if (key.objectid != btrfs_ino(inode))
2786 if (key.type != BTRFS_EXTENT_DATA_KEY)
2788 if (key.offset >= new->file_pos + new->len)
2791 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2793 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2794 if (key.offset + num_bytes < new->file_pos)
2797 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2801 extent_offset = btrfs_file_extent_offset(l, extent);
2803 old = kmalloc(sizeof(*old), GFP_NOFS);
2807 offset = max(new->file_pos, key.offset);
2808 end = min(new->file_pos + new->len, key.offset + num_bytes);
2810 old->bytenr = disk_bytenr;
2811 old->extent_offset = extent_offset;
2812 old->offset = offset - key.offset;
2813 old->len = end - offset;
2816 list_add_tail(&old->list, &new->head);
2822 btrfs_free_path(path);
2823 atomic_inc(&root->fs_info->defrag_running);
2828 btrfs_free_path(path);
2830 free_sa_defrag_extent(new);
2834 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2837 struct btrfs_block_group_cache *cache;
2839 cache = btrfs_lookup_block_group(root->fs_info, start);
2842 spin_lock(&cache->lock);
2843 cache->delalloc_bytes -= len;
2844 spin_unlock(&cache->lock);
2846 btrfs_put_block_group(cache);
2849 /* as ordered data IO finishes, this gets called so we can finish
2850 * an ordered extent if the range of bytes in the file it covers are
2853 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2855 struct inode *inode = ordered_extent->inode;
2856 struct btrfs_root *root = BTRFS_I(inode)->root;
2857 struct btrfs_trans_handle *trans = NULL;
2858 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2859 struct extent_state *cached_state = NULL;
2860 struct new_sa_defrag_extent *new = NULL;
2861 int compress_type = 0;
2863 u64 logical_len = ordered_extent->len;
2865 bool truncated = false;
2867 nolock = btrfs_is_free_space_inode(inode);
2869 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2874 btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2875 ordered_extent->file_offset +
2876 ordered_extent->len - 1);
2878 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2880 logical_len = ordered_extent->truncated_len;
2881 /* Truncated the entire extent, don't bother adding */
2886 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2887 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2890 * For mwrite(mmap + memset to write) case, we still reserve
2891 * space for NOCOW range.
2892 * As NOCOW won't cause a new delayed ref, just free the space
2894 btrfs_qgroup_free_data(inode, ordered_extent->file_offset,
2895 ordered_extent->len);
2896 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2898 trans = btrfs_join_transaction_nolock(root);
2900 trans = btrfs_join_transaction(root);
2901 if (IS_ERR(trans)) {
2902 ret = PTR_ERR(trans);
2906 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2907 ret = btrfs_update_inode_fallback(trans, root, inode);
2908 if (ret) /* -ENOMEM or corruption */
2909 btrfs_abort_transaction(trans, ret);
2913 lock_extent_bits(io_tree, ordered_extent->file_offset,
2914 ordered_extent->file_offset + ordered_extent->len - 1,
2917 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2918 ordered_extent->file_offset + ordered_extent->len - 1,
2919 EXTENT_DEFRAG, 1, cached_state);
2921 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2922 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2923 /* the inode is shared */
2924 new = record_old_file_extents(inode, ordered_extent);
2926 clear_extent_bit(io_tree, ordered_extent->file_offset,
2927 ordered_extent->file_offset + ordered_extent->len - 1,
2928 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2932 trans = btrfs_join_transaction_nolock(root);
2934 trans = btrfs_join_transaction(root);
2935 if (IS_ERR(trans)) {
2936 ret = PTR_ERR(trans);
2941 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2943 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2944 compress_type = ordered_extent->compress_type;
2945 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2946 BUG_ON(compress_type);
2947 ret = btrfs_mark_extent_written(trans, inode,
2948 ordered_extent->file_offset,
2949 ordered_extent->file_offset +
2952 BUG_ON(root == root->fs_info->tree_root);
2953 ret = insert_reserved_file_extent(trans, inode,
2954 ordered_extent->file_offset,
2955 ordered_extent->start,
2956 ordered_extent->disk_len,
2957 logical_len, logical_len,
2958 compress_type, 0, 0,
2959 BTRFS_FILE_EXTENT_REG);
2961 btrfs_release_delalloc_bytes(root,
2962 ordered_extent->start,
2963 ordered_extent->disk_len);
2965 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2966 ordered_extent->file_offset, ordered_extent->len,
2969 btrfs_abort_transaction(trans, ret);
2973 add_pending_csums(trans, inode, ordered_extent->file_offset,
2974 &ordered_extent->list);
2976 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2977 ret = btrfs_update_inode_fallback(trans, root, inode);
2978 if (ret) { /* -ENOMEM or corruption */
2979 btrfs_abort_transaction(trans, ret);
2984 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2985 ordered_extent->file_offset +
2986 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2988 if (root != root->fs_info->tree_root)
2989 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2991 btrfs_end_transaction(trans, root);
2993 if (ret || truncated) {
2997 start = ordered_extent->file_offset + logical_len;
2999 start = ordered_extent->file_offset;
3000 end = ordered_extent->file_offset + ordered_extent->len - 1;
3001 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
3003 /* Drop the cache for the part of the extent we didn't write. */
3004 btrfs_drop_extent_cache(inode, start, end, 0);
3007 * If the ordered extent had an IOERR or something else went
3008 * wrong we need to return the space for this ordered extent
3009 * back to the allocator. We only free the extent in the
3010 * truncated case if we didn't write out the extent at all.
3012 if ((ret || !logical_len) &&
3013 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3014 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3015 btrfs_free_reserved_extent(root, ordered_extent->start,
3016 ordered_extent->disk_len, 1);
3021 * This needs to be done to make sure anybody waiting knows we are done
3022 * updating everything for this ordered extent.
3024 btrfs_remove_ordered_extent(inode, ordered_extent);
3026 /* for snapshot-aware defrag */
3029 free_sa_defrag_extent(new);
3030 atomic_dec(&root->fs_info->defrag_running);
3032 relink_file_extents(new);
3037 btrfs_put_ordered_extent(ordered_extent);
3038 /* once for the tree */
3039 btrfs_put_ordered_extent(ordered_extent);
3044 static void finish_ordered_fn(struct btrfs_work *work)
3046 struct btrfs_ordered_extent *ordered_extent;
3047 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3048 btrfs_finish_ordered_io(ordered_extent);
3051 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3052 struct extent_state *state, int uptodate)
3054 struct inode *inode = page->mapping->host;
3055 struct btrfs_root *root = BTRFS_I(inode)->root;
3056 struct btrfs_ordered_extent *ordered_extent = NULL;
3057 struct btrfs_workqueue *wq;
3058 btrfs_work_func_t func;
3060 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3062 ClearPagePrivate2(page);
3063 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3064 end - start + 1, uptodate))
3067 if (btrfs_is_free_space_inode(inode)) {
3068 wq = root->fs_info->endio_freespace_worker;
3069 func = btrfs_freespace_write_helper;
3071 wq = root->fs_info->endio_write_workers;
3072 func = btrfs_endio_write_helper;
3075 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3077 btrfs_queue_work(wq, &ordered_extent->work);
3082 static int __readpage_endio_check(struct inode *inode,
3083 struct btrfs_io_bio *io_bio,
3084 int icsum, struct page *page,
3085 int pgoff, u64 start, size_t len)
3091 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3093 kaddr = kmap_atomic(page);
3094 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3095 btrfs_csum_final(csum, (char *)&csum);
3096 if (csum != csum_expected)
3099 kunmap_atomic(kaddr);
3102 btrfs_warn_rl(BTRFS_I(inode)->root->fs_info,
3103 "csum failed ino %llu off %llu csum %u expected csum %u",
3104 btrfs_ino(inode), start, csum, csum_expected);
3105 memset(kaddr + pgoff, 1, len);
3106 flush_dcache_page(page);
3107 kunmap_atomic(kaddr);
3108 if (csum_expected == 0)
3114 * when reads are done, we need to check csums to verify the data is correct
3115 * if there's a match, we allow the bio to finish. If not, the code in
3116 * extent_io.c will try to find good copies for us.
3118 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3119 u64 phy_offset, struct page *page,
3120 u64 start, u64 end, int mirror)
3122 size_t offset = start - page_offset(page);
3123 struct inode *inode = page->mapping->host;
3124 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3125 struct btrfs_root *root = BTRFS_I(inode)->root;
3127 if (PageChecked(page)) {
3128 ClearPageChecked(page);
3132 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3135 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3136 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3137 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3141 phy_offset >>= inode->i_sb->s_blocksize_bits;
3142 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3143 start, (size_t)(end - start + 1));
3146 void btrfs_add_delayed_iput(struct inode *inode)
3148 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3149 struct btrfs_inode *binode = BTRFS_I(inode);
3151 if (atomic_add_unless(&inode->i_count, -1, 1))
3154 spin_lock(&fs_info->delayed_iput_lock);
3155 if (binode->delayed_iput_count == 0) {
3156 ASSERT(list_empty(&binode->delayed_iput));
3157 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3159 binode->delayed_iput_count++;
3161 spin_unlock(&fs_info->delayed_iput_lock);
3164 void btrfs_run_delayed_iputs(struct btrfs_root *root)
3166 struct btrfs_fs_info *fs_info = root->fs_info;
3168 spin_lock(&fs_info->delayed_iput_lock);
3169 while (!list_empty(&fs_info->delayed_iputs)) {
3170 struct btrfs_inode *inode;
3172 inode = list_first_entry(&fs_info->delayed_iputs,
3173 struct btrfs_inode, delayed_iput);
3174 if (inode->delayed_iput_count) {
3175 inode->delayed_iput_count--;
3176 list_move_tail(&inode->delayed_iput,
3177 &fs_info->delayed_iputs);
3179 list_del_init(&inode->delayed_iput);
3181 spin_unlock(&fs_info->delayed_iput_lock);
3182 iput(&inode->vfs_inode);
3183 spin_lock(&fs_info->delayed_iput_lock);
3185 spin_unlock(&fs_info->delayed_iput_lock);
3189 * This is called in transaction commit time. If there are no orphan
3190 * files in the subvolume, it removes orphan item and frees block_rsv
3193 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3194 struct btrfs_root *root)
3196 struct btrfs_block_rsv *block_rsv;
3199 if (atomic_read(&root->orphan_inodes) ||
3200 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3203 spin_lock(&root->orphan_lock);
3204 if (atomic_read(&root->orphan_inodes)) {
3205 spin_unlock(&root->orphan_lock);
3209 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3210 spin_unlock(&root->orphan_lock);
3214 block_rsv = root->orphan_block_rsv;
3215 root->orphan_block_rsv = NULL;
3216 spin_unlock(&root->orphan_lock);
3218 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3219 btrfs_root_refs(&root->root_item) > 0) {
3220 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
3221 root->root_key.objectid);
3223 btrfs_abort_transaction(trans, ret);
3225 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3230 WARN_ON(block_rsv->size > 0);
3231 btrfs_free_block_rsv(root, block_rsv);
3236 * This creates an orphan entry for the given inode in case something goes
3237 * wrong in the middle of an unlink/truncate.
3239 * NOTE: caller of this function should reserve 5 units of metadata for
3242 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3244 struct btrfs_root *root = BTRFS_I(inode)->root;
3245 struct btrfs_block_rsv *block_rsv = NULL;
3250 if (!root->orphan_block_rsv) {
3251 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3256 spin_lock(&root->orphan_lock);
3257 if (!root->orphan_block_rsv) {
3258 root->orphan_block_rsv = block_rsv;
3259 } else if (block_rsv) {
3260 btrfs_free_block_rsv(root, block_rsv);
3264 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3265 &BTRFS_I(inode)->runtime_flags)) {
3268 * For proper ENOSPC handling, we should do orphan
3269 * cleanup when mounting. But this introduces backward
3270 * compatibility issue.
3272 if (!xchg(&root->orphan_item_inserted, 1))
3278 atomic_inc(&root->orphan_inodes);
3281 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3282 &BTRFS_I(inode)->runtime_flags))
3284 spin_unlock(&root->orphan_lock);
3286 /* grab metadata reservation from transaction handle */
3288 ret = btrfs_orphan_reserve_metadata(trans, inode);
3291 atomic_dec(&root->orphan_inodes);
3292 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3293 &BTRFS_I(inode)->runtime_flags);
3295 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3296 &BTRFS_I(inode)->runtime_flags);
3301 /* insert an orphan item to track this unlinked/truncated file */
3303 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3305 atomic_dec(&root->orphan_inodes);
3307 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3308 &BTRFS_I(inode)->runtime_flags);
3309 btrfs_orphan_release_metadata(inode);
3311 if (ret != -EEXIST) {
3312 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3313 &BTRFS_I(inode)->runtime_flags);
3314 btrfs_abort_transaction(trans, ret);
3321 /* insert an orphan item to track subvolume contains orphan files */
3323 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3324 root->root_key.objectid);
3325 if (ret && ret != -EEXIST) {
3326 btrfs_abort_transaction(trans, ret);
3334 * We have done the truncate/delete so we can go ahead and remove the orphan
3335 * item for this particular inode.
3337 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3338 struct inode *inode)
3340 struct btrfs_root *root = BTRFS_I(inode)->root;
3341 int delete_item = 0;
3342 int release_rsv = 0;
3345 spin_lock(&root->orphan_lock);
3346 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3347 &BTRFS_I(inode)->runtime_flags))
3350 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3351 &BTRFS_I(inode)->runtime_flags))
3353 spin_unlock(&root->orphan_lock);
3356 atomic_dec(&root->orphan_inodes);
3358 ret = btrfs_del_orphan_item(trans, root,
3363 btrfs_orphan_release_metadata(inode);
3369 * this cleans up any orphans that may be left on the list from the last use
3372 int btrfs_orphan_cleanup(struct btrfs_root *root)
3374 struct btrfs_path *path;
3375 struct extent_buffer *leaf;
3376 struct btrfs_key key, found_key;
3377 struct btrfs_trans_handle *trans;
3378 struct inode *inode;
3379 u64 last_objectid = 0;
3380 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3382 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3385 path = btrfs_alloc_path();
3390 path->reada = READA_BACK;
3392 key.objectid = BTRFS_ORPHAN_OBJECTID;
3393 key.type = BTRFS_ORPHAN_ITEM_KEY;
3394 key.offset = (u64)-1;
3397 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3402 * if ret == 0 means we found what we were searching for, which
3403 * is weird, but possible, so only screw with path if we didn't
3404 * find the key and see if we have stuff that matches
3408 if (path->slots[0] == 0)
3413 /* pull out the item */
3414 leaf = path->nodes[0];
3415 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3417 /* make sure the item matches what we want */
3418 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3420 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3423 /* release the path since we're done with it */
3424 btrfs_release_path(path);
3427 * this is where we are basically btrfs_lookup, without the
3428 * crossing root thing. we store the inode number in the
3429 * offset of the orphan item.
3432 if (found_key.offset == last_objectid) {
3433 btrfs_err(root->fs_info,
3434 "Error removing orphan entry, stopping orphan cleanup");
3439 last_objectid = found_key.offset;
3441 found_key.objectid = found_key.offset;
3442 found_key.type = BTRFS_INODE_ITEM_KEY;
3443 found_key.offset = 0;
3444 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3445 ret = PTR_ERR_OR_ZERO(inode);
3446 if (ret && ret != -ENOENT)
3449 if (ret == -ENOENT && root == root->fs_info->tree_root) {
3450 struct btrfs_root *dead_root;
3451 struct btrfs_fs_info *fs_info = root->fs_info;
3452 int is_dead_root = 0;
3455 * this is an orphan in the tree root. Currently these
3456 * could come from 2 sources:
3457 * a) a snapshot deletion in progress
3458 * b) a free space cache inode
3459 * We need to distinguish those two, as the snapshot
3460 * orphan must not get deleted.
3461 * find_dead_roots already ran before us, so if this
3462 * is a snapshot deletion, we should find the root
3463 * in the dead_roots list
3465 spin_lock(&fs_info->trans_lock);
3466 list_for_each_entry(dead_root, &fs_info->dead_roots,
3468 if (dead_root->root_key.objectid ==
3469 found_key.objectid) {
3474 spin_unlock(&fs_info->trans_lock);
3476 /* prevent this orphan from being found again */
3477 key.offset = found_key.objectid - 1;
3482 * Inode is already gone but the orphan item is still there,
3483 * kill the orphan item.
3485 if (ret == -ENOENT) {
3486 trans = btrfs_start_transaction(root, 1);
3487 if (IS_ERR(trans)) {
3488 ret = PTR_ERR(trans);
3491 btrfs_debug(root->fs_info, "auto deleting %Lu",
3492 found_key.objectid);
3493 ret = btrfs_del_orphan_item(trans, root,
3494 found_key.objectid);
3495 btrfs_end_transaction(trans, root);
3502 * add this inode to the orphan list so btrfs_orphan_del does
3503 * the proper thing when we hit it
3505 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3506 &BTRFS_I(inode)->runtime_flags);
3507 atomic_inc(&root->orphan_inodes);
3509 /* if we have links, this was a truncate, lets do that */
3510 if (inode->i_nlink) {
3511 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3517 /* 1 for the orphan item deletion. */
3518 trans = btrfs_start_transaction(root, 1);
3519 if (IS_ERR(trans)) {
3521 ret = PTR_ERR(trans);
3524 ret = btrfs_orphan_add(trans, inode);
3525 btrfs_end_transaction(trans, root);
3531 ret = btrfs_truncate(inode);
3533 btrfs_orphan_del(NULL, inode);
3538 /* this will do delete_inode and everything for us */
3543 /* release the path since we're done with it */
3544 btrfs_release_path(path);
3546 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3548 if (root->orphan_block_rsv)
3549 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3552 if (root->orphan_block_rsv ||
3553 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3554 trans = btrfs_join_transaction(root);
3556 btrfs_end_transaction(trans, root);
3560 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3562 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3566 btrfs_err(root->fs_info,
3567 "could not do orphan cleanup %d", ret);
3568 btrfs_free_path(path);
3573 * very simple check to peek ahead in the leaf looking for xattrs. If we
3574 * don't find any xattrs, we know there can't be any acls.
3576 * slot is the slot the inode is in, objectid is the objectid of the inode
3578 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3579 int slot, u64 objectid,
3580 int *first_xattr_slot)
3582 u32 nritems = btrfs_header_nritems(leaf);
3583 struct btrfs_key found_key;
3584 static u64 xattr_access = 0;
3585 static u64 xattr_default = 0;
3588 if (!xattr_access) {
3589 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3590 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3591 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3592 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3596 *first_xattr_slot = -1;
3597 while (slot < nritems) {
3598 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3600 /* we found a different objectid, there must not be acls */
3601 if (found_key.objectid != objectid)
3604 /* we found an xattr, assume we've got an acl */
3605 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3606 if (*first_xattr_slot == -1)
3607 *first_xattr_slot = slot;
3608 if (found_key.offset == xattr_access ||
3609 found_key.offset == xattr_default)
3614 * we found a key greater than an xattr key, there can't
3615 * be any acls later on
3617 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3624 * it goes inode, inode backrefs, xattrs, extents,
3625 * so if there are a ton of hard links to an inode there can
3626 * be a lot of backrefs. Don't waste time searching too hard,
3627 * this is just an optimization
3632 /* we hit the end of the leaf before we found an xattr or
3633 * something larger than an xattr. We have to assume the inode
3636 if (*first_xattr_slot == -1)
3637 *first_xattr_slot = slot;
3642 * read an inode from the btree into the in-memory inode
3644 static int btrfs_read_locked_inode(struct inode *inode)
3646 struct btrfs_path *path;
3647 struct extent_buffer *leaf;
3648 struct btrfs_inode_item *inode_item;
3649 struct btrfs_root *root = BTRFS_I(inode)->root;
3650 struct btrfs_key location;
3655 bool filled = false;
3656 int first_xattr_slot;
3658 ret = btrfs_fill_inode(inode, &rdev);
3662 path = btrfs_alloc_path();
3668 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3670 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3677 leaf = path->nodes[0];
3682 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3683 struct btrfs_inode_item);
3684 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3685 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3686 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3687 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3688 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3690 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3691 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3693 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3694 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3696 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3697 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3699 BTRFS_I(inode)->i_otime.tv_sec =
3700 btrfs_timespec_sec(leaf, &inode_item->otime);
3701 BTRFS_I(inode)->i_otime.tv_nsec =
3702 btrfs_timespec_nsec(leaf, &inode_item->otime);
3704 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3705 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3706 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3708 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3709 inode->i_generation = BTRFS_I(inode)->generation;
3711 rdev = btrfs_inode_rdev(leaf, inode_item);
3713 BTRFS_I(inode)->index_cnt = (u64)-1;
3714 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3718 * If we were modified in the current generation and evicted from memory
3719 * and then re-read we need to do a full sync since we don't have any
3720 * idea about which extents were modified before we were evicted from
3723 * This is required for both inode re-read from disk and delayed inode
3724 * in delayed_nodes_tree.
3726 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3727 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3728 &BTRFS_I(inode)->runtime_flags);
3731 * We don't persist the id of the transaction where an unlink operation
3732 * against the inode was last made. So here we assume the inode might
3733 * have been evicted, and therefore the exact value of last_unlink_trans
3734 * lost, and set it to last_trans to avoid metadata inconsistencies
3735 * between the inode and its parent if the inode is fsync'ed and the log
3736 * replayed. For example, in the scenario:
3739 * ln mydir/foo mydir/bar
3742 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3743 * xfs_io -c fsync mydir/foo
3745 * mount fs, triggers fsync log replay
3747 * We must make sure that when we fsync our inode foo we also log its
3748 * parent inode, otherwise after log replay the parent still has the
3749 * dentry with the "bar" name but our inode foo has a link count of 1
3750 * and doesn't have an inode ref with the name "bar" anymore.
3752 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3753 * but it guarantees correctness at the expense of occasional full
3754 * transaction commits on fsync if our inode is a directory, or if our
3755 * inode is not a directory, logging its parent unnecessarily.
3757 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3760 if (inode->i_nlink != 1 ||
3761 path->slots[0] >= btrfs_header_nritems(leaf))
3764 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3765 if (location.objectid != btrfs_ino(inode))
3768 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3769 if (location.type == BTRFS_INODE_REF_KEY) {
3770 struct btrfs_inode_ref *ref;
3772 ref = (struct btrfs_inode_ref *)ptr;
3773 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3774 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3775 struct btrfs_inode_extref *extref;
3777 extref = (struct btrfs_inode_extref *)ptr;
3778 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3783 * try to precache a NULL acl entry for files that don't have
3784 * any xattrs or acls
3786 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3787 btrfs_ino(inode), &first_xattr_slot);
3788 if (first_xattr_slot != -1) {
3789 path->slots[0] = first_xattr_slot;
3790 ret = btrfs_load_inode_props(inode, path);
3792 btrfs_err(root->fs_info,
3793 "error loading props for ino %llu (root %llu): %d",
3795 root->root_key.objectid, ret);
3797 btrfs_free_path(path);
3800 cache_no_acl(inode);
3802 switch (inode->i_mode & S_IFMT) {
3804 inode->i_mapping->a_ops = &btrfs_aops;
3805 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3806 inode->i_fop = &btrfs_file_operations;
3807 inode->i_op = &btrfs_file_inode_operations;
3810 inode->i_fop = &btrfs_dir_file_operations;
3811 if (root == root->fs_info->tree_root)
3812 inode->i_op = &btrfs_dir_ro_inode_operations;
3814 inode->i_op = &btrfs_dir_inode_operations;
3817 inode->i_op = &btrfs_symlink_inode_operations;
3818 inode_nohighmem(inode);
3819 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3822 inode->i_op = &btrfs_special_inode_operations;
3823 init_special_inode(inode, inode->i_mode, rdev);
3827 btrfs_update_iflags(inode);
3831 btrfs_free_path(path);
3832 make_bad_inode(inode);
3837 * given a leaf and an inode, copy the inode fields into the leaf
3839 static void fill_inode_item(struct btrfs_trans_handle *trans,
3840 struct extent_buffer *leaf,
3841 struct btrfs_inode_item *item,
3842 struct inode *inode)
3844 struct btrfs_map_token token;
3846 btrfs_init_map_token(&token);
3848 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3849 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3850 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3852 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3853 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3855 btrfs_set_token_timespec_sec(leaf, &item->atime,
3856 inode->i_atime.tv_sec, &token);
3857 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3858 inode->i_atime.tv_nsec, &token);
3860 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3861 inode->i_mtime.tv_sec, &token);
3862 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3863 inode->i_mtime.tv_nsec, &token);
3865 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3866 inode->i_ctime.tv_sec, &token);
3867 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3868 inode->i_ctime.tv_nsec, &token);
3870 btrfs_set_token_timespec_sec(leaf, &item->otime,
3871 BTRFS_I(inode)->i_otime.tv_sec, &token);
3872 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3873 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3875 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3877 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3879 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3880 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3881 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3882 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3883 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3887 * copy everything in the in-memory inode into the btree.
3889 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3890 struct btrfs_root *root, struct inode *inode)
3892 struct btrfs_inode_item *inode_item;
3893 struct btrfs_path *path;
3894 struct extent_buffer *leaf;
3897 path = btrfs_alloc_path();
3901 path->leave_spinning = 1;
3902 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3910 leaf = path->nodes[0];
3911 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3912 struct btrfs_inode_item);
3914 fill_inode_item(trans, leaf, inode_item, inode);
3915 btrfs_mark_buffer_dirty(leaf);
3916 btrfs_set_inode_last_trans(trans, inode);
3919 btrfs_free_path(path);
3924 * copy everything in the in-memory inode into the btree.
3926 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3927 struct btrfs_root *root, struct inode *inode)
3932 * If the inode is a free space inode, we can deadlock during commit
3933 * if we put it into the delayed code.
3935 * The data relocation inode should also be directly updated
3938 if (!btrfs_is_free_space_inode(inode)
3939 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3940 && !root->fs_info->log_root_recovering) {
3941 btrfs_update_root_times(trans, root);
3943 ret = btrfs_delayed_update_inode(trans, root, inode);
3945 btrfs_set_inode_last_trans(trans, inode);
3949 return btrfs_update_inode_item(trans, root, inode);
3952 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3953 struct btrfs_root *root,
3954 struct inode *inode)
3958 ret = btrfs_update_inode(trans, root, inode);
3960 return btrfs_update_inode_item(trans, root, inode);
3965 * unlink helper that gets used here in inode.c and in the tree logging
3966 * recovery code. It remove a link in a directory with a given name, and
3967 * also drops the back refs in the inode to the directory
3969 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3970 struct btrfs_root *root,
3971 struct inode *dir, struct inode *inode,
3972 const char *name, int name_len)
3974 struct btrfs_path *path;
3976 struct extent_buffer *leaf;
3977 struct btrfs_dir_item *di;
3978 struct btrfs_key key;
3980 u64 ino = btrfs_ino(inode);
3981 u64 dir_ino = btrfs_ino(dir);
3983 path = btrfs_alloc_path();
3989 path->leave_spinning = 1;
3990 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3991 name, name_len, -1);
4000 leaf = path->nodes[0];
4001 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4002 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4005 btrfs_release_path(path);
4008 * If we don't have dir index, we have to get it by looking up
4009 * the inode ref, since we get the inode ref, remove it directly,
4010 * it is unnecessary to do delayed deletion.
4012 * But if we have dir index, needn't search inode ref to get it.
4013 * Since the inode ref is close to the inode item, it is better
4014 * that we delay to delete it, and just do this deletion when
4015 * we update the inode item.
4017 if (BTRFS_I(inode)->dir_index) {
4018 ret = btrfs_delayed_delete_inode_ref(inode);
4020 index = BTRFS_I(inode)->dir_index;
4025 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4028 btrfs_info(root->fs_info,
4029 "failed to delete reference to %.*s, inode %llu parent %llu",
4030 name_len, name, ino, dir_ino);
4031 btrfs_abort_transaction(trans, ret);
4035 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4037 btrfs_abort_transaction(trans, ret);
4041 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
4043 if (ret != 0 && ret != -ENOENT) {
4044 btrfs_abort_transaction(trans, ret);
4048 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
4053 btrfs_abort_transaction(trans, ret);
4055 btrfs_free_path(path);
4059 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4060 inode_inc_iversion(inode);
4061 inode_inc_iversion(dir);
4062 inode->i_ctime = dir->i_mtime =
4063 dir->i_ctime = current_fs_time(inode->i_sb);
4064 ret = btrfs_update_inode(trans, root, dir);
4069 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4070 struct btrfs_root *root,
4071 struct inode *dir, struct inode *inode,
4072 const char *name, int name_len)
4075 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4078 ret = btrfs_update_inode(trans, root, inode);
4084 * helper to start transaction for unlink and rmdir.
4086 * unlink and rmdir are special in btrfs, they do not always free space, so
4087 * if we cannot make our reservations the normal way try and see if there is
4088 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4089 * allow the unlink to occur.
4091 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4093 struct btrfs_root *root = BTRFS_I(dir)->root;
4096 * 1 for the possible orphan item
4097 * 1 for the dir item
4098 * 1 for the dir index
4099 * 1 for the inode ref
4102 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4105 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4107 struct btrfs_root *root = BTRFS_I(dir)->root;
4108 struct btrfs_trans_handle *trans;
4109 struct inode *inode = d_inode(dentry);
4112 trans = __unlink_start_trans(dir);
4114 return PTR_ERR(trans);
4116 btrfs_record_unlink_dir(trans, dir, d_inode(dentry), 0);
4118 ret = btrfs_unlink_inode(trans, root, dir, d_inode(dentry),
4119 dentry->d_name.name, dentry->d_name.len);
4123 if (inode->i_nlink == 0) {
4124 ret = btrfs_orphan_add(trans, inode);
4130 btrfs_end_transaction(trans, root);
4131 btrfs_btree_balance_dirty(root);
4135 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4136 struct btrfs_root *root,
4137 struct inode *dir, u64 objectid,
4138 const char *name, int name_len)
4140 struct btrfs_path *path;
4141 struct extent_buffer *leaf;
4142 struct btrfs_dir_item *di;
4143 struct btrfs_key key;
4146 u64 dir_ino = btrfs_ino(dir);
4148 path = btrfs_alloc_path();
4152 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4153 name, name_len, -1);
4154 if (IS_ERR_OR_NULL(di)) {
4162 leaf = path->nodes[0];
4163 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4164 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4165 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4167 btrfs_abort_transaction(trans, ret);
4170 btrfs_release_path(path);
4172 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4173 objectid, root->root_key.objectid,
4174 dir_ino, &index, name, name_len);
4176 if (ret != -ENOENT) {
4177 btrfs_abort_transaction(trans, ret);
4180 di = btrfs_search_dir_index_item(root, path, dir_ino,
4182 if (IS_ERR_OR_NULL(di)) {
4187 btrfs_abort_transaction(trans, ret);
4191 leaf = path->nodes[0];
4192 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4193 btrfs_release_path(path);
4196 btrfs_release_path(path);
4198 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4200 btrfs_abort_transaction(trans, ret);
4204 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4205 inode_inc_iversion(dir);
4206 dir->i_mtime = dir->i_ctime = current_fs_time(dir->i_sb);
4207 ret = btrfs_update_inode_fallback(trans, root, dir);
4209 btrfs_abort_transaction(trans, ret);
4211 btrfs_free_path(path);
4215 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4217 struct inode *inode = d_inode(dentry);
4219 struct btrfs_root *root = BTRFS_I(dir)->root;
4220 struct btrfs_trans_handle *trans;
4221 u64 last_unlink_trans;
4223 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4225 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
4228 trans = __unlink_start_trans(dir);
4230 return PTR_ERR(trans);
4232 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4233 err = btrfs_unlink_subvol(trans, root, dir,
4234 BTRFS_I(inode)->location.objectid,
4235 dentry->d_name.name,
4236 dentry->d_name.len);
4240 err = btrfs_orphan_add(trans, inode);
4244 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4246 /* now the directory is empty */
4247 err = btrfs_unlink_inode(trans, root, dir, d_inode(dentry),
4248 dentry->d_name.name, dentry->d_name.len);
4250 btrfs_i_size_write(inode, 0);
4252 * Propagate the last_unlink_trans value of the deleted dir to
4253 * its parent directory. This is to prevent an unrecoverable
4254 * log tree in the case we do something like this:
4256 * 2) create snapshot under dir foo
4257 * 3) delete the snapshot
4260 * 6) fsync foo or some file inside foo
4262 if (last_unlink_trans >= trans->transid)
4263 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4266 btrfs_end_transaction(trans, root);
4267 btrfs_btree_balance_dirty(root);
4272 static int truncate_space_check(struct btrfs_trans_handle *trans,
4273 struct btrfs_root *root,
4279 * This is only used to apply pressure to the enospc system, we don't
4280 * intend to use this reservation at all.
4282 bytes_deleted = btrfs_csum_bytes_to_leaves(root, bytes_deleted);
4283 bytes_deleted *= root->nodesize;
4284 ret = btrfs_block_rsv_add(root, &root->fs_info->trans_block_rsv,
4285 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4287 trace_btrfs_space_reservation(root->fs_info, "transaction",
4290 trans->bytes_reserved += bytes_deleted;
4296 static int truncate_inline_extent(struct inode *inode,
4297 struct btrfs_path *path,
4298 struct btrfs_key *found_key,
4302 struct extent_buffer *leaf = path->nodes[0];
4303 int slot = path->slots[0];
4304 struct btrfs_file_extent_item *fi;
4305 u32 size = (u32)(new_size - found_key->offset);
4306 struct btrfs_root *root = BTRFS_I(inode)->root;
4308 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4310 if (btrfs_file_extent_compression(leaf, fi) != BTRFS_COMPRESS_NONE) {
4311 loff_t offset = new_size;
4312 loff_t page_end = ALIGN(offset, PAGE_SIZE);
4315 * Zero out the remaining of the last page of our inline extent,
4316 * instead of directly truncating our inline extent here - that
4317 * would be much more complex (decompressing all the data, then
4318 * compressing the truncated data, which might be bigger than
4319 * the size of the inline extent, resize the extent, etc).
4320 * We release the path because to get the page we might need to
4321 * read the extent item from disk (data not in the page cache).
4323 btrfs_release_path(path);
4324 return btrfs_truncate_block(inode, offset, page_end - offset,
4328 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4329 size = btrfs_file_extent_calc_inline_size(size);
4330 btrfs_truncate_item(root, path, size, 1);
4332 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4333 inode_sub_bytes(inode, item_end + 1 - new_size);
4339 * this can truncate away extent items, csum items and directory items.
4340 * It starts at a high offset and removes keys until it can't find
4341 * any higher than new_size
4343 * csum items that cross the new i_size are truncated to the new size
4346 * min_type is the minimum key type to truncate down to. If set to 0, this
4347 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4349 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4350 struct btrfs_root *root,
4351 struct inode *inode,
4352 u64 new_size, u32 min_type)
4354 struct btrfs_path *path;
4355 struct extent_buffer *leaf;
4356 struct btrfs_file_extent_item *fi;
4357 struct btrfs_key key;
4358 struct btrfs_key found_key;
4359 u64 extent_start = 0;
4360 u64 extent_num_bytes = 0;
4361 u64 extent_offset = 0;
4363 u64 last_size = new_size;
4364 u32 found_type = (u8)-1;
4367 int pending_del_nr = 0;
4368 int pending_del_slot = 0;
4369 int extent_type = -1;
4372 u64 ino = btrfs_ino(inode);
4373 u64 bytes_deleted = 0;
4375 bool should_throttle = 0;
4376 bool should_end = 0;
4378 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4381 * for non-free space inodes and ref cows, we want to back off from
4384 if (!btrfs_is_free_space_inode(inode) &&
4385 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4388 path = btrfs_alloc_path();
4391 path->reada = READA_BACK;
4394 * We want to drop from the next block forward in case this new size is
4395 * not block aligned since we will be keeping the last block of the
4396 * extent just the way it is.
4398 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4399 root == root->fs_info->tree_root)
4400 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4401 root->sectorsize), (u64)-1, 0);
4404 * This function is also used to drop the items in the log tree before
4405 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4406 * it is used to drop the loged items. So we shouldn't kill the delayed
4409 if (min_type == 0 && root == BTRFS_I(inode)->root)
4410 btrfs_kill_delayed_inode_items(inode);
4413 key.offset = (u64)-1;
4418 * with a 16K leaf size and 128MB extents, you can actually queue
4419 * up a huge file in a single leaf. Most of the time that
4420 * bytes_deleted is > 0, it will be huge by the time we get here
4422 if (be_nice && bytes_deleted > SZ_32M) {
4423 if (btrfs_should_end_transaction(trans, root)) {
4430 path->leave_spinning = 1;
4431 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4438 /* there are no items in the tree for us to truncate, we're
4441 if (path->slots[0] == 0)
4448 leaf = path->nodes[0];
4449 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4450 found_type = found_key.type;
4452 if (found_key.objectid != ino)
4455 if (found_type < min_type)
4458 item_end = found_key.offset;
4459 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4460 fi = btrfs_item_ptr(leaf, path->slots[0],
4461 struct btrfs_file_extent_item);
4462 extent_type = btrfs_file_extent_type(leaf, fi);
4463 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4465 btrfs_file_extent_num_bytes(leaf, fi);
4466 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4467 item_end += btrfs_file_extent_inline_len(leaf,
4468 path->slots[0], fi);
4472 if (found_type > min_type) {
4475 if (item_end < new_size)
4477 if (found_key.offset >= new_size)
4483 /* FIXME, shrink the extent if the ref count is only 1 */
4484 if (found_type != BTRFS_EXTENT_DATA_KEY)
4488 last_size = found_key.offset;
4490 last_size = new_size;
4492 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4494 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4496 u64 orig_num_bytes =
4497 btrfs_file_extent_num_bytes(leaf, fi);
4498 extent_num_bytes = ALIGN(new_size -
4501 btrfs_set_file_extent_num_bytes(leaf, fi,
4503 num_dec = (orig_num_bytes -
4505 if (test_bit(BTRFS_ROOT_REF_COWS,
4508 inode_sub_bytes(inode, num_dec);
4509 btrfs_mark_buffer_dirty(leaf);
4512 btrfs_file_extent_disk_num_bytes(leaf,
4514 extent_offset = found_key.offset -
4515 btrfs_file_extent_offset(leaf, fi);
4517 /* FIXME blocksize != 4096 */
4518 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4519 if (extent_start != 0) {
4521 if (test_bit(BTRFS_ROOT_REF_COWS,
4523 inode_sub_bytes(inode, num_dec);
4526 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4528 * we can't truncate inline items that have had
4532 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4533 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4536 * Need to release path in order to truncate a
4537 * compressed extent. So delete any accumulated
4538 * extent items so far.
4540 if (btrfs_file_extent_compression(leaf, fi) !=
4541 BTRFS_COMPRESS_NONE && pending_del_nr) {
4542 err = btrfs_del_items(trans, root, path,
4546 btrfs_abort_transaction(trans,
4553 err = truncate_inline_extent(inode, path,
4558 btrfs_abort_transaction(trans, err);
4561 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4563 inode_sub_bytes(inode, item_end + 1 - new_size);
4568 if (!pending_del_nr) {
4569 /* no pending yet, add ourselves */
4570 pending_del_slot = path->slots[0];
4572 } else if (pending_del_nr &&
4573 path->slots[0] + 1 == pending_del_slot) {
4574 /* hop on the pending chunk */
4576 pending_del_slot = path->slots[0];
4583 should_throttle = 0;
4586 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4587 root == root->fs_info->tree_root)) {
4588 btrfs_set_path_blocking(path);
4589 bytes_deleted += extent_num_bytes;
4590 ret = btrfs_free_extent(trans, root, extent_start,
4591 extent_num_bytes, 0,
4592 btrfs_header_owner(leaf),
4593 ino, extent_offset);
4595 if (btrfs_should_throttle_delayed_refs(trans, root))
4596 btrfs_async_run_delayed_refs(root,
4598 trans->delayed_ref_updates * 2, 0);
4600 if (truncate_space_check(trans, root,
4601 extent_num_bytes)) {
4604 if (btrfs_should_throttle_delayed_refs(trans,
4606 should_throttle = 1;
4611 if (found_type == BTRFS_INODE_ITEM_KEY)
4614 if (path->slots[0] == 0 ||
4615 path->slots[0] != pending_del_slot ||
4616 should_throttle || should_end) {
4617 if (pending_del_nr) {
4618 ret = btrfs_del_items(trans, root, path,
4622 btrfs_abort_transaction(trans, ret);
4627 btrfs_release_path(path);
4628 if (should_throttle) {
4629 unsigned long updates = trans->delayed_ref_updates;
4631 trans->delayed_ref_updates = 0;
4632 ret = btrfs_run_delayed_refs(trans, root, updates * 2);
4638 * if we failed to refill our space rsv, bail out
4639 * and let the transaction restart
4651 if (pending_del_nr) {
4652 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4655 btrfs_abort_transaction(trans, ret);
4658 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4659 btrfs_ordered_update_i_size(inode, last_size, NULL);
4661 btrfs_free_path(path);
4663 if (be_nice && bytes_deleted > SZ_32M) {
4664 unsigned long updates = trans->delayed_ref_updates;
4666 trans->delayed_ref_updates = 0;
4667 ret = btrfs_run_delayed_refs(trans, root, updates * 2);
4676 * btrfs_truncate_block - read, zero a chunk and write a block
4677 * @inode - inode that we're zeroing
4678 * @from - the offset to start zeroing
4679 * @len - the length to zero, 0 to zero the entire range respective to the
4681 * @front - zero up to the offset instead of from the offset on
4683 * This will find the block for the "from" offset and cow the block and zero the
4684 * part we want to zero. This is used with truncate and hole punching.
4686 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4689 struct address_space *mapping = inode->i_mapping;
4690 struct btrfs_root *root = BTRFS_I(inode)->root;
4691 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4692 struct btrfs_ordered_extent *ordered;
4693 struct extent_state *cached_state = NULL;
4695 u32 blocksize = root->sectorsize;
4696 pgoff_t index = from >> PAGE_SHIFT;
4697 unsigned offset = from & (blocksize - 1);
4699 gfp_t mask = btrfs_alloc_write_mask(mapping);
4704 if ((offset & (blocksize - 1)) == 0 &&
4705 (!len || ((len & (blocksize - 1)) == 0)))
4708 ret = btrfs_delalloc_reserve_space(inode,
4709 round_down(from, blocksize), blocksize);
4714 page = find_or_create_page(mapping, index, mask);
4716 btrfs_delalloc_release_space(inode,
4717 round_down(from, blocksize),
4723 block_start = round_down(from, blocksize);
4724 block_end = block_start + blocksize - 1;
4726 if (!PageUptodate(page)) {
4727 ret = btrfs_readpage(NULL, page);
4729 if (page->mapping != mapping) {
4734 if (!PageUptodate(page)) {
4739 wait_on_page_writeback(page);
4741 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4742 set_page_extent_mapped(page);
4744 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4746 unlock_extent_cached(io_tree, block_start, block_end,
4747 &cached_state, GFP_NOFS);
4750 btrfs_start_ordered_extent(inode, ordered, 1);
4751 btrfs_put_ordered_extent(ordered);
4755 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4756 EXTENT_DIRTY | EXTENT_DELALLOC |
4757 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4758 0, 0, &cached_state, GFP_NOFS);
4760 ret = btrfs_set_extent_delalloc(inode, block_start, block_end,
4763 unlock_extent_cached(io_tree, block_start, block_end,
4764 &cached_state, GFP_NOFS);
4768 if (offset != blocksize) {
4770 len = blocksize - offset;
4773 memset(kaddr + (block_start - page_offset(page)),
4776 memset(kaddr + (block_start - page_offset(page)) + offset,
4778 flush_dcache_page(page);
4781 ClearPageChecked(page);
4782 set_page_dirty(page);
4783 unlock_extent_cached(io_tree, block_start, block_end, &cached_state,
4788 btrfs_delalloc_release_space(inode, block_start,
4796 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4797 u64 offset, u64 len)
4799 struct btrfs_trans_handle *trans;
4803 * Still need to make sure the inode looks like it's been updated so
4804 * that any holes get logged if we fsync.
4806 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4807 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4808 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4809 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4814 * 1 - for the one we're dropping
4815 * 1 - for the one we're adding
4816 * 1 - for updating the inode.
4818 trans = btrfs_start_transaction(root, 3);
4820 return PTR_ERR(trans);
4822 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4824 btrfs_abort_transaction(trans, ret);
4825 btrfs_end_transaction(trans, root);
4829 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4830 0, 0, len, 0, len, 0, 0, 0);
4832 btrfs_abort_transaction(trans, ret);
4834 btrfs_update_inode(trans, root, inode);
4835 btrfs_end_transaction(trans, root);
4840 * This function puts in dummy file extents for the area we're creating a hole
4841 * for. So if we are truncating this file to a larger size we need to insert
4842 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4843 * the range between oldsize and size
4845 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4847 struct btrfs_root *root = BTRFS_I(inode)->root;
4848 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4849 struct extent_map *em = NULL;
4850 struct extent_state *cached_state = NULL;
4851 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4852 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4853 u64 block_end = ALIGN(size, root->sectorsize);
4860 * If our size started in the middle of a block we need to zero out the
4861 * rest of the block before we expand the i_size, otherwise we could
4862 * expose stale data.
4864 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4868 if (size <= hole_start)
4872 struct btrfs_ordered_extent *ordered;
4874 lock_extent_bits(io_tree, hole_start, block_end - 1,
4876 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4877 block_end - hole_start);
4880 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4881 &cached_state, GFP_NOFS);
4882 btrfs_start_ordered_extent(inode, ordered, 1);
4883 btrfs_put_ordered_extent(ordered);
4886 cur_offset = hole_start;
4888 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4889 block_end - cur_offset, 0);
4895 last_byte = min(extent_map_end(em), block_end);
4896 last_byte = ALIGN(last_byte , root->sectorsize);
4897 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4898 struct extent_map *hole_em;
4899 hole_size = last_byte - cur_offset;
4901 err = maybe_insert_hole(root, inode, cur_offset,
4905 btrfs_drop_extent_cache(inode, cur_offset,
4906 cur_offset + hole_size - 1, 0);
4907 hole_em = alloc_extent_map();
4909 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4910 &BTRFS_I(inode)->runtime_flags);
4913 hole_em->start = cur_offset;
4914 hole_em->len = hole_size;
4915 hole_em->orig_start = cur_offset;
4917 hole_em->block_start = EXTENT_MAP_HOLE;
4918 hole_em->block_len = 0;
4919 hole_em->orig_block_len = 0;
4920 hole_em->ram_bytes = hole_size;
4921 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4922 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4923 hole_em->generation = root->fs_info->generation;
4926 write_lock(&em_tree->lock);
4927 err = add_extent_mapping(em_tree, hole_em, 1);
4928 write_unlock(&em_tree->lock);
4931 btrfs_drop_extent_cache(inode, cur_offset,
4935 free_extent_map(hole_em);
4938 free_extent_map(em);
4940 cur_offset = last_byte;
4941 if (cur_offset >= block_end)
4944 free_extent_map(em);
4945 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4950 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4952 struct btrfs_root *root = BTRFS_I(inode)->root;
4953 struct btrfs_trans_handle *trans;
4954 loff_t oldsize = i_size_read(inode);
4955 loff_t newsize = attr->ia_size;
4956 int mask = attr->ia_valid;
4960 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4961 * special case where we need to update the times despite not having
4962 * these flags set. For all other operations the VFS set these flags
4963 * explicitly if it wants a timestamp update.
4965 if (newsize != oldsize) {
4966 inode_inc_iversion(inode);
4967 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4968 inode->i_ctime = inode->i_mtime =
4969 current_fs_time(inode->i_sb);
4972 if (newsize > oldsize) {
4974 * Don't do an expanding truncate while snapshoting is ongoing.
4975 * This is to ensure the snapshot captures a fully consistent
4976 * state of this file - if the snapshot captures this expanding
4977 * truncation, it must capture all writes that happened before
4980 btrfs_wait_for_snapshot_creation(root);
4981 ret = btrfs_cont_expand(inode, oldsize, newsize);
4983 btrfs_end_write_no_snapshoting(root);
4987 trans = btrfs_start_transaction(root, 1);
4988 if (IS_ERR(trans)) {
4989 btrfs_end_write_no_snapshoting(root);
4990 return PTR_ERR(trans);
4993 i_size_write(inode, newsize);
4994 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4995 pagecache_isize_extended(inode, oldsize, newsize);
4996 ret = btrfs_update_inode(trans, root, inode);
4997 btrfs_end_write_no_snapshoting(root);
4998 btrfs_end_transaction(trans, root);
5002 * We're truncating a file that used to have good data down to
5003 * zero. Make sure it gets into the ordered flush list so that
5004 * any new writes get down to disk quickly.
5007 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5008 &BTRFS_I(inode)->runtime_flags);
5011 * 1 for the orphan item we're going to add
5012 * 1 for the orphan item deletion.
5014 trans = btrfs_start_transaction(root, 2);
5016 return PTR_ERR(trans);
5019 * We need to do this in case we fail at _any_ point during the
5020 * actual truncate. Once we do the truncate_setsize we could
5021 * invalidate pages which forces any outstanding ordered io to
5022 * be instantly completed which will give us extents that need
5023 * to be truncated. If we fail to get an orphan inode down we
5024 * could have left over extents that were never meant to live,
5025 * so we need to guarantee from this point on that everything
5026 * will be consistent.
5028 ret = btrfs_orphan_add(trans, inode);
5029 btrfs_end_transaction(trans, root);
5033 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5034 truncate_setsize(inode, newsize);
5036 /* Disable nonlocked read DIO to avoid the end less truncate */
5037 btrfs_inode_block_unlocked_dio(inode);
5038 inode_dio_wait(inode);
5039 btrfs_inode_resume_unlocked_dio(inode);
5041 ret = btrfs_truncate(inode);
5042 if (ret && inode->i_nlink) {
5046 * failed to truncate, disk_i_size is only adjusted down
5047 * as we remove extents, so it should represent the true
5048 * size of the inode, so reset the in memory size and
5049 * delete our orphan entry.
5051 trans = btrfs_join_transaction(root);
5052 if (IS_ERR(trans)) {
5053 btrfs_orphan_del(NULL, inode);
5056 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5057 err = btrfs_orphan_del(trans, inode);
5059 btrfs_abort_transaction(trans, err);
5060 btrfs_end_transaction(trans, root);
5067 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5069 struct inode *inode = d_inode(dentry);
5070 struct btrfs_root *root = BTRFS_I(inode)->root;
5073 if (btrfs_root_readonly(root))
5076 err = inode_change_ok(inode, attr);
5080 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5081 err = btrfs_setsize(inode, attr);
5086 if (attr->ia_valid) {
5087 setattr_copy(inode, attr);
5088 inode_inc_iversion(inode);
5089 err = btrfs_dirty_inode(inode);
5091 if (!err && attr->ia_valid & ATTR_MODE)
5092 err = posix_acl_chmod(inode, inode->i_mode);
5099 * While truncating the inode pages during eviction, we get the VFS calling
5100 * btrfs_invalidatepage() against each page of the inode. This is slow because
5101 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5102 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5103 * extent_state structures over and over, wasting lots of time.
5105 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5106 * those expensive operations on a per page basis and do only the ordered io
5107 * finishing, while we release here the extent_map and extent_state structures,
5108 * without the excessive merging and splitting.
5110 static void evict_inode_truncate_pages(struct inode *inode)
5112 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5113 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5114 struct rb_node *node;
5116 ASSERT(inode->i_state & I_FREEING);
5117 truncate_inode_pages_final(&inode->i_data);
5119 write_lock(&map_tree->lock);
5120 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5121 struct extent_map *em;
5123 node = rb_first(&map_tree->map);
5124 em = rb_entry(node, struct extent_map, rb_node);
5125 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5126 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5127 remove_extent_mapping(map_tree, em);
5128 free_extent_map(em);
5129 if (need_resched()) {
5130 write_unlock(&map_tree->lock);
5132 write_lock(&map_tree->lock);
5135 write_unlock(&map_tree->lock);
5138 * Keep looping until we have no more ranges in the io tree.
5139 * We can have ongoing bios started by readpages (called from readahead)
5140 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5141 * still in progress (unlocked the pages in the bio but did not yet
5142 * unlocked the ranges in the io tree). Therefore this means some
5143 * ranges can still be locked and eviction started because before
5144 * submitting those bios, which are executed by a separate task (work
5145 * queue kthread), inode references (inode->i_count) were not taken
5146 * (which would be dropped in the end io callback of each bio).
5147 * Therefore here we effectively end up waiting for those bios and
5148 * anyone else holding locked ranges without having bumped the inode's
5149 * reference count - if we don't do it, when they access the inode's
5150 * io_tree to unlock a range it may be too late, leading to an
5151 * use-after-free issue.
5153 spin_lock(&io_tree->lock);
5154 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5155 struct extent_state *state;
5156 struct extent_state *cached_state = NULL;
5160 node = rb_first(&io_tree->state);
5161 state = rb_entry(node, struct extent_state, rb_node);
5162 start = state->start;
5164 spin_unlock(&io_tree->lock);
5166 lock_extent_bits(io_tree, start, end, &cached_state);
5169 * If still has DELALLOC flag, the extent didn't reach disk,
5170 * and its reserved space won't be freed by delayed_ref.
5171 * So we need to free its reserved space here.
5172 * (Refer to comment in btrfs_invalidatepage, case 2)
5174 * Note, end is the bytenr of last byte, so we need + 1 here.
5176 if (state->state & EXTENT_DELALLOC)
5177 btrfs_qgroup_free_data(inode, start, end - start + 1);
5179 clear_extent_bit(io_tree, start, end,
5180 EXTENT_LOCKED | EXTENT_DIRTY |
5181 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5182 EXTENT_DEFRAG, 1, 1,
5183 &cached_state, GFP_NOFS);
5186 spin_lock(&io_tree->lock);
5188 spin_unlock(&io_tree->lock);
5191 void btrfs_evict_inode(struct inode *inode)
5193 struct btrfs_trans_handle *trans;
5194 struct btrfs_root *root = BTRFS_I(inode)->root;
5195 struct btrfs_block_rsv *rsv, *global_rsv;
5196 int steal_from_global = 0;
5200 trace_btrfs_inode_evict(inode);
5203 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
5207 min_size = btrfs_calc_trunc_metadata_size(root, 1);
5209 evict_inode_truncate_pages(inode);
5211 if (inode->i_nlink &&
5212 ((btrfs_root_refs(&root->root_item) != 0 &&
5213 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5214 btrfs_is_free_space_inode(inode)))
5217 if (is_bad_inode(inode)) {
5218 btrfs_orphan_del(NULL, inode);
5221 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5222 if (!special_file(inode->i_mode))
5223 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5225 btrfs_free_io_failure_record(inode, 0, (u64)-1);
5227 if (root->fs_info->log_root_recovering) {
5228 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5229 &BTRFS_I(inode)->runtime_flags));
5233 if (inode->i_nlink > 0) {
5234 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5235 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5239 ret = btrfs_commit_inode_delayed_inode(inode);
5241 btrfs_orphan_del(NULL, inode);
5245 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
5247 btrfs_orphan_del(NULL, inode);
5250 rsv->size = min_size;
5252 global_rsv = &root->fs_info->global_block_rsv;
5254 btrfs_i_size_write(inode, 0);
5257 * This is a bit simpler than btrfs_truncate since we've already
5258 * reserved our space for our orphan item in the unlink, so we just
5259 * need to reserve some slack space in case we add bytes and update
5260 * inode item when doing the truncate.
5263 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5264 BTRFS_RESERVE_FLUSH_LIMIT);
5267 * Try and steal from the global reserve since we will
5268 * likely not use this space anyway, we want to try as
5269 * hard as possible to get this to work.
5272 steal_from_global++;
5274 steal_from_global = 0;
5278 * steal_from_global == 0: we reserved stuff, hooray!
5279 * steal_from_global == 1: we didn't reserve stuff, boo!
5280 * steal_from_global == 2: we've committed, still not a lot of
5281 * room but maybe we'll have room in the global reserve this
5283 * steal_from_global == 3: abandon all hope!
5285 if (steal_from_global > 2) {
5286 btrfs_warn(root->fs_info,
5287 "Could not get space for a delete, will truncate on mount %d",
5289 btrfs_orphan_del(NULL, inode);
5290 btrfs_free_block_rsv(root, rsv);
5294 trans = btrfs_join_transaction(root);
5295 if (IS_ERR(trans)) {
5296 btrfs_orphan_del(NULL, inode);
5297 btrfs_free_block_rsv(root, rsv);
5302 * We can't just steal from the global reserve, we need to make
5303 * sure there is room to do it, if not we need to commit and try
5306 if (steal_from_global) {
5307 if (!btrfs_check_space_for_delayed_refs(trans, root))
5308 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5315 * Couldn't steal from the global reserve, we have too much
5316 * pending stuff built up, commit the transaction and try it
5320 ret = btrfs_commit_transaction(trans, root);
5322 btrfs_orphan_del(NULL, inode);
5323 btrfs_free_block_rsv(root, rsv);
5328 steal_from_global = 0;
5331 trans->block_rsv = rsv;
5333 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5334 if (ret != -ENOSPC && ret != -EAGAIN)
5337 trans->block_rsv = &root->fs_info->trans_block_rsv;
5338 btrfs_end_transaction(trans, root);
5340 btrfs_btree_balance_dirty(root);
5343 btrfs_free_block_rsv(root, rsv);
5346 * Errors here aren't a big deal, it just means we leave orphan items
5347 * in the tree. They will be cleaned up on the next mount.
5350 trans->block_rsv = root->orphan_block_rsv;
5351 btrfs_orphan_del(trans, inode);
5353 btrfs_orphan_del(NULL, inode);
5356 trans->block_rsv = &root->fs_info->trans_block_rsv;
5357 if (!(root == root->fs_info->tree_root ||
5358 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5359 btrfs_return_ino(root, btrfs_ino(inode));
5361 btrfs_end_transaction(trans, root);
5362 btrfs_btree_balance_dirty(root);
5364 btrfs_remove_delayed_node(inode);
5369 * this returns the key found in the dir entry in the location pointer.
5370 * If no dir entries were found, location->objectid is 0.
5372 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5373 struct btrfs_key *location)
5375 const char *name = dentry->d_name.name;
5376 int namelen = dentry->d_name.len;
5377 struct btrfs_dir_item *di;
5378 struct btrfs_path *path;
5379 struct btrfs_root *root = BTRFS_I(dir)->root;
5382 path = btrfs_alloc_path();
5386 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
5391 if (IS_ERR_OR_NULL(di))
5394 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5396 btrfs_free_path(path);
5399 location->objectid = 0;
5404 * when we hit a tree root in a directory, the btrfs part of the inode
5405 * needs to be changed to reflect the root directory of the tree root. This
5406 * is kind of like crossing a mount point.
5408 static int fixup_tree_root_location(struct btrfs_root *root,
5410 struct dentry *dentry,
5411 struct btrfs_key *location,
5412 struct btrfs_root **sub_root)
5414 struct btrfs_path *path;
5415 struct btrfs_root *new_root;
5416 struct btrfs_root_ref *ref;
5417 struct extent_buffer *leaf;
5418 struct btrfs_key key;
5422 path = btrfs_alloc_path();
5429 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5430 key.type = BTRFS_ROOT_REF_KEY;
5431 key.offset = location->objectid;
5433 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, path,
5441 leaf = path->nodes[0];
5442 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5443 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5444 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5447 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5448 (unsigned long)(ref + 1),
5449 dentry->d_name.len);
5453 btrfs_release_path(path);
5455 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
5456 if (IS_ERR(new_root)) {
5457 err = PTR_ERR(new_root);
5461 *sub_root = new_root;
5462 location->objectid = btrfs_root_dirid(&new_root->root_item);
5463 location->type = BTRFS_INODE_ITEM_KEY;
5464 location->offset = 0;
5467 btrfs_free_path(path);
5471 static void inode_tree_add(struct inode *inode)
5473 struct btrfs_root *root = BTRFS_I(inode)->root;
5474 struct btrfs_inode *entry;
5476 struct rb_node *parent;
5477 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5478 u64 ino = btrfs_ino(inode);
5480 if (inode_unhashed(inode))
5483 spin_lock(&root->inode_lock);
5484 p = &root->inode_tree.rb_node;
5487 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5489 if (ino < btrfs_ino(&entry->vfs_inode))
5490 p = &parent->rb_left;
5491 else if (ino > btrfs_ino(&entry->vfs_inode))
5492 p = &parent->rb_right;
5494 WARN_ON(!(entry->vfs_inode.i_state &
5495 (I_WILL_FREE | I_FREEING)));
5496 rb_replace_node(parent, new, &root->inode_tree);
5497 RB_CLEAR_NODE(parent);
5498 spin_unlock(&root->inode_lock);
5502 rb_link_node(new, parent, p);
5503 rb_insert_color(new, &root->inode_tree);
5504 spin_unlock(&root->inode_lock);
5507 static void inode_tree_del(struct inode *inode)
5509 struct btrfs_root *root = BTRFS_I(inode)->root;
5512 spin_lock(&root->inode_lock);
5513 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5514 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5515 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5516 empty = RB_EMPTY_ROOT(&root->inode_tree);
5518 spin_unlock(&root->inode_lock);
5520 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5521 synchronize_srcu(&root->fs_info->subvol_srcu);
5522 spin_lock(&root->inode_lock);
5523 empty = RB_EMPTY_ROOT(&root->inode_tree);
5524 spin_unlock(&root->inode_lock);
5526 btrfs_add_dead_root(root);
5530 void btrfs_invalidate_inodes(struct btrfs_root *root)
5532 struct rb_node *node;
5533 struct rb_node *prev;
5534 struct btrfs_inode *entry;
5535 struct inode *inode;
5538 if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
5539 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5541 spin_lock(&root->inode_lock);
5543 node = root->inode_tree.rb_node;
5547 entry = rb_entry(node, struct btrfs_inode, rb_node);
5549 if (objectid < btrfs_ino(&entry->vfs_inode))
5550 node = node->rb_left;
5551 else if (objectid > btrfs_ino(&entry->vfs_inode))
5552 node = node->rb_right;
5558 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5559 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
5563 prev = rb_next(prev);
5567 entry = rb_entry(node, struct btrfs_inode, rb_node);
5568 objectid = btrfs_ino(&entry->vfs_inode) + 1;
5569 inode = igrab(&entry->vfs_inode);
5571 spin_unlock(&root->inode_lock);
5572 if (atomic_read(&inode->i_count) > 1)
5573 d_prune_aliases(inode);
5575 * btrfs_drop_inode will have it removed from
5576 * the inode cache when its usage count
5581 spin_lock(&root->inode_lock);
5585 if (cond_resched_lock(&root->inode_lock))
5588 node = rb_next(node);
5590 spin_unlock(&root->inode_lock);
5593 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5595 struct btrfs_iget_args *args = p;
5596 inode->i_ino = args->location->objectid;
5597 memcpy(&BTRFS_I(inode)->location, args->location,
5598 sizeof(*args->location));
5599 BTRFS_I(inode)->root = args->root;
5603 static int btrfs_find_actor(struct inode *inode, void *opaque)
5605 struct btrfs_iget_args *args = opaque;
5606 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5607 args->root == BTRFS_I(inode)->root;
5610 static struct inode *btrfs_iget_locked(struct super_block *s,
5611 struct btrfs_key *location,
5612 struct btrfs_root *root)
5614 struct inode *inode;
5615 struct btrfs_iget_args args;
5616 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5618 args.location = location;
5621 inode = iget5_locked(s, hashval, btrfs_find_actor,
5622 btrfs_init_locked_inode,
5627 /* Get an inode object given its location and corresponding root.
5628 * Returns in *is_new if the inode was read from disk
5630 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5631 struct btrfs_root *root, int *new)
5633 struct inode *inode;
5635 inode = btrfs_iget_locked(s, location, root);
5637 return ERR_PTR(-ENOMEM);
5639 if (inode->i_state & I_NEW) {
5642 ret = btrfs_read_locked_inode(inode);
5643 if (!is_bad_inode(inode)) {
5644 inode_tree_add(inode);
5645 unlock_new_inode(inode);
5649 unlock_new_inode(inode);
5652 inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5659 static struct inode *new_simple_dir(struct super_block *s,
5660 struct btrfs_key *key,
5661 struct btrfs_root *root)
5663 struct inode *inode = new_inode(s);
5666 return ERR_PTR(-ENOMEM);
5668 BTRFS_I(inode)->root = root;
5669 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5670 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5672 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5673 inode->i_op = &btrfs_dir_ro_inode_operations;
5674 inode->i_fop = &simple_dir_operations;
5675 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5676 inode->i_mtime = current_fs_time(inode->i_sb);
5677 inode->i_atime = inode->i_mtime;
5678 inode->i_ctime = inode->i_mtime;
5679 BTRFS_I(inode)->i_otime = inode->i_mtime;
5684 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5686 struct inode *inode;
5687 struct btrfs_root *root = BTRFS_I(dir)->root;
5688 struct btrfs_root *sub_root = root;
5689 struct btrfs_key location;
5693 if (dentry->d_name.len > BTRFS_NAME_LEN)
5694 return ERR_PTR(-ENAMETOOLONG);
5696 ret = btrfs_inode_by_name(dir, dentry, &location);
5698 return ERR_PTR(ret);
5700 if (location.objectid == 0)
5701 return ERR_PTR(-ENOENT);
5703 if (location.type == BTRFS_INODE_ITEM_KEY) {
5704 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5708 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5710 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5711 ret = fixup_tree_root_location(root, dir, dentry,
5712 &location, &sub_root);
5715 inode = ERR_PTR(ret);
5717 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5719 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5721 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5723 if (!IS_ERR(inode) && root != sub_root) {
5724 down_read(&root->fs_info->cleanup_work_sem);
5725 if (!(inode->i_sb->s_flags & MS_RDONLY))
5726 ret = btrfs_orphan_cleanup(sub_root);
5727 up_read(&root->fs_info->cleanup_work_sem);
5730 inode = ERR_PTR(ret);
5737 static int btrfs_dentry_delete(const struct dentry *dentry)
5739 struct btrfs_root *root;
5740 struct inode *inode = d_inode(dentry);
5742 if (!inode && !IS_ROOT(dentry))
5743 inode = d_inode(dentry->d_parent);
5746 root = BTRFS_I(inode)->root;
5747 if (btrfs_root_refs(&root->root_item) == 0)
5750 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5756 static void btrfs_dentry_release(struct dentry *dentry)
5758 kfree(dentry->d_fsdata);
5761 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5764 struct inode *inode;
5766 inode = btrfs_lookup_dentry(dir, dentry);
5767 if (IS_ERR(inode)) {
5768 if (PTR_ERR(inode) == -ENOENT)
5771 return ERR_CAST(inode);
5774 return d_splice_alias(inode, dentry);
5777 unsigned char btrfs_filetype_table[] = {
5778 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5781 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5783 struct inode *inode = file_inode(file);
5784 struct btrfs_root *root = BTRFS_I(inode)->root;
5785 struct btrfs_item *item;
5786 struct btrfs_dir_item *di;
5787 struct btrfs_key key;
5788 struct btrfs_key found_key;
5789 struct btrfs_path *path;
5790 struct list_head ins_list;
5791 struct list_head del_list;
5793 struct extent_buffer *leaf;
5795 unsigned char d_type;
5800 int key_type = BTRFS_DIR_INDEX_KEY;
5804 int is_curr = 0; /* ctx->pos points to the current index? */
5808 /* FIXME, use a real flag for deciding about the key type */
5809 if (root->fs_info->tree_root == root)
5810 key_type = BTRFS_DIR_ITEM_KEY;
5812 if (!dir_emit_dots(file, ctx))
5815 path = btrfs_alloc_path();
5819 path->reada = READA_FORWARD;
5821 if (key_type == BTRFS_DIR_INDEX_KEY) {
5822 INIT_LIST_HEAD(&ins_list);
5823 INIT_LIST_HEAD(&del_list);
5824 put = btrfs_readdir_get_delayed_items(inode, &ins_list,
5828 key.type = key_type;
5829 key.offset = ctx->pos;
5830 key.objectid = btrfs_ino(inode);
5832 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5838 leaf = path->nodes[0];
5839 slot = path->slots[0];
5840 if (slot >= btrfs_header_nritems(leaf)) {
5841 ret = btrfs_next_leaf(root, path);
5849 item = btrfs_item_nr(slot);
5850 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5852 if (found_key.objectid != key.objectid)
5854 if (found_key.type != key_type)
5856 if (found_key.offset < ctx->pos)
5858 if (key_type == BTRFS_DIR_INDEX_KEY &&
5859 btrfs_should_delete_dir_index(&del_list,
5863 ctx->pos = found_key.offset;
5866 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5868 di_total = btrfs_item_size(leaf, item);
5870 while (di_cur < di_total) {
5871 struct btrfs_key location;
5873 if (verify_dir_item(root, leaf, di))
5876 name_len = btrfs_dir_name_len(leaf, di);
5877 if (name_len <= sizeof(tmp_name)) {
5878 name_ptr = tmp_name;
5880 name_ptr = kmalloc(name_len, GFP_KERNEL);
5886 read_extent_buffer(leaf, name_ptr,
5887 (unsigned long)(di + 1), name_len);
5889 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5890 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5893 /* is this a reference to our own snapshot? If so
5896 * In contrast to old kernels, we insert the snapshot's
5897 * dir item and dir index after it has been created, so
5898 * we won't find a reference to our own snapshot. We
5899 * still keep the following code for backward
5902 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5903 location.objectid == root->root_key.objectid) {
5907 over = !dir_emit(ctx, name_ptr, name_len,
5908 location.objectid, d_type);
5911 if (name_ptr != tmp_name)
5917 di_len = btrfs_dir_name_len(leaf, di) +
5918 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5920 di = (struct btrfs_dir_item *)((char *)di + di_len);
5926 if (key_type == BTRFS_DIR_INDEX_KEY) {
5929 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list, &emitted);
5935 * If we haven't emitted any dir entry, we must not touch ctx->pos as
5936 * it was was set to the termination value in previous call. We assume
5937 * that "." and ".." were emitted if we reach this point and set the
5938 * termination value as well for an empty directory.
5940 if (ctx->pos > 2 && !emitted)
5943 /* Reached end of directory/root. Bump pos past the last item. */
5947 * Stop new entries from being returned after we return the last
5950 * New directory entries are assigned a strictly increasing
5951 * offset. This means that new entries created during readdir
5952 * are *guaranteed* to be seen in the future by that readdir.
5953 * This has broken buggy programs which operate on names as
5954 * they're returned by readdir. Until we re-use freed offsets
5955 * we have this hack to stop new entries from being returned
5956 * under the assumption that they'll never reach this huge
5959 * This is being careful not to overflow 32bit loff_t unless the
5960 * last entry requires it because doing so has broken 32bit apps
5963 if (key_type == BTRFS_DIR_INDEX_KEY) {
5964 if (ctx->pos >= INT_MAX)
5965 ctx->pos = LLONG_MAX;
5973 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5974 btrfs_free_path(path);
5978 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5980 struct btrfs_root *root = BTRFS_I(inode)->root;
5981 struct btrfs_trans_handle *trans;
5983 bool nolock = false;
5985 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5988 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5991 if (wbc->sync_mode == WB_SYNC_ALL) {
5993 trans = btrfs_join_transaction_nolock(root);
5995 trans = btrfs_join_transaction(root);
5997 return PTR_ERR(trans);
5998 ret = btrfs_commit_transaction(trans, root);
6004 * This is somewhat expensive, updating the tree every time the
6005 * inode changes. But, it is most likely to find the inode in cache.
6006 * FIXME, needs more benchmarking...there are no reasons other than performance
6007 * to keep or drop this code.
6009 static int btrfs_dirty_inode(struct inode *inode)
6011 struct btrfs_root *root = BTRFS_I(inode)->root;
6012 struct btrfs_trans_handle *trans;
6015 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6018 trans = btrfs_join_transaction(root);
6020 return PTR_ERR(trans);
6022 ret = btrfs_update_inode(trans, root, inode);
6023 if (ret && ret == -ENOSPC) {
6024 /* whoops, lets try again with the full transaction */
6025 btrfs_end_transaction(trans, root);
6026 trans = btrfs_start_transaction(root, 1);
6028 return PTR_ERR(trans);
6030 ret = btrfs_update_inode(trans, root, inode);
6032 btrfs_end_transaction(trans, root);
6033 if (BTRFS_I(inode)->delayed_node)
6034 btrfs_balance_delayed_items(root);
6040 * This is a copy of file_update_time. We need this so we can return error on
6041 * ENOSPC for updating the inode in the case of file write and mmap writes.
6043 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6046 struct btrfs_root *root = BTRFS_I(inode)->root;
6048 if (btrfs_root_readonly(root))
6051 if (flags & S_VERSION)
6052 inode_inc_iversion(inode);
6053 if (flags & S_CTIME)
6054 inode->i_ctime = *now;
6055 if (flags & S_MTIME)
6056 inode->i_mtime = *now;
6057 if (flags & S_ATIME)
6058 inode->i_atime = *now;
6059 return btrfs_dirty_inode(inode);
6063 * find the highest existing sequence number in a directory
6064 * and then set the in-memory index_cnt variable to reflect
6065 * free sequence numbers
6067 static int btrfs_set_inode_index_count(struct inode *inode)
6069 struct btrfs_root *root = BTRFS_I(inode)->root;
6070 struct btrfs_key key, found_key;
6071 struct btrfs_path *path;
6072 struct extent_buffer *leaf;
6075 key.objectid = btrfs_ino(inode);
6076 key.type = BTRFS_DIR_INDEX_KEY;
6077 key.offset = (u64)-1;
6079 path = btrfs_alloc_path();
6083 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6086 /* FIXME: we should be able to handle this */
6092 * MAGIC NUMBER EXPLANATION:
6093 * since we search a directory based on f_pos we have to start at 2
6094 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6095 * else has to start at 2
6097 if (path->slots[0] == 0) {
6098 BTRFS_I(inode)->index_cnt = 2;
6104 leaf = path->nodes[0];
6105 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6107 if (found_key.objectid != btrfs_ino(inode) ||
6108 found_key.type != BTRFS_DIR_INDEX_KEY) {
6109 BTRFS_I(inode)->index_cnt = 2;
6113 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
6115 btrfs_free_path(path);
6120 * helper to find a free sequence number in a given directory. This current
6121 * code is very simple, later versions will do smarter things in the btree
6123 int btrfs_set_inode_index(struct inode *dir, u64 *index)
6127 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
6128 ret = btrfs_inode_delayed_dir_index_count(dir);
6130 ret = btrfs_set_inode_index_count(dir);
6136 *index = BTRFS_I(dir)->index_cnt;
6137 BTRFS_I(dir)->index_cnt++;
6142 static int btrfs_insert_inode_locked(struct inode *inode)
6144 struct btrfs_iget_args args;
6145 args.location = &BTRFS_I(inode)->location;
6146 args.root = BTRFS_I(inode)->root;
6148 return insert_inode_locked4(inode,
6149 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6150 btrfs_find_actor, &args);
6153 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6154 struct btrfs_root *root,
6156 const char *name, int name_len,
6157 u64 ref_objectid, u64 objectid,
6158 umode_t mode, u64 *index)
6160 struct inode *inode;
6161 struct btrfs_inode_item *inode_item;
6162 struct btrfs_key *location;
6163 struct btrfs_path *path;
6164 struct btrfs_inode_ref *ref;
6165 struct btrfs_key key[2];
6167 int nitems = name ? 2 : 1;
6171 path = btrfs_alloc_path();
6173 return ERR_PTR(-ENOMEM);
6175 inode = new_inode(root->fs_info->sb);
6177 btrfs_free_path(path);
6178 return ERR_PTR(-ENOMEM);
6182 * O_TMPFILE, set link count to 0, so that after this point,
6183 * we fill in an inode item with the correct link count.
6186 set_nlink(inode, 0);
6189 * we have to initialize this early, so we can reclaim the inode
6190 * number if we fail afterwards in this function.
6192 inode->i_ino = objectid;
6195 trace_btrfs_inode_request(dir);
6197 ret = btrfs_set_inode_index(dir, index);
6199 btrfs_free_path(path);
6201 return ERR_PTR(ret);
6207 * index_cnt is ignored for everything but a dir,
6208 * btrfs_get_inode_index_count has an explanation for the magic
6211 BTRFS_I(inode)->index_cnt = 2;
6212 BTRFS_I(inode)->dir_index = *index;
6213 BTRFS_I(inode)->root = root;
6214 BTRFS_I(inode)->generation = trans->transid;
6215 inode->i_generation = BTRFS_I(inode)->generation;
6218 * We could have gotten an inode number from somebody who was fsynced
6219 * and then removed in this same transaction, so let's just set full
6220 * sync since it will be a full sync anyway and this will blow away the
6221 * old info in the log.
6223 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6225 key[0].objectid = objectid;
6226 key[0].type = BTRFS_INODE_ITEM_KEY;
6229 sizes[0] = sizeof(struct btrfs_inode_item);
6233 * Start new inodes with an inode_ref. This is slightly more
6234 * efficient for small numbers of hard links since they will
6235 * be packed into one item. Extended refs will kick in if we
6236 * add more hard links than can fit in the ref item.
6238 key[1].objectid = objectid;
6239 key[1].type = BTRFS_INODE_REF_KEY;
6240 key[1].offset = ref_objectid;
6242 sizes[1] = name_len + sizeof(*ref);
6245 location = &BTRFS_I(inode)->location;
6246 location->objectid = objectid;
6247 location->offset = 0;
6248 location->type = BTRFS_INODE_ITEM_KEY;
6250 ret = btrfs_insert_inode_locked(inode);
6254 path->leave_spinning = 1;
6255 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6259 inode_init_owner(inode, dir, mode);
6260 inode_set_bytes(inode, 0);
6262 inode->i_mtime = current_fs_time(inode->i_sb);
6263 inode->i_atime = inode->i_mtime;
6264 inode->i_ctime = inode->i_mtime;
6265 BTRFS_I(inode)->i_otime = inode->i_mtime;
6267 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6268 struct btrfs_inode_item);
6269 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
6270 sizeof(*inode_item));
6271 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6274 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6275 struct btrfs_inode_ref);
6276 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6277 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6278 ptr = (unsigned long)(ref + 1);
6279 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6282 btrfs_mark_buffer_dirty(path->nodes[0]);
6283 btrfs_free_path(path);
6285 btrfs_inherit_iflags(inode, dir);
6287 if (S_ISREG(mode)) {
6288 if (btrfs_test_opt(root->fs_info, NODATASUM))
6289 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6290 if (btrfs_test_opt(root->fs_info, NODATACOW))
6291 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6292 BTRFS_INODE_NODATASUM;
6295 inode_tree_add(inode);
6297 trace_btrfs_inode_new(inode);
6298 btrfs_set_inode_last_trans(trans, inode);
6300 btrfs_update_root_times(trans, root);
6302 ret = btrfs_inode_inherit_props(trans, inode, dir);
6304 btrfs_err(root->fs_info,
6305 "error inheriting props for ino %llu (root %llu): %d",
6306 btrfs_ino(inode), root->root_key.objectid, ret);
6311 unlock_new_inode(inode);
6314 BTRFS_I(dir)->index_cnt--;
6315 btrfs_free_path(path);
6317 return ERR_PTR(ret);
6320 static inline u8 btrfs_inode_type(struct inode *inode)
6322 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6326 * utility function to add 'inode' into 'parent_inode' with
6327 * a give name and a given sequence number.
6328 * if 'add_backref' is true, also insert a backref from the
6329 * inode to the parent directory.
6331 int btrfs_add_link(struct btrfs_trans_handle *trans,
6332 struct inode *parent_inode, struct inode *inode,
6333 const char *name, int name_len, int add_backref, u64 index)
6336 struct btrfs_key key;
6337 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
6338 u64 ino = btrfs_ino(inode);
6339 u64 parent_ino = btrfs_ino(parent_inode);
6341 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6342 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
6345 key.type = BTRFS_INODE_ITEM_KEY;
6349 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6350 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
6351 key.objectid, root->root_key.objectid,
6352 parent_ino, index, name, name_len);
6353 } else if (add_backref) {
6354 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6358 /* Nothing to clean up yet */
6362 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6364 btrfs_inode_type(inode), index);
6365 if (ret == -EEXIST || ret == -EOVERFLOW)
6368 btrfs_abort_transaction(trans, ret);
6372 btrfs_i_size_write(parent_inode, parent_inode->i_size +
6374 inode_inc_iversion(parent_inode);
6375 parent_inode->i_mtime = parent_inode->i_ctime =
6376 current_fs_time(parent_inode->i_sb);
6377 ret = btrfs_update_inode(trans, root, parent_inode);
6379 btrfs_abort_transaction(trans, ret);
6383 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6386 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
6387 key.objectid, root->root_key.objectid,
6388 parent_ino, &local_index, name, name_len);
6390 } else if (add_backref) {
6394 err = btrfs_del_inode_ref(trans, root, name, name_len,
6395 ino, parent_ino, &local_index);
6400 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6401 struct inode *dir, struct dentry *dentry,
6402 struct inode *inode, int backref, u64 index)
6404 int err = btrfs_add_link(trans, dir, inode,
6405 dentry->d_name.name, dentry->d_name.len,
6412 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6413 umode_t mode, dev_t rdev)
6415 struct btrfs_trans_handle *trans;
6416 struct btrfs_root *root = BTRFS_I(dir)->root;
6417 struct inode *inode = NULL;
6424 * 2 for inode item and ref
6426 * 1 for xattr if selinux is on
6428 trans = btrfs_start_transaction(root, 5);
6430 return PTR_ERR(trans);
6432 err = btrfs_find_free_ino(root, &objectid);
6436 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6437 dentry->d_name.len, btrfs_ino(dir), objectid,
6439 if (IS_ERR(inode)) {
6440 err = PTR_ERR(inode);
6445 * If the active LSM wants to access the inode during
6446 * d_instantiate it needs these. Smack checks to see
6447 * if the filesystem supports xattrs by looking at the
6450 inode->i_op = &btrfs_special_inode_operations;
6451 init_special_inode(inode, inode->i_mode, rdev);
6453 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6455 goto out_unlock_inode;
6457 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6459 goto out_unlock_inode;
6461 btrfs_update_inode(trans, root, inode);
6462 unlock_new_inode(inode);
6463 d_instantiate(dentry, inode);
6467 btrfs_end_transaction(trans, root);
6468 btrfs_balance_delayed_items(root);
6469 btrfs_btree_balance_dirty(root);
6471 inode_dec_link_count(inode);
6478 unlock_new_inode(inode);
6483 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6484 umode_t mode, bool excl)
6486 struct btrfs_trans_handle *trans;
6487 struct btrfs_root *root = BTRFS_I(dir)->root;
6488 struct inode *inode = NULL;
6489 int drop_inode_on_err = 0;
6495 * 2 for inode item and ref
6497 * 1 for xattr if selinux is on
6499 trans = btrfs_start_transaction(root, 5);
6501 return PTR_ERR(trans);
6503 err = btrfs_find_free_ino(root, &objectid);
6507 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6508 dentry->d_name.len, btrfs_ino(dir), objectid,
6510 if (IS_ERR(inode)) {
6511 err = PTR_ERR(inode);
6514 drop_inode_on_err = 1;
6516 * If the active LSM wants to access the inode during
6517 * d_instantiate it needs these. Smack checks to see
6518 * if the filesystem supports xattrs by looking at the
6521 inode->i_fop = &btrfs_file_operations;
6522 inode->i_op = &btrfs_file_inode_operations;
6523 inode->i_mapping->a_ops = &btrfs_aops;
6525 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6527 goto out_unlock_inode;
6529 err = btrfs_update_inode(trans, root, inode);
6531 goto out_unlock_inode;
6533 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6535 goto out_unlock_inode;
6537 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6538 unlock_new_inode(inode);
6539 d_instantiate(dentry, inode);
6542 btrfs_end_transaction(trans, root);
6543 if (err && drop_inode_on_err) {
6544 inode_dec_link_count(inode);
6547 btrfs_balance_delayed_items(root);
6548 btrfs_btree_balance_dirty(root);
6552 unlock_new_inode(inode);
6557 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6558 struct dentry *dentry)
6560 struct btrfs_trans_handle *trans = NULL;
6561 struct btrfs_root *root = BTRFS_I(dir)->root;
6562 struct inode *inode = d_inode(old_dentry);
6567 /* do not allow sys_link's with other subvols of the same device */
6568 if (root->objectid != BTRFS_I(inode)->root->objectid)
6571 if (inode->i_nlink >= BTRFS_LINK_MAX)
6574 err = btrfs_set_inode_index(dir, &index);
6579 * 2 items for inode and inode ref
6580 * 2 items for dir items
6581 * 1 item for parent inode
6583 trans = btrfs_start_transaction(root, 5);
6584 if (IS_ERR(trans)) {
6585 err = PTR_ERR(trans);
6590 /* There are several dir indexes for this inode, clear the cache. */
6591 BTRFS_I(inode)->dir_index = 0ULL;
6593 inode_inc_iversion(inode);
6594 inode->i_ctime = current_fs_time(inode->i_sb);
6596 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6598 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
6603 struct dentry *parent = dentry->d_parent;
6604 err = btrfs_update_inode(trans, root, inode);
6607 if (inode->i_nlink == 1) {
6609 * If new hard link count is 1, it's a file created
6610 * with open(2) O_TMPFILE flag.
6612 err = btrfs_orphan_del(trans, inode);
6616 d_instantiate(dentry, inode);
6617 btrfs_log_new_name(trans, inode, NULL, parent);
6620 btrfs_balance_delayed_items(root);
6623 btrfs_end_transaction(trans, root);
6625 inode_dec_link_count(inode);
6628 btrfs_btree_balance_dirty(root);
6632 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6634 struct inode *inode = NULL;
6635 struct btrfs_trans_handle *trans;
6636 struct btrfs_root *root = BTRFS_I(dir)->root;
6638 int drop_on_err = 0;
6643 * 2 items for inode and ref
6644 * 2 items for dir items
6645 * 1 for xattr if selinux is on
6647 trans = btrfs_start_transaction(root, 5);
6649 return PTR_ERR(trans);
6651 err = btrfs_find_free_ino(root, &objectid);
6655 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6656 dentry->d_name.len, btrfs_ino(dir), objectid,
6657 S_IFDIR | mode, &index);
6658 if (IS_ERR(inode)) {
6659 err = PTR_ERR(inode);
6664 /* these must be set before we unlock the inode */
6665 inode->i_op = &btrfs_dir_inode_operations;
6666 inode->i_fop = &btrfs_dir_file_operations;
6668 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6670 goto out_fail_inode;
6672 btrfs_i_size_write(inode, 0);
6673 err = btrfs_update_inode(trans, root, inode);
6675 goto out_fail_inode;
6677 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6678 dentry->d_name.len, 0, index);
6680 goto out_fail_inode;
6682 d_instantiate(dentry, inode);
6684 * mkdir is special. We're unlocking after we call d_instantiate
6685 * to avoid a race with nfsd calling d_instantiate.
6687 unlock_new_inode(inode);
6691 btrfs_end_transaction(trans, root);
6693 inode_dec_link_count(inode);
6696 btrfs_balance_delayed_items(root);
6697 btrfs_btree_balance_dirty(root);
6701 unlock_new_inode(inode);
6705 /* Find next extent map of a given extent map, caller needs to ensure locks */
6706 static struct extent_map *next_extent_map(struct extent_map *em)
6708 struct rb_node *next;
6710 next = rb_next(&em->rb_node);
6713 return container_of(next, struct extent_map, rb_node);
6716 static struct extent_map *prev_extent_map(struct extent_map *em)
6718 struct rb_node *prev;
6720 prev = rb_prev(&em->rb_node);
6723 return container_of(prev, struct extent_map, rb_node);
6726 /* helper for btfs_get_extent. Given an existing extent in the tree,
6727 * the existing extent is the nearest extent to map_start,
6728 * and an extent that you want to insert, deal with overlap and insert
6729 * the best fitted new extent into the tree.
6731 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6732 struct extent_map *existing,
6733 struct extent_map *em,
6736 struct extent_map *prev;
6737 struct extent_map *next;
6742 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6744 if (existing->start > map_start) {
6746 prev = prev_extent_map(next);
6749 next = next_extent_map(prev);
6752 start = prev ? extent_map_end(prev) : em->start;
6753 start = max_t(u64, start, em->start);
6754 end = next ? next->start : extent_map_end(em);
6755 end = min_t(u64, end, extent_map_end(em));
6756 start_diff = start - em->start;
6758 em->len = end - start;
6759 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6760 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6761 em->block_start += start_diff;
6762 em->block_len -= start_diff;
6764 return add_extent_mapping(em_tree, em, 0);
6767 static noinline int uncompress_inline(struct btrfs_path *path,
6769 size_t pg_offset, u64 extent_offset,
6770 struct btrfs_file_extent_item *item)
6773 struct extent_buffer *leaf = path->nodes[0];
6776 unsigned long inline_size;
6780 WARN_ON(pg_offset != 0);
6781 compress_type = btrfs_file_extent_compression(leaf, item);
6782 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6783 inline_size = btrfs_file_extent_inline_item_len(leaf,
6784 btrfs_item_nr(path->slots[0]));
6785 tmp = kmalloc(inline_size, GFP_NOFS);
6788 ptr = btrfs_file_extent_inline_start(item);
6790 read_extent_buffer(leaf, tmp, ptr, inline_size);
6792 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6793 ret = btrfs_decompress(compress_type, tmp, page,
6794 extent_offset, inline_size, max_size);
6800 * a bit scary, this does extent mapping from logical file offset to the disk.
6801 * the ugly parts come from merging extents from the disk with the in-ram
6802 * representation. This gets more complex because of the data=ordered code,
6803 * where the in-ram extents might be locked pending data=ordered completion.
6805 * This also copies inline extents directly into the page.
6808 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6809 size_t pg_offset, u64 start, u64 len,
6814 u64 extent_start = 0;
6816 u64 objectid = btrfs_ino(inode);
6818 struct btrfs_path *path = NULL;
6819 struct btrfs_root *root = BTRFS_I(inode)->root;
6820 struct btrfs_file_extent_item *item;
6821 struct extent_buffer *leaf;
6822 struct btrfs_key found_key;
6823 struct extent_map *em = NULL;
6824 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6825 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6826 struct btrfs_trans_handle *trans = NULL;
6827 const bool new_inline = !page || create;
6830 read_lock(&em_tree->lock);
6831 em = lookup_extent_mapping(em_tree, start, len);
6833 em->bdev = root->fs_info->fs_devices->latest_bdev;
6834 read_unlock(&em_tree->lock);
6837 if (em->start > start || em->start + em->len <= start)
6838 free_extent_map(em);
6839 else if (em->block_start == EXTENT_MAP_INLINE && page)
6840 free_extent_map(em);
6844 em = alloc_extent_map();
6849 em->bdev = root->fs_info->fs_devices->latest_bdev;
6850 em->start = EXTENT_MAP_HOLE;
6851 em->orig_start = EXTENT_MAP_HOLE;
6853 em->block_len = (u64)-1;
6856 path = btrfs_alloc_path();
6862 * Chances are we'll be called again, so go ahead and do
6865 path->reada = READA_FORWARD;
6868 ret = btrfs_lookup_file_extent(trans, root, path,
6869 objectid, start, trans != NULL);
6876 if (path->slots[0] == 0)
6881 leaf = path->nodes[0];
6882 item = btrfs_item_ptr(leaf, path->slots[0],
6883 struct btrfs_file_extent_item);
6884 /* are we inside the extent that was found? */
6885 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6886 found_type = found_key.type;
6887 if (found_key.objectid != objectid ||
6888 found_type != BTRFS_EXTENT_DATA_KEY) {
6890 * If we backup past the first extent we want to move forward
6891 * and see if there is an extent in front of us, otherwise we'll
6892 * say there is a hole for our whole search range which can
6899 found_type = btrfs_file_extent_type(leaf, item);
6900 extent_start = found_key.offset;
6901 if (found_type == BTRFS_FILE_EXTENT_REG ||
6902 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6903 extent_end = extent_start +
6904 btrfs_file_extent_num_bytes(leaf, item);
6905 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6907 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6908 extent_end = ALIGN(extent_start + size, root->sectorsize);
6911 if (start >= extent_end) {
6913 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6914 ret = btrfs_next_leaf(root, path);
6921 leaf = path->nodes[0];
6923 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6924 if (found_key.objectid != objectid ||
6925 found_key.type != BTRFS_EXTENT_DATA_KEY)
6927 if (start + len <= found_key.offset)
6929 if (start > found_key.offset)
6932 em->orig_start = start;
6933 em->len = found_key.offset - start;
6937 btrfs_extent_item_to_extent_map(inode, path, item, new_inline, em);
6939 if (found_type == BTRFS_FILE_EXTENT_REG ||
6940 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6942 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6946 size_t extent_offset;
6952 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6953 extent_offset = page_offset(page) + pg_offset - extent_start;
6954 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6955 size - extent_offset);
6956 em->start = extent_start + extent_offset;
6957 em->len = ALIGN(copy_size, root->sectorsize);
6958 em->orig_block_len = em->len;
6959 em->orig_start = em->start;
6960 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6961 if (create == 0 && !PageUptodate(page)) {
6962 if (btrfs_file_extent_compression(leaf, item) !=
6963 BTRFS_COMPRESS_NONE) {
6964 ret = uncompress_inline(path, page, pg_offset,
6965 extent_offset, item);
6972 read_extent_buffer(leaf, map + pg_offset, ptr,
6974 if (pg_offset + copy_size < PAGE_SIZE) {
6975 memset(map + pg_offset + copy_size, 0,
6976 PAGE_SIZE - pg_offset -
6981 flush_dcache_page(page);
6982 } else if (create && PageUptodate(page)) {
6986 free_extent_map(em);
6989 btrfs_release_path(path);
6990 trans = btrfs_join_transaction(root);
6993 return ERR_CAST(trans);
6997 write_extent_buffer(leaf, map + pg_offset, ptr,
7000 btrfs_mark_buffer_dirty(leaf);
7002 set_extent_uptodate(io_tree, em->start,
7003 extent_map_end(em) - 1, NULL, GFP_NOFS);
7008 em->orig_start = start;
7011 em->block_start = EXTENT_MAP_HOLE;
7012 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
7014 btrfs_release_path(path);
7015 if (em->start > start || extent_map_end(em) <= start) {
7016 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
7017 em->start, em->len, start, len);
7023 write_lock(&em_tree->lock);
7024 ret = add_extent_mapping(em_tree, em, 0);
7025 /* it is possible that someone inserted the extent into the tree
7026 * while we had the lock dropped. It is also possible that
7027 * an overlapping map exists in the tree
7029 if (ret == -EEXIST) {
7030 struct extent_map *existing;
7034 existing = search_extent_mapping(em_tree, start, len);
7036 * existing will always be non-NULL, since there must be
7037 * extent causing the -EEXIST.
7039 if (existing->start == em->start &&
7040 extent_map_end(existing) == extent_map_end(em) &&
7041 em->block_start == existing->block_start) {
7043 * these two extents are the same, it happens
7044 * with inlines especially
7046 free_extent_map(em);
7050 } else if (start >= extent_map_end(existing) ||
7051 start <= existing->start) {
7053 * The existing extent map is the one nearest to
7054 * the [start, start + len) range which overlaps
7056 err = merge_extent_mapping(em_tree, existing,
7058 free_extent_map(existing);
7060 free_extent_map(em);
7064 free_extent_map(em);
7069 write_unlock(&em_tree->lock);
7072 trace_btrfs_get_extent(root, em);
7074 btrfs_free_path(path);
7076 ret = btrfs_end_transaction(trans, root);
7081 free_extent_map(em);
7082 return ERR_PTR(err);
7084 BUG_ON(!em); /* Error is always set */
7088 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
7089 size_t pg_offset, u64 start, u64 len,
7092 struct extent_map *em;
7093 struct extent_map *hole_em = NULL;
7094 u64 range_start = start;
7100 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7107 * - a pre-alloc extent,
7108 * there might actually be delalloc bytes behind it.
7110 if (em->block_start != EXTENT_MAP_HOLE &&
7111 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7117 /* check to see if we've wrapped (len == -1 or similar) */
7126 /* ok, we didn't find anything, lets look for delalloc */
7127 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
7128 end, len, EXTENT_DELALLOC, 1);
7129 found_end = range_start + found;
7130 if (found_end < range_start)
7131 found_end = (u64)-1;
7134 * we didn't find anything useful, return
7135 * the original results from get_extent()
7137 if (range_start > end || found_end <= start) {
7143 /* adjust the range_start to make sure it doesn't
7144 * go backwards from the start they passed in
7146 range_start = max(start, range_start);
7147 found = found_end - range_start;
7150 u64 hole_start = start;
7153 em = alloc_extent_map();
7159 * when btrfs_get_extent can't find anything it
7160 * returns one huge hole
7162 * make sure what it found really fits our range, and
7163 * adjust to make sure it is based on the start from
7167 u64 calc_end = extent_map_end(hole_em);
7169 if (calc_end <= start || (hole_em->start > end)) {
7170 free_extent_map(hole_em);
7173 hole_start = max(hole_em->start, start);
7174 hole_len = calc_end - hole_start;
7178 if (hole_em && range_start > hole_start) {
7179 /* our hole starts before our delalloc, so we
7180 * have to return just the parts of the hole
7181 * that go until the delalloc starts
7183 em->len = min(hole_len,
7184 range_start - hole_start);
7185 em->start = hole_start;
7186 em->orig_start = hole_start;
7188 * don't adjust block start at all,
7189 * it is fixed at EXTENT_MAP_HOLE
7191 em->block_start = hole_em->block_start;
7192 em->block_len = hole_len;
7193 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7194 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7196 em->start = range_start;
7198 em->orig_start = range_start;
7199 em->block_start = EXTENT_MAP_DELALLOC;
7200 em->block_len = found;
7202 } else if (hole_em) {
7207 free_extent_map(hole_em);
7209 free_extent_map(em);
7210 return ERR_PTR(err);
7215 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7218 const u64 orig_start,
7219 const u64 block_start,
7220 const u64 block_len,
7221 const u64 orig_block_len,
7222 const u64 ram_bytes,
7225 struct extent_map *em = NULL;
7228 down_read(&BTRFS_I(inode)->dio_sem);
7229 if (type != BTRFS_ORDERED_NOCOW) {
7230 em = create_pinned_em(inode, start, len, orig_start,
7231 block_start, block_len, orig_block_len,
7236 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7237 len, block_len, type);
7240 free_extent_map(em);
7241 btrfs_drop_extent_cache(inode, start,
7242 start + len - 1, 0);
7247 up_read(&BTRFS_I(inode)->dio_sem);
7252 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7255 struct btrfs_root *root = BTRFS_I(inode)->root;
7256 struct extent_map *em;
7257 struct btrfs_key ins;
7261 alloc_hint = get_extent_allocation_hint(inode, start, len);
7262 ret = btrfs_reserve_extent(root, len, len, root->sectorsize, 0,
7263 alloc_hint, &ins, 1, 1);
7265 return ERR_PTR(ret);
7267 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7268 ins.objectid, ins.offset, ins.offset,
7270 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
7272 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
7278 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7279 * block must be cow'd
7281 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7282 u64 *orig_start, u64 *orig_block_len,
7285 struct btrfs_trans_handle *trans;
7286 struct btrfs_path *path;
7288 struct extent_buffer *leaf;
7289 struct btrfs_root *root = BTRFS_I(inode)->root;
7290 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7291 struct btrfs_file_extent_item *fi;
7292 struct btrfs_key key;
7299 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7301 path = btrfs_alloc_path();
7305 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
7310 slot = path->slots[0];
7313 /* can't find the item, must cow */
7320 leaf = path->nodes[0];
7321 btrfs_item_key_to_cpu(leaf, &key, slot);
7322 if (key.objectid != btrfs_ino(inode) ||
7323 key.type != BTRFS_EXTENT_DATA_KEY) {
7324 /* not our file or wrong item type, must cow */
7328 if (key.offset > offset) {
7329 /* Wrong offset, must cow */
7333 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7334 found_type = btrfs_file_extent_type(leaf, fi);
7335 if (found_type != BTRFS_FILE_EXTENT_REG &&
7336 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7337 /* not a regular extent, must cow */
7341 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7344 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7345 if (extent_end <= offset)
7348 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7349 if (disk_bytenr == 0)
7352 if (btrfs_file_extent_compression(leaf, fi) ||
7353 btrfs_file_extent_encryption(leaf, fi) ||
7354 btrfs_file_extent_other_encoding(leaf, fi))
7357 backref_offset = btrfs_file_extent_offset(leaf, fi);
7360 *orig_start = key.offset - backref_offset;
7361 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7362 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7365 if (btrfs_extent_readonly(root, disk_bytenr))
7368 num_bytes = min(offset + *len, extent_end) - offset;
7369 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7372 range_end = round_up(offset + num_bytes, root->sectorsize) - 1;
7373 ret = test_range_bit(io_tree, offset, range_end,
7374 EXTENT_DELALLOC, 0, NULL);
7381 btrfs_release_path(path);
7384 * look for other files referencing this extent, if we
7385 * find any we must cow
7387 trans = btrfs_join_transaction(root);
7388 if (IS_ERR(trans)) {
7393 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
7394 key.offset - backref_offset, disk_bytenr);
7395 btrfs_end_transaction(trans, root);
7402 * adjust disk_bytenr and num_bytes to cover just the bytes
7403 * in this extent we are about to write. If there
7404 * are any csums in that range we have to cow in order
7405 * to keep the csums correct
7407 disk_bytenr += backref_offset;
7408 disk_bytenr += offset - key.offset;
7409 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
7412 * all of the above have passed, it is safe to overwrite this extent
7418 btrfs_free_path(path);
7422 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7424 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7426 void **pagep = NULL;
7427 struct page *page = NULL;
7431 start_idx = start >> PAGE_SHIFT;
7434 * end is the last byte in the last page. end == start is legal
7436 end_idx = end >> PAGE_SHIFT;
7440 /* Most of the code in this while loop is lifted from
7441 * find_get_page. It's been modified to begin searching from a
7442 * page and return just the first page found in that range. If the
7443 * found idx is less than or equal to the end idx then we know that
7444 * a page exists. If no pages are found or if those pages are
7445 * outside of the range then we're fine (yay!) */
7446 while (page == NULL &&
7447 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7448 page = radix_tree_deref_slot(pagep);
7449 if (unlikely(!page))
7452 if (radix_tree_exception(page)) {
7453 if (radix_tree_deref_retry(page)) {
7458 * Otherwise, shmem/tmpfs must be storing a swap entry
7459 * here as an exceptional entry: so return it without
7460 * attempting to raise page count.
7463 break; /* TODO: Is this relevant for this use case? */
7466 if (!page_cache_get_speculative(page)) {
7472 * Has the page moved?
7473 * This is part of the lockless pagecache protocol. See
7474 * include/linux/pagemap.h for details.
7476 if (unlikely(page != *pagep)) {
7483 if (page->index <= end_idx)
7492 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7493 struct extent_state **cached_state, int writing)
7495 struct btrfs_ordered_extent *ordered;
7499 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7502 * We're concerned with the entire range that we're going to be
7503 * doing DIO to, so we need to make sure there's no ordered
7504 * extents in this range.
7506 ordered = btrfs_lookup_ordered_range(inode, lockstart,
7507 lockend - lockstart + 1);
7510 * We need to make sure there are no buffered pages in this
7511 * range either, we could have raced between the invalidate in
7512 * generic_file_direct_write and locking the extent. The
7513 * invalidate needs to happen so that reads after a write do not
7518 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7521 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7522 cached_state, GFP_NOFS);
7526 * If we are doing a DIO read and the ordered extent we
7527 * found is for a buffered write, we can not wait for it
7528 * to complete and retry, because if we do so we can
7529 * deadlock with concurrent buffered writes on page
7530 * locks. This happens only if our DIO read covers more
7531 * than one extent map, if at this point has already
7532 * created an ordered extent for a previous extent map
7533 * and locked its range in the inode's io tree, and a
7534 * concurrent write against that previous extent map's
7535 * range and this range started (we unlock the ranges
7536 * in the io tree only when the bios complete and
7537 * buffered writes always lock pages before attempting
7538 * to lock range in the io tree).
7541 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7542 btrfs_start_ordered_extent(inode, ordered, 1);
7545 btrfs_put_ordered_extent(ordered);
7548 * We could trigger writeback for this range (and wait
7549 * for it to complete) and then invalidate the pages for
7550 * this range (through invalidate_inode_pages2_range()),
7551 * but that can lead us to a deadlock with a concurrent
7552 * call to readpages() (a buffered read or a defrag call
7553 * triggered a readahead) on a page lock due to an
7554 * ordered dio extent we created before but did not have
7555 * yet a corresponding bio submitted (whence it can not
7556 * complete), which makes readpages() wait for that
7557 * ordered extent to complete while holding a lock on
7572 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
7573 u64 len, u64 orig_start,
7574 u64 block_start, u64 block_len,
7575 u64 orig_block_len, u64 ram_bytes,
7578 struct extent_map_tree *em_tree;
7579 struct extent_map *em;
7580 struct btrfs_root *root = BTRFS_I(inode)->root;
7583 em_tree = &BTRFS_I(inode)->extent_tree;
7584 em = alloc_extent_map();
7586 return ERR_PTR(-ENOMEM);
7589 em->orig_start = orig_start;
7590 em->mod_start = start;
7593 em->block_len = block_len;
7594 em->block_start = block_start;
7595 em->bdev = root->fs_info->fs_devices->latest_bdev;
7596 em->orig_block_len = orig_block_len;
7597 em->ram_bytes = ram_bytes;
7598 em->generation = -1;
7599 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7600 if (type == BTRFS_ORDERED_PREALLOC)
7601 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7604 btrfs_drop_extent_cache(inode, em->start,
7605 em->start + em->len - 1, 0);
7606 write_lock(&em_tree->lock);
7607 ret = add_extent_mapping(em_tree, em, 1);
7608 write_unlock(&em_tree->lock);
7609 } while (ret == -EEXIST);
7612 free_extent_map(em);
7613 return ERR_PTR(ret);
7619 static void adjust_dio_outstanding_extents(struct inode *inode,
7620 struct btrfs_dio_data *dio_data,
7623 unsigned num_extents;
7625 num_extents = (unsigned) div64_u64(len + BTRFS_MAX_EXTENT_SIZE - 1,
7626 BTRFS_MAX_EXTENT_SIZE);
7628 * If we have an outstanding_extents count still set then we're
7629 * within our reservation, otherwise we need to adjust our inode
7630 * counter appropriately.
7632 if (dio_data->outstanding_extents) {
7633 dio_data->outstanding_extents -= num_extents;
7635 spin_lock(&BTRFS_I(inode)->lock);
7636 BTRFS_I(inode)->outstanding_extents += num_extents;
7637 spin_unlock(&BTRFS_I(inode)->lock);
7641 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7642 struct buffer_head *bh_result, int create)
7644 struct extent_map *em;
7645 struct btrfs_root *root = BTRFS_I(inode)->root;
7646 struct extent_state *cached_state = NULL;
7647 struct btrfs_dio_data *dio_data = NULL;
7648 u64 start = iblock << inode->i_blkbits;
7649 u64 lockstart, lockend;
7650 u64 len = bh_result->b_size;
7651 int unlock_bits = EXTENT_LOCKED;
7655 unlock_bits |= EXTENT_DIRTY;
7657 len = min_t(u64, len, root->sectorsize);
7660 lockend = start + len - 1;
7662 if (current->journal_info) {
7664 * Need to pull our outstanding extents and set journal_info to NULL so
7665 * that anything that needs to check if there's a transaction doesn't get
7668 dio_data = current->journal_info;
7669 current->journal_info = NULL;
7673 * If this errors out it's because we couldn't invalidate pagecache for
7674 * this range and we need to fallback to buffered.
7676 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7682 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7689 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7690 * io. INLINE is special, and we could probably kludge it in here, but
7691 * it's still buffered so for safety lets just fall back to the generic
7694 * For COMPRESSED we _have_ to read the entire extent in so we can
7695 * decompress it, so there will be buffering required no matter what we
7696 * do, so go ahead and fallback to buffered.
7698 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7699 * to buffered IO. Don't blame me, this is the price we pay for using
7702 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7703 em->block_start == EXTENT_MAP_INLINE) {
7704 free_extent_map(em);
7709 /* Just a good old fashioned hole, return */
7710 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7711 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7712 free_extent_map(em);
7717 * We don't allocate a new extent in the following cases
7719 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7721 * 2) The extent is marked as PREALLOC. We're good to go here and can
7722 * just use the extent.
7726 len = min(len, em->len - (start - em->start));
7727 lockstart = start + len;
7731 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7732 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7733 em->block_start != EXTENT_MAP_HOLE)) {
7735 u64 block_start, orig_start, orig_block_len, ram_bytes;
7737 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7738 type = BTRFS_ORDERED_PREALLOC;
7740 type = BTRFS_ORDERED_NOCOW;
7741 len = min(len, em->len - (start - em->start));
7742 block_start = em->block_start + (start - em->start);
7744 if (can_nocow_extent(inode, start, &len, &orig_start,
7745 &orig_block_len, &ram_bytes) == 1 &&
7746 btrfs_inc_nocow_writers(root->fs_info, block_start)) {
7747 struct extent_map *em2;
7749 em2 = btrfs_create_dio_extent(inode, start, len,
7750 orig_start, block_start,
7751 len, orig_block_len,
7753 btrfs_dec_nocow_writers(root->fs_info, block_start);
7754 if (type == BTRFS_ORDERED_PREALLOC) {
7755 free_extent_map(em);
7758 if (em2 && IS_ERR(em2)) {
7763 * For inode marked NODATACOW or extent marked PREALLOC,
7764 * use the existing or preallocated extent, so does not
7765 * need to adjust btrfs_space_info's bytes_may_use.
7767 btrfs_free_reserved_data_space_noquota(inode,
7774 * this will cow the extent, reset the len in case we changed
7777 len = bh_result->b_size;
7778 free_extent_map(em);
7779 em = btrfs_new_extent_direct(inode, start, len);
7784 len = min(len, em->len - (start - em->start));
7786 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7788 bh_result->b_size = len;
7789 bh_result->b_bdev = em->bdev;
7790 set_buffer_mapped(bh_result);
7792 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7793 set_buffer_new(bh_result);
7796 * Need to update the i_size under the extent lock so buffered
7797 * readers will get the updated i_size when we unlock.
7799 if (start + len > i_size_read(inode))
7800 i_size_write(inode, start + len);
7802 adjust_dio_outstanding_extents(inode, dio_data, len);
7803 WARN_ON(dio_data->reserve < len);
7804 dio_data->reserve -= len;
7805 dio_data->unsubmitted_oe_range_end = start + len;
7806 current->journal_info = dio_data;
7810 * In the case of write we need to clear and unlock the entire range,
7811 * in the case of read we need to unlock only the end area that we
7812 * aren't using if there is any left over space.
7814 if (lockstart < lockend) {
7815 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7816 lockend, unlock_bits, 1, 0,
7817 &cached_state, GFP_NOFS);
7819 free_extent_state(cached_state);
7822 free_extent_map(em);
7827 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7828 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7831 current->journal_info = dio_data;
7833 * Compensate the delalloc release we do in btrfs_direct_IO() when we
7834 * write less data then expected, so that we don't underflow our inode's
7835 * outstanding extents counter.
7837 if (create && dio_data)
7838 adjust_dio_outstanding_extents(inode, dio_data, len);
7843 static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7844 int rw, int mirror_num)
7846 struct btrfs_root *root = BTRFS_I(inode)->root;
7849 BUG_ON(rw & REQ_WRITE);
7853 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7854 BTRFS_WQ_ENDIO_DIO_REPAIR);
7858 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
7864 static int btrfs_check_dio_repairable(struct inode *inode,
7865 struct bio *failed_bio,
7866 struct io_failure_record *failrec,
7871 num_copies = btrfs_num_copies(BTRFS_I(inode)->root->fs_info,
7872 failrec->logical, failrec->len);
7873 if (num_copies == 1) {
7875 * we only have a single copy of the data, so don't bother with
7876 * all the retry and error correction code that follows. no
7877 * matter what the error is, it is very likely to persist.
7879 pr_debug("Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d\n",
7880 num_copies, failrec->this_mirror, failed_mirror);
7884 failrec->failed_mirror = failed_mirror;
7885 failrec->this_mirror++;
7886 if (failrec->this_mirror == failed_mirror)
7887 failrec->this_mirror++;
7889 if (failrec->this_mirror > num_copies) {
7890 pr_debug("Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d\n",
7891 num_copies, failrec->this_mirror, failed_mirror);
7898 static int dio_read_error(struct inode *inode, struct bio *failed_bio,
7899 struct page *page, unsigned int pgoff,
7900 u64 start, u64 end, int failed_mirror,
7901 bio_end_io_t *repair_endio, void *repair_arg)
7903 struct io_failure_record *failrec;
7909 BUG_ON(failed_bio->bi_rw & REQ_WRITE);
7911 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7915 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7918 free_io_failure(inode, failrec);
7922 if ((failed_bio->bi_vcnt > 1)
7923 || (failed_bio->bi_io_vec->bv_len
7924 > BTRFS_I(inode)->root->sectorsize))
7925 read_mode = READ_SYNC | REQ_FAILFAST_DEV;
7927 read_mode = READ_SYNC;
7929 isector = start - btrfs_io_bio(failed_bio)->logical;
7930 isector >>= inode->i_sb->s_blocksize_bits;
7931 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7932 pgoff, isector, repair_endio, repair_arg);
7934 free_io_failure(inode, failrec);
7938 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7939 "Repair DIO Read Error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d\n",
7940 read_mode, failrec->this_mirror, failrec->in_validation);
7942 ret = submit_dio_repair_bio(inode, bio, read_mode,
7943 failrec->this_mirror);
7945 free_io_failure(inode, failrec);
7952 struct btrfs_retry_complete {
7953 struct completion done;
7954 struct inode *inode;
7959 static void btrfs_retry_endio_nocsum(struct bio *bio)
7961 struct btrfs_retry_complete *done = bio->bi_private;
7962 struct inode *inode;
7963 struct bio_vec *bvec;
7969 ASSERT(bio->bi_vcnt == 1);
7970 inode = bio->bi_io_vec->bv_page->mapping->host;
7971 ASSERT(bio->bi_io_vec->bv_len == BTRFS_I(inode)->root->sectorsize);
7974 bio_for_each_segment_all(bvec, bio, i)
7975 clean_io_failure(done->inode, done->start, bvec->bv_page, 0);
7977 complete(&done->done);
7981 static int __btrfs_correct_data_nocsum(struct inode *inode,
7982 struct btrfs_io_bio *io_bio)
7984 struct btrfs_fs_info *fs_info;
7985 struct bio_vec *bvec;
7986 struct btrfs_retry_complete done;
7994 fs_info = BTRFS_I(inode)->root->fs_info;
7995 sectorsize = BTRFS_I(inode)->root->sectorsize;
7997 start = io_bio->logical;
8000 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
8001 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec->bv_len);
8002 pgoff = bvec->bv_offset;
8004 next_block_or_try_again:
8007 init_completion(&done.done);
8009 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page,
8010 pgoff, start, start + sectorsize - 1,
8012 btrfs_retry_endio_nocsum, &done);
8016 wait_for_completion(&done.done);
8018 if (!done.uptodate) {
8019 /* We might have another mirror, so try again */
8020 goto next_block_or_try_again;
8023 start += sectorsize;
8026 pgoff += sectorsize;
8027 goto next_block_or_try_again;
8034 static void btrfs_retry_endio(struct bio *bio)
8036 struct btrfs_retry_complete *done = bio->bi_private;
8037 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8038 struct inode *inode;
8039 struct bio_vec *bvec;
8050 start = done->start;
8052 ASSERT(bio->bi_vcnt == 1);
8053 inode = bio->bi_io_vec->bv_page->mapping->host;
8054 ASSERT(bio->bi_io_vec->bv_len == BTRFS_I(inode)->root->sectorsize);
8056 bio_for_each_segment_all(bvec, bio, i) {
8057 ret = __readpage_endio_check(done->inode, io_bio, i,
8058 bvec->bv_page, bvec->bv_offset,
8059 done->start, bvec->bv_len);
8061 clean_io_failure(done->inode, done->start,
8062 bvec->bv_page, bvec->bv_offset);
8067 done->uptodate = uptodate;
8069 complete(&done->done);
8073 static int __btrfs_subio_endio_read(struct inode *inode,
8074 struct btrfs_io_bio *io_bio, int err)
8076 struct btrfs_fs_info *fs_info;
8077 struct bio_vec *bvec;
8078 struct btrfs_retry_complete done;
8088 fs_info = BTRFS_I(inode)->root->fs_info;
8089 sectorsize = BTRFS_I(inode)->root->sectorsize;
8092 start = io_bio->logical;
8095 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
8096 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec->bv_len);
8098 pgoff = bvec->bv_offset;
8100 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8101 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8102 bvec->bv_page, pgoff, start,
8109 init_completion(&done.done);
8111 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page,
8112 pgoff, start, start + sectorsize - 1,
8114 btrfs_retry_endio, &done);
8120 wait_for_completion(&done.done);
8122 if (!done.uptodate) {
8123 /* We might have another mirror, so try again */
8127 offset += sectorsize;
8128 start += sectorsize;
8133 pgoff += sectorsize;
8141 static int btrfs_subio_endio_read(struct inode *inode,
8142 struct btrfs_io_bio *io_bio, int err)
8144 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8148 return __btrfs_correct_data_nocsum(inode, io_bio);
8152 return __btrfs_subio_endio_read(inode, io_bio, err);
8156 static void btrfs_endio_direct_read(struct bio *bio)
8158 struct btrfs_dio_private *dip = bio->bi_private;
8159 struct inode *inode = dip->inode;
8160 struct bio *dio_bio;
8161 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8162 int err = bio->bi_error;
8164 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8165 err = btrfs_subio_endio_read(inode, io_bio, err);
8167 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8168 dip->logical_offset + dip->bytes - 1);
8169 dio_bio = dip->dio_bio;
8173 dio_bio->bi_error = bio->bi_error;
8174 dio_end_io(dio_bio, bio->bi_error);
8177 io_bio->end_io(io_bio, err);
8181 static void btrfs_endio_direct_write_update_ordered(struct inode *inode,
8186 struct btrfs_root *root = BTRFS_I(inode)->root;
8187 struct btrfs_ordered_extent *ordered = NULL;
8188 u64 ordered_offset = offset;
8189 u64 ordered_bytes = bytes;
8193 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
8200 btrfs_init_work(&ordered->work, btrfs_endio_write_helper,
8201 finish_ordered_fn, NULL, NULL);
8202 btrfs_queue_work(root->fs_info->endio_write_workers,
8206 * our bio might span multiple ordered extents. If we haven't
8207 * completed the accounting for the whole dio, go back and try again
8209 if (ordered_offset < offset + bytes) {
8210 ordered_bytes = offset + bytes - ordered_offset;
8216 static void btrfs_endio_direct_write(struct bio *bio)
8218 struct btrfs_dio_private *dip = bio->bi_private;
8219 struct bio *dio_bio = dip->dio_bio;
8221 btrfs_endio_direct_write_update_ordered(dip->inode,
8222 dip->logical_offset,
8228 dio_bio->bi_error = bio->bi_error;
8229 dio_end_io(dio_bio, bio->bi_error);
8233 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
8234 struct bio *bio, int mirror_num,
8235 unsigned long bio_flags, u64 offset)
8238 struct btrfs_root *root = BTRFS_I(inode)->root;
8239 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
8240 BUG_ON(ret); /* -ENOMEM */
8244 static void btrfs_end_dio_bio(struct bio *bio)
8246 struct btrfs_dio_private *dip = bio->bi_private;
8247 int err = bio->bi_error;
8250 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8251 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
8252 btrfs_ino(dip->inode), bio->bi_rw,
8253 (unsigned long long)bio->bi_iter.bi_sector,
8254 bio->bi_iter.bi_size, err);
8256 if (dip->subio_endio)
8257 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8263 * before atomic variable goto zero, we must make sure
8264 * dip->errors is perceived to be set.
8266 smp_mb__before_atomic();
8269 /* if there are more bios still pending for this dio, just exit */
8270 if (!atomic_dec_and_test(&dip->pending_bios))
8274 bio_io_error(dip->orig_bio);
8276 dip->dio_bio->bi_error = 0;
8277 bio_endio(dip->orig_bio);
8283 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
8284 u64 first_sector, gfp_t gfp_flags)
8287 bio = btrfs_bio_alloc(bdev, first_sector, BIO_MAX_PAGES, gfp_flags);
8289 bio_associate_current(bio);
8293 static inline int btrfs_lookup_and_bind_dio_csum(struct btrfs_root *root,
8294 struct inode *inode,
8295 struct btrfs_dio_private *dip,
8299 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8300 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8304 * We load all the csum data we need when we submit
8305 * the first bio to reduce the csum tree search and
8308 if (dip->logical_offset == file_offset) {
8309 ret = btrfs_lookup_bio_sums_dio(root, inode, dip->orig_bio,
8315 if (bio == dip->orig_bio)
8318 file_offset -= dip->logical_offset;
8319 file_offset >>= inode->i_sb->s_blocksize_bits;
8320 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8325 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
8326 int rw, u64 file_offset, int skip_sum,
8329 struct btrfs_dio_private *dip = bio->bi_private;
8330 int write = rw & REQ_WRITE;
8331 struct btrfs_root *root = BTRFS_I(inode)->root;
8335 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8340 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
8341 BTRFS_WQ_ENDIO_DATA);
8349 if (write && async_submit) {
8350 ret = btrfs_wq_submit_bio(root->fs_info,
8351 inode, rw, bio, 0, 0,
8353 __btrfs_submit_bio_start_direct_io,
8354 __btrfs_submit_bio_done);
8358 * If we aren't doing async submit, calculate the csum of the
8361 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
8365 ret = btrfs_lookup_and_bind_dio_csum(root, inode, dip, bio,
8371 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
8377 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
8380 struct inode *inode = dip->inode;
8381 struct btrfs_root *root = BTRFS_I(inode)->root;
8383 struct bio *orig_bio = dip->orig_bio;
8384 struct bio_vec *bvec = orig_bio->bi_io_vec;
8385 u64 start_sector = orig_bio->bi_iter.bi_sector;
8386 u64 file_offset = dip->logical_offset;
8389 u32 blocksize = root->sectorsize;
8390 int async_submit = 0;
8395 map_length = orig_bio->bi_iter.bi_size;
8396 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
8397 &map_length, NULL, 0);
8401 if (map_length >= orig_bio->bi_iter.bi_size) {
8403 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8407 /* async crcs make it difficult to collect full stripe writes. */
8408 if (btrfs_get_alloc_profile(root, 1) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8413 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
8417 bio->bi_private = dip;
8418 bio->bi_end_io = btrfs_end_dio_bio;
8419 btrfs_io_bio(bio)->logical = file_offset;
8420 atomic_inc(&dip->pending_bios);
8422 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
8423 nr_sectors = BTRFS_BYTES_TO_BLKS(root->fs_info, bvec->bv_len);
8426 if (unlikely(map_length < submit_len + blocksize ||
8427 bio_add_page(bio, bvec->bv_page, blocksize,
8428 bvec->bv_offset + (i * blocksize)) < blocksize)) {
8430 * inc the count before we submit the bio so
8431 * we know the end IO handler won't happen before
8432 * we inc the count. Otherwise, the dip might get freed
8433 * before we're done setting it up
8435 atomic_inc(&dip->pending_bios);
8436 ret = __btrfs_submit_dio_bio(bio, inode, rw,
8437 file_offset, skip_sum,
8441 atomic_dec(&dip->pending_bios);
8445 start_sector += submit_len >> 9;
8446 file_offset += submit_len;
8450 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
8451 start_sector, GFP_NOFS);
8454 bio->bi_private = dip;
8455 bio->bi_end_io = btrfs_end_dio_bio;
8456 btrfs_io_bio(bio)->logical = file_offset;
8458 map_length = orig_bio->bi_iter.bi_size;
8459 ret = btrfs_map_block(root->fs_info, rw,
8461 &map_length, NULL, 0);
8469 submit_len += blocksize;
8479 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
8488 * before atomic variable goto zero, we must
8489 * make sure dip->errors is perceived to be set.
8491 smp_mb__before_atomic();
8492 if (atomic_dec_and_test(&dip->pending_bios))
8493 bio_io_error(dip->orig_bio);
8495 /* bio_end_io() will handle error, so we needn't return it */
8499 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
8500 struct inode *inode, loff_t file_offset)
8502 struct btrfs_dio_private *dip = NULL;
8503 struct bio *io_bio = NULL;
8504 struct btrfs_io_bio *btrfs_bio;
8506 int write = rw & REQ_WRITE;
8509 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8511 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
8517 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8523 dip->private = dio_bio->bi_private;
8525 dip->logical_offset = file_offset;
8526 dip->bytes = dio_bio->bi_iter.bi_size;
8527 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8528 io_bio->bi_private = dip;
8529 dip->orig_bio = io_bio;
8530 dip->dio_bio = dio_bio;
8531 atomic_set(&dip->pending_bios, 0);
8532 btrfs_bio = btrfs_io_bio(io_bio);
8533 btrfs_bio->logical = file_offset;
8536 io_bio->bi_end_io = btrfs_endio_direct_write;
8538 io_bio->bi_end_io = btrfs_endio_direct_read;
8539 dip->subio_endio = btrfs_subio_endio_read;
8543 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8544 * even if we fail to submit a bio, because in such case we do the
8545 * corresponding error handling below and it must not be done a second
8546 * time by btrfs_direct_IO().
8549 struct btrfs_dio_data *dio_data = current->journal_info;
8551 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8553 dio_data->unsubmitted_oe_range_start =
8554 dio_data->unsubmitted_oe_range_end;
8557 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
8561 if (btrfs_bio->end_io)
8562 btrfs_bio->end_io(btrfs_bio, ret);
8566 * If we arrived here it means either we failed to submit the dip
8567 * or we either failed to clone the dio_bio or failed to allocate the
8568 * dip. If we cloned the dio_bio and allocated the dip, we can just
8569 * call bio_endio against our io_bio so that we get proper resource
8570 * cleanup if we fail to submit the dip, otherwise, we must do the
8571 * same as btrfs_endio_direct_[write|read] because we can't call these
8572 * callbacks - they require an allocated dip and a clone of dio_bio.
8574 if (io_bio && dip) {
8575 io_bio->bi_error = -EIO;
8578 * The end io callbacks free our dip, do the final put on io_bio
8579 * and all the cleanup and final put for dio_bio (through
8586 btrfs_endio_direct_write_update_ordered(inode,
8588 dio_bio->bi_iter.bi_size,
8591 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8592 file_offset + dio_bio->bi_iter.bi_size - 1);
8594 dio_bio->bi_error = -EIO;
8596 * Releases and cleans up our dio_bio, no need to bio_put()
8597 * nor bio_endio()/bio_io_error() against dio_bio.
8599 dio_end_io(dio_bio, ret);
8606 static ssize_t check_direct_IO(struct btrfs_root *root, struct kiocb *iocb,
8607 const struct iov_iter *iter, loff_t offset)
8611 unsigned blocksize_mask = root->sectorsize - 1;
8612 ssize_t retval = -EINVAL;
8614 if (offset & blocksize_mask)
8617 if (iov_iter_alignment(iter) & blocksize_mask)
8620 /* If this is a write we don't need to check anymore */
8621 if (iov_iter_rw(iter) == WRITE)
8624 * Check to make sure we don't have duplicate iov_base's in this
8625 * iovec, if so return EINVAL, otherwise we'll get csum errors
8626 * when reading back.
8628 for (seg = 0; seg < iter->nr_segs; seg++) {
8629 for (i = seg + 1; i < iter->nr_segs; i++) {
8630 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8639 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8641 struct file *file = iocb->ki_filp;
8642 struct inode *inode = file->f_mapping->host;
8643 struct btrfs_root *root = BTRFS_I(inode)->root;
8644 struct btrfs_dio_data dio_data = { 0 };
8645 loff_t offset = iocb->ki_pos;
8649 bool relock = false;
8652 if (check_direct_IO(BTRFS_I(inode)->root, iocb, iter, offset))
8655 inode_dio_begin(inode);
8656 smp_mb__after_atomic();
8659 * The generic stuff only does filemap_write_and_wait_range, which
8660 * isn't enough if we've written compressed pages to this area, so
8661 * we need to flush the dirty pages again to make absolutely sure
8662 * that any outstanding dirty pages are on disk.
8664 count = iov_iter_count(iter);
8665 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8666 &BTRFS_I(inode)->runtime_flags))
8667 filemap_fdatawrite_range(inode->i_mapping, offset,
8668 offset + count - 1);
8670 if (iov_iter_rw(iter) == WRITE) {
8672 * If the write DIO is beyond the EOF, we need update
8673 * the isize, but it is protected by i_mutex. So we can
8674 * not unlock the i_mutex at this case.
8676 if (offset + count <= inode->i_size) {
8677 inode_unlock(inode);
8680 ret = btrfs_delalloc_reserve_space(inode, offset, count);
8683 dio_data.outstanding_extents = div64_u64(count +
8684 BTRFS_MAX_EXTENT_SIZE - 1,
8685 BTRFS_MAX_EXTENT_SIZE);
8688 * We need to know how many extents we reserved so that we can
8689 * do the accounting properly if we go over the number we
8690 * originally calculated. Abuse current->journal_info for this.
8692 dio_data.reserve = round_up(count, root->sectorsize);
8693 dio_data.unsubmitted_oe_range_start = (u64)offset;
8694 dio_data.unsubmitted_oe_range_end = (u64)offset;
8695 current->journal_info = &dio_data;
8696 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8697 &BTRFS_I(inode)->runtime_flags)) {
8698 inode_dio_end(inode);
8699 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8703 ret = __blockdev_direct_IO(iocb, inode,
8704 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
8705 iter, btrfs_get_blocks_direct, NULL,
8706 btrfs_submit_direct, flags);
8707 if (iov_iter_rw(iter) == WRITE) {
8708 current->journal_info = NULL;
8709 if (ret < 0 && ret != -EIOCBQUEUED) {
8710 if (dio_data.reserve)
8711 btrfs_delalloc_release_space(inode, offset,
8714 * On error we might have left some ordered extents
8715 * without submitting corresponding bios for them, so
8716 * cleanup them up to avoid other tasks getting them
8717 * and waiting for them to complete forever.
8719 if (dio_data.unsubmitted_oe_range_start <
8720 dio_data.unsubmitted_oe_range_end)
8721 btrfs_endio_direct_write_update_ordered(inode,
8722 dio_data.unsubmitted_oe_range_start,
8723 dio_data.unsubmitted_oe_range_end -
8724 dio_data.unsubmitted_oe_range_start,
8726 } else if (ret >= 0 && (size_t)ret < count)
8727 btrfs_delalloc_release_space(inode, offset,
8728 count - (size_t)ret);
8732 inode_dio_end(inode);
8739 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8741 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8742 __u64 start, __u64 len)
8746 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8750 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
8753 int btrfs_readpage(struct file *file, struct page *page)
8755 struct extent_io_tree *tree;
8756 tree = &BTRFS_I(page->mapping->host)->io_tree;
8757 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8760 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8762 struct extent_io_tree *tree;
8763 struct inode *inode = page->mapping->host;
8766 if (current->flags & PF_MEMALLOC) {
8767 redirty_page_for_writepage(wbc, page);
8773 * If we are under memory pressure we will call this directly from the
8774 * VM, we need to make sure we have the inode referenced for the ordered
8775 * extent. If not just return like we didn't do anything.
8777 if (!igrab(inode)) {
8778 redirty_page_for_writepage(wbc, page);
8779 return AOP_WRITEPAGE_ACTIVATE;
8781 tree = &BTRFS_I(page->mapping->host)->io_tree;
8782 ret = extent_write_full_page(tree, page, btrfs_get_extent, wbc);
8783 btrfs_add_delayed_iput(inode);
8787 static int btrfs_writepages(struct address_space *mapping,
8788 struct writeback_control *wbc)
8790 struct extent_io_tree *tree;
8792 tree = &BTRFS_I(mapping->host)->io_tree;
8793 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8797 btrfs_readpages(struct file *file, struct address_space *mapping,
8798 struct list_head *pages, unsigned nr_pages)
8800 struct extent_io_tree *tree;
8801 tree = &BTRFS_I(mapping->host)->io_tree;
8802 return extent_readpages(tree, mapping, pages, nr_pages,
8805 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8807 struct extent_io_tree *tree;
8808 struct extent_map_tree *map;
8811 tree = &BTRFS_I(page->mapping->host)->io_tree;
8812 map = &BTRFS_I(page->mapping->host)->extent_tree;
8813 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8815 ClearPagePrivate(page);
8816 set_page_private(page, 0);
8822 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8824 if (PageWriteback(page) || PageDirty(page))
8826 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
8829 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8830 unsigned int length)
8832 struct inode *inode = page->mapping->host;
8833 struct extent_io_tree *tree;
8834 struct btrfs_ordered_extent *ordered;
8835 struct extent_state *cached_state = NULL;
8836 u64 page_start = page_offset(page);
8837 u64 page_end = page_start + PAGE_SIZE - 1;
8840 int inode_evicting = inode->i_state & I_FREEING;
8843 * we have the page locked, so new writeback can't start,
8844 * and the dirty bit won't be cleared while we are here.
8846 * Wait for IO on this page so that we can safely clear
8847 * the PagePrivate2 bit and do ordered accounting
8849 wait_on_page_writeback(page);
8851 tree = &BTRFS_I(inode)->io_tree;
8853 btrfs_releasepage(page, GFP_NOFS);
8857 if (!inode_evicting)
8858 lock_extent_bits(tree, page_start, page_end, &cached_state);
8861 ordered = btrfs_lookup_ordered_range(inode, start,
8862 page_end - start + 1);
8864 end = min(page_end, ordered->file_offset + ordered->len - 1);
8866 * IO on this page will never be started, so we need
8867 * to account for any ordered extents now
8869 if (!inode_evicting)
8870 clear_extent_bit(tree, start, end,
8871 EXTENT_DIRTY | EXTENT_DELALLOC |
8872 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8873 EXTENT_DEFRAG, 1, 0, &cached_state,
8876 * whoever cleared the private bit is responsible
8877 * for the finish_ordered_io
8879 if (TestClearPagePrivate2(page)) {
8880 struct btrfs_ordered_inode_tree *tree;
8883 tree = &BTRFS_I(inode)->ordered_tree;
8885 spin_lock_irq(&tree->lock);
8886 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8887 new_len = start - ordered->file_offset;
8888 if (new_len < ordered->truncated_len)
8889 ordered->truncated_len = new_len;
8890 spin_unlock_irq(&tree->lock);
8892 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8894 end - start + 1, 1))
8895 btrfs_finish_ordered_io(ordered);
8897 btrfs_put_ordered_extent(ordered);
8898 if (!inode_evicting) {
8899 cached_state = NULL;
8900 lock_extent_bits(tree, start, end,
8905 if (start < page_end)
8910 * Qgroup reserved space handler
8911 * Page here will be either
8912 * 1) Already written to disk
8913 * In this case, its reserved space is released from data rsv map
8914 * and will be freed by delayed_ref handler finally.
8915 * So even we call qgroup_free_data(), it won't decrease reserved
8917 * 2) Not written to disk
8918 * This means the reserved space should be freed here.
8920 btrfs_qgroup_free_data(inode, page_start, PAGE_SIZE);
8921 if (!inode_evicting) {
8922 clear_extent_bit(tree, page_start, page_end,
8923 EXTENT_LOCKED | EXTENT_DIRTY |
8924 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8925 EXTENT_DEFRAG, 1, 1,
8926 &cached_state, GFP_NOFS);
8928 __btrfs_releasepage(page, GFP_NOFS);
8931 ClearPageChecked(page);
8932 if (PagePrivate(page)) {
8933 ClearPagePrivate(page);
8934 set_page_private(page, 0);
8940 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8941 * called from a page fault handler when a page is first dirtied. Hence we must
8942 * be careful to check for EOF conditions here. We set the page up correctly
8943 * for a written page which means we get ENOSPC checking when writing into
8944 * holes and correct delalloc and unwritten extent mapping on filesystems that
8945 * support these features.
8947 * We are not allowed to take the i_mutex here so we have to play games to
8948 * protect against truncate races as the page could now be beyond EOF. Because
8949 * vmtruncate() writes the inode size before removing pages, once we have the
8950 * page lock we can determine safely if the page is beyond EOF. If it is not
8951 * beyond EOF, then the page is guaranteed safe against truncation until we
8954 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
8956 struct page *page = vmf->page;
8957 struct inode *inode = file_inode(vma->vm_file);
8958 struct btrfs_root *root = BTRFS_I(inode)->root;
8959 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8960 struct btrfs_ordered_extent *ordered;
8961 struct extent_state *cached_state = NULL;
8963 unsigned long zero_start;
8972 reserved_space = PAGE_SIZE;
8974 sb_start_pagefault(inode->i_sb);
8975 page_start = page_offset(page);
8976 page_end = page_start + PAGE_SIZE - 1;
8980 * Reserving delalloc space after obtaining the page lock can lead to
8981 * deadlock. For example, if a dirty page is locked by this function
8982 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8983 * dirty page write out, then the btrfs_writepage() function could
8984 * end up waiting indefinitely to get a lock on the page currently
8985 * being processed by btrfs_page_mkwrite() function.
8987 ret = btrfs_delalloc_reserve_space(inode, page_start,
8990 ret = file_update_time(vma->vm_file);
8996 else /* -ENOSPC, -EIO, etc */
8997 ret = VM_FAULT_SIGBUS;
9003 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
9006 size = i_size_read(inode);
9008 if ((page->mapping != inode->i_mapping) ||
9009 (page_start >= size)) {
9010 /* page got truncated out from underneath us */
9013 wait_on_page_writeback(page);
9015 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
9016 set_page_extent_mapped(page);
9019 * we can't set the delalloc bits if there are pending ordered
9020 * extents. Drop our locks and wait for them to finish
9022 ordered = btrfs_lookup_ordered_range(inode, page_start, page_end);
9024 unlock_extent_cached(io_tree, page_start, page_end,
9025 &cached_state, GFP_NOFS);
9027 btrfs_start_ordered_extent(inode, ordered, 1);
9028 btrfs_put_ordered_extent(ordered);
9032 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9033 reserved_space = round_up(size - page_start, root->sectorsize);
9034 if (reserved_space < PAGE_SIZE) {
9035 end = page_start + reserved_space - 1;
9036 spin_lock(&BTRFS_I(inode)->lock);
9037 BTRFS_I(inode)->outstanding_extents++;
9038 spin_unlock(&BTRFS_I(inode)->lock);
9039 btrfs_delalloc_release_space(inode, page_start,
9040 PAGE_SIZE - reserved_space);
9045 * XXX - page_mkwrite gets called every time the page is dirtied, even
9046 * if it was already dirty, so for space accounting reasons we need to
9047 * clear any delalloc bits for the range we are fixing to save. There
9048 * is probably a better way to do this, but for now keep consistent with
9049 * prepare_pages in the normal write path.
9051 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9052 EXTENT_DIRTY | EXTENT_DELALLOC |
9053 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
9054 0, 0, &cached_state, GFP_NOFS);
9056 ret = btrfs_set_extent_delalloc(inode, page_start, end,
9059 unlock_extent_cached(io_tree, page_start, page_end,
9060 &cached_state, GFP_NOFS);
9061 ret = VM_FAULT_SIGBUS;
9066 /* page is wholly or partially inside EOF */
9067 if (page_start + PAGE_SIZE > size)
9068 zero_start = size & ~PAGE_MASK;
9070 zero_start = PAGE_SIZE;
9072 if (zero_start != PAGE_SIZE) {
9074 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9075 flush_dcache_page(page);
9078 ClearPageChecked(page);
9079 set_page_dirty(page);
9080 SetPageUptodate(page);
9082 BTRFS_I(inode)->last_trans = root->fs_info->generation;
9083 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9084 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9086 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
9090 sb_end_pagefault(inode->i_sb);
9091 return VM_FAULT_LOCKED;
9095 btrfs_delalloc_release_space(inode, page_start, reserved_space);
9097 sb_end_pagefault(inode->i_sb);
9101 static int btrfs_truncate(struct inode *inode)
9103 struct btrfs_root *root = BTRFS_I(inode)->root;
9104 struct btrfs_block_rsv *rsv;
9107 struct btrfs_trans_handle *trans;
9108 u64 mask = root->sectorsize - 1;
9109 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
9111 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9117 * Yes ladies and gentlemen, this is indeed ugly. The fact is we have
9118 * 3 things going on here
9120 * 1) We need to reserve space for our orphan item and the space to
9121 * delete our orphan item. Lord knows we don't want to have a dangling
9122 * orphan item because we didn't reserve space to remove it.
9124 * 2) We need to reserve space to update our inode.
9126 * 3) We need to have something to cache all the space that is going to
9127 * be free'd up by the truncate operation, but also have some slack
9128 * space reserved in case it uses space during the truncate (thank you
9129 * very much snapshotting).
9131 * And we need these to all be separate. The fact is we can use a lot of
9132 * space doing the truncate, and we have no earthly idea how much space
9133 * we will use, so we need the truncate reservation to be separate so it
9134 * doesn't end up using space reserved for updating the inode or
9135 * removing the orphan item. We also need to be able to stop the
9136 * transaction and start a new one, which means we need to be able to
9137 * update the inode several times, and we have no idea of knowing how
9138 * many times that will be, so we can't just reserve 1 item for the
9139 * entirety of the operation, so that has to be done separately as well.
9140 * Then there is the orphan item, which does indeed need to be held on
9141 * to for the whole operation, and we need nobody to touch this reserved
9142 * space except the orphan code.
9144 * So that leaves us with
9146 * 1) root->orphan_block_rsv - for the orphan deletion.
9147 * 2) rsv - for the truncate reservation, which we will steal from the
9148 * transaction reservation.
9149 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
9150 * updating the inode.
9152 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
9155 rsv->size = min_size;
9159 * 1 for the truncate slack space
9160 * 1 for updating the inode.
9162 trans = btrfs_start_transaction(root, 2);
9163 if (IS_ERR(trans)) {
9164 err = PTR_ERR(trans);
9168 /* Migrate the slack space for the truncate to our reserve */
9169 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
9174 * So if we truncate and then write and fsync we normally would just
9175 * write the extents that changed, which is a problem if we need to
9176 * first truncate that entire inode. So set this flag so we write out
9177 * all of the extents in the inode to the sync log so we're completely
9180 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9181 trans->block_rsv = rsv;
9184 ret = btrfs_truncate_inode_items(trans, root, inode,
9186 BTRFS_EXTENT_DATA_KEY);
9187 if (ret != -ENOSPC && ret != -EAGAIN) {
9192 trans->block_rsv = &root->fs_info->trans_block_rsv;
9193 ret = btrfs_update_inode(trans, root, inode);
9199 btrfs_end_transaction(trans, root);
9200 btrfs_btree_balance_dirty(root);
9202 trans = btrfs_start_transaction(root, 2);
9203 if (IS_ERR(trans)) {
9204 ret = err = PTR_ERR(trans);
9209 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
9211 BUG_ON(ret); /* shouldn't happen */
9212 trans->block_rsv = rsv;
9215 if (ret == 0 && inode->i_nlink > 0) {
9216 trans->block_rsv = root->orphan_block_rsv;
9217 ret = btrfs_orphan_del(trans, inode);
9223 trans->block_rsv = &root->fs_info->trans_block_rsv;
9224 ret = btrfs_update_inode(trans, root, inode);
9228 ret = btrfs_end_transaction(trans, root);
9229 btrfs_btree_balance_dirty(root);
9232 btrfs_free_block_rsv(root, rsv);
9241 * create a new subvolume directory/inode (helper for the ioctl).
9243 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9244 struct btrfs_root *new_root,
9245 struct btrfs_root *parent_root,
9248 struct inode *inode;
9252 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9253 new_dirid, new_dirid,
9254 S_IFDIR | (~current_umask() & S_IRWXUGO),
9257 return PTR_ERR(inode);
9258 inode->i_op = &btrfs_dir_inode_operations;
9259 inode->i_fop = &btrfs_dir_file_operations;
9261 set_nlink(inode, 1);
9262 btrfs_i_size_write(inode, 0);
9263 unlock_new_inode(inode);
9265 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9267 btrfs_err(new_root->fs_info,
9268 "error inheriting subvolume %llu properties: %d",
9269 new_root->root_key.objectid, err);
9271 err = btrfs_update_inode(trans, new_root, inode);
9277 struct inode *btrfs_alloc_inode(struct super_block *sb)
9279 struct btrfs_inode *ei;
9280 struct inode *inode;
9282 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
9289 ei->last_sub_trans = 0;
9290 ei->logged_trans = 0;
9291 ei->delalloc_bytes = 0;
9292 ei->defrag_bytes = 0;
9293 ei->disk_i_size = 0;
9296 ei->index_cnt = (u64)-1;
9298 ei->last_unlink_trans = 0;
9299 ei->last_log_commit = 0;
9300 ei->delayed_iput_count = 0;
9302 spin_lock_init(&ei->lock);
9303 ei->outstanding_extents = 0;
9304 ei->reserved_extents = 0;
9306 ei->runtime_flags = 0;
9307 ei->force_compress = BTRFS_COMPRESS_NONE;
9309 ei->delayed_node = NULL;
9311 ei->i_otime.tv_sec = 0;
9312 ei->i_otime.tv_nsec = 0;
9314 inode = &ei->vfs_inode;
9315 extent_map_tree_init(&ei->extent_tree);
9316 extent_io_tree_init(&ei->io_tree, &inode->i_data);
9317 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
9318 ei->io_tree.track_uptodate = 1;
9319 ei->io_failure_tree.track_uptodate = 1;
9320 atomic_set(&ei->sync_writers, 0);
9321 mutex_init(&ei->log_mutex);
9322 mutex_init(&ei->delalloc_mutex);
9323 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9324 INIT_LIST_HEAD(&ei->delalloc_inodes);
9325 INIT_LIST_HEAD(&ei->delayed_iput);
9326 RB_CLEAR_NODE(&ei->rb_node);
9327 init_rwsem(&ei->dio_sem);
9332 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9333 void btrfs_test_destroy_inode(struct inode *inode)
9335 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
9336 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9340 static void btrfs_i_callback(struct rcu_head *head)
9342 struct inode *inode = container_of(head, struct inode, i_rcu);
9343 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9346 void btrfs_destroy_inode(struct inode *inode)
9348 struct btrfs_ordered_extent *ordered;
9349 struct btrfs_root *root = BTRFS_I(inode)->root;
9351 WARN_ON(!hlist_empty(&inode->i_dentry));
9352 WARN_ON(inode->i_data.nrpages);
9353 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9354 WARN_ON(BTRFS_I(inode)->reserved_extents);
9355 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9356 WARN_ON(BTRFS_I(inode)->csum_bytes);
9357 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9360 * This can happen where we create an inode, but somebody else also
9361 * created the same inode and we need to destroy the one we already
9367 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9368 &BTRFS_I(inode)->runtime_flags)) {
9369 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
9371 atomic_dec(&root->orphan_inodes);
9375 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9379 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
9380 ordered->file_offset, ordered->len);
9381 btrfs_remove_ordered_extent(inode, ordered);
9382 btrfs_put_ordered_extent(ordered);
9383 btrfs_put_ordered_extent(ordered);
9386 btrfs_qgroup_check_reserved_leak(inode);
9387 inode_tree_del(inode);
9388 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
9390 call_rcu(&inode->i_rcu, btrfs_i_callback);
9393 int btrfs_drop_inode(struct inode *inode)
9395 struct btrfs_root *root = BTRFS_I(inode)->root;
9400 /* the snap/subvol tree is on deleting */
9401 if (btrfs_root_refs(&root->root_item) == 0)
9404 return generic_drop_inode(inode);
9407 static void init_once(void *foo)
9409 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9411 inode_init_once(&ei->vfs_inode);
9414 void btrfs_destroy_cachep(void)
9417 * Make sure all delayed rcu free inodes are flushed before we
9421 kmem_cache_destroy(btrfs_inode_cachep);
9422 kmem_cache_destroy(btrfs_trans_handle_cachep);
9423 kmem_cache_destroy(btrfs_transaction_cachep);
9424 kmem_cache_destroy(btrfs_path_cachep);
9425 kmem_cache_destroy(btrfs_free_space_cachep);
9428 int btrfs_init_cachep(void)
9430 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9431 sizeof(struct btrfs_inode), 0,
9432 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9434 if (!btrfs_inode_cachep)
9437 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9438 sizeof(struct btrfs_trans_handle), 0,
9439 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9440 if (!btrfs_trans_handle_cachep)
9443 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
9444 sizeof(struct btrfs_transaction), 0,
9445 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9446 if (!btrfs_transaction_cachep)
9449 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9450 sizeof(struct btrfs_path), 0,
9451 SLAB_MEM_SPREAD, NULL);
9452 if (!btrfs_path_cachep)
9455 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9456 sizeof(struct btrfs_free_space), 0,
9457 SLAB_MEM_SPREAD, NULL);
9458 if (!btrfs_free_space_cachep)
9463 btrfs_destroy_cachep();
9467 static int btrfs_getattr(struct vfsmount *mnt,
9468 struct dentry *dentry, struct kstat *stat)
9471 struct inode *inode = d_inode(dentry);
9472 u32 blocksize = inode->i_sb->s_blocksize;
9474 generic_fillattr(inode, stat);
9475 stat->dev = BTRFS_I(inode)->root->anon_dev;
9477 spin_lock(&BTRFS_I(inode)->lock);
9478 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
9479 spin_unlock(&BTRFS_I(inode)->lock);
9480 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9481 ALIGN(delalloc_bytes, blocksize)) >> 9;
9485 static int btrfs_rename_exchange(struct inode *old_dir,
9486 struct dentry *old_dentry,
9487 struct inode *new_dir,
9488 struct dentry *new_dentry)
9490 struct btrfs_trans_handle *trans;
9491 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9492 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9493 struct inode *new_inode = new_dentry->d_inode;
9494 struct inode *old_inode = old_dentry->d_inode;
9495 struct timespec ctime = CURRENT_TIME;
9496 struct dentry *parent;
9497 u64 old_ino = btrfs_ino(old_inode);
9498 u64 new_ino = btrfs_ino(new_inode);
9503 bool root_log_pinned = false;
9504 bool dest_log_pinned = false;
9506 /* we only allow rename subvolume link between subvolumes */
9507 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9510 /* close the race window with snapshot create/destroy ioctl */
9511 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9512 down_read(&root->fs_info->subvol_sem);
9513 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9514 down_read(&dest->fs_info->subvol_sem);
9517 * We want to reserve the absolute worst case amount of items. So if
9518 * both inodes are subvols and we need to unlink them then that would
9519 * require 4 item modifications, but if they are both normal inodes it
9520 * would require 5 item modifications, so we'll assume their normal
9521 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9522 * should cover the worst case number of items we'll modify.
9524 trans = btrfs_start_transaction(root, 12);
9525 if (IS_ERR(trans)) {
9526 ret = PTR_ERR(trans);
9531 * We need to find a free sequence number both in the source and
9532 * in the destination directory for the exchange.
9534 ret = btrfs_set_inode_index(new_dir, &old_idx);
9537 ret = btrfs_set_inode_index(old_dir, &new_idx);
9541 BTRFS_I(old_inode)->dir_index = 0ULL;
9542 BTRFS_I(new_inode)->dir_index = 0ULL;
9544 /* Reference for the source. */
9545 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9546 /* force full log commit if subvolume involved. */
9547 btrfs_set_log_full_commit(root->fs_info, trans);
9549 btrfs_pin_log_trans(root);
9550 root_log_pinned = true;
9551 ret = btrfs_insert_inode_ref(trans, dest,
9552 new_dentry->d_name.name,
9553 new_dentry->d_name.len,
9555 btrfs_ino(new_dir), old_idx);
9560 /* And now for the dest. */
9561 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9562 /* force full log commit if subvolume involved. */
9563 btrfs_set_log_full_commit(dest->fs_info, trans);
9565 btrfs_pin_log_trans(dest);
9566 dest_log_pinned = true;
9567 ret = btrfs_insert_inode_ref(trans, root,
9568 old_dentry->d_name.name,
9569 old_dentry->d_name.len,
9571 btrfs_ino(old_dir), new_idx);
9576 /* Update inode version and ctime/mtime. */
9577 inode_inc_iversion(old_dir);
9578 inode_inc_iversion(new_dir);
9579 inode_inc_iversion(old_inode);
9580 inode_inc_iversion(new_inode);
9581 old_dir->i_ctime = old_dir->i_mtime = ctime;
9582 new_dir->i_ctime = new_dir->i_mtime = ctime;
9583 old_inode->i_ctime = ctime;
9584 new_inode->i_ctime = ctime;
9586 if (old_dentry->d_parent != new_dentry->d_parent) {
9587 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
9588 btrfs_record_unlink_dir(trans, new_dir, new_inode, 1);
9591 /* src is a subvolume */
9592 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9593 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9594 ret = btrfs_unlink_subvol(trans, root, old_dir,
9596 old_dentry->d_name.name,
9597 old_dentry->d_name.len);
9598 } else { /* src is an inode */
9599 ret = __btrfs_unlink_inode(trans, root, old_dir,
9600 old_dentry->d_inode,
9601 old_dentry->d_name.name,
9602 old_dentry->d_name.len);
9604 ret = btrfs_update_inode(trans, root, old_inode);
9607 btrfs_abort_transaction(trans, ret);
9611 /* dest is a subvolume */
9612 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9613 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9614 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9616 new_dentry->d_name.name,
9617 new_dentry->d_name.len);
9618 } else { /* dest is an inode */
9619 ret = __btrfs_unlink_inode(trans, dest, new_dir,
9620 new_dentry->d_inode,
9621 new_dentry->d_name.name,
9622 new_dentry->d_name.len);
9624 ret = btrfs_update_inode(trans, dest, new_inode);
9627 btrfs_abort_transaction(trans, ret);
9631 ret = btrfs_add_link(trans, new_dir, old_inode,
9632 new_dentry->d_name.name,
9633 new_dentry->d_name.len, 0, old_idx);
9635 btrfs_abort_transaction(trans, ret);
9639 ret = btrfs_add_link(trans, old_dir, new_inode,
9640 old_dentry->d_name.name,
9641 old_dentry->d_name.len, 0, new_idx);
9643 btrfs_abort_transaction(trans, ret);
9647 if (old_inode->i_nlink == 1)
9648 BTRFS_I(old_inode)->dir_index = old_idx;
9649 if (new_inode->i_nlink == 1)
9650 BTRFS_I(new_inode)->dir_index = new_idx;
9652 if (root_log_pinned) {
9653 parent = new_dentry->d_parent;
9654 btrfs_log_new_name(trans, old_inode, old_dir, parent);
9655 btrfs_end_log_trans(root);
9656 root_log_pinned = false;
9658 if (dest_log_pinned) {
9659 parent = old_dentry->d_parent;
9660 btrfs_log_new_name(trans, new_inode, new_dir, parent);
9661 btrfs_end_log_trans(dest);
9662 dest_log_pinned = false;
9666 * If we have pinned a log and an error happened, we unpin tasks
9667 * trying to sync the log and force them to fallback to a transaction
9668 * commit if the log currently contains any of the inodes involved in
9669 * this rename operation (to ensure we do not persist a log with an
9670 * inconsistent state for any of these inodes or leading to any
9671 * inconsistencies when replayed). If the transaction was aborted, the
9672 * abortion reason is propagated to userspace when attempting to commit
9673 * the transaction. If the log does not contain any of these inodes, we
9674 * allow the tasks to sync it.
9676 if (ret && (root_log_pinned || dest_log_pinned)) {
9677 if (btrfs_inode_in_log(old_dir, root->fs_info->generation) ||
9678 btrfs_inode_in_log(new_dir, root->fs_info->generation) ||
9679 btrfs_inode_in_log(old_inode, root->fs_info->generation) ||
9681 btrfs_inode_in_log(new_inode, root->fs_info->generation)))
9682 btrfs_set_log_full_commit(root->fs_info, trans);
9684 if (root_log_pinned) {
9685 btrfs_end_log_trans(root);
9686 root_log_pinned = false;
9688 if (dest_log_pinned) {
9689 btrfs_end_log_trans(dest);
9690 dest_log_pinned = false;
9693 ret = btrfs_end_transaction(trans, root);
9695 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9696 up_read(&dest->fs_info->subvol_sem);
9697 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9698 up_read(&root->fs_info->subvol_sem);
9703 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9704 struct btrfs_root *root,
9706 struct dentry *dentry)
9709 struct inode *inode;
9713 ret = btrfs_find_free_ino(root, &objectid);
9717 inode = btrfs_new_inode(trans, root, dir,
9718 dentry->d_name.name,
9722 S_IFCHR | WHITEOUT_MODE,
9725 if (IS_ERR(inode)) {
9726 ret = PTR_ERR(inode);
9730 inode->i_op = &btrfs_special_inode_operations;
9731 init_special_inode(inode, inode->i_mode,
9734 ret = btrfs_init_inode_security(trans, inode, dir,
9739 ret = btrfs_add_nondir(trans, dir, dentry,
9744 ret = btrfs_update_inode(trans, root, inode);
9746 unlock_new_inode(inode);
9748 inode_dec_link_count(inode);
9754 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9755 struct inode *new_dir, struct dentry *new_dentry,
9758 struct btrfs_trans_handle *trans;
9759 unsigned int trans_num_items;
9760 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9761 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9762 struct inode *new_inode = d_inode(new_dentry);
9763 struct inode *old_inode = d_inode(old_dentry);
9767 u64 old_ino = btrfs_ino(old_inode);
9768 bool log_pinned = false;
9770 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9773 /* we only allow rename subvolume link between subvolumes */
9774 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9777 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9778 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
9781 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9782 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9786 /* check for collisions, even if the name isn't there */
9787 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9788 new_dentry->d_name.name,
9789 new_dentry->d_name.len);
9792 if (ret == -EEXIST) {
9794 * eexist without a new_inode */
9795 if (WARN_ON(!new_inode)) {
9799 /* maybe -EOVERFLOW */
9806 * we're using rename to replace one file with another. Start IO on it
9807 * now so we don't add too much work to the end of the transaction
9809 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9810 filemap_flush(old_inode->i_mapping);
9812 /* close the racy window with snapshot create/destroy ioctl */
9813 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9814 down_read(&root->fs_info->subvol_sem);
9816 * We want to reserve the absolute worst case amount of items. So if
9817 * both inodes are subvols and we need to unlink them then that would
9818 * require 4 item modifications, but if they are both normal inodes it
9819 * would require 5 item modifications, so we'll assume they are normal
9820 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9821 * should cover the worst case number of items we'll modify.
9822 * If our rename has the whiteout flag, we need more 5 units for the
9823 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9824 * when selinux is enabled).
9826 trans_num_items = 11;
9827 if (flags & RENAME_WHITEOUT)
9828 trans_num_items += 5;
9829 trans = btrfs_start_transaction(root, trans_num_items);
9830 if (IS_ERR(trans)) {
9831 ret = PTR_ERR(trans);
9836 btrfs_record_root_in_trans(trans, dest);
9838 ret = btrfs_set_inode_index(new_dir, &index);
9842 BTRFS_I(old_inode)->dir_index = 0ULL;
9843 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9844 /* force full log commit if subvolume involved. */
9845 btrfs_set_log_full_commit(root->fs_info, trans);
9847 btrfs_pin_log_trans(root);
9849 ret = btrfs_insert_inode_ref(trans, dest,
9850 new_dentry->d_name.name,
9851 new_dentry->d_name.len,
9853 btrfs_ino(new_dir), index);
9858 inode_inc_iversion(old_dir);
9859 inode_inc_iversion(new_dir);
9860 inode_inc_iversion(old_inode);
9861 old_dir->i_ctime = old_dir->i_mtime =
9862 new_dir->i_ctime = new_dir->i_mtime =
9863 old_inode->i_ctime = current_fs_time(old_dir->i_sb);
9865 if (old_dentry->d_parent != new_dentry->d_parent)
9866 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
9868 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9869 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9870 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9871 old_dentry->d_name.name,
9872 old_dentry->d_name.len);
9874 ret = __btrfs_unlink_inode(trans, root, old_dir,
9875 d_inode(old_dentry),
9876 old_dentry->d_name.name,
9877 old_dentry->d_name.len);
9879 ret = btrfs_update_inode(trans, root, old_inode);
9882 btrfs_abort_transaction(trans, ret);
9887 inode_inc_iversion(new_inode);
9888 new_inode->i_ctime = current_fs_time(new_inode->i_sb);
9889 if (unlikely(btrfs_ino(new_inode) ==
9890 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9891 root_objectid = BTRFS_I(new_inode)->location.objectid;
9892 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9894 new_dentry->d_name.name,
9895 new_dentry->d_name.len);
9896 BUG_ON(new_inode->i_nlink == 0);
9898 ret = btrfs_unlink_inode(trans, dest, new_dir,
9899 d_inode(new_dentry),
9900 new_dentry->d_name.name,
9901 new_dentry->d_name.len);
9903 if (!ret && new_inode->i_nlink == 0)
9904 ret = btrfs_orphan_add(trans, d_inode(new_dentry));
9906 btrfs_abort_transaction(trans, ret);
9911 ret = btrfs_add_link(trans, new_dir, old_inode,
9912 new_dentry->d_name.name,
9913 new_dentry->d_name.len, 0, index);
9915 btrfs_abort_transaction(trans, ret);
9919 if (old_inode->i_nlink == 1)
9920 BTRFS_I(old_inode)->dir_index = index;
9923 struct dentry *parent = new_dentry->d_parent;
9925 btrfs_log_new_name(trans, old_inode, old_dir, parent);
9926 btrfs_end_log_trans(root);
9930 if (flags & RENAME_WHITEOUT) {
9931 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9935 btrfs_abort_transaction(trans, ret);
9941 * If we have pinned the log and an error happened, we unpin tasks
9942 * trying to sync the log and force them to fallback to a transaction
9943 * commit if the log currently contains any of the inodes involved in
9944 * this rename operation (to ensure we do not persist a log with an
9945 * inconsistent state for any of these inodes or leading to any
9946 * inconsistencies when replayed). If the transaction was aborted, the
9947 * abortion reason is propagated to userspace when attempting to commit
9948 * the transaction. If the log does not contain any of these inodes, we
9949 * allow the tasks to sync it.
9951 if (ret && log_pinned) {
9952 if (btrfs_inode_in_log(old_dir, root->fs_info->generation) ||
9953 btrfs_inode_in_log(new_dir, root->fs_info->generation) ||
9954 btrfs_inode_in_log(old_inode, root->fs_info->generation) ||
9956 btrfs_inode_in_log(new_inode, root->fs_info->generation)))
9957 btrfs_set_log_full_commit(root->fs_info, trans);
9959 btrfs_end_log_trans(root);
9962 btrfs_end_transaction(trans, root);
9964 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9965 up_read(&root->fs_info->subvol_sem);
9970 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9971 struct inode *new_dir, struct dentry *new_dentry,
9974 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9977 if (flags & RENAME_EXCHANGE)
9978 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9981 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9984 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9986 struct btrfs_delalloc_work *delalloc_work;
9987 struct inode *inode;
9989 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9991 inode = delalloc_work->inode;
9992 filemap_flush(inode->i_mapping);
9993 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9994 &BTRFS_I(inode)->runtime_flags))
9995 filemap_flush(inode->i_mapping);
9997 if (delalloc_work->delay_iput)
9998 btrfs_add_delayed_iput(inode);
10001 complete(&delalloc_work->completion);
10004 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
10007 struct btrfs_delalloc_work *work;
10009 work = kmalloc(sizeof(*work), GFP_NOFS);
10013 init_completion(&work->completion);
10014 INIT_LIST_HEAD(&work->list);
10015 work->inode = inode;
10016 work->delay_iput = delay_iput;
10017 WARN_ON_ONCE(!inode);
10018 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10019 btrfs_run_delalloc_work, NULL, NULL);
10024 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
10026 wait_for_completion(&work->completion);
10031 * some fairly slow code that needs optimization. This walks the list
10032 * of all the inodes with pending delalloc and forces them to disk.
10034 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
10037 struct btrfs_inode *binode;
10038 struct inode *inode;
10039 struct btrfs_delalloc_work *work, *next;
10040 struct list_head works;
10041 struct list_head splice;
10044 INIT_LIST_HEAD(&works);
10045 INIT_LIST_HEAD(&splice);
10047 mutex_lock(&root->delalloc_mutex);
10048 spin_lock(&root->delalloc_lock);
10049 list_splice_init(&root->delalloc_inodes, &splice);
10050 while (!list_empty(&splice)) {
10051 binode = list_entry(splice.next, struct btrfs_inode,
10054 list_move_tail(&binode->delalloc_inodes,
10055 &root->delalloc_inodes);
10056 inode = igrab(&binode->vfs_inode);
10058 cond_resched_lock(&root->delalloc_lock);
10061 spin_unlock(&root->delalloc_lock);
10063 work = btrfs_alloc_delalloc_work(inode, delay_iput);
10066 btrfs_add_delayed_iput(inode);
10072 list_add_tail(&work->list, &works);
10073 btrfs_queue_work(root->fs_info->flush_workers,
10076 if (nr != -1 && ret >= nr)
10079 spin_lock(&root->delalloc_lock);
10081 spin_unlock(&root->delalloc_lock);
10084 list_for_each_entry_safe(work, next, &works, list) {
10085 list_del_init(&work->list);
10086 btrfs_wait_and_free_delalloc_work(work);
10089 if (!list_empty_careful(&splice)) {
10090 spin_lock(&root->delalloc_lock);
10091 list_splice_tail(&splice, &root->delalloc_inodes);
10092 spin_unlock(&root->delalloc_lock);
10094 mutex_unlock(&root->delalloc_mutex);
10098 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
10102 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
10105 ret = __start_delalloc_inodes(root, delay_iput, -1);
10109 * the filemap_flush will queue IO into the worker threads, but
10110 * we have to make sure the IO is actually started and that
10111 * ordered extents get created before we return
10113 atomic_inc(&root->fs_info->async_submit_draining);
10114 while (atomic_read(&root->fs_info->nr_async_submits) ||
10115 atomic_read(&root->fs_info->async_delalloc_pages)) {
10116 wait_event(root->fs_info->async_submit_wait,
10117 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
10118 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
10120 atomic_dec(&root->fs_info->async_submit_draining);
10124 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
10127 struct btrfs_root *root;
10128 struct list_head splice;
10131 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10134 INIT_LIST_HEAD(&splice);
10136 mutex_lock(&fs_info->delalloc_root_mutex);
10137 spin_lock(&fs_info->delalloc_root_lock);
10138 list_splice_init(&fs_info->delalloc_roots, &splice);
10139 while (!list_empty(&splice) && nr) {
10140 root = list_first_entry(&splice, struct btrfs_root,
10142 root = btrfs_grab_fs_root(root);
10144 list_move_tail(&root->delalloc_root,
10145 &fs_info->delalloc_roots);
10146 spin_unlock(&fs_info->delalloc_root_lock);
10148 ret = __start_delalloc_inodes(root, delay_iput, nr);
10149 btrfs_put_fs_root(root);
10157 spin_lock(&fs_info->delalloc_root_lock);
10159 spin_unlock(&fs_info->delalloc_root_lock);
10162 atomic_inc(&fs_info->async_submit_draining);
10163 while (atomic_read(&fs_info->nr_async_submits) ||
10164 atomic_read(&fs_info->async_delalloc_pages)) {
10165 wait_event(fs_info->async_submit_wait,
10166 (atomic_read(&fs_info->nr_async_submits) == 0 &&
10167 atomic_read(&fs_info->async_delalloc_pages) == 0));
10169 atomic_dec(&fs_info->async_submit_draining);
10171 if (!list_empty_careful(&splice)) {
10172 spin_lock(&fs_info->delalloc_root_lock);
10173 list_splice_tail(&splice, &fs_info->delalloc_roots);
10174 spin_unlock(&fs_info->delalloc_root_lock);
10176 mutex_unlock(&fs_info->delalloc_root_mutex);
10180 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10181 const char *symname)
10183 struct btrfs_trans_handle *trans;
10184 struct btrfs_root *root = BTRFS_I(dir)->root;
10185 struct btrfs_path *path;
10186 struct btrfs_key key;
10187 struct inode *inode = NULL;
10189 int drop_inode = 0;
10195 struct btrfs_file_extent_item *ei;
10196 struct extent_buffer *leaf;
10198 name_len = strlen(symname);
10199 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
10200 return -ENAMETOOLONG;
10203 * 2 items for inode item and ref
10204 * 2 items for dir items
10205 * 1 item for updating parent inode item
10206 * 1 item for the inline extent item
10207 * 1 item for xattr if selinux is on
10209 trans = btrfs_start_transaction(root, 7);
10211 return PTR_ERR(trans);
10213 err = btrfs_find_free_ino(root, &objectid);
10217 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10218 dentry->d_name.len, btrfs_ino(dir), objectid,
10219 S_IFLNK|S_IRWXUGO, &index);
10220 if (IS_ERR(inode)) {
10221 err = PTR_ERR(inode);
10226 * If the active LSM wants to access the inode during
10227 * d_instantiate it needs these. Smack checks to see
10228 * if the filesystem supports xattrs by looking at the
10231 inode->i_fop = &btrfs_file_operations;
10232 inode->i_op = &btrfs_file_inode_operations;
10233 inode->i_mapping->a_ops = &btrfs_aops;
10234 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10236 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10238 goto out_unlock_inode;
10240 path = btrfs_alloc_path();
10243 goto out_unlock_inode;
10245 key.objectid = btrfs_ino(inode);
10247 key.type = BTRFS_EXTENT_DATA_KEY;
10248 datasize = btrfs_file_extent_calc_inline_size(name_len);
10249 err = btrfs_insert_empty_item(trans, root, path, &key,
10252 btrfs_free_path(path);
10253 goto out_unlock_inode;
10255 leaf = path->nodes[0];
10256 ei = btrfs_item_ptr(leaf, path->slots[0],
10257 struct btrfs_file_extent_item);
10258 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10259 btrfs_set_file_extent_type(leaf, ei,
10260 BTRFS_FILE_EXTENT_INLINE);
10261 btrfs_set_file_extent_encryption(leaf, ei, 0);
10262 btrfs_set_file_extent_compression(leaf, ei, 0);
10263 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10264 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10266 ptr = btrfs_file_extent_inline_start(ei);
10267 write_extent_buffer(leaf, symname, ptr, name_len);
10268 btrfs_mark_buffer_dirty(leaf);
10269 btrfs_free_path(path);
10271 inode->i_op = &btrfs_symlink_inode_operations;
10272 inode_nohighmem(inode);
10273 inode->i_mapping->a_ops = &btrfs_symlink_aops;
10274 inode_set_bytes(inode, name_len);
10275 btrfs_i_size_write(inode, name_len);
10276 err = btrfs_update_inode(trans, root, inode);
10278 * Last step, add directory indexes for our symlink inode. This is the
10279 * last step to avoid extra cleanup of these indexes if an error happens
10283 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
10286 goto out_unlock_inode;
10289 unlock_new_inode(inode);
10290 d_instantiate(dentry, inode);
10293 btrfs_end_transaction(trans, root);
10295 inode_dec_link_count(inode);
10298 btrfs_btree_balance_dirty(root);
10303 unlock_new_inode(inode);
10307 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10308 u64 start, u64 num_bytes, u64 min_size,
10309 loff_t actual_len, u64 *alloc_hint,
10310 struct btrfs_trans_handle *trans)
10312 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10313 struct extent_map *em;
10314 struct btrfs_root *root = BTRFS_I(inode)->root;
10315 struct btrfs_key ins;
10316 u64 cur_offset = start;
10319 u64 last_alloc = (u64)-1;
10321 bool own_trans = true;
10322 u64 end = start + num_bytes - 1;
10326 while (num_bytes > 0) {
10328 trans = btrfs_start_transaction(root, 3);
10329 if (IS_ERR(trans)) {
10330 ret = PTR_ERR(trans);
10335 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10336 cur_bytes = max(cur_bytes, min_size);
10338 * If we are severely fragmented we could end up with really
10339 * small allocations, so if the allocator is returning small
10340 * chunks lets make its job easier by only searching for those
10343 cur_bytes = min(cur_bytes, last_alloc);
10344 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10345 min_size, 0, *alloc_hint, &ins, 1, 0);
10348 btrfs_end_transaction(trans, root);
10351 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
10353 last_alloc = ins.offset;
10354 ret = insert_reserved_file_extent(trans, inode,
10355 cur_offset, ins.objectid,
10356 ins.offset, ins.offset,
10357 ins.offset, 0, 0, 0,
10358 BTRFS_FILE_EXTENT_PREALLOC);
10360 btrfs_free_reserved_extent(root, ins.objectid,
10362 btrfs_abort_transaction(trans, ret);
10364 btrfs_end_transaction(trans, root);
10368 btrfs_drop_extent_cache(inode, cur_offset,
10369 cur_offset + ins.offset -1, 0);
10371 em = alloc_extent_map();
10373 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10374 &BTRFS_I(inode)->runtime_flags);
10378 em->start = cur_offset;
10379 em->orig_start = cur_offset;
10380 em->len = ins.offset;
10381 em->block_start = ins.objectid;
10382 em->block_len = ins.offset;
10383 em->orig_block_len = ins.offset;
10384 em->ram_bytes = ins.offset;
10385 em->bdev = root->fs_info->fs_devices->latest_bdev;
10386 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10387 em->generation = trans->transid;
10390 write_lock(&em_tree->lock);
10391 ret = add_extent_mapping(em_tree, em, 1);
10392 write_unlock(&em_tree->lock);
10393 if (ret != -EEXIST)
10395 btrfs_drop_extent_cache(inode, cur_offset,
10396 cur_offset + ins.offset - 1,
10399 free_extent_map(em);
10401 num_bytes -= ins.offset;
10402 cur_offset += ins.offset;
10403 *alloc_hint = ins.objectid + ins.offset;
10405 inode_inc_iversion(inode);
10406 inode->i_ctime = current_fs_time(inode->i_sb);
10407 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10408 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10409 (actual_len > inode->i_size) &&
10410 (cur_offset > inode->i_size)) {
10411 if (cur_offset > actual_len)
10412 i_size = actual_len;
10414 i_size = cur_offset;
10415 i_size_write(inode, i_size);
10416 btrfs_ordered_update_i_size(inode, i_size, NULL);
10419 ret = btrfs_update_inode(trans, root, inode);
10422 btrfs_abort_transaction(trans, ret);
10424 btrfs_end_transaction(trans, root);
10429 btrfs_end_transaction(trans, root);
10431 if (cur_offset < end)
10432 btrfs_free_reserved_data_space(inode, cur_offset,
10433 end - cur_offset + 1);
10437 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10438 u64 start, u64 num_bytes, u64 min_size,
10439 loff_t actual_len, u64 *alloc_hint)
10441 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10442 min_size, actual_len, alloc_hint,
10446 int btrfs_prealloc_file_range_trans(struct inode *inode,
10447 struct btrfs_trans_handle *trans, int mode,
10448 u64 start, u64 num_bytes, u64 min_size,
10449 loff_t actual_len, u64 *alloc_hint)
10451 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10452 min_size, actual_len, alloc_hint, trans);
10455 static int btrfs_set_page_dirty(struct page *page)
10457 return __set_page_dirty_nobuffers(page);
10460 static int btrfs_permission(struct inode *inode, int mask)
10462 struct btrfs_root *root = BTRFS_I(inode)->root;
10463 umode_t mode = inode->i_mode;
10465 if (mask & MAY_WRITE &&
10466 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10467 if (btrfs_root_readonly(root))
10469 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10472 return generic_permission(inode, mask);
10475 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10477 struct btrfs_trans_handle *trans;
10478 struct btrfs_root *root = BTRFS_I(dir)->root;
10479 struct inode *inode = NULL;
10485 * 5 units required for adding orphan entry
10487 trans = btrfs_start_transaction(root, 5);
10489 return PTR_ERR(trans);
10491 ret = btrfs_find_free_ino(root, &objectid);
10495 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10496 btrfs_ino(dir), objectid, mode, &index);
10497 if (IS_ERR(inode)) {
10498 ret = PTR_ERR(inode);
10503 inode->i_fop = &btrfs_file_operations;
10504 inode->i_op = &btrfs_file_inode_operations;
10506 inode->i_mapping->a_ops = &btrfs_aops;
10507 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10509 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10513 ret = btrfs_update_inode(trans, root, inode);
10516 ret = btrfs_orphan_add(trans, inode);
10521 * We set number of links to 0 in btrfs_new_inode(), and here we set
10522 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10525 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10527 set_nlink(inode, 1);
10528 unlock_new_inode(inode);
10529 d_tmpfile(dentry, inode);
10530 mark_inode_dirty(inode);
10533 btrfs_end_transaction(trans, root);
10536 btrfs_balance_delayed_items(root);
10537 btrfs_btree_balance_dirty(root);
10541 unlock_new_inode(inode);
10546 /* Inspired by filemap_check_errors() */
10547 int btrfs_inode_check_errors(struct inode *inode)
10551 if (test_bit(AS_ENOSPC, &inode->i_mapping->flags) &&
10552 test_and_clear_bit(AS_ENOSPC, &inode->i_mapping->flags))
10554 if (test_bit(AS_EIO, &inode->i_mapping->flags) &&
10555 test_and_clear_bit(AS_EIO, &inode->i_mapping->flags))
10561 static const struct inode_operations btrfs_dir_inode_operations = {
10562 .getattr = btrfs_getattr,
10563 .lookup = btrfs_lookup,
10564 .create = btrfs_create,
10565 .unlink = btrfs_unlink,
10566 .link = btrfs_link,
10567 .mkdir = btrfs_mkdir,
10568 .rmdir = btrfs_rmdir,
10569 .rename2 = btrfs_rename2,
10570 .symlink = btrfs_symlink,
10571 .setattr = btrfs_setattr,
10572 .mknod = btrfs_mknod,
10573 .setxattr = generic_setxattr,
10574 .getxattr = generic_getxattr,
10575 .listxattr = btrfs_listxattr,
10576 .removexattr = generic_removexattr,
10577 .permission = btrfs_permission,
10578 .get_acl = btrfs_get_acl,
10579 .set_acl = btrfs_set_acl,
10580 .update_time = btrfs_update_time,
10581 .tmpfile = btrfs_tmpfile,
10583 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10584 .lookup = btrfs_lookup,
10585 .permission = btrfs_permission,
10586 .get_acl = btrfs_get_acl,
10587 .set_acl = btrfs_set_acl,
10588 .update_time = btrfs_update_time,
10591 static const struct file_operations btrfs_dir_file_operations = {
10592 .llseek = generic_file_llseek,
10593 .read = generic_read_dir,
10594 .iterate_shared = btrfs_real_readdir,
10595 .unlocked_ioctl = btrfs_ioctl,
10596 #ifdef CONFIG_COMPAT
10597 .compat_ioctl = btrfs_compat_ioctl,
10599 .release = btrfs_release_file,
10600 .fsync = btrfs_sync_file,
10603 static const struct extent_io_ops btrfs_extent_io_ops = {
10604 .fill_delalloc = run_delalloc_range,
10605 .submit_bio_hook = btrfs_submit_bio_hook,
10606 .merge_bio_hook = btrfs_merge_bio_hook,
10607 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10608 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10609 .writepage_start_hook = btrfs_writepage_start_hook,
10610 .set_bit_hook = btrfs_set_bit_hook,
10611 .clear_bit_hook = btrfs_clear_bit_hook,
10612 .merge_extent_hook = btrfs_merge_extent_hook,
10613 .split_extent_hook = btrfs_split_extent_hook,
10617 * btrfs doesn't support the bmap operation because swapfiles
10618 * use bmap to make a mapping of extents in the file. They assume
10619 * these extents won't change over the life of the file and they
10620 * use the bmap result to do IO directly to the drive.
10622 * the btrfs bmap call would return logical addresses that aren't
10623 * suitable for IO and they also will change frequently as COW
10624 * operations happen. So, swapfile + btrfs == corruption.
10626 * For now we're avoiding this by dropping bmap.
10628 static const struct address_space_operations btrfs_aops = {
10629 .readpage = btrfs_readpage,
10630 .writepage = btrfs_writepage,
10631 .writepages = btrfs_writepages,
10632 .readpages = btrfs_readpages,
10633 .direct_IO = btrfs_direct_IO,
10634 .invalidatepage = btrfs_invalidatepage,
10635 .releasepage = btrfs_releasepage,
10636 .set_page_dirty = btrfs_set_page_dirty,
10637 .error_remove_page = generic_error_remove_page,
10640 static const struct address_space_operations btrfs_symlink_aops = {
10641 .readpage = btrfs_readpage,
10642 .writepage = btrfs_writepage,
10643 .invalidatepage = btrfs_invalidatepage,
10644 .releasepage = btrfs_releasepage,
10647 static const struct inode_operations btrfs_file_inode_operations = {
10648 .getattr = btrfs_getattr,
10649 .setattr = btrfs_setattr,
10650 .setxattr = generic_setxattr,
10651 .getxattr = generic_getxattr,
10652 .listxattr = btrfs_listxattr,
10653 .removexattr = generic_removexattr,
10654 .permission = btrfs_permission,
10655 .fiemap = btrfs_fiemap,
10656 .get_acl = btrfs_get_acl,
10657 .set_acl = btrfs_set_acl,
10658 .update_time = btrfs_update_time,
10660 static const struct inode_operations btrfs_special_inode_operations = {
10661 .getattr = btrfs_getattr,
10662 .setattr = btrfs_setattr,
10663 .permission = btrfs_permission,
10664 .setxattr = generic_setxattr,
10665 .getxattr = generic_getxattr,
10666 .listxattr = btrfs_listxattr,
10667 .removexattr = generic_removexattr,
10668 .get_acl = btrfs_get_acl,
10669 .set_acl = btrfs_set_acl,
10670 .update_time = btrfs_update_time,
10672 static const struct inode_operations btrfs_symlink_inode_operations = {
10673 .readlink = generic_readlink,
10674 .get_link = page_get_link,
10675 .getattr = btrfs_getattr,
10676 .setattr = btrfs_setattr,
10677 .permission = btrfs_permission,
10678 .setxattr = generic_setxattr,
10679 .getxattr = generic_getxattr,
10680 .listxattr = btrfs_listxattr,
10681 .removexattr = generic_removexattr,
10682 .update_time = btrfs_update_time,
10685 const struct dentry_operations btrfs_dentry_operations = {
10686 .d_delete = btrfs_dentry_delete,
10687 .d_release = btrfs_dentry_release,