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/compat.h>
34 #include <linux/bit_spinlock.h>
35 #include <linux/xattr.h>
36 #include <linux/posix_acl.h>
37 #include <linux/falloc.h>
38 #include <linux/slab.h>
39 #include <linux/ratelimit.h>
40 #include <linux/mount.h>
41 #include <linux/btrfs.h>
42 #include <linux/blkdev.h>
43 #include <linux/posix_acl_xattr.h>
44 #include <linux/uio.h>
47 #include "transaction.h"
48 #include "btrfs_inode.h"
49 #include "print-tree.h"
50 #include "ordered-data.h"
54 #include "compression.h"
56 #include "free-space-cache.h"
57 #include "inode-map.h"
64 struct btrfs_iget_args {
65 struct btrfs_key *location;
66 struct btrfs_root *root;
69 struct btrfs_dio_data {
70 u64 outstanding_extents;
72 u64 unsubmitted_oe_range_start;
73 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_path_cachep;
90 struct kmem_cache *btrfs_free_space_cachep;
93 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
94 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
95 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
96 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
97 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
98 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
99 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
100 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
103 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
104 static int btrfs_truncate(struct inode *inode);
105 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
106 static noinline int cow_file_range(struct inode *inode,
107 struct page *locked_page,
108 u64 start, u64 end, u64 delalloc_end,
109 int *page_started, unsigned long *nr_written,
110 int unlock, struct btrfs_dedupe_hash *hash);
111 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
112 u64 orig_start, u64 block_start,
113 u64 block_len, u64 orig_block_len,
114 u64 ram_bytes, int compress_type,
117 static void __endio_write_update_ordered(struct inode *inode,
118 const u64 offset, const u64 bytes,
119 const bool uptodate);
122 * Cleanup all submitted ordered extents in specified range to handle errors
123 * from the fill_dellaloc() callback.
125 * NOTE: caller must ensure that when an error happens, it can not call
126 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
127 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
128 * to be released, which we want to happen only when finishing the ordered
129 * extent (btrfs_finish_ordered_io()). Also note that the caller of the
130 * fill_delalloc() callback already does proper cleanup for the first page of
131 * the range, that is, it invokes the callback writepage_end_io_hook() for the
132 * range of the first page.
134 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
138 return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
139 bytes - PAGE_SIZE, false);
142 static int btrfs_dirty_inode(struct inode *inode);
144 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
145 void btrfs_test_inode_set_ops(struct inode *inode)
147 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
151 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
152 struct inode *inode, struct inode *dir,
153 const struct qstr *qstr)
157 err = btrfs_init_acl(trans, inode, dir);
159 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
164 * this does all the hard work for inserting an inline extent into
165 * the btree. The caller should have done a btrfs_drop_extents so that
166 * no overlapping inline items exist in the btree
168 static int insert_inline_extent(struct btrfs_trans_handle *trans,
169 struct btrfs_path *path, int extent_inserted,
170 struct btrfs_root *root, struct inode *inode,
171 u64 start, size_t size, size_t compressed_size,
173 struct page **compressed_pages)
175 struct extent_buffer *leaf;
176 struct page *page = NULL;
179 struct btrfs_file_extent_item *ei;
181 size_t cur_size = size;
182 unsigned long offset;
184 if (compressed_size && compressed_pages)
185 cur_size = compressed_size;
187 inode_add_bytes(inode, size);
189 if (!extent_inserted) {
190 struct btrfs_key key;
193 key.objectid = btrfs_ino(BTRFS_I(inode));
195 key.type = BTRFS_EXTENT_DATA_KEY;
197 datasize = btrfs_file_extent_calc_inline_size(cur_size);
198 path->leave_spinning = 1;
199 ret = btrfs_insert_empty_item(trans, root, path, &key,
204 leaf = path->nodes[0];
205 ei = btrfs_item_ptr(leaf, path->slots[0],
206 struct btrfs_file_extent_item);
207 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
208 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
209 btrfs_set_file_extent_encryption(leaf, ei, 0);
210 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
211 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
212 ptr = btrfs_file_extent_inline_start(ei);
214 if (compress_type != BTRFS_COMPRESS_NONE) {
217 while (compressed_size > 0) {
218 cpage = compressed_pages[i];
219 cur_size = min_t(unsigned long, compressed_size,
222 kaddr = kmap_atomic(cpage);
223 write_extent_buffer(leaf, kaddr, ptr, cur_size);
224 kunmap_atomic(kaddr);
228 compressed_size -= cur_size;
230 btrfs_set_file_extent_compression(leaf, ei,
233 page = find_get_page(inode->i_mapping,
234 start >> PAGE_SHIFT);
235 btrfs_set_file_extent_compression(leaf, ei, 0);
236 kaddr = kmap_atomic(page);
237 offset = start & (PAGE_SIZE - 1);
238 write_extent_buffer(leaf, kaddr + offset, ptr, size);
239 kunmap_atomic(kaddr);
242 btrfs_mark_buffer_dirty(leaf);
243 btrfs_release_path(path);
246 * we're an inline extent, so nobody can
247 * extend the file past i_size without locking
248 * a page we already have locked.
250 * We must do any isize and inode updates
251 * before we unlock the pages. Otherwise we
252 * could end up racing with unlink.
254 BTRFS_I(inode)->disk_i_size = inode->i_size;
255 ret = btrfs_update_inode(trans, root, inode);
263 * conditionally insert an inline extent into the file. This
264 * does the checks required to make sure the data is small enough
265 * to fit as an inline extent.
267 static noinline int cow_file_range_inline(struct btrfs_root *root,
268 struct inode *inode, u64 start,
269 u64 end, size_t compressed_size,
271 struct page **compressed_pages)
273 struct btrfs_fs_info *fs_info = root->fs_info;
274 struct btrfs_trans_handle *trans;
275 u64 isize = i_size_read(inode);
276 u64 actual_end = min(end + 1, isize);
277 u64 inline_len = actual_end - start;
278 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
279 u64 data_len = inline_len;
281 struct btrfs_path *path;
282 int extent_inserted = 0;
283 u32 extent_item_size;
286 data_len = compressed_size;
289 actual_end > fs_info->sectorsize ||
290 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
292 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
294 data_len > fs_info->max_inline) {
298 path = btrfs_alloc_path();
302 trans = btrfs_join_transaction(root);
304 btrfs_free_path(path);
305 return PTR_ERR(trans);
307 trans->block_rsv = &fs_info->delalloc_block_rsv;
309 if (compressed_size && compressed_pages)
310 extent_item_size = btrfs_file_extent_calc_inline_size(
313 extent_item_size = btrfs_file_extent_calc_inline_size(
316 ret = __btrfs_drop_extents(trans, root, inode, path,
317 start, aligned_end, NULL,
318 1, 1, extent_item_size, &extent_inserted);
320 btrfs_abort_transaction(trans, ret);
324 if (isize > actual_end)
325 inline_len = min_t(u64, isize, actual_end);
326 ret = insert_inline_extent(trans, path, extent_inserted,
328 inline_len, compressed_size,
329 compress_type, compressed_pages);
330 if (ret && ret != -ENOSPC) {
331 btrfs_abort_transaction(trans, ret);
333 } else if (ret == -ENOSPC) {
338 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
339 btrfs_delalloc_release_metadata(BTRFS_I(inode), end + 1 - start);
340 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
343 * Don't forget to free the reserved space, as for inlined extent
344 * it won't count as data extent, free them directly here.
345 * And at reserve time, it's always aligned to page size, so
346 * just free one page here.
348 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
349 btrfs_free_path(path);
350 btrfs_end_transaction(trans);
354 struct async_extent {
359 unsigned long nr_pages;
361 struct list_head list;
366 struct btrfs_root *root;
367 struct page *locked_page;
370 struct list_head extents;
371 struct btrfs_work work;
374 static noinline int add_async_extent(struct async_cow *cow,
375 u64 start, u64 ram_size,
378 unsigned long nr_pages,
381 struct async_extent *async_extent;
383 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
384 BUG_ON(!async_extent); /* -ENOMEM */
385 async_extent->start = start;
386 async_extent->ram_size = ram_size;
387 async_extent->compressed_size = compressed_size;
388 async_extent->pages = pages;
389 async_extent->nr_pages = nr_pages;
390 async_extent->compress_type = compress_type;
391 list_add_tail(&async_extent->list, &cow->extents);
395 static inline int inode_need_compress(struct inode *inode)
397 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
400 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
402 /* bad compression ratios */
403 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
405 if (btrfs_test_opt(fs_info, COMPRESS) ||
406 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
407 BTRFS_I(inode)->force_compress)
412 static inline void inode_should_defrag(struct btrfs_inode *inode,
413 u64 start, u64 end, u64 num_bytes, u64 small_write)
415 /* If this is a small write inside eof, kick off a defrag */
416 if (num_bytes < small_write &&
417 (start > 0 || end + 1 < inode->disk_i_size))
418 btrfs_add_inode_defrag(NULL, inode);
422 * we create compressed extents in two phases. The first
423 * phase compresses a range of pages that have already been
424 * locked (both pages and state bits are locked).
426 * This is done inside an ordered work queue, and the compression
427 * is spread across many cpus. The actual IO submission is step
428 * two, and the ordered work queue takes care of making sure that
429 * happens in the same order things were put onto the queue by
430 * writepages and friends.
432 * If this code finds it can't get good compression, it puts an
433 * entry onto the work queue to write the uncompressed bytes. This
434 * makes sure that both compressed inodes and uncompressed inodes
435 * are written in the same order that the flusher thread sent them
438 static noinline void compress_file_range(struct inode *inode,
439 struct page *locked_page,
441 struct async_cow *async_cow,
444 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
445 struct btrfs_root *root = BTRFS_I(inode)->root;
447 u64 blocksize = fs_info->sectorsize;
449 u64 isize = i_size_read(inode);
451 struct page **pages = NULL;
452 unsigned long nr_pages;
453 unsigned long total_compressed = 0;
454 unsigned long total_in = 0;
457 int compress_type = fs_info->compress_type;
460 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
463 actual_end = min_t(u64, isize, end + 1);
466 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
467 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
468 nr_pages = min_t(unsigned long, nr_pages,
469 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
472 * we don't want to send crud past the end of i_size through
473 * compression, that's just a waste of CPU time. So, if the
474 * end of the file is before the start of our current
475 * requested range of bytes, we bail out to the uncompressed
476 * cleanup code that can deal with all of this.
478 * It isn't really the fastest way to fix things, but this is a
479 * very uncommon corner.
481 if (actual_end <= start)
482 goto cleanup_and_bail_uncompressed;
484 total_compressed = actual_end - start;
487 * skip compression for a small file range(<=blocksize) that
488 * isn't an inline extent, since it doesn't save disk space at all.
490 if (total_compressed <= blocksize &&
491 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
492 goto cleanup_and_bail_uncompressed;
494 total_compressed = min_t(unsigned long, total_compressed,
495 BTRFS_MAX_UNCOMPRESSED);
496 num_bytes = ALIGN(end - start + 1, blocksize);
497 num_bytes = max(blocksize, num_bytes);
502 * we do compression for mount -o compress and when the
503 * inode has not been flagged as nocompress. This flag can
504 * change at any time if we discover bad compression ratios.
506 if (inode_need_compress(inode)) {
508 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
510 /* just bail out to the uncompressed code */
514 if (BTRFS_I(inode)->force_compress)
515 compress_type = BTRFS_I(inode)->force_compress;
518 * we need to call clear_page_dirty_for_io on each
519 * page in the range. Otherwise applications with the file
520 * mmap'd can wander in and change the page contents while
521 * we are compressing them.
523 * If the compression fails for any reason, we set the pages
524 * dirty again later on.
526 extent_range_clear_dirty_for_io(inode, start, end);
528 ret = btrfs_compress_pages(compress_type,
529 inode->i_mapping, start,
536 unsigned long offset = total_compressed &
538 struct page *page = pages[nr_pages - 1];
541 /* zero the tail end of the last page, we might be
542 * sending it down to disk
545 kaddr = kmap_atomic(page);
546 memset(kaddr + offset, 0,
548 kunmap_atomic(kaddr);
555 /* lets try to make an inline extent */
556 if (ret || total_in < (actual_end - start)) {
557 /* we didn't compress the entire range, try
558 * to make an uncompressed inline extent.
560 ret = cow_file_range_inline(root, inode, start, end,
561 0, BTRFS_COMPRESS_NONE, NULL);
563 /* try making a compressed inline extent */
564 ret = cow_file_range_inline(root, inode, start, end,
566 compress_type, pages);
569 unsigned long clear_flags = EXTENT_DELALLOC |
570 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG;
571 unsigned long page_error_op;
573 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
574 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
577 * inline extent creation worked or returned error,
578 * we don't need to create any more async work items.
579 * Unlock and free up our temp pages.
581 extent_clear_unlock_delalloc(inode, start, end, end,
589 btrfs_free_reserved_data_space_noquota(inode,
598 * we aren't doing an inline extent round the compressed size
599 * up to a block size boundary so the allocator does sane
602 total_compressed = ALIGN(total_compressed, blocksize);
605 * one last check to make sure the compression is really a
606 * win, compare the page count read with the blocks on disk,
607 * compression must free at least one sector size
609 total_in = ALIGN(total_in, PAGE_SIZE);
610 if (total_compressed + blocksize <= total_in) {
611 num_bytes = total_in;
615 * The async work queues will take care of doing actual
616 * allocation on disk for these compressed pages, and
617 * will submit them to the elevator.
619 add_async_extent(async_cow, start, num_bytes,
620 total_compressed, pages, nr_pages,
623 if (start + num_bytes < end) {
634 * the compression code ran but failed to make things smaller,
635 * free any pages it allocated and our page pointer array
637 for (i = 0; i < nr_pages; i++) {
638 WARN_ON(pages[i]->mapping);
643 total_compressed = 0;
646 /* flag the file so we don't compress in the future */
647 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
648 !(BTRFS_I(inode)->force_compress)) {
649 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
652 cleanup_and_bail_uncompressed:
654 * No compression, but we still need to write the pages in the file
655 * we've been given so far. redirty the locked page if it corresponds
656 * to our extent and set things up for the async work queue to run
657 * cow_file_range to do the normal delalloc dance.
659 if (page_offset(locked_page) >= start &&
660 page_offset(locked_page) <= end)
661 __set_page_dirty_nobuffers(locked_page);
662 /* unlocked later on in the async handlers */
665 extent_range_redirty_for_io(inode, start, end);
666 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
667 BTRFS_COMPRESS_NONE);
673 for (i = 0; i < nr_pages; i++) {
674 WARN_ON(pages[i]->mapping);
680 static void free_async_extent_pages(struct async_extent *async_extent)
684 if (!async_extent->pages)
687 for (i = 0; i < async_extent->nr_pages; i++) {
688 WARN_ON(async_extent->pages[i]->mapping);
689 put_page(async_extent->pages[i]);
691 kfree(async_extent->pages);
692 async_extent->nr_pages = 0;
693 async_extent->pages = NULL;
697 * phase two of compressed writeback. This is the ordered portion
698 * of the code, which only gets called in the order the work was
699 * queued. We walk all the async extents created by compress_file_range
700 * and send them down to the disk.
702 static noinline void submit_compressed_extents(struct inode *inode,
703 struct async_cow *async_cow)
705 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
706 struct async_extent *async_extent;
708 struct btrfs_key ins;
709 struct extent_map *em;
710 struct btrfs_root *root = BTRFS_I(inode)->root;
711 struct extent_io_tree *io_tree;
715 while (!list_empty(&async_cow->extents)) {
716 async_extent = list_entry(async_cow->extents.next,
717 struct async_extent, list);
718 list_del(&async_extent->list);
720 io_tree = &BTRFS_I(inode)->io_tree;
723 /* did the compression code fall back to uncompressed IO? */
724 if (!async_extent->pages) {
725 int page_started = 0;
726 unsigned long nr_written = 0;
728 lock_extent(io_tree, async_extent->start,
729 async_extent->start +
730 async_extent->ram_size - 1);
732 /* allocate blocks */
733 ret = cow_file_range(inode, async_cow->locked_page,
735 async_extent->start +
736 async_extent->ram_size - 1,
737 async_extent->start +
738 async_extent->ram_size - 1,
739 &page_started, &nr_written, 0,
745 * if page_started, cow_file_range inserted an
746 * inline extent and took care of all the unlocking
747 * and IO for us. Otherwise, we need to submit
748 * all those pages down to the drive.
750 if (!page_started && !ret)
751 extent_write_locked_range(io_tree,
752 inode, async_extent->start,
753 async_extent->start +
754 async_extent->ram_size - 1,
758 unlock_page(async_cow->locked_page);
764 lock_extent(io_tree, async_extent->start,
765 async_extent->start + async_extent->ram_size - 1);
767 ret = btrfs_reserve_extent(root, async_extent->ram_size,
768 async_extent->compressed_size,
769 async_extent->compressed_size,
770 0, alloc_hint, &ins, 1, 1);
772 free_async_extent_pages(async_extent);
774 if (ret == -ENOSPC) {
775 unlock_extent(io_tree, async_extent->start,
776 async_extent->start +
777 async_extent->ram_size - 1);
780 * we need to redirty the pages if we decide to
781 * fallback to uncompressed IO, otherwise we
782 * will not submit these pages down to lower
785 extent_range_redirty_for_io(inode,
787 async_extent->start +
788 async_extent->ram_size - 1);
795 * here we're doing allocation and writeback of the
798 em = create_io_em(inode, async_extent->start,
799 async_extent->ram_size, /* len */
800 async_extent->start, /* orig_start */
801 ins.objectid, /* block_start */
802 ins.offset, /* block_len */
803 ins.offset, /* orig_block_len */
804 async_extent->ram_size, /* ram_bytes */
805 async_extent->compress_type,
806 BTRFS_ORDERED_COMPRESSED);
808 /* ret value is not necessary due to void function */
809 goto out_free_reserve;
812 ret = btrfs_add_ordered_extent_compress(inode,
815 async_extent->ram_size,
817 BTRFS_ORDERED_COMPRESSED,
818 async_extent->compress_type);
820 btrfs_drop_extent_cache(BTRFS_I(inode),
822 async_extent->start +
823 async_extent->ram_size - 1, 0);
824 goto out_free_reserve;
826 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
829 * clear dirty, set writeback and unlock the pages.
831 extent_clear_unlock_delalloc(inode, async_extent->start,
832 async_extent->start +
833 async_extent->ram_size - 1,
834 async_extent->start +
835 async_extent->ram_size - 1,
836 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
837 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
839 if (btrfs_submit_compressed_write(inode,
841 async_extent->ram_size,
843 ins.offset, async_extent->pages,
844 async_extent->nr_pages)) {
845 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
846 struct page *p = async_extent->pages[0];
847 const u64 start = async_extent->start;
848 const u64 end = start + async_extent->ram_size - 1;
850 p->mapping = inode->i_mapping;
851 tree->ops->writepage_end_io_hook(p, start, end,
854 extent_clear_unlock_delalloc(inode, start, end, end,
858 free_async_extent_pages(async_extent);
860 alloc_hint = ins.objectid + ins.offset;
866 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
867 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
869 extent_clear_unlock_delalloc(inode, async_extent->start,
870 async_extent->start +
871 async_extent->ram_size - 1,
872 async_extent->start +
873 async_extent->ram_size - 1,
874 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
875 EXTENT_DELALLOC_NEW |
876 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
877 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
878 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
880 free_async_extent_pages(async_extent);
885 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
888 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
889 struct extent_map *em;
892 read_lock(&em_tree->lock);
893 em = search_extent_mapping(em_tree, start, num_bytes);
896 * if block start isn't an actual block number then find the
897 * first block in this inode and use that as a hint. If that
898 * block is also bogus then just don't worry about it.
900 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
902 em = search_extent_mapping(em_tree, 0, 0);
903 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
904 alloc_hint = em->block_start;
908 alloc_hint = em->block_start;
912 read_unlock(&em_tree->lock);
918 * when extent_io.c finds a delayed allocation range in the file,
919 * the call backs end up in this code. The basic idea is to
920 * allocate extents on disk for the range, and create ordered data structs
921 * in ram to track those extents.
923 * locked_page is the page that writepage had locked already. We use
924 * it to make sure we don't do extra locks or unlocks.
926 * *page_started is set to one if we unlock locked_page and do everything
927 * required to start IO on it. It may be clean and already done with
930 static noinline int cow_file_range(struct inode *inode,
931 struct page *locked_page,
932 u64 start, u64 end, u64 delalloc_end,
933 int *page_started, unsigned long *nr_written,
934 int unlock, struct btrfs_dedupe_hash *hash)
936 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
937 struct btrfs_root *root = BTRFS_I(inode)->root;
940 unsigned long ram_size;
942 u64 cur_alloc_size = 0;
943 u64 blocksize = fs_info->sectorsize;
944 struct btrfs_key ins;
945 struct extent_map *em;
947 unsigned long page_ops;
948 bool extent_reserved = false;
951 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
957 num_bytes = ALIGN(end - start + 1, blocksize);
958 num_bytes = max(blocksize, num_bytes);
959 disk_num_bytes = num_bytes;
961 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
964 /* lets try to make an inline extent */
965 ret = cow_file_range_inline(root, inode, start, end, 0,
966 BTRFS_COMPRESS_NONE, NULL);
968 extent_clear_unlock_delalloc(inode, start, end,
970 EXTENT_LOCKED | EXTENT_DELALLOC |
971 EXTENT_DELALLOC_NEW |
972 EXTENT_DEFRAG, PAGE_UNLOCK |
973 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
975 btrfs_free_reserved_data_space_noquota(inode, start,
977 *nr_written = *nr_written +
978 (end - start + PAGE_SIZE) / PAGE_SIZE;
981 } else if (ret < 0) {
986 BUG_ON(disk_num_bytes >
987 btrfs_super_total_bytes(fs_info->super_copy));
989 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
990 btrfs_drop_extent_cache(BTRFS_I(inode), start,
991 start + num_bytes - 1, 0);
993 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 fs_info->sectorsize, 0, alloc_hint,
1000 cur_alloc_size = ins.offset;
1001 extent_reserved = true;
1003 ram_size = ins.offset;
1004 em = create_io_em(inode, start, ins.offset, /* len */
1005 start, /* orig_start */
1006 ins.objectid, /* block_start */
1007 ins.offset, /* block_len */
1008 ins.offset, /* orig_block_len */
1009 ram_size, /* ram_bytes */
1010 BTRFS_COMPRESS_NONE, /* compress_type */
1011 BTRFS_ORDERED_REGULAR /* type */);
1014 free_extent_map(em);
1016 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1017 ram_size, cur_alloc_size, 0);
1019 goto out_drop_extent_cache;
1021 if (root->root_key.objectid ==
1022 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1023 ret = btrfs_reloc_clone_csums(inode, start,
1026 * Only drop cache here, and process as normal.
1028 * We must not allow extent_clear_unlock_delalloc()
1029 * at out_unlock label to free meta of this ordered
1030 * extent, as its meta should be freed by
1031 * btrfs_finish_ordered_io().
1033 * So we must continue until @start is increased to
1034 * skip current ordered extent.
1037 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1038 start + ram_size - 1, 0);
1041 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1043 /* we're not doing compressed IO, don't unlock the first
1044 * page (which the caller expects to stay locked), don't
1045 * clear any dirty bits and don't set any writeback bits
1047 * Do set the Private2 bit so we know this page was properly
1048 * setup for writepage
1050 page_ops = unlock ? PAGE_UNLOCK : 0;
1051 page_ops |= PAGE_SET_PRIVATE2;
1053 extent_clear_unlock_delalloc(inode, start,
1054 start + ram_size - 1,
1055 delalloc_end, locked_page,
1056 EXTENT_LOCKED | EXTENT_DELALLOC,
1058 if (disk_num_bytes < cur_alloc_size)
1061 disk_num_bytes -= cur_alloc_size;
1062 num_bytes -= cur_alloc_size;
1063 alloc_hint = ins.objectid + ins.offset;
1064 start += cur_alloc_size;
1065 extent_reserved = false;
1068 * btrfs_reloc_clone_csums() error, since start is increased
1069 * extent_clear_unlock_delalloc() at out_unlock label won't
1070 * free metadata of current ordered extent, we're OK to exit.
1078 out_drop_extent_cache:
1079 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1081 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1082 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1084 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1085 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1086 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1089 * If we reserved an extent for our delalloc range (or a subrange) and
1090 * failed to create the respective ordered extent, then it means that
1091 * when we reserved the extent we decremented the extent's size from
1092 * the data space_info's bytes_may_use counter and incremented the
1093 * space_info's bytes_reserved counter by the same amount. We must make
1094 * sure extent_clear_unlock_delalloc() does not try to decrement again
1095 * the data space_info's bytes_may_use counter, therefore we do not pass
1096 * it the flag EXTENT_CLEAR_DATA_RESV.
1098 if (extent_reserved) {
1099 extent_clear_unlock_delalloc(inode, start,
1100 start + cur_alloc_size,
1101 start + cur_alloc_size,
1105 start += cur_alloc_size;
1109 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1111 clear_bits | EXTENT_CLEAR_DATA_RESV,
1117 * work queue call back to started compression on a file and pages
1119 static noinline void async_cow_start(struct btrfs_work *work)
1121 struct async_cow *async_cow;
1123 async_cow = container_of(work, struct async_cow, work);
1125 compress_file_range(async_cow->inode, async_cow->locked_page,
1126 async_cow->start, async_cow->end, async_cow,
1128 if (num_added == 0) {
1129 btrfs_add_delayed_iput(async_cow->inode);
1130 async_cow->inode = NULL;
1135 * work queue call back to submit previously compressed pages
1137 static noinline void async_cow_submit(struct btrfs_work *work)
1139 struct btrfs_fs_info *fs_info;
1140 struct async_cow *async_cow;
1141 struct btrfs_root *root;
1142 unsigned long nr_pages;
1144 async_cow = container_of(work, struct async_cow, work);
1146 root = async_cow->root;
1147 fs_info = root->fs_info;
1148 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1152 * atomic_sub_return implies a barrier for waitqueue_active
1154 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1156 waitqueue_active(&fs_info->async_submit_wait))
1157 wake_up(&fs_info->async_submit_wait);
1159 if (async_cow->inode)
1160 submit_compressed_extents(async_cow->inode, async_cow);
1163 static noinline void async_cow_free(struct btrfs_work *work)
1165 struct async_cow *async_cow;
1166 async_cow = container_of(work, struct async_cow, work);
1167 if (async_cow->inode)
1168 btrfs_add_delayed_iput(async_cow->inode);
1172 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1173 u64 start, u64 end, int *page_started,
1174 unsigned long *nr_written)
1176 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1177 struct async_cow *async_cow;
1178 struct btrfs_root *root = BTRFS_I(inode)->root;
1179 unsigned long nr_pages;
1182 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1183 1, 0, NULL, GFP_NOFS);
1184 while (start < end) {
1185 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1186 BUG_ON(!async_cow); /* -ENOMEM */
1187 async_cow->inode = igrab(inode);
1188 async_cow->root = root;
1189 async_cow->locked_page = locked_page;
1190 async_cow->start = start;
1192 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1193 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1196 cur_end = min(end, start + SZ_512K - 1);
1198 async_cow->end = cur_end;
1199 INIT_LIST_HEAD(&async_cow->extents);
1201 btrfs_init_work(&async_cow->work,
1202 btrfs_delalloc_helper,
1203 async_cow_start, async_cow_submit,
1206 nr_pages = (cur_end - start + PAGE_SIZE) >>
1208 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1210 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1212 while (atomic_read(&fs_info->async_submit_draining) &&
1213 atomic_read(&fs_info->async_delalloc_pages)) {
1214 wait_event(fs_info->async_submit_wait,
1215 (atomic_read(&fs_info->async_delalloc_pages) ==
1219 *nr_written += nr_pages;
1220 start = cur_end + 1;
1226 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1227 u64 bytenr, u64 num_bytes)
1230 struct btrfs_ordered_sum *sums;
1233 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1234 bytenr + num_bytes - 1, &list, 0);
1235 if (ret == 0 && list_empty(&list))
1238 while (!list_empty(&list)) {
1239 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1240 list_del(&sums->list);
1247 * when nowcow writeback call back. This checks for snapshots or COW copies
1248 * of the extents that exist in the file, and COWs the file as required.
1250 * If no cow copies or snapshots exist, we write directly to the existing
1253 static noinline int run_delalloc_nocow(struct inode *inode,
1254 struct page *locked_page,
1255 u64 start, u64 end, int *page_started, int force,
1256 unsigned long *nr_written)
1258 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1259 struct btrfs_root *root = BTRFS_I(inode)->root;
1260 struct extent_buffer *leaf;
1261 struct btrfs_path *path;
1262 struct btrfs_file_extent_item *fi;
1263 struct btrfs_key found_key;
1264 struct extent_map *em;
1279 u64 ino = btrfs_ino(BTRFS_I(inode));
1281 path = btrfs_alloc_path();
1283 extent_clear_unlock_delalloc(inode, start, end, end,
1285 EXTENT_LOCKED | EXTENT_DELALLOC |
1286 EXTENT_DO_ACCOUNTING |
1287 EXTENT_DEFRAG, PAGE_UNLOCK |
1289 PAGE_SET_WRITEBACK |
1290 PAGE_END_WRITEBACK);
1294 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1296 cow_start = (u64)-1;
1299 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1303 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1304 leaf = path->nodes[0];
1305 btrfs_item_key_to_cpu(leaf, &found_key,
1306 path->slots[0] - 1);
1307 if (found_key.objectid == ino &&
1308 found_key.type == BTRFS_EXTENT_DATA_KEY)
1313 leaf = path->nodes[0];
1314 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1315 ret = btrfs_next_leaf(root, path);
1320 leaf = path->nodes[0];
1326 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1328 if (found_key.objectid > ino)
1330 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1331 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1335 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1336 found_key.offset > end)
1339 if (found_key.offset > cur_offset) {
1340 extent_end = found_key.offset;
1345 fi = btrfs_item_ptr(leaf, path->slots[0],
1346 struct btrfs_file_extent_item);
1347 extent_type = btrfs_file_extent_type(leaf, fi);
1349 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1350 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1351 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1352 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1353 extent_offset = btrfs_file_extent_offset(leaf, fi);
1354 extent_end = found_key.offset +
1355 btrfs_file_extent_num_bytes(leaf, fi);
1357 btrfs_file_extent_disk_num_bytes(leaf, fi);
1358 if (extent_end <= start) {
1362 if (disk_bytenr == 0)
1364 if (btrfs_file_extent_compression(leaf, fi) ||
1365 btrfs_file_extent_encryption(leaf, fi) ||
1366 btrfs_file_extent_other_encoding(leaf, fi))
1368 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1370 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1372 if (btrfs_cross_ref_exist(root, ino,
1374 extent_offset, disk_bytenr))
1376 disk_bytenr += extent_offset;
1377 disk_bytenr += cur_offset - found_key.offset;
1378 num_bytes = min(end + 1, extent_end) - cur_offset;
1380 * if there are pending snapshots for this root,
1381 * we fall into common COW way.
1384 err = btrfs_start_write_no_snapshoting(root);
1389 * force cow if csum exists in the range.
1390 * this ensure that csum for a given extent are
1391 * either valid or do not exist.
1393 if (csum_exist_in_range(fs_info, disk_bytenr,
1396 btrfs_end_write_no_snapshoting(root);
1399 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1401 btrfs_end_write_no_snapshoting(root);
1405 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1406 extent_end = found_key.offset +
1407 btrfs_file_extent_inline_len(leaf,
1408 path->slots[0], fi);
1409 extent_end = ALIGN(extent_end,
1410 fs_info->sectorsize);
1415 if (extent_end <= start) {
1417 if (!nolock && nocow)
1418 btrfs_end_write_no_snapshoting(root);
1420 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1424 if (cow_start == (u64)-1)
1425 cow_start = cur_offset;
1426 cur_offset = extent_end;
1427 if (cur_offset > end)
1433 btrfs_release_path(path);
1434 if (cow_start != (u64)-1) {
1435 ret = cow_file_range(inode, locked_page,
1436 cow_start, found_key.offset - 1,
1437 end, page_started, nr_written, 1,
1440 if (!nolock && nocow)
1441 btrfs_end_write_no_snapshoting(root);
1443 btrfs_dec_nocow_writers(fs_info,
1447 cow_start = (u64)-1;
1450 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1451 u64 orig_start = found_key.offset - extent_offset;
1453 em = create_io_em(inode, cur_offset, num_bytes,
1455 disk_bytenr, /* block_start */
1456 num_bytes, /* block_len */
1457 disk_num_bytes, /* orig_block_len */
1458 ram_bytes, BTRFS_COMPRESS_NONE,
1459 BTRFS_ORDERED_PREALLOC);
1461 if (!nolock && nocow)
1462 btrfs_end_write_no_snapshoting(root);
1464 btrfs_dec_nocow_writers(fs_info,
1469 free_extent_map(em);
1472 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1473 type = BTRFS_ORDERED_PREALLOC;
1475 type = BTRFS_ORDERED_NOCOW;
1478 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1479 num_bytes, num_bytes, type);
1481 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1482 BUG_ON(ret); /* -ENOMEM */
1484 if (root->root_key.objectid ==
1485 BTRFS_DATA_RELOC_TREE_OBJECTID)
1487 * Error handled later, as we must prevent
1488 * extent_clear_unlock_delalloc() in error handler
1489 * from freeing metadata of created ordered extent.
1491 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1494 extent_clear_unlock_delalloc(inode, cur_offset,
1495 cur_offset + num_bytes - 1, end,
1496 locked_page, EXTENT_LOCKED |
1498 EXTENT_CLEAR_DATA_RESV,
1499 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1501 if (!nolock && nocow)
1502 btrfs_end_write_no_snapshoting(root);
1503 cur_offset = extent_end;
1506 * btrfs_reloc_clone_csums() error, now we're OK to call error
1507 * handler, as metadata for created ordered extent will only
1508 * be freed by btrfs_finish_ordered_io().
1512 if (cur_offset > end)
1515 btrfs_release_path(path);
1517 if (cur_offset <= end && cow_start == (u64)-1) {
1518 cow_start = cur_offset;
1522 if (cow_start != (u64)-1) {
1523 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1524 page_started, nr_written, 1, NULL);
1530 if (ret && cur_offset < end)
1531 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1532 locked_page, EXTENT_LOCKED |
1533 EXTENT_DELALLOC | EXTENT_DEFRAG |
1534 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1536 PAGE_SET_WRITEBACK |
1537 PAGE_END_WRITEBACK);
1538 btrfs_free_path(path);
1542 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1545 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1546 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1550 * @defrag_bytes is a hint value, no spinlock held here,
1551 * if is not zero, it means the file is defragging.
1552 * Force cow if given extent needs to be defragged.
1554 if (BTRFS_I(inode)->defrag_bytes &&
1555 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1556 EXTENT_DEFRAG, 0, NULL))
1563 * extent_io.c call back to do delayed allocation processing
1565 static int run_delalloc_range(void *private_data, struct page *locked_page,
1566 u64 start, u64 end, int *page_started,
1567 unsigned long *nr_written)
1569 struct inode *inode = private_data;
1571 int force_cow = need_force_cow(inode, start, end);
1573 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1574 ret = run_delalloc_nocow(inode, locked_page, start, end,
1575 page_started, 1, nr_written);
1576 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1577 ret = run_delalloc_nocow(inode, locked_page, start, end,
1578 page_started, 0, nr_written);
1579 } else if (!inode_need_compress(inode)) {
1580 ret = cow_file_range(inode, locked_page, start, end, end,
1581 page_started, nr_written, 1, NULL);
1583 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1584 &BTRFS_I(inode)->runtime_flags);
1585 ret = cow_file_range_async(inode, locked_page, start, end,
1586 page_started, nr_written);
1589 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1593 static void btrfs_split_extent_hook(void *private_data,
1594 struct extent_state *orig, u64 split)
1596 struct inode *inode = private_data;
1599 /* not delalloc, ignore it */
1600 if (!(orig->state & EXTENT_DELALLOC))
1603 size = orig->end - orig->start + 1;
1604 if (size > BTRFS_MAX_EXTENT_SIZE) {
1609 * See the explanation in btrfs_merge_extent_hook, the same
1610 * applies here, just in reverse.
1612 new_size = orig->end - split + 1;
1613 num_extents = count_max_extents(new_size);
1614 new_size = split - orig->start;
1615 num_extents += count_max_extents(new_size);
1616 if (count_max_extents(size) >= num_extents)
1620 spin_lock(&BTRFS_I(inode)->lock);
1621 BTRFS_I(inode)->outstanding_extents++;
1622 spin_unlock(&BTRFS_I(inode)->lock);
1626 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1627 * extents so we can keep track of new extents that are just merged onto old
1628 * extents, such as when we are doing sequential writes, so we can properly
1629 * account for the metadata space we'll need.
1631 static void btrfs_merge_extent_hook(void *private_data,
1632 struct extent_state *new,
1633 struct extent_state *other)
1635 struct inode *inode = private_data;
1636 u64 new_size, old_size;
1639 /* not delalloc, ignore it */
1640 if (!(other->state & EXTENT_DELALLOC))
1643 if (new->start > other->start)
1644 new_size = new->end - other->start + 1;
1646 new_size = other->end - new->start + 1;
1648 /* we're not bigger than the max, unreserve the space and go */
1649 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1650 spin_lock(&BTRFS_I(inode)->lock);
1651 BTRFS_I(inode)->outstanding_extents--;
1652 spin_unlock(&BTRFS_I(inode)->lock);
1657 * We have to add up either side to figure out how many extents were
1658 * accounted for before we merged into one big extent. If the number of
1659 * extents we accounted for is <= the amount we need for the new range
1660 * then we can return, otherwise drop. Think of it like this
1664 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1665 * need 2 outstanding extents, on one side we have 1 and the other side
1666 * we have 1 so they are == and we can return. But in this case
1668 * [MAX_SIZE+4k][MAX_SIZE+4k]
1670 * Each range on their own accounts for 2 extents, but merged together
1671 * they are only 3 extents worth of accounting, so we need to drop in
1674 old_size = other->end - other->start + 1;
1675 num_extents = count_max_extents(old_size);
1676 old_size = new->end - new->start + 1;
1677 num_extents += count_max_extents(old_size);
1678 if (count_max_extents(new_size) >= num_extents)
1681 spin_lock(&BTRFS_I(inode)->lock);
1682 BTRFS_I(inode)->outstanding_extents--;
1683 spin_unlock(&BTRFS_I(inode)->lock);
1686 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1687 struct inode *inode)
1689 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1691 spin_lock(&root->delalloc_lock);
1692 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1693 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1694 &root->delalloc_inodes);
1695 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1696 &BTRFS_I(inode)->runtime_flags);
1697 root->nr_delalloc_inodes++;
1698 if (root->nr_delalloc_inodes == 1) {
1699 spin_lock(&fs_info->delalloc_root_lock);
1700 BUG_ON(!list_empty(&root->delalloc_root));
1701 list_add_tail(&root->delalloc_root,
1702 &fs_info->delalloc_roots);
1703 spin_unlock(&fs_info->delalloc_root_lock);
1706 spin_unlock(&root->delalloc_lock);
1709 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1710 struct btrfs_inode *inode)
1712 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1714 spin_lock(&root->delalloc_lock);
1715 if (!list_empty(&inode->delalloc_inodes)) {
1716 list_del_init(&inode->delalloc_inodes);
1717 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1718 &inode->runtime_flags);
1719 root->nr_delalloc_inodes--;
1720 if (!root->nr_delalloc_inodes) {
1721 spin_lock(&fs_info->delalloc_root_lock);
1722 BUG_ON(list_empty(&root->delalloc_root));
1723 list_del_init(&root->delalloc_root);
1724 spin_unlock(&fs_info->delalloc_root_lock);
1727 spin_unlock(&root->delalloc_lock);
1731 * extent_io.c set_bit_hook, used to track delayed allocation
1732 * bytes in this file, and to maintain the list of inodes that
1733 * have pending delalloc work to be done.
1735 static void btrfs_set_bit_hook(void *private_data,
1736 struct extent_state *state, unsigned *bits)
1738 struct inode *inode = private_data;
1740 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1742 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1745 * set_bit and clear bit hooks normally require _irqsave/restore
1746 * but in this case, we are only testing for the DELALLOC
1747 * bit, which is only set or cleared with irqs on
1749 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1750 struct btrfs_root *root = BTRFS_I(inode)->root;
1751 u64 len = state->end + 1 - state->start;
1752 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1754 if (*bits & EXTENT_FIRST_DELALLOC) {
1755 *bits &= ~EXTENT_FIRST_DELALLOC;
1757 spin_lock(&BTRFS_I(inode)->lock);
1758 BTRFS_I(inode)->outstanding_extents++;
1759 spin_unlock(&BTRFS_I(inode)->lock);
1762 /* For sanity tests */
1763 if (btrfs_is_testing(fs_info))
1766 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1767 fs_info->delalloc_batch);
1768 spin_lock(&BTRFS_I(inode)->lock);
1769 BTRFS_I(inode)->delalloc_bytes += len;
1770 if (*bits & EXTENT_DEFRAG)
1771 BTRFS_I(inode)->defrag_bytes += len;
1772 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1773 &BTRFS_I(inode)->runtime_flags))
1774 btrfs_add_delalloc_inodes(root, inode);
1775 spin_unlock(&BTRFS_I(inode)->lock);
1778 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1779 (*bits & EXTENT_DELALLOC_NEW)) {
1780 spin_lock(&BTRFS_I(inode)->lock);
1781 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1783 spin_unlock(&BTRFS_I(inode)->lock);
1788 * extent_io.c clear_bit_hook, see set_bit_hook for why
1790 static void btrfs_clear_bit_hook(void *private_data,
1791 struct extent_state *state,
1794 struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1795 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1796 u64 len = state->end + 1 - state->start;
1797 u32 num_extents = count_max_extents(len);
1799 spin_lock(&inode->lock);
1800 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1801 inode->defrag_bytes -= len;
1802 spin_unlock(&inode->lock);
1805 * set_bit and clear bit hooks normally require _irqsave/restore
1806 * but in this case, we are only testing for the DELALLOC
1807 * bit, which is only set or cleared with irqs on
1809 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1810 struct btrfs_root *root = inode->root;
1811 bool do_list = !btrfs_is_free_space_inode(inode);
1813 if (*bits & EXTENT_FIRST_DELALLOC) {
1814 *bits &= ~EXTENT_FIRST_DELALLOC;
1815 } else if (!(*bits & EXTENT_CLEAR_META_RESV)) {
1816 spin_lock(&inode->lock);
1817 inode->outstanding_extents -= num_extents;
1818 spin_unlock(&inode->lock);
1822 * We don't reserve metadata space for space cache inodes so we
1823 * don't need to call dellalloc_release_metadata if there is an
1826 if (*bits & EXTENT_CLEAR_META_RESV &&
1827 root != fs_info->tree_root)
1828 btrfs_delalloc_release_metadata(inode, len);
1830 /* For sanity tests. */
1831 if (btrfs_is_testing(fs_info))
1834 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1835 do_list && !(state->state & EXTENT_NORESERVE) &&
1836 (*bits & EXTENT_CLEAR_DATA_RESV))
1837 btrfs_free_reserved_data_space_noquota(
1841 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1842 fs_info->delalloc_batch);
1843 spin_lock(&inode->lock);
1844 inode->delalloc_bytes -= len;
1845 if (do_list && inode->delalloc_bytes == 0 &&
1846 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1847 &inode->runtime_flags))
1848 btrfs_del_delalloc_inode(root, inode);
1849 spin_unlock(&inode->lock);
1852 if ((state->state & EXTENT_DELALLOC_NEW) &&
1853 (*bits & EXTENT_DELALLOC_NEW)) {
1854 spin_lock(&inode->lock);
1855 ASSERT(inode->new_delalloc_bytes >= len);
1856 inode->new_delalloc_bytes -= len;
1857 spin_unlock(&inode->lock);
1862 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1863 * we don't create bios that span stripes or chunks
1865 * return 1 if page cannot be merged to bio
1866 * return 0 if page can be merged to bio
1867 * return error otherwise
1869 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1870 size_t size, struct bio *bio,
1871 unsigned long bio_flags)
1873 struct inode *inode = page->mapping->host;
1874 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1875 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1880 if (bio_flags & EXTENT_BIO_COMPRESSED)
1883 length = bio->bi_iter.bi_size;
1884 map_length = length;
1885 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1889 if (map_length < length + size)
1895 * in order to insert checksums into the metadata in large chunks,
1896 * we wait until bio submission time. All the pages in the bio are
1897 * checksummed and sums are attached onto the ordered extent record.
1899 * At IO completion time the cums attached on the ordered extent record
1900 * are inserted into the btree
1902 static blk_status_t __btrfs_submit_bio_start(void *private_data, struct bio *bio,
1903 int mirror_num, unsigned long bio_flags,
1906 struct inode *inode = private_data;
1907 blk_status_t ret = 0;
1909 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1910 BUG_ON(ret); /* -ENOMEM */
1915 * in order to insert checksums into the metadata in large chunks,
1916 * we wait until bio submission time. All the pages in the bio are
1917 * checksummed and sums are attached onto the ordered extent record.
1919 * At IO completion time the cums attached on the ordered extent record
1920 * are inserted into the btree
1922 static blk_status_t __btrfs_submit_bio_done(void *private_data, struct bio *bio,
1923 int mirror_num, unsigned long bio_flags,
1926 struct inode *inode = private_data;
1927 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1930 ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1932 bio->bi_status = ret;
1939 * extent_io.c submission hook. This does the right thing for csum calculation
1940 * on write, or reading the csums from the tree before a read
1942 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1943 int mirror_num, unsigned long bio_flags,
1946 struct inode *inode = private_data;
1947 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1948 struct btrfs_root *root = BTRFS_I(inode)->root;
1949 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1950 blk_status_t ret = 0;
1952 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1954 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1956 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1957 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1959 if (bio_op(bio) != REQ_OP_WRITE) {
1960 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1964 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1965 ret = btrfs_submit_compressed_read(inode, bio,
1969 } else if (!skip_sum) {
1970 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
1975 } else if (async && !skip_sum) {
1976 /* csum items have already been cloned */
1977 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1979 /* we're doing a write, do the async checksumming */
1980 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
1982 __btrfs_submit_bio_start,
1983 __btrfs_submit_bio_done);
1985 } else if (!skip_sum) {
1986 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1992 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
1996 bio->bi_status = ret;
2003 * given a list of ordered sums record them in the inode. This happens
2004 * at IO completion time based on sums calculated at bio submission time.
2006 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2007 struct inode *inode, struct list_head *list)
2009 struct btrfs_ordered_sum *sum;
2011 list_for_each_entry(sum, list, list) {
2012 trans->adding_csums = 1;
2013 btrfs_csum_file_blocks(trans,
2014 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2015 trans->adding_csums = 0;
2020 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2021 struct extent_state **cached_state, int dedupe)
2023 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2024 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2028 /* see btrfs_writepage_start_hook for details on why this is required */
2029 struct btrfs_writepage_fixup {
2031 struct btrfs_work work;
2034 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2036 struct btrfs_writepage_fixup *fixup;
2037 struct btrfs_ordered_extent *ordered;
2038 struct extent_state *cached_state = NULL;
2039 struct extent_changeset *data_reserved = NULL;
2041 struct inode *inode;
2046 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2050 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2051 ClearPageChecked(page);
2055 inode = page->mapping->host;
2056 page_start = page_offset(page);
2057 page_end = page_offset(page) + PAGE_SIZE - 1;
2059 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2062 /* already ordered? We're done */
2063 if (PagePrivate2(page))
2066 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2069 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2070 page_end, &cached_state, GFP_NOFS);
2072 btrfs_start_ordered_extent(inode, ordered, 1);
2073 btrfs_put_ordered_extent(ordered);
2077 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2080 mapping_set_error(page->mapping, ret);
2081 end_extent_writepage(page, ret, page_start, page_end);
2082 ClearPageChecked(page);
2086 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state,
2088 ClearPageChecked(page);
2089 set_page_dirty(page);
2091 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2092 &cached_state, GFP_NOFS);
2097 extent_changeset_free(data_reserved);
2101 * There are a few paths in the higher layers of the kernel that directly
2102 * set the page dirty bit without asking the filesystem if it is a
2103 * good idea. This causes problems because we want to make sure COW
2104 * properly happens and the data=ordered rules are followed.
2106 * In our case any range that doesn't have the ORDERED bit set
2107 * hasn't been properly setup for IO. We kick off an async process
2108 * to fix it up. The async helper will wait for ordered extents, set
2109 * the delalloc bit and make it safe to write the page.
2111 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2113 struct inode *inode = page->mapping->host;
2114 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2115 struct btrfs_writepage_fixup *fixup;
2117 /* this page is properly in the ordered list */
2118 if (TestClearPagePrivate2(page))
2121 if (PageChecked(page))
2124 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2128 SetPageChecked(page);
2130 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2131 btrfs_writepage_fixup_worker, NULL, NULL);
2133 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2137 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2138 struct inode *inode, u64 file_pos,
2139 u64 disk_bytenr, u64 disk_num_bytes,
2140 u64 num_bytes, u64 ram_bytes,
2141 u8 compression, u8 encryption,
2142 u16 other_encoding, int extent_type)
2144 struct btrfs_root *root = BTRFS_I(inode)->root;
2145 struct btrfs_file_extent_item *fi;
2146 struct btrfs_path *path;
2147 struct extent_buffer *leaf;
2148 struct btrfs_key ins;
2150 int extent_inserted = 0;
2153 path = btrfs_alloc_path();
2158 * we may be replacing one extent in the tree with another.
2159 * The new extent is pinned in the extent map, and we don't want
2160 * to drop it from the cache until it is completely in the btree.
2162 * So, tell btrfs_drop_extents to leave this extent in the cache.
2163 * the caller is expected to unpin it and allow it to be merged
2166 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2167 file_pos + num_bytes, NULL, 0,
2168 1, sizeof(*fi), &extent_inserted);
2172 if (!extent_inserted) {
2173 ins.objectid = btrfs_ino(BTRFS_I(inode));
2174 ins.offset = file_pos;
2175 ins.type = BTRFS_EXTENT_DATA_KEY;
2177 path->leave_spinning = 1;
2178 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2183 leaf = path->nodes[0];
2184 fi = btrfs_item_ptr(leaf, path->slots[0],
2185 struct btrfs_file_extent_item);
2186 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2187 btrfs_set_file_extent_type(leaf, fi, extent_type);
2188 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2189 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2190 btrfs_set_file_extent_offset(leaf, fi, 0);
2191 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2192 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2193 btrfs_set_file_extent_compression(leaf, fi, compression);
2194 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2195 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2197 btrfs_mark_buffer_dirty(leaf);
2198 btrfs_release_path(path);
2200 inode_add_bytes(inode, num_bytes);
2202 ins.objectid = disk_bytenr;
2203 ins.offset = disk_num_bytes;
2204 ins.type = BTRFS_EXTENT_ITEM_KEY;
2207 * Release the reserved range from inode dirty range map, as it is
2208 * already moved into delayed_ref_head
2210 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2214 ret = btrfs_alloc_reserved_file_extent(trans, root->root_key.objectid,
2215 btrfs_ino(BTRFS_I(inode)), file_pos, qg_released, &ins);
2217 btrfs_free_path(path);
2222 /* snapshot-aware defrag */
2223 struct sa_defrag_extent_backref {
2224 struct rb_node node;
2225 struct old_sa_defrag_extent *old;
2234 struct old_sa_defrag_extent {
2235 struct list_head list;
2236 struct new_sa_defrag_extent *new;
2245 struct new_sa_defrag_extent {
2246 struct rb_root root;
2247 struct list_head head;
2248 struct btrfs_path *path;
2249 struct inode *inode;
2257 static int backref_comp(struct sa_defrag_extent_backref *b1,
2258 struct sa_defrag_extent_backref *b2)
2260 if (b1->root_id < b2->root_id)
2262 else if (b1->root_id > b2->root_id)
2265 if (b1->inum < b2->inum)
2267 else if (b1->inum > b2->inum)
2270 if (b1->file_pos < b2->file_pos)
2272 else if (b1->file_pos > b2->file_pos)
2276 * [------------------------------] ===> (a range of space)
2277 * |<--->| |<---->| =============> (fs/file tree A)
2278 * |<---------------------------->| ===> (fs/file tree B)
2280 * A range of space can refer to two file extents in one tree while
2281 * refer to only one file extent in another tree.
2283 * So we may process a disk offset more than one time(two extents in A)
2284 * and locate at the same extent(one extent in B), then insert two same
2285 * backrefs(both refer to the extent in B).
2290 static void backref_insert(struct rb_root *root,
2291 struct sa_defrag_extent_backref *backref)
2293 struct rb_node **p = &root->rb_node;
2294 struct rb_node *parent = NULL;
2295 struct sa_defrag_extent_backref *entry;
2300 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2302 ret = backref_comp(backref, entry);
2306 p = &(*p)->rb_right;
2309 rb_link_node(&backref->node, parent, p);
2310 rb_insert_color(&backref->node, root);
2314 * Note the backref might has changed, and in this case we just return 0.
2316 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2319 struct btrfs_file_extent_item *extent;
2320 struct old_sa_defrag_extent *old = ctx;
2321 struct new_sa_defrag_extent *new = old->new;
2322 struct btrfs_path *path = new->path;
2323 struct btrfs_key key;
2324 struct btrfs_root *root;
2325 struct sa_defrag_extent_backref *backref;
2326 struct extent_buffer *leaf;
2327 struct inode *inode = new->inode;
2328 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2334 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2335 inum == btrfs_ino(BTRFS_I(inode)))
2338 key.objectid = root_id;
2339 key.type = BTRFS_ROOT_ITEM_KEY;
2340 key.offset = (u64)-1;
2342 root = btrfs_read_fs_root_no_name(fs_info, &key);
2344 if (PTR_ERR(root) == -ENOENT)
2347 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2348 inum, offset, root_id);
2349 return PTR_ERR(root);
2352 key.objectid = inum;
2353 key.type = BTRFS_EXTENT_DATA_KEY;
2354 if (offset > (u64)-1 << 32)
2357 key.offset = offset;
2359 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2360 if (WARN_ON(ret < 0))
2367 leaf = path->nodes[0];
2368 slot = path->slots[0];
2370 if (slot >= btrfs_header_nritems(leaf)) {
2371 ret = btrfs_next_leaf(root, path);
2374 } else if (ret > 0) {
2383 btrfs_item_key_to_cpu(leaf, &key, slot);
2385 if (key.objectid > inum)
2388 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2391 extent = btrfs_item_ptr(leaf, slot,
2392 struct btrfs_file_extent_item);
2394 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2398 * 'offset' refers to the exact key.offset,
2399 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2400 * (key.offset - extent_offset).
2402 if (key.offset != offset)
2405 extent_offset = btrfs_file_extent_offset(leaf, extent);
2406 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2408 if (extent_offset >= old->extent_offset + old->offset +
2409 old->len || extent_offset + num_bytes <=
2410 old->extent_offset + old->offset)
2415 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2421 backref->root_id = root_id;
2422 backref->inum = inum;
2423 backref->file_pos = offset;
2424 backref->num_bytes = num_bytes;
2425 backref->extent_offset = extent_offset;
2426 backref->generation = btrfs_file_extent_generation(leaf, extent);
2428 backref_insert(&new->root, backref);
2431 btrfs_release_path(path);
2436 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2437 struct new_sa_defrag_extent *new)
2439 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2440 struct old_sa_defrag_extent *old, *tmp;
2445 list_for_each_entry_safe(old, tmp, &new->head, list) {
2446 ret = iterate_inodes_from_logical(old->bytenr +
2447 old->extent_offset, fs_info,
2448 path, record_one_backref,
2450 if (ret < 0 && ret != -ENOENT)
2453 /* no backref to be processed for this extent */
2455 list_del(&old->list);
2460 if (list_empty(&new->head))
2466 static int relink_is_mergable(struct extent_buffer *leaf,
2467 struct btrfs_file_extent_item *fi,
2468 struct new_sa_defrag_extent *new)
2470 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2473 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2476 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2479 if (btrfs_file_extent_encryption(leaf, fi) ||
2480 btrfs_file_extent_other_encoding(leaf, fi))
2487 * Note the backref might has changed, and in this case we just return 0.
2489 static noinline int relink_extent_backref(struct btrfs_path *path,
2490 struct sa_defrag_extent_backref *prev,
2491 struct sa_defrag_extent_backref *backref)
2493 struct btrfs_file_extent_item *extent;
2494 struct btrfs_file_extent_item *item;
2495 struct btrfs_ordered_extent *ordered;
2496 struct btrfs_trans_handle *trans;
2497 struct btrfs_root *root;
2498 struct btrfs_key key;
2499 struct extent_buffer *leaf;
2500 struct old_sa_defrag_extent *old = backref->old;
2501 struct new_sa_defrag_extent *new = old->new;
2502 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2503 struct inode *inode;
2504 struct extent_state *cached = NULL;
2513 if (prev && prev->root_id == backref->root_id &&
2514 prev->inum == backref->inum &&
2515 prev->file_pos + prev->num_bytes == backref->file_pos)
2518 /* step 1: get root */
2519 key.objectid = backref->root_id;
2520 key.type = BTRFS_ROOT_ITEM_KEY;
2521 key.offset = (u64)-1;
2523 index = srcu_read_lock(&fs_info->subvol_srcu);
2525 root = btrfs_read_fs_root_no_name(fs_info, &key);
2527 srcu_read_unlock(&fs_info->subvol_srcu, index);
2528 if (PTR_ERR(root) == -ENOENT)
2530 return PTR_ERR(root);
2533 if (btrfs_root_readonly(root)) {
2534 srcu_read_unlock(&fs_info->subvol_srcu, index);
2538 /* step 2: get inode */
2539 key.objectid = backref->inum;
2540 key.type = BTRFS_INODE_ITEM_KEY;
2543 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2544 if (IS_ERR(inode)) {
2545 srcu_read_unlock(&fs_info->subvol_srcu, index);
2549 srcu_read_unlock(&fs_info->subvol_srcu, index);
2551 /* step 3: relink backref */
2552 lock_start = backref->file_pos;
2553 lock_end = backref->file_pos + backref->num_bytes - 1;
2554 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2557 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2559 btrfs_put_ordered_extent(ordered);
2563 trans = btrfs_join_transaction(root);
2564 if (IS_ERR(trans)) {
2565 ret = PTR_ERR(trans);
2569 key.objectid = backref->inum;
2570 key.type = BTRFS_EXTENT_DATA_KEY;
2571 key.offset = backref->file_pos;
2573 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2576 } else if (ret > 0) {
2581 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2582 struct btrfs_file_extent_item);
2584 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2585 backref->generation)
2588 btrfs_release_path(path);
2590 start = backref->file_pos;
2591 if (backref->extent_offset < old->extent_offset + old->offset)
2592 start += old->extent_offset + old->offset -
2593 backref->extent_offset;
2595 len = min(backref->extent_offset + backref->num_bytes,
2596 old->extent_offset + old->offset + old->len);
2597 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2599 ret = btrfs_drop_extents(trans, root, inode, start,
2604 key.objectid = btrfs_ino(BTRFS_I(inode));
2605 key.type = BTRFS_EXTENT_DATA_KEY;
2608 path->leave_spinning = 1;
2610 struct btrfs_file_extent_item *fi;
2612 struct btrfs_key found_key;
2614 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2619 leaf = path->nodes[0];
2620 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2622 fi = btrfs_item_ptr(leaf, path->slots[0],
2623 struct btrfs_file_extent_item);
2624 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2626 if (extent_len + found_key.offset == start &&
2627 relink_is_mergable(leaf, fi, new)) {
2628 btrfs_set_file_extent_num_bytes(leaf, fi,
2630 btrfs_mark_buffer_dirty(leaf);
2631 inode_add_bytes(inode, len);
2637 btrfs_release_path(path);
2642 ret = btrfs_insert_empty_item(trans, root, path, &key,
2645 btrfs_abort_transaction(trans, ret);
2649 leaf = path->nodes[0];
2650 item = btrfs_item_ptr(leaf, path->slots[0],
2651 struct btrfs_file_extent_item);
2652 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2653 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2654 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2655 btrfs_set_file_extent_num_bytes(leaf, item, len);
2656 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2657 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2658 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2659 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2660 btrfs_set_file_extent_encryption(leaf, item, 0);
2661 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2663 btrfs_mark_buffer_dirty(leaf);
2664 inode_add_bytes(inode, len);
2665 btrfs_release_path(path);
2667 ret = btrfs_inc_extent_ref(trans, fs_info, new->bytenr,
2669 backref->root_id, backref->inum,
2670 new->file_pos); /* start - extent_offset */
2672 btrfs_abort_transaction(trans, ret);
2678 btrfs_release_path(path);
2679 path->leave_spinning = 0;
2680 btrfs_end_transaction(trans);
2682 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2688 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2690 struct old_sa_defrag_extent *old, *tmp;
2695 list_for_each_entry_safe(old, tmp, &new->head, list) {
2701 static void relink_file_extents(struct new_sa_defrag_extent *new)
2703 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2704 struct btrfs_path *path;
2705 struct sa_defrag_extent_backref *backref;
2706 struct sa_defrag_extent_backref *prev = NULL;
2707 struct inode *inode;
2708 struct btrfs_root *root;
2709 struct rb_node *node;
2713 root = BTRFS_I(inode)->root;
2715 path = btrfs_alloc_path();
2719 if (!record_extent_backrefs(path, new)) {
2720 btrfs_free_path(path);
2723 btrfs_release_path(path);
2726 node = rb_first(&new->root);
2729 rb_erase(node, &new->root);
2731 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2733 ret = relink_extent_backref(path, prev, backref);
2746 btrfs_free_path(path);
2748 free_sa_defrag_extent(new);
2750 atomic_dec(&fs_info->defrag_running);
2751 wake_up(&fs_info->transaction_wait);
2754 static struct new_sa_defrag_extent *
2755 record_old_file_extents(struct inode *inode,
2756 struct btrfs_ordered_extent *ordered)
2758 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2759 struct btrfs_root *root = BTRFS_I(inode)->root;
2760 struct btrfs_path *path;
2761 struct btrfs_key key;
2762 struct old_sa_defrag_extent *old;
2763 struct new_sa_defrag_extent *new;
2766 new = kmalloc(sizeof(*new), GFP_NOFS);
2771 new->file_pos = ordered->file_offset;
2772 new->len = ordered->len;
2773 new->bytenr = ordered->start;
2774 new->disk_len = ordered->disk_len;
2775 new->compress_type = ordered->compress_type;
2776 new->root = RB_ROOT;
2777 INIT_LIST_HEAD(&new->head);
2779 path = btrfs_alloc_path();
2783 key.objectid = btrfs_ino(BTRFS_I(inode));
2784 key.type = BTRFS_EXTENT_DATA_KEY;
2785 key.offset = new->file_pos;
2787 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2790 if (ret > 0 && path->slots[0] > 0)
2793 /* find out all the old extents for the file range */
2795 struct btrfs_file_extent_item *extent;
2796 struct extent_buffer *l;
2805 slot = path->slots[0];
2807 if (slot >= btrfs_header_nritems(l)) {
2808 ret = btrfs_next_leaf(root, path);
2816 btrfs_item_key_to_cpu(l, &key, slot);
2818 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2820 if (key.type != BTRFS_EXTENT_DATA_KEY)
2822 if (key.offset >= new->file_pos + new->len)
2825 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2827 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2828 if (key.offset + num_bytes < new->file_pos)
2831 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2835 extent_offset = btrfs_file_extent_offset(l, extent);
2837 old = kmalloc(sizeof(*old), GFP_NOFS);
2841 offset = max(new->file_pos, key.offset);
2842 end = min(new->file_pos + new->len, key.offset + num_bytes);
2844 old->bytenr = disk_bytenr;
2845 old->extent_offset = extent_offset;
2846 old->offset = offset - key.offset;
2847 old->len = end - offset;
2850 list_add_tail(&old->list, &new->head);
2856 btrfs_free_path(path);
2857 atomic_inc(&fs_info->defrag_running);
2862 btrfs_free_path(path);
2864 free_sa_defrag_extent(new);
2868 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2871 struct btrfs_block_group_cache *cache;
2873 cache = btrfs_lookup_block_group(fs_info, start);
2876 spin_lock(&cache->lock);
2877 cache->delalloc_bytes -= len;
2878 spin_unlock(&cache->lock);
2880 btrfs_put_block_group(cache);
2883 /* as ordered data IO finishes, this gets called so we can finish
2884 * an ordered extent if the range of bytes in the file it covers are
2887 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2889 struct inode *inode = ordered_extent->inode;
2890 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2891 struct btrfs_root *root = BTRFS_I(inode)->root;
2892 struct btrfs_trans_handle *trans = NULL;
2893 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2894 struct extent_state *cached_state = NULL;
2895 struct new_sa_defrag_extent *new = NULL;
2896 int compress_type = 0;
2898 u64 logical_len = ordered_extent->len;
2900 bool truncated = false;
2901 bool range_locked = false;
2902 bool clear_new_delalloc_bytes = false;
2904 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2905 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2906 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2907 clear_new_delalloc_bytes = true;
2909 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2911 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2916 btrfs_free_io_failure_record(BTRFS_I(inode),
2917 ordered_extent->file_offset,
2918 ordered_extent->file_offset +
2919 ordered_extent->len - 1);
2921 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2923 logical_len = ordered_extent->truncated_len;
2924 /* Truncated the entire extent, don't bother adding */
2929 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2930 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2933 * For mwrite(mmap + memset to write) case, we still reserve
2934 * space for NOCOW range.
2935 * As NOCOW won't cause a new delayed ref, just free the space
2937 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2938 ordered_extent->len);
2939 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2941 trans = btrfs_join_transaction_nolock(root);
2943 trans = btrfs_join_transaction(root);
2944 if (IS_ERR(trans)) {
2945 ret = PTR_ERR(trans);
2949 trans->block_rsv = &fs_info->delalloc_block_rsv;
2950 ret = btrfs_update_inode_fallback(trans, root, inode);
2951 if (ret) /* -ENOMEM or corruption */
2952 btrfs_abort_transaction(trans, ret);
2956 range_locked = true;
2957 lock_extent_bits(io_tree, ordered_extent->file_offset,
2958 ordered_extent->file_offset + ordered_extent->len - 1,
2961 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2962 ordered_extent->file_offset + ordered_extent->len - 1,
2963 EXTENT_DEFRAG, 0, cached_state);
2965 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2966 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2967 /* the inode is shared */
2968 new = record_old_file_extents(inode, ordered_extent);
2970 clear_extent_bit(io_tree, ordered_extent->file_offset,
2971 ordered_extent->file_offset + ordered_extent->len - 1,
2972 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2976 trans = btrfs_join_transaction_nolock(root);
2978 trans = btrfs_join_transaction(root);
2979 if (IS_ERR(trans)) {
2980 ret = PTR_ERR(trans);
2985 trans->block_rsv = &fs_info->delalloc_block_rsv;
2987 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2988 compress_type = ordered_extent->compress_type;
2989 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2990 BUG_ON(compress_type);
2991 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
2992 ordered_extent->file_offset,
2993 ordered_extent->file_offset +
2996 BUG_ON(root == fs_info->tree_root);
2997 ret = insert_reserved_file_extent(trans, inode,
2998 ordered_extent->file_offset,
2999 ordered_extent->start,
3000 ordered_extent->disk_len,
3001 logical_len, logical_len,
3002 compress_type, 0, 0,
3003 BTRFS_FILE_EXTENT_REG);
3005 btrfs_release_delalloc_bytes(fs_info,
3006 ordered_extent->start,
3007 ordered_extent->disk_len);
3009 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3010 ordered_extent->file_offset, ordered_extent->len,
3013 btrfs_abort_transaction(trans, ret);
3017 add_pending_csums(trans, inode, &ordered_extent->list);
3019 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3020 ret = btrfs_update_inode_fallback(trans, root, inode);
3021 if (ret) { /* -ENOMEM or corruption */
3022 btrfs_abort_transaction(trans, ret);
3027 if (range_locked || clear_new_delalloc_bytes) {
3028 unsigned int clear_bits = 0;
3031 clear_bits |= EXTENT_LOCKED;
3032 if (clear_new_delalloc_bytes)
3033 clear_bits |= EXTENT_DELALLOC_NEW;
3034 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3035 ordered_extent->file_offset,
3036 ordered_extent->file_offset +
3037 ordered_extent->len - 1,
3039 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3040 0, &cached_state, GFP_NOFS);
3043 if (root != fs_info->tree_root)
3044 btrfs_delalloc_release_metadata(BTRFS_I(inode),
3045 ordered_extent->len);
3047 btrfs_end_transaction(trans);
3049 if (ret || truncated) {
3053 start = ordered_extent->file_offset + logical_len;
3055 start = ordered_extent->file_offset;
3056 end = ordered_extent->file_offset + ordered_extent->len - 1;
3057 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
3059 /* Drop the cache for the part of the extent we didn't write. */
3060 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3063 * If the ordered extent had an IOERR or something else went
3064 * wrong we need to return the space for this ordered extent
3065 * back to the allocator. We only free the extent in the
3066 * truncated case if we didn't write out the extent at all.
3068 if ((ret || !logical_len) &&
3069 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3070 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))