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 |
575 * we aren't doing an inline extent round the compressed size
576 * up to a block size boundary so the allocator does sane
579 total_compressed = ALIGN(total_compressed, blocksize);
582 * one last check to make sure the compression is really a
583 * win, compare the page count read with the blocks on disk
585 total_in = ALIGN(total_in, PAGE_SIZE);
586 if (total_compressed >= total_in) {
589 num_bytes = total_in;
593 * The async work queues will take care of doing actual
594 * allocation on disk for these compressed pages, and
595 * will submit them to the elevator.
597 add_async_extent(async_cow, start, num_bytes,
598 total_compressed, pages, nr_pages_ret,
601 if (start + num_bytes < end) {
612 * the compression code ran but failed to make things smaller,
613 * free any pages it allocated and our page pointer array
615 for (i = 0; i < nr_pages_ret; i++) {
616 WARN_ON(pages[i]->mapping);
621 total_compressed = 0;
624 /* flag the file so we don't compress in the future */
625 if (!btrfs_test_opt(root->fs_info, FORCE_COMPRESS) &&
626 !(BTRFS_I(inode)->force_compress)) {
627 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
630 cleanup_and_bail_uncompressed:
632 * No compression, but we still need to write the pages in the file
633 * we've been given so far. redirty the locked page if it corresponds
634 * to our extent and set things up for the async work queue to run
635 * cow_file_range to do the normal delalloc dance.
637 if (page_offset(locked_page) >= start &&
638 page_offset(locked_page) <= end)
639 __set_page_dirty_nobuffers(locked_page);
640 /* unlocked later on in the async handlers */
643 extent_range_redirty_for_io(inode, start, end);
644 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
645 BTRFS_COMPRESS_NONE);
651 for (i = 0; i < nr_pages_ret; i++) {
652 WARN_ON(pages[i]->mapping);
658 static void free_async_extent_pages(struct async_extent *async_extent)
662 if (!async_extent->pages)
665 for (i = 0; i < async_extent->nr_pages; i++) {
666 WARN_ON(async_extent->pages[i]->mapping);
667 put_page(async_extent->pages[i]);
669 kfree(async_extent->pages);
670 async_extent->nr_pages = 0;
671 async_extent->pages = NULL;
675 * phase two of compressed writeback. This is the ordered portion
676 * of the code, which only gets called in the order the work was
677 * queued. We walk all the async extents created by compress_file_range
678 * and send them down to the disk.
680 static noinline void submit_compressed_extents(struct inode *inode,
681 struct async_cow *async_cow)
683 struct async_extent *async_extent;
685 struct btrfs_key ins;
686 struct extent_map *em;
687 struct btrfs_root *root = BTRFS_I(inode)->root;
688 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
689 struct extent_io_tree *io_tree;
693 while (!list_empty(&async_cow->extents)) {
694 async_extent = list_entry(async_cow->extents.next,
695 struct async_extent, list);
696 list_del(&async_extent->list);
698 io_tree = &BTRFS_I(inode)->io_tree;
701 /* did the compression code fall back to uncompressed IO? */
702 if (!async_extent->pages) {
703 int page_started = 0;
704 unsigned long nr_written = 0;
706 lock_extent(io_tree, async_extent->start,
707 async_extent->start +
708 async_extent->ram_size - 1);
710 /* allocate blocks */
711 ret = cow_file_range(inode, async_cow->locked_page,
713 async_extent->start +
714 async_extent->ram_size - 1,
715 async_extent->start +
716 async_extent->ram_size - 1,
717 &page_started, &nr_written, 0,
723 * if page_started, cow_file_range inserted an
724 * inline extent and took care of all the unlocking
725 * and IO for us. Otherwise, we need to submit
726 * all those pages down to the drive.
728 if (!page_started && !ret)
729 extent_write_locked_range(io_tree,
730 inode, async_extent->start,
731 async_extent->start +
732 async_extent->ram_size - 1,
736 unlock_page(async_cow->locked_page);
742 lock_extent(io_tree, async_extent->start,
743 async_extent->start + async_extent->ram_size - 1);
745 ret = btrfs_reserve_extent(root,
746 async_extent->compressed_size,
747 async_extent->compressed_size,
748 0, alloc_hint, &ins, 1, 1);
750 free_async_extent_pages(async_extent);
752 if (ret == -ENOSPC) {
753 unlock_extent(io_tree, async_extent->start,
754 async_extent->start +
755 async_extent->ram_size - 1);
758 * we need to redirty the pages if we decide to
759 * fallback to uncompressed IO, otherwise we
760 * will not submit these pages down to lower
763 extent_range_redirty_for_io(inode,
765 async_extent->start +
766 async_extent->ram_size - 1);
773 * here we're doing allocation and writeback of the
776 btrfs_drop_extent_cache(inode, async_extent->start,
777 async_extent->start +
778 async_extent->ram_size - 1, 0);
780 em = alloc_extent_map();
783 goto out_free_reserve;
785 em->start = async_extent->start;
786 em->len = async_extent->ram_size;
787 em->orig_start = em->start;
788 em->mod_start = em->start;
789 em->mod_len = em->len;
791 em->block_start = ins.objectid;
792 em->block_len = ins.offset;
793 em->orig_block_len = ins.offset;
794 em->ram_bytes = async_extent->ram_size;
795 em->bdev = root->fs_info->fs_devices->latest_bdev;
796 em->compress_type = async_extent->compress_type;
797 set_bit(EXTENT_FLAG_PINNED, &em->flags);
798 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
802 write_lock(&em_tree->lock);
803 ret = add_extent_mapping(em_tree, em, 1);
804 write_unlock(&em_tree->lock);
805 if (ret != -EEXIST) {
809 btrfs_drop_extent_cache(inode, async_extent->start,
810 async_extent->start +
811 async_extent->ram_size - 1, 0);
815 goto out_free_reserve;
817 ret = btrfs_add_ordered_extent_compress(inode,
820 async_extent->ram_size,
822 BTRFS_ORDERED_COMPRESSED,
823 async_extent->compress_type);
825 btrfs_drop_extent_cache(inode, async_extent->start,
826 async_extent->start +
827 async_extent->ram_size - 1, 0);
828 goto out_free_reserve;
830 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
833 * clear dirty, set writeback and unlock the pages.
835 extent_clear_unlock_delalloc(inode, async_extent->start,
836 async_extent->start +
837 async_extent->ram_size - 1,
838 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
839 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
841 ret = btrfs_submit_compressed_write(inode,
843 async_extent->ram_size,
845 ins.offset, async_extent->pages,
846 async_extent->nr_pages);
848 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
849 struct page *p = async_extent->pages[0];
850 const u64 start = async_extent->start;
851 const u64 end = start + async_extent->ram_size - 1;
853 p->mapping = inode->i_mapping;
854 tree->ops->writepage_end_io_hook(p, start, end,
857 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
860 free_async_extent_pages(async_extent);
862 alloc_hint = ins.objectid + ins.offset;
868 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
869 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
871 extent_clear_unlock_delalloc(inode, async_extent->start,
872 async_extent->start +
873 async_extent->ram_size - 1,
874 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
875 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
876 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
877 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
879 free_async_extent_pages(async_extent);
884 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
887 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
888 struct extent_map *em;
891 read_lock(&em_tree->lock);
892 em = search_extent_mapping(em_tree, start, num_bytes);
895 * if block start isn't an actual block number then find the
896 * first block in this inode and use that as a hint. If that
897 * block is also bogus then just don't worry about it.
899 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
901 em = search_extent_mapping(em_tree, 0, 0);
902 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
903 alloc_hint = em->block_start;
907 alloc_hint = em->block_start;
911 read_unlock(&em_tree->lock);
917 * when extent_io.c finds a delayed allocation range in the file,
918 * the call backs end up in this code. The basic idea is to
919 * allocate extents on disk for the range, and create ordered data structs
920 * in ram to track those extents.
922 * locked_page is the page that writepage had locked already. We use
923 * it to make sure we don't do extra locks or unlocks.
925 * *page_started is set to one if we unlock locked_page and do everything
926 * required to start IO on it. It may be clean and already done with
929 static noinline int cow_file_range(struct inode *inode,
930 struct page *locked_page,
931 u64 start, u64 end, u64 delalloc_end,
932 int *page_started, unsigned long *nr_written,
933 int unlock, struct btrfs_dedupe_hash *hash)
935 struct btrfs_root *root = BTRFS_I(inode)->root;
938 unsigned long ram_size;
941 u64 blocksize = root->sectorsize;
942 struct btrfs_key ins;
943 struct extent_map *em;
944 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
947 if (btrfs_is_free_space_inode(inode)) {
953 num_bytes = ALIGN(end - start + 1, blocksize);
954 num_bytes = max(blocksize, num_bytes);
955 disk_num_bytes = num_bytes;
957 /* if this is a small write inside eof, kick off defrag */
958 if (num_bytes < SZ_64K &&
959 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
960 btrfs_add_inode_defrag(NULL, inode);
963 /* lets try to make an inline extent */
964 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
967 extent_clear_unlock_delalloc(inode, start, end, NULL,
968 EXTENT_LOCKED | EXTENT_DELALLOC |
969 EXTENT_DEFRAG, PAGE_UNLOCK |
970 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
973 *nr_written = *nr_written +
974 (end - start + PAGE_SIZE) / PAGE_SIZE;
977 } else if (ret < 0) {
982 BUG_ON(disk_num_bytes >
983 btrfs_super_total_bytes(root->fs_info->super_copy));
985 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
986 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
988 while (disk_num_bytes > 0) {
991 cur_alloc_size = disk_num_bytes;
992 ret = btrfs_reserve_extent(root, cur_alloc_size,
993 root->sectorsize, 0, alloc_hint,
998 em = alloc_extent_map();
1004 em->orig_start = em->start;
1005 ram_size = ins.offset;
1006 em->len = ins.offset;
1007 em->mod_start = em->start;
1008 em->mod_len = em->len;
1010 em->block_start = ins.objectid;
1011 em->block_len = ins.offset;
1012 em->orig_block_len = ins.offset;
1013 em->ram_bytes = ram_size;
1014 em->bdev = root->fs_info->fs_devices->latest_bdev;
1015 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1016 em->generation = -1;
1019 write_lock(&em_tree->lock);
1020 ret = add_extent_mapping(em_tree, em, 1);
1021 write_unlock(&em_tree->lock);
1022 if (ret != -EEXIST) {
1023 free_extent_map(em);
1026 btrfs_drop_extent_cache(inode, start,
1027 start + ram_size - 1, 0);
1032 cur_alloc_size = ins.offset;
1033 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1034 ram_size, cur_alloc_size, 0);
1036 goto out_drop_extent_cache;
1038 if (root->root_key.objectid ==
1039 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1040 ret = btrfs_reloc_clone_csums(inode, start,
1043 goto out_drop_extent_cache;
1046 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
1048 if (disk_num_bytes < cur_alloc_size)
1051 /* we're not doing compressed IO, don't unlock the first
1052 * page (which the caller expects to stay locked), don't
1053 * clear any dirty bits and don't set any writeback bits
1055 * Do set the Private2 bit so we know this page was properly
1056 * setup for writepage
1058 op = unlock ? PAGE_UNLOCK : 0;
1059 op |= PAGE_SET_PRIVATE2;
1061 extent_clear_unlock_delalloc(inode, start,
1062 start + ram_size - 1, locked_page,
1063 EXTENT_LOCKED | EXTENT_DELALLOC,
1065 disk_num_bytes -= cur_alloc_size;
1066 num_bytes -= cur_alloc_size;
1067 alloc_hint = ins.objectid + ins.offset;
1068 start += cur_alloc_size;
1073 out_drop_extent_cache:
1074 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1076 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
1077 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1079 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1080 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1081 EXTENT_DELALLOC | EXTENT_DEFRAG,
1082 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1083 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1088 * work queue call back to started compression on a file and pages
1090 static noinline void async_cow_start(struct btrfs_work *work)
1092 struct async_cow *async_cow;
1094 async_cow = container_of(work, struct async_cow, work);
1096 compress_file_range(async_cow->inode, async_cow->locked_page,
1097 async_cow->start, async_cow->end, async_cow,
1099 if (num_added == 0) {
1100 btrfs_add_delayed_iput(async_cow->inode);
1101 async_cow->inode = NULL;
1106 * work queue call back to submit previously compressed pages
1108 static noinline void async_cow_submit(struct btrfs_work *work)
1110 struct async_cow *async_cow;
1111 struct btrfs_root *root;
1112 unsigned long nr_pages;
1114 async_cow = container_of(work, struct async_cow, work);
1116 root = async_cow->root;
1117 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1121 * atomic_sub_return implies a barrier for waitqueue_active
1123 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1125 waitqueue_active(&root->fs_info->async_submit_wait))
1126 wake_up(&root->fs_info->async_submit_wait);
1128 if (async_cow->inode)
1129 submit_compressed_extents(async_cow->inode, async_cow);
1132 static noinline void async_cow_free(struct btrfs_work *work)
1134 struct async_cow *async_cow;
1135 async_cow = container_of(work, struct async_cow, work);
1136 if (async_cow->inode)
1137 btrfs_add_delayed_iput(async_cow->inode);
1141 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1142 u64 start, u64 end, int *page_started,
1143 unsigned long *nr_written)
1145 struct async_cow *async_cow;
1146 struct btrfs_root *root = BTRFS_I(inode)->root;
1147 unsigned long nr_pages;
1149 int limit = 10 * SZ_1M;
1151 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1152 1, 0, NULL, GFP_NOFS);
1153 while (start < end) {
1154 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1155 BUG_ON(!async_cow); /* -ENOMEM */
1156 async_cow->inode = igrab(inode);
1157 async_cow->root = root;
1158 async_cow->locked_page = locked_page;
1159 async_cow->start = start;
1161 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1162 !btrfs_test_opt(root->fs_info, FORCE_COMPRESS))
1165 cur_end = min(end, start + SZ_512K - 1);
1167 async_cow->end = cur_end;
1168 INIT_LIST_HEAD(&async_cow->extents);
1170 btrfs_init_work(&async_cow->work,
1171 btrfs_delalloc_helper,
1172 async_cow_start, async_cow_submit,
1175 nr_pages = (cur_end - start + PAGE_SIZE) >>
1177 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1179 btrfs_queue_work(root->fs_info->delalloc_workers,
1182 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1183 wait_event(root->fs_info->async_submit_wait,
1184 (atomic_read(&root->fs_info->async_delalloc_pages) <
1188 while (atomic_read(&root->fs_info->async_submit_draining) &&
1189 atomic_read(&root->fs_info->async_delalloc_pages)) {
1190 wait_event(root->fs_info->async_submit_wait,
1191 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1195 *nr_written += nr_pages;
1196 start = cur_end + 1;
1202 static noinline int csum_exist_in_range(struct btrfs_root *root,
1203 u64 bytenr, u64 num_bytes)
1206 struct btrfs_ordered_sum *sums;
1209 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1210 bytenr + num_bytes - 1, &list, 0);
1211 if (ret == 0 && list_empty(&list))
1214 while (!list_empty(&list)) {
1215 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1216 list_del(&sums->list);
1223 * when nowcow writeback call back. This checks for snapshots or COW copies
1224 * of the extents that exist in the file, and COWs the file as required.
1226 * If no cow copies or snapshots exist, we write directly to the existing
1229 static noinline int run_delalloc_nocow(struct inode *inode,
1230 struct page *locked_page,
1231 u64 start, u64 end, int *page_started, int force,
1232 unsigned long *nr_written)
1234 struct btrfs_root *root = BTRFS_I(inode)->root;
1235 struct btrfs_trans_handle *trans;
1236 struct extent_buffer *leaf;
1237 struct btrfs_path *path;
1238 struct btrfs_file_extent_item *fi;
1239 struct btrfs_key found_key;
1254 u64 ino = btrfs_ino(inode);
1256 path = btrfs_alloc_path();
1258 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1259 EXTENT_LOCKED | EXTENT_DELALLOC |
1260 EXTENT_DO_ACCOUNTING |
1261 EXTENT_DEFRAG, PAGE_UNLOCK |
1263 PAGE_SET_WRITEBACK |
1264 PAGE_END_WRITEBACK);
1268 nolock = btrfs_is_free_space_inode(inode);
1271 trans = btrfs_join_transaction_nolock(root);
1273 trans = btrfs_join_transaction(root);
1275 if (IS_ERR(trans)) {
1276 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1277 EXTENT_LOCKED | EXTENT_DELALLOC |
1278 EXTENT_DO_ACCOUNTING |
1279 EXTENT_DEFRAG, PAGE_UNLOCK |
1281 PAGE_SET_WRITEBACK |
1282 PAGE_END_WRITEBACK);
1283 btrfs_free_path(path);
1284 return PTR_ERR(trans);
1287 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1289 cow_start = (u64)-1;
1292 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1296 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1297 leaf = path->nodes[0];
1298 btrfs_item_key_to_cpu(leaf, &found_key,
1299 path->slots[0] - 1);
1300 if (found_key.objectid == ino &&
1301 found_key.type == BTRFS_EXTENT_DATA_KEY)
1306 leaf = path->nodes[0];
1307 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1308 ret = btrfs_next_leaf(root, path);
1313 leaf = path->nodes[0];
1319 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1321 if (found_key.objectid > ino)
1323 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1324 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1328 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1329 found_key.offset > end)
1332 if (found_key.offset > cur_offset) {
1333 extent_end = found_key.offset;
1338 fi = btrfs_item_ptr(leaf, path->slots[0],
1339 struct btrfs_file_extent_item);
1340 extent_type = btrfs_file_extent_type(leaf, fi);
1342 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1343 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1344 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1345 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1346 extent_offset = btrfs_file_extent_offset(leaf, fi);
1347 extent_end = found_key.offset +
1348 btrfs_file_extent_num_bytes(leaf, fi);
1350 btrfs_file_extent_disk_num_bytes(leaf, fi);
1351 if (extent_end <= start) {
1355 if (disk_bytenr == 0)
1357 if (btrfs_file_extent_compression(leaf, fi) ||
1358 btrfs_file_extent_encryption(leaf, fi) ||
1359 btrfs_file_extent_other_encoding(leaf, fi))
1361 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1363 if (btrfs_extent_readonly(root, disk_bytenr))
1365 if (btrfs_cross_ref_exist(trans, root, ino,
1367 extent_offset, disk_bytenr))
1369 disk_bytenr += extent_offset;
1370 disk_bytenr += cur_offset - found_key.offset;
1371 num_bytes = min(end + 1, extent_end) - cur_offset;
1373 * if there are pending snapshots for this root,
1374 * we fall into common COW way.
1377 err = btrfs_start_write_no_snapshoting(root);
1382 * force cow if csum exists in the range.
1383 * this ensure that csum for a given extent are
1384 * either valid or do not exist.
1386 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1388 if (!btrfs_inc_nocow_writers(root->fs_info,
1392 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1393 extent_end = found_key.offset +
1394 btrfs_file_extent_inline_len(leaf,
1395 path->slots[0], fi);
1396 extent_end = ALIGN(extent_end, root->sectorsize);
1401 if (extent_end <= start) {
1403 if (!nolock && nocow)
1404 btrfs_end_write_no_snapshoting(root);
1406 btrfs_dec_nocow_writers(root->fs_info,
1411 if (cow_start == (u64)-1)
1412 cow_start = cur_offset;
1413 cur_offset = extent_end;
1414 if (cur_offset > end)
1420 btrfs_release_path(path);
1421 if (cow_start != (u64)-1) {
1422 ret = cow_file_range(inode, locked_page,
1423 cow_start, found_key.offset - 1,
1424 end, page_started, nr_written, 1,
1427 if (!nolock && nocow)
1428 btrfs_end_write_no_snapshoting(root);
1430 btrfs_dec_nocow_writers(root->fs_info,
1434 cow_start = (u64)-1;
1437 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1438 struct extent_map *em;
1439 struct extent_map_tree *em_tree;
1440 em_tree = &BTRFS_I(inode)->extent_tree;
1441 em = alloc_extent_map();
1442 BUG_ON(!em); /* -ENOMEM */
1443 em->start = cur_offset;
1444 em->orig_start = found_key.offset - extent_offset;
1445 em->len = num_bytes;
1446 em->block_len = num_bytes;
1447 em->block_start = disk_bytenr;
1448 em->orig_block_len = disk_num_bytes;
1449 em->ram_bytes = ram_bytes;
1450 em->bdev = root->fs_info->fs_devices->latest_bdev;
1451 em->mod_start = em->start;
1452 em->mod_len = em->len;
1453 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1454 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1455 em->generation = -1;
1457 write_lock(&em_tree->lock);
1458 ret = add_extent_mapping(em_tree, em, 1);
1459 write_unlock(&em_tree->lock);
1460 if (ret != -EEXIST) {
1461 free_extent_map(em);
1464 btrfs_drop_extent_cache(inode, em->start,
1465 em->start + em->len - 1, 0);
1467 type = BTRFS_ORDERED_PREALLOC;
1469 type = BTRFS_ORDERED_NOCOW;
1472 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1473 num_bytes, num_bytes, type);
1475 btrfs_dec_nocow_writers(root->fs_info, disk_bytenr);
1476 BUG_ON(ret); /* -ENOMEM */
1478 if (root->root_key.objectid ==
1479 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1480 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1483 if (!nolock && nocow)
1484 btrfs_end_write_no_snapshoting(root);
1489 extent_clear_unlock_delalloc(inode, cur_offset,
1490 cur_offset + num_bytes - 1,
1491 locked_page, EXTENT_LOCKED |
1492 EXTENT_DELALLOC, PAGE_UNLOCK |
1494 if (!nolock && nocow)
1495 btrfs_end_write_no_snapshoting(root);
1496 cur_offset = extent_end;
1497 if (cur_offset > end)
1500 btrfs_release_path(path);
1502 if (cur_offset <= end && cow_start == (u64)-1) {
1503 cow_start = cur_offset;
1507 if (cow_start != (u64)-1) {
1508 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1509 page_started, nr_written, 1, NULL);
1515 err = btrfs_end_transaction(trans, root);
1519 if (ret && cur_offset < end)
1520 extent_clear_unlock_delalloc(inode, cur_offset, end,
1521 locked_page, EXTENT_LOCKED |
1522 EXTENT_DELALLOC | EXTENT_DEFRAG |
1523 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1525 PAGE_SET_WRITEBACK |
1526 PAGE_END_WRITEBACK);
1527 btrfs_free_path(path);
1531 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1534 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1535 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1539 * @defrag_bytes is a hint value, no spinlock held here,
1540 * if is not zero, it means the file is defragging.
1541 * Force cow if given extent needs to be defragged.
1543 if (BTRFS_I(inode)->defrag_bytes &&
1544 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1545 EXTENT_DEFRAG, 0, NULL))
1552 * extent_io.c call back to do delayed allocation processing
1554 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1555 u64 start, u64 end, int *page_started,
1556 unsigned long *nr_written)
1559 int force_cow = need_force_cow(inode, start, end);
1561 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1562 ret = run_delalloc_nocow(inode, locked_page, start, end,
1563 page_started, 1, nr_written);
1564 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1565 ret = run_delalloc_nocow(inode, locked_page, start, end,
1566 page_started, 0, nr_written);
1567 } else if (!inode_need_compress(inode)) {
1568 ret = cow_file_range(inode, locked_page, start, end, end,
1569 page_started, nr_written, 1, NULL);
1571 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1572 &BTRFS_I(inode)->runtime_flags);
1573 ret = cow_file_range_async(inode, locked_page, start, end,
1574 page_started, nr_written);
1579 static void btrfs_split_extent_hook(struct inode *inode,
1580 struct extent_state *orig, u64 split)
1584 /* not delalloc, ignore it */
1585 if (!(orig->state & EXTENT_DELALLOC))
1588 size = orig->end - orig->start + 1;
1589 if (size > BTRFS_MAX_EXTENT_SIZE) {
1594 * See the explanation in btrfs_merge_extent_hook, the same
1595 * applies here, just in reverse.
1597 new_size = orig->end - split + 1;
1598 num_extents = div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1599 BTRFS_MAX_EXTENT_SIZE);
1600 new_size = split - orig->start;
1601 num_extents += div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1602 BTRFS_MAX_EXTENT_SIZE);
1603 if (div64_u64(size + BTRFS_MAX_EXTENT_SIZE - 1,
1604 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1608 spin_lock(&BTRFS_I(inode)->lock);
1609 BTRFS_I(inode)->outstanding_extents++;
1610 spin_unlock(&BTRFS_I(inode)->lock);
1614 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1615 * extents so we can keep track of new extents that are just merged onto old
1616 * extents, such as when we are doing sequential writes, so we can properly
1617 * account for the metadata space we'll need.
1619 static void btrfs_merge_extent_hook(struct inode *inode,
1620 struct extent_state *new,
1621 struct extent_state *other)
1623 u64 new_size, old_size;
1626 /* not delalloc, ignore it */
1627 if (!(other->state & EXTENT_DELALLOC))
1630 if (new->start > other->start)
1631 new_size = new->end - other->start + 1;
1633 new_size = other->end - new->start + 1;
1635 /* we're not bigger than the max, unreserve the space and go */
1636 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1637 spin_lock(&BTRFS_I(inode)->lock);
1638 BTRFS_I(inode)->outstanding_extents--;
1639 spin_unlock(&BTRFS_I(inode)->lock);
1644 * We have to add up either side to figure out how many extents were
1645 * accounted for before we merged into one big extent. If the number of
1646 * extents we accounted for is <= the amount we need for the new range
1647 * then we can return, otherwise drop. Think of it like this
1651 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1652 * need 2 outstanding extents, on one side we have 1 and the other side
1653 * we have 1 so they are == and we can return. But in this case
1655 * [MAX_SIZE+4k][MAX_SIZE+4k]
1657 * Each range on their own accounts for 2 extents, but merged together
1658 * they are only 3 extents worth of accounting, so we need to drop in
1661 old_size = other->end - other->start + 1;
1662 num_extents = div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1663 BTRFS_MAX_EXTENT_SIZE);
1664 old_size = new->end - new->start + 1;
1665 num_extents += div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1666 BTRFS_MAX_EXTENT_SIZE);
1668 if (div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1669 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1672 spin_lock(&BTRFS_I(inode)->lock);
1673 BTRFS_I(inode)->outstanding_extents--;
1674 spin_unlock(&BTRFS_I(inode)->lock);
1677 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1678 struct inode *inode)
1680 spin_lock(&root->delalloc_lock);
1681 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1682 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1683 &root->delalloc_inodes);
1684 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1685 &BTRFS_I(inode)->runtime_flags);
1686 root->nr_delalloc_inodes++;
1687 if (root->nr_delalloc_inodes == 1) {
1688 spin_lock(&root->fs_info->delalloc_root_lock);
1689 BUG_ON(!list_empty(&root->delalloc_root));
1690 list_add_tail(&root->delalloc_root,
1691 &root->fs_info->delalloc_roots);
1692 spin_unlock(&root->fs_info->delalloc_root_lock);
1695 spin_unlock(&root->delalloc_lock);
1698 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1699 struct inode *inode)
1701 spin_lock(&root->delalloc_lock);
1702 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1703 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1704 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1705 &BTRFS_I(inode)->runtime_flags);
1706 root->nr_delalloc_inodes--;
1707 if (!root->nr_delalloc_inodes) {
1708 spin_lock(&root->fs_info->delalloc_root_lock);
1709 BUG_ON(list_empty(&root->delalloc_root));
1710 list_del_init(&root->delalloc_root);
1711 spin_unlock(&root->fs_info->delalloc_root_lock);
1714 spin_unlock(&root->delalloc_lock);
1718 * extent_io.c set_bit_hook, used to track delayed allocation
1719 * bytes in this file, and to maintain the list of inodes that
1720 * have pending delalloc work to be done.
1722 static void btrfs_set_bit_hook(struct inode *inode,
1723 struct extent_state *state, unsigned *bits)
1726 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1729 * set_bit and clear bit hooks normally require _irqsave/restore
1730 * but in this case, we are only testing for the DELALLOC
1731 * bit, which is only set or cleared with irqs on
1733 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1734 struct btrfs_root *root = BTRFS_I(inode)->root;
1735 u64 len = state->end + 1 - state->start;
1736 bool do_list = !btrfs_is_free_space_inode(inode);
1738 if (*bits & EXTENT_FIRST_DELALLOC) {
1739 *bits &= ~EXTENT_FIRST_DELALLOC;
1741 spin_lock(&BTRFS_I(inode)->lock);
1742 BTRFS_I(inode)->outstanding_extents++;
1743 spin_unlock(&BTRFS_I(inode)->lock);
1746 /* For sanity tests */
1747 if (btrfs_is_testing(root->fs_info))
1750 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1751 root->fs_info->delalloc_batch);
1752 spin_lock(&BTRFS_I(inode)->lock);
1753 BTRFS_I(inode)->delalloc_bytes += len;
1754 if (*bits & EXTENT_DEFRAG)
1755 BTRFS_I(inode)->defrag_bytes += len;
1756 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1757 &BTRFS_I(inode)->runtime_flags))
1758 btrfs_add_delalloc_inodes(root, inode);
1759 spin_unlock(&BTRFS_I(inode)->lock);
1764 * extent_io.c clear_bit_hook, see set_bit_hook for why
1766 static void btrfs_clear_bit_hook(struct inode *inode,
1767 struct extent_state *state,
1770 u64 len = state->end + 1 - state->start;
1771 u64 num_extents = div64_u64(len + BTRFS_MAX_EXTENT_SIZE -1,
1772 BTRFS_MAX_EXTENT_SIZE);
1774 spin_lock(&BTRFS_I(inode)->lock);
1775 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1776 BTRFS_I(inode)->defrag_bytes -= len;
1777 spin_unlock(&BTRFS_I(inode)->lock);
1780 * set_bit and clear bit hooks normally require _irqsave/restore
1781 * but in this case, we are only testing for the DELALLOC
1782 * bit, which is only set or cleared with irqs on
1784 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1785 struct btrfs_root *root = BTRFS_I(inode)->root;
1786 bool do_list = !btrfs_is_free_space_inode(inode);
1788 if (*bits & EXTENT_FIRST_DELALLOC) {
1789 *bits &= ~EXTENT_FIRST_DELALLOC;
1790 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1791 spin_lock(&BTRFS_I(inode)->lock);
1792 BTRFS_I(inode)->outstanding_extents -= num_extents;
1793 spin_unlock(&BTRFS_I(inode)->lock);
1797 * We don't reserve metadata space for space cache inodes so we
1798 * don't need to call dellalloc_release_metadata if there is an
1801 if (*bits & EXTENT_DO_ACCOUNTING &&
1802 root != root->fs_info->tree_root)
1803 btrfs_delalloc_release_metadata(inode, len);
1805 /* For sanity tests. */
1806 if (btrfs_is_testing(root->fs_info))
1809 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1810 && do_list && !(state->state & EXTENT_NORESERVE))
1811 btrfs_free_reserved_data_space_noquota(inode,
1814 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1815 root->fs_info->delalloc_batch);
1816 spin_lock(&BTRFS_I(inode)->lock);
1817 BTRFS_I(inode)->delalloc_bytes -= len;
1818 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1819 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1820 &BTRFS_I(inode)->runtime_flags))
1821 btrfs_del_delalloc_inode(root, inode);
1822 spin_unlock(&BTRFS_I(inode)->lock);
1827 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1828 * we don't create bios that span stripes or chunks
1830 * return 1 if page cannot be merged to bio
1831 * return 0 if page can be merged to bio
1832 * return error otherwise
1834 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1835 size_t size, struct bio *bio,
1836 unsigned long bio_flags)
1838 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1839 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1844 if (bio_flags & EXTENT_BIO_COMPRESSED)
1847 length = bio->bi_iter.bi_size;
1848 map_length = length;
1849 ret = btrfs_map_block(root->fs_info, bio_op(bio), logical,
1850 &map_length, NULL, 0);
1853 if (map_length < length + size)
1859 * in order to insert checksums into the metadata in large chunks,
1860 * we wait until bio submission time. All the pages in the bio are
1861 * checksummed and sums are attached onto the ordered extent record.
1863 * At IO completion time the cums attached on the ordered extent record
1864 * are inserted into the btree
1866 static int __btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
1867 int mirror_num, unsigned long bio_flags,
1870 struct btrfs_root *root = BTRFS_I(inode)->root;
1873 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1874 BUG_ON(ret); /* -ENOMEM */
1879 * in order to insert checksums into the metadata in large chunks,
1880 * we wait until bio submission time. All the pages in the bio are
1881 * checksummed and sums are attached onto the ordered extent record.
1883 * At IO completion time the cums attached on the ordered extent record
1884 * are inserted into the btree
1886 static int __btrfs_submit_bio_done(struct inode *inode, struct bio *bio,
1887 int mirror_num, unsigned long bio_flags,
1890 struct btrfs_root *root = BTRFS_I(inode)->root;
1893 ret = btrfs_map_bio(root, bio, mirror_num, 1);
1895 bio->bi_error = ret;
1902 * extent_io.c submission hook. This does the right thing for csum calculation
1903 * on write, or reading the csums from the tree before a read
1905 static int btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
1906 int mirror_num, unsigned long bio_flags,
1909 struct btrfs_root *root = BTRFS_I(inode)->root;
1910 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1913 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1915 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1917 if (btrfs_is_free_space_inode(inode))
1918 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1920 if (bio_op(bio) != REQ_OP_WRITE) {
1921 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1925 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1926 ret = btrfs_submit_compressed_read(inode, bio,
1930 } else if (!skip_sum) {
1931 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1936 } else if (async && !skip_sum) {
1937 /* csum items have already been cloned */
1938 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1940 /* we're doing a write, do the async checksumming */
1941 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1942 inode, bio, mirror_num,
1943 bio_flags, bio_offset,
1944 __btrfs_submit_bio_start,
1945 __btrfs_submit_bio_done);
1947 } else if (!skip_sum) {
1948 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1954 ret = btrfs_map_bio(root, bio, mirror_num, 0);
1958 bio->bi_error = ret;
1965 * given a list of ordered sums record them in the inode. This happens
1966 * at IO completion time based on sums calculated at bio submission time.
1968 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1969 struct inode *inode, u64 file_offset,
1970 struct list_head *list)
1972 struct btrfs_ordered_sum *sum;
1974 list_for_each_entry(sum, list, list) {
1975 trans->adding_csums = 1;
1976 btrfs_csum_file_blocks(trans,
1977 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1978 trans->adding_csums = 0;
1983 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1984 struct extent_state **cached_state)
1986 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
1987 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1991 /* see btrfs_writepage_start_hook for details on why this is required */
1992 struct btrfs_writepage_fixup {
1994 struct btrfs_work work;
1997 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1999 struct btrfs_writepage_fixup *fixup;
2000 struct btrfs_ordered_extent *ordered;
2001 struct extent_state *cached_state = NULL;
2003 struct inode *inode;
2008 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2012 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2013 ClearPageChecked(page);
2017 inode = page->mapping->host;
2018 page_start = page_offset(page);
2019 page_end = page_offset(page) + PAGE_SIZE - 1;
2021 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2024 /* already ordered? We're done */
2025 if (PagePrivate2(page))
2028 ordered = btrfs_lookup_ordered_range(inode, page_start,
2031 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2032 page_end, &cached_state, GFP_NOFS);
2034 btrfs_start_ordered_extent(inode, ordered, 1);
2035 btrfs_put_ordered_extent(ordered);
2039 ret = btrfs_delalloc_reserve_space(inode, page_start,
2042 mapping_set_error(page->mapping, ret);
2043 end_extent_writepage(page, ret, page_start, page_end);
2044 ClearPageChecked(page);
2048 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
2049 ClearPageChecked(page);
2050 set_page_dirty(page);
2052 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2053 &cached_state, GFP_NOFS);
2061 * There are a few paths in the higher layers of the kernel that directly
2062 * set the page dirty bit without asking the filesystem if it is a
2063 * good idea. This causes problems because we want to make sure COW
2064 * properly happens and the data=ordered rules are followed.
2066 * In our case any range that doesn't have the ORDERED bit set
2067 * hasn't been properly setup for IO. We kick off an async process
2068 * to fix it up. The async helper will wait for ordered extents, set
2069 * the delalloc bit and make it safe to write the page.
2071 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2073 struct inode *inode = page->mapping->host;
2074 struct btrfs_writepage_fixup *fixup;
2075 struct btrfs_root *root = BTRFS_I(inode)->root;
2077 /* this page is properly in the ordered list */
2078 if (TestClearPagePrivate2(page))
2081 if (PageChecked(page))
2084 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2088 SetPageChecked(page);
2090 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2091 btrfs_writepage_fixup_worker, NULL, NULL);
2093 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
2097 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2098 struct inode *inode, u64 file_pos,
2099 u64 disk_bytenr, u64 disk_num_bytes,
2100 u64 num_bytes, u64 ram_bytes,
2101 u8 compression, u8 encryption,
2102 u16 other_encoding, int extent_type)
2104 struct btrfs_root *root = BTRFS_I(inode)->root;
2105 struct btrfs_file_extent_item *fi;
2106 struct btrfs_path *path;
2107 struct extent_buffer *leaf;
2108 struct btrfs_key ins;
2109 int extent_inserted = 0;
2112 path = btrfs_alloc_path();
2117 * we may be replacing one extent in the tree with another.
2118 * The new extent is pinned in the extent map, and we don't want
2119 * to drop it from the cache until it is completely in the btree.
2121 * So, tell btrfs_drop_extents to leave this extent in the cache.
2122 * the caller is expected to unpin it and allow it to be merged
2125 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2126 file_pos + num_bytes, NULL, 0,
2127 1, sizeof(*fi), &extent_inserted);
2131 if (!extent_inserted) {
2132 ins.objectid = btrfs_ino(inode);
2133 ins.offset = file_pos;
2134 ins.type = BTRFS_EXTENT_DATA_KEY;
2136 path->leave_spinning = 1;
2137 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2142 leaf = path->nodes[0];
2143 fi = btrfs_item_ptr(leaf, path->slots[0],
2144 struct btrfs_file_extent_item);
2145 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2146 btrfs_set_file_extent_type(leaf, fi, extent_type);
2147 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2148 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2149 btrfs_set_file_extent_offset(leaf, fi, 0);
2150 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2151 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2152 btrfs_set_file_extent_compression(leaf, fi, compression);
2153 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2154 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2156 btrfs_mark_buffer_dirty(leaf);
2157 btrfs_release_path(path);
2159 inode_add_bytes(inode, num_bytes);
2161 ins.objectid = disk_bytenr;
2162 ins.offset = disk_num_bytes;
2163 ins.type = BTRFS_EXTENT_ITEM_KEY;
2164 ret = btrfs_alloc_reserved_file_extent(trans, root,
2165 root->root_key.objectid,
2166 btrfs_ino(inode), file_pos,
2169 * Release the reserved range from inode dirty range map, as it is
2170 * already moved into delayed_ref_head
2172 btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2174 btrfs_free_path(path);
2179 /* snapshot-aware defrag */
2180 struct sa_defrag_extent_backref {
2181 struct rb_node node;
2182 struct old_sa_defrag_extent *old;
2191 struct old_sa_defrag_extent {
2192 struct list_head list;
2193 struct new_sa_defrag_extent *new;
2202 struct new_sa_defrag_extent {
2203 struct rb_root root;
2204 struct list_head head;
2205 struct btrfs_path *path;
2206 struct inode *inode;
2214 static int backref_comp(struct sa_defrag_extent_backref *b1,
2215 struct sa_defrag_extent_backref *b2)
2217 if (b1->root_id < b2->root_id)
2219 else if (b1->root_id > b2->root_id)
2222 if (b1->inum < b2->inum)
2224 else if (b1->inum > b2->inum)
2227 if (b1->file_pos < b2->file_pos)
2229 else if (b1->file_pos > b2->file_pos)
2233 * [------------------------------] ===> (a range of space)
2234 * |<--->| |<---->| =============> (fs/file tree A)
2235 * |<---------------------------->| ===> (fs/file tree B)
2237 * A range of space can refer to two file extents in one tree while
2238 * refer to only one file extent in another tree.
2240 * So we may process a disk offset more than one time(two extents in A)
2241 * and locate at the same extent(one extent in B), then insert two same
2242 * backrefs(both refer to the extent in B).
2247 static void backref_insert(struct rb_root *root,
2248 struct sa_defrag_extent_backref *backref)
2250 struct rb_node **p = &root->rb_node;
2251 struct rb_node *parent = NULL;
2252 struct sa_defrag_extent_backref *entry;
2257 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2259 ret = backref_comp(backref, entry);
2263 p = &(*p)->rb_right;
2266 rb_link_node(&backref->node, parent, p);
2267 rb_insert_color(&backref->node, root);
2271 * Note the backref might has changed, and in this case we just return 0.
2273 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2276 struct btrfs_file_extent_item *extent;
2277 struct btrfs_fs_info *fs_info;
2278 struct old_sa_defrag_extent *old = ctx;
2279 struct new_sa_defrag_extent *new = old->new;
2280 struct btrfs_path *path = new->path;
2281 struct btrfs_key key;
2282 struct btrfs_root *root;
2283 struct sa_defrag_extent_backref *backref;
2284 struct extent_buffer *leaf;
2285 struct inode *inode = new->inode;
2291 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2292 inum == btrfs_ino(inode))
2295 key.objectid = root_id;
2296 key.type = BTRFS_ROOT_ITEM_KEY;
2297 key.offset = (u64)-1;
2299 fs_info = BTRFS_I(inode)->root->fs_info;
2300 root = btrfs_read_fs_root_no_name(fs_info, &key);
2302 if (PTR_ERR(root) == -ENOENT)
2305 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2306 inum, offset, root_id);
2307 return PTR_ERR(root);
2310 key.objectid = inum;
2311 key.type = BTRFS_EXTENT_DATA_KEY;
2312 if (offset > (u64)-1 << 32)
2315 key.offset = offset;
2317 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2318 if (WARN_ON(ret < 0))
2325 leaf = path->nodes[0];
2326 slot = path->slots[0];
2328 if (slot >= btrfs_header_nritems(leaf)) {
2329 ret = btrfs_next_leaf(root, path);
2332 } else if (ret > 0) {
2341 btrfs_item_key_to_cpu(leaf, &key, slot);
2343 if (key.objectid > inum)
2346 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2349 extent = btrfs_item_ptr(leaf, slot,
2350 struct btrfs_file_extent_item);
2352 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2356 * 'offset' refers to the exact key.offset,
2357 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2358 * (key.offset - extent_offset).
2360 if (key.offset != offset)
2363 extent_offset = btrfs_file_extent_offset(leaf, extent);
2364 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2366 if (extent_offset >= old->extent_offset + old->offset +
2367 old->len || extent_offset + num_bytes <=
2368 old->extent_offset + old->offset)
2373 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2379 backref->root_id = root_id;
2380 backref->inum = inum;
2381 backref->file_pos = offset;
2382 backref->num_bytes = num_bytes;
2383 backref->extent_offset = extent_offset;
2384 backref->generation = btrfs_file_extent_generation(leaf, extent);
2386 backref_insert(&new->root, backref);
2389 btrfs_release_path(path);
2394 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2395 struct new_sa_defrag_extent *new)
2397 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2398 struct old_sa_defrag_extent *old, *tmp;
2403 list_for_each_entry_safe(old, tmp, &new->head, list) {
2404 ret = iterate_inodes_from_logical(old->bytenr +
2405 old->extent_offset, fs_info,
2406 path, record_one_backref,
2408 if (ret < 0 && ret != -ENOENT)
2411 /* no backref to be processed for this extent */
2413 list_del(&old->list);
2418 if (list_empty(&new->head))
2424 static int relink_is_mergable(struct extent_buffer *leaf,
2425 struct btrfs_file_extent_item *fi,
2426 struct new_sa_defrag_extent *new)
2428 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2431 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2434 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2437 if (btrfs_file_extent_encryption(leaf, fi) ||
2438 btrfs_file_extent_other_encoding(leaf, fi))
2445 * Note the backref might has changed, and in this case we just return 0.
2447 static noinline int relink_extent_backref(struct btrfs_path *path,
2448 struct sa_defrag_extent_backref *prev,
2449 struct sa_defrag_extent_backref *backref)
2451 struct btrfs_file_extent_item *extent;
2452 struct btrfs_file_extent_item *item;
2453 struct btrfs_ordered_extent *ordered;
2454 struct btrfs_trans_handle *trans;
2455 struct btrfs_fs_info *fs_info;
2456 struct btrfs_root *root;
2457 struct btrfs_key key;
2458 struct extent_buffer *leaf;
2459 struct old_sa_defrag_extent *old = backref->old;
2460 struct new_sa_defrag_extent *new = old->new;
2461 struct inode *src_inode = new->inode;
2462 struct inode *inode;
2463 struct extent_state *cached = NULL;
2472 if (prev && prev->root_id == backref->root_id &&
2473 prev->inum == backref->inum &&
2474 prev->file_pos + prev->num_bytes == backref->file_pos)
2477 /* step 1: get root */
2478 key.objectid = backref->root_id;
2479 key.type = BTRFS_ROOT_ITEM_KEY;
2480 key.offset = (u64)-1;
2482 fs_info = BTRFS_I(src_inode)->root->fs_info;
2483 index = srcu_read_lock(&fs_info->subvol_srcu);
2485 root = btrfs_read_fs_root_no_name(fs_info, &key);
2487 srcu_read_unlock(&fs_info->subvol_srcu, index);
2488 if (PTR_ERR(root) == -ENOENT)
2490 return PTR_ERR(root);
2493 if (btrfs_root_readonly(root)) {
2494 srcu_read_unlock(&fs_info->subvol_srcu, index);
2498 /* step 2: get inode */
2499 key.objectid = backref->inum;
2500 key.type = BTRFS_INODE_ITEM_KEY;
2503 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2504 if (IS_ERR(inode)) {
2505 srcu_read_unlock(&fs_info->subvol_srcu, index);
2509 srcu_read_unlock(&fs_info->subvol_srcu, index);
2511 /* step 3: relink backref */
2512 lock_start = backref->file_pos;
2513 lock_end = backref->file_pos + backref->num_bytes - 1;
2514 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2517 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2519 btrfs_put_ordered_extent(ordered);
2523 trans = btrfs_join_transaction(root);
2524 if (IS_ERR(trans)) {
2525 ret = PTR_ERR(trans);
2529 key.objectid = backref->inum;
2530 key.type = BTRFS_EXTENT_DATA_KEY;
2531 key.offset = backref->file_pos;
2533 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2536 } else if (ret > 0) {
2541 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2542 struct btrfs_file_extent_item);
2544 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2545 backref->generation)
2548 btrfs_release_path(path);
2550 start = backref->file_pos;
2551 if (backref->extent_offset < old->extent_offset + old->offset)
2552 start += old->extent_offset + old->offset -
2553 backref->extent_offset;
2555 len = min(backref->extent_offset + backref->num_bytes,
2556 old->extent_offset + old->offset + old->len);
2557 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2559 ret = btrfs_drop_extents(trans, root, inode, start,
2564 key.objectid = btrfs_ino(inode);
2565 key.type = BTRFS_EXTENT_DATA_KEY;
2568 path->leave_spinning = 1;
2570 struct btrfs_file_extent_item *fi;
2572 struct btrfs_key found_key;
2574 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2579 leaf = path->nodes[0];
2580 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2582 fi = btrfs_item_ptr(leaf, path->slots[0],
2583 struct btrfs_file_extent_item);
2584 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2586 if (extent_len + found_key.offset == start &&
2587 relink_is_mergable(leaf, fi, new)) {
2588 btrfs_set_file_extent_num_bytes(leaf, fi,
2590 btrfs_mark_buffer_dirty(leaf);
2591 inode_add_bytes(inode, len);
2597 btrfs_release_path(path);
2602 ret = btrfs_insert_empty_item(trans, root, path, &key,
2605 btrfs_abort_transaction(trans, ret);
2609 leaf = path->nodes[0];
2610 item = btrfs_item_ptr(leaf, path->slots[0],
2611 struct btrfs_file_extent_item);
2612 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2613 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2614 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2615 btrfs_set_file_extent_num_bytes(leaf, item, len);
2616 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2617 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2618 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2619 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2620 btrfs_set_file_extent_encryption(leaf, item, 0);
2621 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2623 btrfs_mark_buffer_dirty(leaf);
2624 inode_add_bytes(inode, len);
2625 btrfs_release_path(path);
2627 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2629 backref->root_id, backref->inum,
2630 new->file_pos); /* start - extent_offset */
2632 btrfs_abort_transaction(trans, ret);
2638 btrfs_release_path(path);
2639 path->leave_spinning = 0;
2640 btrfs_end_transaction(trans, root);
2642 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2648 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2650 struct old_sa_defrag_extent *old, *tmp;
2655 list_for_each_entry_safe(old, tmp, &new->head, list) {
2661 static void relink_file_extents(struct new_sa_defrag_extent *new)
2663 struct btrfs_path *path;
2664 struct sa_defrag_extent_backref *backref;
2665 struct sa_defrag_extent_backref *prev = NULL;
2666 struct inode *inode;
2667 struct btrfs_root *root;
2668 struct rb_node *node;
2672 root = BTRFS_I(inode)->root;
2674 path = btrfs_alloc_path();
2678 if (!record_extent_backrefs(path, new)) {
2679 btrfs_free_path(path);
2682 btrfs_release_path(path);
2685 node = rb_first(&new->root);
2688 rb_erase(node, &new->root);
2690 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2692 ret = relink_extent_backref(path, prev, backref);
2705 btrfs_free_path(path);
2707 free_sa_defrag_extent(new);
2709 atomic_dec(&root->fs_info->defrag_running);
2710 wake_up(&root->fs_info->transaction_wait);
2713 static struct new_sa_defrag_extent *
2714 record_old_file_extents(struct inode *inode,
2715 struct btrfs_ordered_extent *ordered)
2717 struct btrfs_root *root = BTRFS_I(inode)->root;
2718 struct btrfs_path *path;
2719 struct btrfs_key key;
2720 struct old_sa_defrag_extent *old;
2721 struct new_sa_defrag_extent *new;
2724 new = kmalloc(sizeof(*new), GFP_NOFS);
2729 new->file_pos = ordered->file_offset;
2730 new->len = ordered->len;
2731 new->bytenr = ordered->start;
2732 new->disk_len = ordered->disk_len;
2733 new->compress_type = ordered->compress_type;
2734 new->root = RB_ROOT;
2735 INIT_LIST_HEAD(&new->head);
2737 path = btrfs_alloc_path();
2741 key.objectid = btrfs_ino(inode);
2742 key.type = BTRFS_EXTENT_DATA_KEY;
2743 key.offset = new->file_pos;
2745 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2748 if (ret > 0 && path->slots[0] > 0)
2751 /* find out all the old extents for the file range */
2753 struct btrfs_file_extent_item *extent;
2754 struct extent_buffer *l;
2763 slot = path->slots[0];
2765 if (slot >= btrfs_header_nritems(l)) {
2766 ret = btrfs_next_leaf(root, path);
2774 btrfs_item_key_to_cpu(l, &key, slot);
2776 if (key.objectid != btrfs_ino(inode))
2778 if (key.type != BTRFS_EXTENT_DATA_KEY)
2780 if (key.offset >= new->file_pos + new->len)
2783 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2785 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2786 if (key.offset + num_bytes < new->file_pos)
2789 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2793 extent_offset = btrfs_file_extent_offset(l, extent);
2795 old = kmalloc(sizeof(*old), GFP_NOFS);
2799 offset = max(new->file_pos, key.offset);
2800 end = min(new->file_pos + new->len, key.offset + num_bytes);
2802 old->bytenr = disk_bytenr;
2803 old->extent_offset = extent_offset;
2804 old->offset = offset - key.offset;
2805 old->len = end - offset;
2808 list_add_tail(&old->list, &new->head);
2814 btrfs_free_path(path);
2815 atomic_inc(&root->fs_info->defrag_running);
2820 btrfs_free_path(path);
2822 free_sa_defrag_extent(new);
2826 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2829 struct btrfs_block_group_cache *cache;
2831 cache = btrfs_lookup_block_group(root->fs_info, start);
2834 spin_lock(&cache->lock);
2835 cache->delalloc_bytes -= len;
2836 spin_unlock(&cache->lock);
2838 btrfs_put_block_group(cache);
2841 /* as ordered data IO finishes, this gets called so we can finish
2842 * an ordered extent if the range of bytes in the file it covers are
2845 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2847 struct inode *inode = ordered_extent->inode;
2848 struct btrfs_root *root = BTRFS_I(inode)->root;
2849 struct btrfs_trans_handle *trans = NULL;
2850 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2851 struct extent_state *cached_state = NULL;
2852 struct new_sa_defrag_extent *new = NULL;
2853 int compress_type = 0;
2855 u64 logical_len = ordered_extent->len;
2857 bool truncated = false;
2859 nolock = btrfs_is_free_space_inode(inode);
2861 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2866 btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2867 ordered_extent->file_offset +
2868 ordered_extent->len - 1);
2870 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2872 logical_len = ordered_extent->truncated_len;
2873 /* Truncated the entire extent, don't bother adding */
2878 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2879 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2882 * For mwrite(mmap + memset to write) case, we still reserve
2883 * space for NOCOW range.
2884 * As NOCOW won't cause a new delayed ref, just free the space
2886 btrfs_qgroup_free_data(inode, ordered_extent->file_offset,
2887 ordered_extent->len);
2888 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2890 trans = btrfs_join_transaction_nolock(root);
2892 trans = btrfs_join_transaction(root);
2893 if (IS_ERR(trans)) {
2894 ret = PTR_ERR(trans);
2898 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2899 ret = btrfs_update_inode_fallback(trans, root, inode);
2900 if (ret) /* -ENOMEM or corruption */
2901 btrfs_abort_transaction(trans, ret);
2905 lock_extent_bits(io_tree, ordered_extent->file_offset,
2906 ordered_extent->file_offset + ordered_extent->len - 1,
2909 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2910 ordered_extent->file_offset + ordered_extent->len - 1,
2911 EXTENT_DEFRAG, 1, cached_state);
2913 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2914 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2915 /* the inode is shared */
2916 new = record_old_file_extents(inode, ordered_extent);
2918 clear_extent_bit(io_tree, ordered_extent->file_offset,
2919 ordered_extent->file_offset + ordered_extent->len - 1,
2920 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2924 trans = btrfs_join_transaction_nolock(root);
2926 trans = btrfs_join_transaction(root);
2927 if (IS_ERR(trans)) {
2928 ret = PTR_ERR(trans);
2933 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2935 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2936 compress_type = ordered_extent->compress_type;
2937 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2938 BUG_ON(compress_type);
2939 ret = btrfs_mark_extent_written(trans, inode,
2940 ordered_extent->file_offset,
2941 ordered_extent->file_offset +
2944 BUG_ON(root == root->fs_info->tree_root);
2945 ret = insert_reserved_file_extent(trans, inode,
2946 ordered_extent->file_offset,
2947 ordered_extent->start,
2948 ordered_extent->disk_len,
2949 logical_len, logical_len,
2950 compress_type, 0, 0,
2951 BTRFS_FILE_EXTENT_REG);
2953 btrfs_release_delalloc_bytes(root,
2954 ordered_extent->start,
2955 ordered_extent->disk_len);
2957 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2958 ordered_extent->file_offset, ordered_extent->len,
2961 btrfs_abort_transaction(trans, ret);
2965 add_pending_csums(trans, inode, ordered_extent->file_offset,
2966 &ordered_extent->list);
2968 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2969 ret = btrfs_update_inode_fallback(trans, root, inode);
2970 if (ret) { /* -ENOMEM or corruption */
2971 btrfs_abort_transaction(trans, ret);
2976 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2977 ordered_extent->file_offset +
2978 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2980 if (root != root->fs_info->tree_root)
2981 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2983 btrfs_end_transaction(trans, root);
2985 if (ret || truncated) {
2989 start = ordered_extent->file_offset + logical_len;
2991 start = ordered_extent->file_offset;
2992 end = ordered_extent->file_offset + ordered_extent->len - 1;
2993 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2995 /* Drop the cache for the part of the extent we didn't write. */
2996 btrfs_drop_extent_cache(inode, start, end, 0);
2999 * If the ordered extent had an IOERR or something else went
3000 * wrong we need to return the space for this ordered extent
3001 * back to the allocator. We only free the extent in the
3002 * truncated case if we didn't write out the extent at all.
3004 if ((ret || !logical_len) &&
3005 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3006 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3007 btrfs_free_reserved_extent(root, ordered_extent->start,
3008 ordered_extent->disk_len, 1);
3013 * This needs to be done to make sure anybody waiting knows we are done
3014 * updating everything for this ordered extent.
3016 btrfs_remove_ordered_extent(inode, ordered_extent);
3018 /* for snapshot-aware defrag */
3021 free_sa_defrag_extent(new);
3022 atomic_dec(&root->fs_info->defrag_running);
3024 relink_file_extents(new);
3029 btrfs_put_ordered_extent(ordered_extent);
3030 /* once for the tree */
3031 btrfs_put_ordered_extent(ordered_extent);
3036 static void finish_ordered_fn(struct btrfs_work *work)
3038 struct btrfs_ordered_extent *ordered_extent;
3039 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3040 btrfs_finish_ordered_io(ordered_extent);
3043 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3044 struct extent_state *state, int uptodate)
3046 struct inode *inode = page->mapping->host;
3047 struct btrfs_root *root = BTRFS_I(inode)->root;
3048 struct btrfs_ordered_extent *ordered_extent = NULL;
3049 struct btrfs_workqueue *wq;
3050 btrfs_work_func_t func;
3052 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3054 ClearPagePrivate2(page);
3055 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3056 end - start + 1, uptodate))
3059 if (btrfs_is_free_space_inode(inode)) {
3060 wq = root->fs_info->endio_freespace_worker;
3061 func = btrfs_freespace_write_helper;
3063 wq = root->fs_info->endio_write_workers;
3064 func = btrfs_endio_write_helper;
3067 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3069 btrfs_queue_work(wq, &ordered_extent->work);
3074 static int __readpage_endio_check(struct inode *inode,
3075 struct btrfs_io_bio *io_bio,
3076 int icsum, struct page *page,
3077 int pgoff, u64 start, size_t len)
3083 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3085 kaddr = kmap_atomic(page);