1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
7 #include <linux/pagemap.h>
8 #include <linux/time.h>
9 #include <linux/init.h>
10 #include <linux/string.h>
11 #include <linux/backing-dev.h>
12 #include <linux/falloc.h>
13 #include <linux/writeback.h>
14 #include <linux/compat.h>
15 #include <linux/slab.h>
16 #include <linux/btrfs.h>
17 #include <linux/uio.h>
18 #include <linux/iversion.h>
21 #include "transaction.h"
22 #include "btrfs_inode.h"
23 #include "print-tree.h"
28 #include "compression.h"
29 #include "delalloc-space.h"
31 static struct kmem_cache *btrfs_inode_defrag_cachep;
33 * when auto defrag is enabled we
34 * queue up these defrag structs to remember which
35 * inodes need defragging passes
38 struct rb_node rb_node;
42 * transid where the defrag was added, we search for
43 * extents newer than this
50 /* last offset we were able to defrag */
53 /* if we've wrapped around back to zero once already */
57 static int __compare_inode_defrag(struct inode_defrag *defrag1,
58 struct inode_defrag *defrag2)
60 if (defrag1->root > defrag2->root)
62 else if (defrag1->root < defrag2->root)
64 else if (defrag1->ino > defrag2->ino)
66 else if (defrag1->ino < defrag2->ino)
72 /* pop a record for an inode into the defrag tree. The lock
73 * must be held already
75 * If you're inserting a record for an older transid than an
76 * existing record, the transid already in the tree is lowered
78 * If an existing record is found the defrag item you
81 static int __btrfs_add_inode_defrag(struct btrfs_inode *inode,
82 struct inode_defrag *defrag)
84 struct btrfs_fs_info *fs_info = inode->root->fs_info;
85 struct inode_defrag *entry;
87 struct rb_node *parent = NULL;
90 p = &fs_info->defrag_inodes.rb_node;
93 entry = rb_entry(parent, struct inode_defrag, rb_node);
95 ret = __compare_inode_defrag(defrag, entry);
99 p = &parent->rb_right;
101 /* if we're reinserting an entry for
102 * an old defrag run, make sure to
103 * lower the transid of our existing record
105 if (defrag->transid < entry->transid)
106 entry->transid = defrag->transid;
107 if (defrag->last_offset > entry->last_offset)
108 entry->last_offset = defrag->last_offset;
112 set_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags);
113 rb_link_node(&defrag->rb_node, parent, p);
114 rb_insert_color(&defrag->rb_node, &fs_info->defrag_inodes);
118 static inline int __need_auto_defrag(struct btrfs_fs_info *fs_info)
120 if (!btrfs_test_opt(fs_info, AUTO_DEFRAG))
123 if (btrfs_fs_closing(fs_info))
130 * insert a defrag record for this inode if auto defrag is
133 int btrfs_add_inode_defrag(struct btrfs_trans_handle *trans,
134 struct btrfs_inode *inode)
136 struct btrfs_root *root = inode->root;
137 struct btrfs_fs_info *fs_info = root->fs_info;
138 struct inode_defrag *defrag;
142 if (!__need_auto_defrag(fs_info))
145 if (test_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags))
149 transid = trans->transid;
151 transid = inode->root->last_trans;
153 defrag = kmem_cache_zalloc(btrfs_inode_defrag_cachep, GFP_NOFS);
157 defrag->ino = btrfs_ino(inode);
158 defrag->transid = transid;
159 defrag->root = root->root_key.objectid;
161 spin_lock(&fs_info->defrag_inodes_lock);
162 if (!test_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags)) {
164 * If we set IN_DEFRAG flag and evict the inode from memory,
165 * and then re-read this inode, this new inode doesn't have
166 * IN_DEFRAG flag. At the case, we may find the existed defrag.
168 ret = __btrfs_add_inode_defrag(inode, defrag);
170 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
172 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
174 spin_unlock(&fs_info->defrag_inodes_lock);
179 * Requeue the defrag object. If there is a defrag object that points to
180 * the same inode in the tree, we will merge them together (by
181 * __btrfs_add_inode_defrag()) and free the one that we want to requeue.
183 static void btrfs_requeue_inode_defrag(struct btrfs_inode *inode,
184 struct inode_defrag *defrag)
186 struct btrfs_fs_info *fs_info = inode->root->fs_info;
189 if (!__need_auto_defrag(fs_info))
193 * Here we don't check the IN_DEFRAG flag, because we need merge
196 spin_lock(&fs_info->defrag_inodes_lock);
197 ret = __btrfs_add_inode_defrag(inode, defrag);
198 spin_unlock(&fs_info->defrag_inodes_lock);
203 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
207 * pick the defragable inode that we want, if it doesn't exist, we will get
210 static struct inode_defrag *
211 btrfs_pick_defrag_inode(struct btrfs_fs_info *fs_info, u64 root, u64 ino)
213 struct inode_defrag *entry = NULL;
214 struct inode_defrag tmp;
216 struct rb_node *parent = NULL;
222 spin_lock(&fs_info->defrag_inodes_lock);
223 p = fs_info->defrag_inodes.rb_node;
226 entry = rb_entry(parent, struct inode_defrag, rb_node);
228 ret = __compare_inode_defrag(&tmp, entry);
232 p = parent->rb_right;
237 if (parent && __compare_inode_defrag(&tmp, entry) > 0) {
238 parent = rb_next(parent);
240 entry = rb_entry(parent, struct inode_defrag, rb_node);
246 rb_erase(parent, &fs_info->defrag_inodes);
247 spin_unlock(&fs_info->defrag_inodes_lock);
251 void btrfs_cleanup_defrag_inodes(struct btrfs_fs_info *fs_info)
253 struct inode_defrag *defrag;
254 struct rb_node *node;
256 spin_lock(&fs_info->defrag_inodes_lock);
257 node = rb_first(&fs_info->defrag_inodes);
259 rb_erase(node, &fs_info->defrag_inodes);
260 defrag = rb_entry(node, struct inode_defrag, rb_node);
261 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
263 cond_resched_lock(&fs_info->defrag_inodes_lock);
265 node = rb_first(&fs_info->defrag_inodes);
267 spin_unlock(&fs_info->defrag_inodes_lock);
270 #define BTRFS_DEFRAG_BATCH 1024
272 static int __btrfs_run_defrag_inode(struct btrfs_fs_info *fs_info,
273 struct inode_defrag *defrag)
275 struct btrfs_root *inode_root;
277 struct btrfs_key key;
278 struct btrfs_ioctl_defrag_range_args range;
284 key.objectid = defrag->root;
285 key.type = BTRFS_ROOT_ITEM_KEY;
286 key.offset = (u64)-1;
288 index = srcu_read_lock(&fs_info->subvol_srcu);
290 inode_root = btrfs_read_fs_root_no_name(fs_info, &key);
291 if (IS_ERR(inode_root)) {
292 ret = PTR_ERR(inode_root);
296 key.objectid = defrag->ino;
297 key.type = BTRFS_INODE_ITEM_KEY;
299 inode = btrfs_iget(fs_info->sb, &key, inode_root);
301 ret = PTR_ERR(inode);
304 srcu_read_unlock(&fs_info->subvol_srcu, index);
306 /* do a chunk of defrag */
307 clear_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
308 memset(&range, 0, sizeof(range));
310 range.start = defrag->last_offset;
312 sb_start_write(fs_info->sb);
313 num_defrag = btrfs_defrag_file(inode, NULL, &range, defrag->transid,
315 sb_end_write(fs_info->sb);
317 * if we filled the whole defrag batch, there
318 * must be more work to do. Queue this defrag
321 if (num_defrag == BTRFS_DEFRAG_BATCH) {
322 defrag->last_offset = range.start;
323 btrfs_requeue_inode_defrag(BTRFS_I(inode), defrag);
324 } else if (defrag->last_offset && !defrag->cycled) {
326 * we didn't fill our defrag batch, but
327 * we didn't start at zero. Make sure we loop
328 * around to the start of the file.
330 defrag->last_offset = 0;
332 btrfs_requeue_inode_defrag(BTRFS_I(inode), defrag);
334 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
340 srcu_read_unlock(&fs_info->subvol_srcu, index);
341 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
346 * run through the list of inodes in the FS that need
349 int btrfs_run_defrag_inodes(struct btrfs_fs_info *fs_info)
351 struct inode_defrag *defrag;
353 u64 root_objectid = 0;
355 atomic_inc(&fs_info->defrag_running);
357 /* Pause the auto defragger. */
358 if (test_bit(BTRFS_FS_STATE_REMOUNTING,
362 if (!__need_auto_defrag(fs_info))
365 /* find an inode to defrag */
366 defrag = btrfs_pick_defrag_inode(fs_info, root_objectid,
369 if (root_objectid || first_ino) {
378 first_ino = defrag->ino + 1;
379 root_objectid = defrag->root;
381 __btrfs_run_defrag_inode(fs_info, defrag);
383 atomic_dec(&fs_info->defrag_running);
386 * during unmount, we use the transaction_wait queue to
387 * wait for the defragger to stop
389 wake_up(&fs_info->transaction_wait);
393 /* simple helper to fault in pages and copy. This should go away
394 * and be replaced with calls into generic code.
396 static noinline int btrfs_copy_from_user(loff_t pos, size_t write_bytes,
397 struct page **prepared_pages,
401 size_t total_copied = 0;
403 int offset = offset_in_page(pos);
405 while (write_bytes > 0) {
406 size_t count = min_t(size_t,
407 PAGE_SIZE - offset, write_bytes);
408 struct page *page = prepared_pages[pg];
410 * Copy data from userspace to the current page
412 copied = iov_iter_copy_from_user_atomic(page, i, offset, count);
414 /* Flush processor's dcache for this page */
415 flush_dcache_page(page);
418 * if we get a partial write, we can end up with
419 * partially up to date pages. These add
420 * a lot of complexity, so make sure they don't
421 * happen by forcing this copy to be retried.
423 * The rest of the btrfs_file_write code will fall
424 * back to page at a time copies after we return 0.
426 if (!PageUptodate(page) && copied < count)
429 iov_iter_advance(i, copied);
430 write_bytes -= copied;
431 total_copied += copied;
433 /* Return to btrfs_file_write_iter to fault page */
434 if (unlikely(copied == 0))
437 if (copied < PAGE_SIZE - offset) {
448 * unlocks pages after btrfs_file_write is done with them
450 static void btrfs_drop_pages(struct page **pages, size_t num_pages)
453 for (i = 0; i < num_pages; i++) {
454 /* page checked is some magic around finding pages that
455 * have been modified without going through btrfs_set_page_dirty
456 * clear it here. There should be no need to mark the pages
457 * accessed as prepare_pages should have marked them accessed
458 * in prepare_pages via find_or_create_page()
460 ClearPageChecked(pages[i]);
461 unlock_page(pages[i]);
466 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
469 struct extent_state **cached_state)
471 u64 search_start = start;
472 const u64 end = start + len - 1;
474 while (search_start < end) {
475 const u64 search_len = end - search_start + 1;
476 struct extent_map *em;
480 em = btrfs_get_extent(inode, NULL, 0, search_start,
485 if (em->block_start != EXTENT_MAP_HOLE)
489 if (em->start < search_start)
490 em_len -= search_start - em->start;
491 if (em_len > search_len)
494 ret = set_extent_bit(&inode->io_tree, search_start,
495 search_start + em_len - 1,
497 NULL, cached_state, GFP_NOFS);
499 search_start = extent_map_end(em);
508 * after copy_from_user, pages need to be dirtied and we need to make
509 * sure holes are created between the current EOF and the start of
510 * any next extents (if required).
512 * this also makes the decision about creating an inline extent vs
513 * doing real data extents, marking pages dirty and delalloc as required.
515 int btrfs_dirty_pages(struct inode *inode, struct page **pages,
516 size_t num_pages, loff_t pos, size_t write_bytes,
517 struct extent_state **cached)
519 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
524 u64 end_of_last_block;
525 u64 end_pos = pos + write_bytes;
526 loff_t isize = i_size_read(inode);
527 unsigned int extra_bits = 0;
529 start_pos = pos & ~((u64) fs_info->sectorsize - 1);
530 num_bytes = round_up(write_bytes + pos - start_pos,
531 fs_info->sectorsize);
533 end_of_last_block = start_pos + num_bytes - 1;
536 * The pages may have already been dirty, clear out old accounting so
537 * we can set things up properly
539 clear_extent_bit(&BTRFS_I(inode)->io_tree, start_pos, end_of_last_block,
540 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
543 if (!btrfs_is_free_space_inode(BTRFS_I(inode))) {
544 if (start_pos >= isize &&
545 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)) {
547 * There can't be any extents following eof in this case
548 * so just set the delalloc new bit for the range
551 extra_bits |= EXTENT_DELALLOC_NEW;
553 err = btrfs_find_new_delalloc_bytes(BTRFS_I(inode),
561 err = btrfs_set_extent_delalloc(inode, start_pos, end_of_last_block,
566 for (i = 0; i < num_pages; i++) {
567 struct page *p = pages[i];
574 * we've only changed i_size in ram, and we haven't updated
575 * the disk i_size. There is no need to log the inode
579 i_size_write(inode, end_pos);
584 * this drops all the extents in the cache that intersect the range
585 * [start, end]. Existing extents are split as required.
587 void btrfs_drop_extent_cache(struct btrfs_inode *inode, u64 start, u64 end,
590 struct extent_map *em;
591 struct extent_map *split = NULL;
592 struct extent_map *split2 = NULL;
593 struct extent_map_tree *em_tree = &inode->extent_tree;
594 u64 len = end - start + 1;
602 WARN_ON(end < start);
603 if (end == (u64)-1) {
612 split = alloc_extent_map();
614 split2 = alloc_extent_map();
615 if (!split || !split2)
618 write_lock(&em_tree->lock);
619 em = lookup_extent_mapping(em_tree, start, len);
621 write_unlock(&em_tree->lock);
625 gen = em->generation;
626 if (skip_pinned && test_bit(EXTENT_FLAG_PINNED, &em->flags)) {
627 if (testend && em->start + em->len >= start + len) {
629 write_unlock(&em_tree->lock);
632 start = em->start + em->len;
634 len = start + len - (em->start + em->len);
636 write_unlock(&em_tree->lock);
639 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
640 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
641 clear_bit(EXTENT_FLAG_LOGGING, &flags);
642 modified = !list_empty(&em->list);
646 if (em->start < start) {
647 split->start = em->start;
648 split->len = start - em->start;
650 if (em->block_start < EXTENT_MAP_LAST_BYTE) {
651 split->orig_start = em->orig_start;
652 split->block_start = em->block_start;
655 split->block_len = em->block_len;
657 split->block_len = split->len;
658 split->orig_block_len = max(split->block_len,
660 split->ram_bytes = em->ram_bytes;
662 split->orig_start = split->start;
663 split->block_len = 0;
664 split->block_start = em->block_start;
665 split->orig_block_len = 0;
666 split->ram_bytes = split->len;
669 split->generation = gen;
670 split->flags = flags;
671 split->compress_type = em->compress_type;
672 replace_extent_mapping(em_tree, em, split, modified);
673 free_extent_map(split);
677 if (testend && em->start + em->len > start + len) {
678 u64 diff = start + len - em->start;
680 split->start = start + len;
681 split->len = em->start + em->len - (start + len);
682 split->flags = flags;
683 split->compress_type = em->compress_type;
684 split->generation = gen;
686 if (em->block_start < EXTENT_MAP_LAST_BYTE) {
687 split->orig_block_len = max(em->block_len,
690 split->ram_bytes = em->ram_bytes;
692 split->block_len = em->block_len;
693 split->block_start = em->block_start;
694 split->orig_start = em->orig_start;
696 split->block_len = split->len;
697 split->block_start = em->block_start
699 split->orig_start = em->orig_start;
702 split->ram_bytes = split->len;
703 split->orig_start = split->start;
704 split->block_len = 0;
705 split->block_start = em->block_start;
706 split->orig_block_len = 0;
709 if (extent_map_in_tree(em)) {
710 replace_extent_mapping(em_tree, em, split,
713 ret = add_extent_mapping(em_tree, split,
715 ASSERT(ret == 0); /* Logic error */
717 free_extent_map(split);
721 if (extent_map_in_tree(em))
722 remove_extent_mapping(em_tree, em);
723 write_unlock(&em_tree->lock);
727 /* once for the tree*/
731 free_extent_map(split);
733 free_extent_map(split2);
737 * this is very complex, but the basic idea is to drop all extents
738 * in the range start - end. hint_block is filled in with a block number
739 * that would be a good hint to the block allocator for this file.
741 * If an extent intersects the range but is not entirely inside the range
742 * it is either truncated or split. Anything entirely inside the range
743 * is deleted from the tree.
745 int __btrfs_drop_extents(struct btrfs_trans_handle *trans,
746 struct btrfs_root *root, struct inode *inode,
747 struct btrfs_path *path, u64 start, u64 end,
748 u64 *drop_end, int drop_cache,
750 u32 extent_item_size,
753 struct btrfs_fs_info *fs_info = root->fs_info;
754 struct extent_buffer *leaf;
755 struct btrfs_file_extent_item *fi;
756 struct btrfs_ref ref = { 0 };
757 struct btrfs_key key;
758 struct btrfs_key new_key;
759 u64 ino = btrfs_ino(BTRFS_I(inode));
760 u64 search_start = start;
763 u64 extent_offset = 0;
765 u64 last_end = start;
771 int modify_tree = -1;
774 int leafs_visited = 0;
777 btrfs_drop_extent_cache(BTRFS_I(inode), start, end - 1, 0);
779 if (start >= BTRFS_I(inode)->disk_i_size && !replace_extent)
782 update_refs = (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
783 root == fs_info->tree_root);
786 ret = btrfs_lookup_file_extent(trans, root, path, ino,
787 search_start, modify_tree);
790 if (ret > 0 && path->slots[0] > 0 && search_start == start) {
791 leaf = path->nodes[0];
792 btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
793 if (key.objectid == ino &&
794 key.type == BTRFS_EXTENT_DATA_KEY)
800 leaf = path->nodes[0];
801 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
803 ret = btrfs_next_leaf(root, path);
811 leaf = path->nodes[0];
815 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
817 if (key.objectid > ino)
819 if (WARN_ON_ONCE(key.objectid < ino) ||
820 key.type < BTRFS_EXTENT_DATA_KEY) {
825 if (key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= end)
828 fi = btrfs_item_ptr(leaf, path->slots[0],
829 struct btrfs_file_extent_item);
830 extent_type = btrfs_file_extent_type(leaf, fi);
832 if (extent_type == BTRFS_FILE_EXTENT_REG ||
833 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
834 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
835 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
836 extent_offset = btrfs_file_extent_offset(leaf, fi);
837 extent_end = key.offset +
838 btrfs_file_extent_num_bytes(leaf, fi);
839 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
840 extent_end = key.offset +
841 btrfs_file_extent_ram_bytes(leaf, fi);
848 * Don't skip extent items representing 0 byte lengths. They
849 * used to be created (bug) if while punching holes we hit
850 * -ENOSPC condition. So if we find one here, just ensure we
851 * delete it, otherwise we would insert a new file extent item
852 * with the same key (offset) as that 0 bytes length file
853 * extent item in the call to setup_items_for_insert() later
856 if (extent_end == key.offset && extent_end >= search_start) {
857 last_end = extent_end;
858 goto delete_extent_item;
861 if (extent_end <= search_start) {
867 search_start = max(key.offset, start);
868 if (recow || !modify_tree) {
870 btrfs_release_path(path);
875 * | - range to drop - |
876 * | -------- extent -------- |
878 if (start > key.offset && end < extent_end) {
880 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
885 memcpy(&new_key, &key, sizeof(new_key));
886 new_key.offset = start;
887 ret = btrfs_duplicate_item(trans, root, path,
889 if (ret == -EAGAIN) {
890 btrfs_release_path(path);
896 leaf = path->nodes[0];
897 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
898 struct btrfs_file_extent_item);
899 btrfs_set_file_extent_num_bytes(leaf, fi,
902 fi = btrfs_item_ptr(leaf, path->slots[0],
903 struct btrfs_file_extent_item);
905 extent_offset += start - key.offset;
906 btrfs_set_file_extent_offset(leaf, fi, extent_offset);
907 btrfs_set_file_extent_num_bytes(leaf, fi,
909 btrfs_mark_buffer_dirty(leaf);
911 if (update_refs && disk_bytenr > 0) {
912 btrfs_init_generic_ref(&ref,
913 BTRFS_ADD_DELAYED_REF,
914 disk_bytenr, num_bytes, 0);
915 btrfs_init_data_ref(&ref,
916 root->root_key.objectid,
918 start - extent_offset);
919 ret = btrfs_inc_extent_ref(trans, &ref);
920 BUG_ON(ret); /* -ENOMEM */
925 * From here on out we will have actually dropped something, so
926 * last_end can be updated.
928 last_end = extent_end;
931 * | ---- range to drop ----- |
932 * | -------- extent -------- |
934 if (start <= key.offset && end < extent_end) {
935 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
940 memcpy(&new_key, &key, sizeof(new_key));
941 new_key.offset = end;
942 btrfs_set_item_key_safe(fs_info, path, &new_key);
944 extent_offset += end - key.offset;
945 btrfs_set_file_extent_offset(leaf, fi, extent_offset);
946 btrfs_set_file_extent_num_bytes(leaf, fi,
948 btrfs_mark_buffer_dirty(leaf);
949 if (update_refs && disk_bytenr > 0)
950 inode_sub_bytes(inode, end - key.offset);
954 search_start = extent_end;
956 * | ---- range to drop ----- |
957 * | -------- extent -------- |
959 if (start > key.offset && end >= extent_end) {
961 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
966 btrfs_set_file_extent_num_bytes(leaf, fi,
968 btrfs_mark_buffer_dirty(leaf);
969 if (update_refs && disk_bytenr > 0)
970 inode_sub_bytes(inode, extent_end - start);
971 if (end == extent_end)
979 * | ---- range to drop ----- |
980 * | ------ extent ------ |
982 if (start <= key.offset && end >= extent_end) {
985 del_slot = path->slots[0];
988 BUG_ON(del_slot + del_nr != path->slots[0]);
993 extent_type == BTRFS_FILE_EXTENT_INLINE) {
994 inode_sub_bytes(inode,
995 extent_end - key.offset);
996 extent_end = ALIGN(extent_end,
997 fs_info->sectorsize);
998 } else if (update_refs && disk_bytenr > 0) {
999 btrfs_init_generic_ref(&ref,
1000 BTRFS_DROP_DELAYED_REF,
1001 disk_bytenr, num_bytes, 0);
1002 btrfs_init_data_ref(&ref,
1003 root->root_key.objectid,
1005 key.offset - extent_offset);
1006 ret = btrfs_free_extent(trans, &ref);
1007 BUG_ON(ret); /* -ENOMEM */
1008 inode_sub_bytes(inode,
1009 extent_end - key.offset);
1012 if (end == extent_end)
1015 if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
1020 ret = btrfs_del_items(trans, root, path, del_slot,
1023 btrfs_abort_transaction(trans, ret);
1030 btrfs_release_path(path);
1037 if (!ret && del_nr > 0) {
1039 * Set path->slots[0] to first slot, so that after the delete
1040 * if items are move off from our leaf to its immediate left or
1041 * right neighbor leafs, we end up with a correct and adjusted
1042 * path->slots[0] for our insertion (if replace_extent != 0).
1044 path->slots[0] = del_slot;
1045 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
1047 btrfs_abort_transaction(trans, ret);
1050 leaf = path->nodes[0];
1052 * If btrfs_del_items() was called, it might have deleted a leaf, in
1053 * which case it unlocked our path, so check path->locks[0] matches a
1056 if (!ret && replace_extent && leafs_visited == 1 &&
1057 (path->locks[0] == BTRFS_WRITE_LOCK_BLOCKING ||
1058 path->locks[0] == BTRFS_WRITE_LOCK) &&
1059 btrfs_leaf_free_space(leaf) >=
1060 sizeof(struct btrfs_item) + extent_item_size) {
1063 key.type = BTRFS_EXTENT_DATA_KEY;
1065 if (!del_nr && path->slots[0] < btrfs_header_nritems(leaf)) {
1066 struct btrfs_key slot_key;
1068 btrfs_item_key_to_cpu(leaf, &slot_key, path->slots[0]);
1069 if (btrfs_comp_cpu_keys(&key, &slot_key) > 0)
1072 setup_items_for_insert(root, path, &key,
1075 sizeof(struct btrfs_item) +
1076 extent_item_size, 1);
1080 if (!replace_extent || !(*key_inserted))
1081 btrfs_release_path(path);
1083 *drop_end = found ? min(end, last_end) : end;
1087 int btrfs_drop_extents(struct btrfs_trans_handle *trans,
1088 struct btrfs_root *root, struct inode *inode, u64 start,
1089 u64 end, int drop_cache)
1091 struct btrfs_path *path;
1094 path = btrfs_alloc_path();
1097 ret = __btrfs_drop_extents(trans, root, inode, path, start, end, NULL,
1098 drop_cache, 0, 0, NULL);
1099 btrfs_free_path(path);
1103 static int extent_mergeable(struct extent_buffer *leaf, int slot,
1104 u64 objectid, u64 bytenr, u64 orig_offset,
1105 u64 *start, u64 *end)
1107 struct btrfs_file_extent_item *fi;
1108 struct btrfs_key key;
1111 if (slot < 0 || slot >= btrfs_header_nritems(leaf))
1114 btrfs_item_key_to_cpu(leaf, &key, slot);
1115 if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
1118 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
1119 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
1120 btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
1121 btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
1122 btrfs_file_extent_compression(leaf, fi) ||
1123 btrfs_file_extent_encryption(leaf, fi) ||
1124 btrfs_file_extent_other_encoding(leaf, fi))
1127 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
1128 if ((*start && *start != key.offset) || (*end && *end != extent_end))
1131 *start = key.offset;
1137 * Mark extent in the range start - end as written.
1139 * This changes extent type from 'pre-allocated' to 'regular'. If only
1140 * part of extent is marked as written, the extent will be split into
1143 int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
1144 struct btrfs_inode *inode, u64 start, u64 end)
1146 struct btrfs_fs_info *fs_info = trans->fs_info;
1147 struct btrfs_root *root = inode->root;
1148 struct extent_buffer *leaf;
1149 struct btrfs_path *path;
1150 struct btrfs_file_extent_item *fi;
1151 struct btrfs_ref ref = { 0 };
1152 struct btrfs_key key;
1153 struct btrfs_key new_key;
1165 u64 ino = btrfs_ino(inode);
1167 path = btrfs_alloc_path();
1174 key.type = BTRFS_EXTENT_DATA_KEY;
1177 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1180 if (ret > 0 && path->slots[0] > 0)
1183 leaf = path->nodes[0];
1184 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1185 if (key.objectid != ino ||
1186 key.type != BTRFS_EXTENT_DATA_KEY) {
1188 btrfs_abort_transaction(trans, ret);
1191 fi = btrfs_item_ptr(leaf, path->slots[0],
1192 struct btrfs_file_extent_item);
1193 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_PREALLOC) {
1195 btrfs_abort_transaction(trans, ret);
1198 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
1199 if (key.offset > start || extent_end < end) {
1201 btrfs_abort_transaction(trans, ret);
1205 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1206 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1207 orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
1208 memcpy(&new_key, &key, sizeof(new_key));
1210 if (start == key.offset && end < extent_end) {
1213 if (extent_mergeable(leaf, path->slots[0] - 1,
1214 ino, bytenr, orig_offset,
1215 &other_start, &other_end)) {
1216 new_key.offset = end;
1217 btrfs_set_item_key_safe(fs_info, path, &new_key);
1218 fi = btrfs_item_ptr(leaf, path->slots[0],
1219 struct btrfs_file_extent_item);
1220 btrfs_set_file_extent_generation(leaf, fi,
1222 btrfs_set_file_extent_num_bytes(leaf, fi,
1224 btrfs_set_file_extent_offset(leaf, fi,
1226 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
1227 struct btrfs_file_extent_item);
1228 btrfs_set_file_extent_generation(leaf, fi,
1230 btrfs_set_file_extent_num_bytes(leaf, fi,
1232 btrfs_mark_buffer_dirty(leaf);
1237 if (start > key.offset && end == extent_end) {
1240 if (extent_mergeable(leaf, path->slots[0] + 1,
1241 ino, bytenr, orig_offset,
1242 &other_start, &other_end)) {
1243 fi = btrfs_item_ptr(leaf, path->slots[0],
1244 struct btrfs_file_extent_item);
1245 btrfs_set_file_extent_num_bytes(leaf, fi,
1246 start - key.offset);
1247 btrfs_set_file_extent_generation(leaf, fi,
1250 new_key.offset = start;
1251 btrfs_set_item_key_safe(fs_info, path, &new_key);
1253 fi = btrfs_item_ptr(leaf, path->slots[0],
1254 struct btrfs_file_extent_item);
1255 btrfs_set_file_extent_generation(leaf, fi,
1257 btrfs_set_file_extent_num_bytes(leaf, fi,
1259 btrfs_set_file_extent_offset(leaf, fi,
1260 start - orig_offset);
1261 btrfs_mark_buffer_dirty(leaf);
1266 while (start > key.offset || end < extent_end) {
1267 if (key.offset == start)
1270 new_key.offset = split;
1271 ret = btrfs_duplicate_item(trans, root, path, &new_key);
1272 if (ret == -EAGAIN) {
1273 btrfs_release_path(path);
1277 btrfs_abort_transaction(trans, ret);
1281 leaf = path->nodes[0];
1282 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
1283 struct btrfs_file_extent_item);
1284 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1285 btrfs_set_file_extent_num_bytes(leaf, fi,
1286 split - key.offset);
1288 fi = btrfs_item_ptr(leaf, path->slots[0],
1289 struct btrfs_file_extent_item);
1291 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1292 btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
1293 btrfs_set_file_extent_num_bytes(leaf, fi,
1294 extent_end - split);
1295 btrfs_mark_buffer_dirty(leaf);
1297 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, bytenr,
1299 btrfs_init_data_ref(&ref, root->root_key.objectid, ino,
1301 ret = btrfs_inc_extent_ref(trans, &ref);
1303 btrfs_abort_transaction(trans, ret);
1307 if (split == start) {
1310 if (start != key.offset) {
1312 btrfs_abort_transaction(trans, ret);
1323 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
1325 btrfs_init_data_ref(&ref, root->root_key.objectid, ino, orig_offset);
1326 if (extent_mergeable(leaf, path->slots[0] + 1,
1327 ino, bytenr, orig_offset,
1328 &other_start, &other_end)) {
1330 btrfs_release_path(path);
1333 extent_end = other_end;
1334 del_slot = path->slots[0] + 1;
1336 ret = btrfs_free_extent(trans, &ref);
1338 btrfs_abort_transaction(trans, ret);
1344 if (extent_mergeable(leaf, path->slots[0] - 1,
1345 ino, bytenr, orig_offset,
1346 &other_start, &other_end)) {
1348 btrfs_release_path(path);
1351 key.offset = other_start;
1352 del_slot = path->slots[0];
1354 ret = btrfs_free_extent(trans, &ref);
1356 btrfs_abort_transaction(trans, ret);
1361 fi = btrfs_item_ptr(leaf, path->slots[0],
1362 struct btrfs_file_extent_item);
1363 btrfs_set_file_extent_type(leaf, fi,
1364 BTRFS_FILE_EXTENT_REG);
1365 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1366 btrfs_mark_buffer_dirty(leaf);
1368 fi = btrfs_item_ptr(leaf, del_slot - 1,
1369 struct btrfs_file_extent_item);
1370 btrfs_set_file_extent_type(leaf, fi,
1371 BTRFS_FILE_EXTENT_REG);
1372 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1373 btrfs_set_file_extent_num_bytes(leaf, fi,
1374 extent_end - key.offset);
1375 btrfs_mark_buffer_dirty(leaf);
1377 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
1379 btrfs_abort_transaction(trans, ret);
1384 btrfs_free_path(path);
1389 * on error we return an unlocked page and the error value
1390 * on success we return a locked page and 0
1392 static int prepare_uptodate_page(struct inode *inode,
1393 struct page *page, u64 pos,
1394 bool force_uptodate)
1398 if (((pos & (PAGE_SIZE - 1)) || force_uptodate) &&
1399 !PageUptodate(page)) {
1400 ret = btrfs_readpage(NULL, page);
1404 if (!PageUptodate(page)) {
1408 if (page->mapping != inode->i_mapping) {
1417 * this just gets pages into the page cache and locks them down.
1419 static noinline int prepare_pages(struct inode *inode, struct page **pages,
1420 size_t num_pages, loff_t pos,
1421 size_t write_bytes, bool force_uptodate)
1424 unsigned long index = pos >> PAGE_SHIFT;
1425 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1429 for (i = 0; i < num_pages; i++) {
1431 pages[i] = find_or_create_page(inode->i_mapping, index + i,
1432 mask | __GFP_WRITE);
1440 err = prepare_uptodate_page(inode, pages[i], pos,
1442 if (!err && i == num_pages - 1)
1443 err = prepare_uptodate_page(inode, pages[i],
1444 pos + write_bytes, false);
1447 if (err == -EAGAIN) {
1454 wait_on_page_writeback(pages[i]);
1459 while (faili >= 0) {
1460 unlock_page(pages[faili]);
1461 put_page(pages[faili]);
1469 * This function locks the extent and properly waits for data=ordered extents
1470 * to finish before allowing the pages to be modified if need.
1473 * 1 - the extent is locked
1474 * 0 - the extent is not locked, and everything is OK
1475 * -EAGAIN - need re-prepare the pages
1476 * the other < 0 number - Something wrong happens
1479 lock_and_cleanup_extent_if_need(struct btrfs_inode *inode, struct page **pages,
1480 size_t num_pages, loff_t pos,
1482 u64 *lockstart, u64 *lockend,
1483 struct extent_state **cached_state)
1485 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1491 start_pos = round_down(pos, fs_info->sectorsize);
1492 last_pos = start_pos
1493 + round_up(pos + write_bytes - start_pos,
1494 fs_info->sectorsize) - 1;
1496 if (start_pos < inode->vfs_inode.i_size) {
1497 struct btrfs_ordered_extent *ordered;
1499 lock_extent_bits(&inode->io_tree, start_pos, last_pos,
1501 ordered = btrfs_lookup_ordered_range(inode, start_pos,
1502 last_pos - start_pos + 1);
1504 ordered->file_offset + ordered->len > start_pos &&
1505 ordered->file_offset <= last_pos) {
1506 unlock_extent_cached(&inode->io_tree, start_pos,
1507 last_pos, cached_state);
1508 for (i = 0; i < num_pages; i++) {
1509 unlock_page(pages[i]);
1512 btrfs_start_ordered_extent(&inode->vfs_inode,
1514 btrfs_put_ordered_extent(ordered);
1518 btrfs_put_ordered_extent(ordered);
1520 *lockstart = start_pos;
1521 *lockend = last_pos;
1526 * It's possible the pages are dirty right now, but we don't want
1527 * to clean them yet because copy_from_user may catch a page fault
1528 * and we might have to fall back to one page at a time. If that
1529 * happens, we'll unlock these pages and we'd have a window where
1530 * reclaim could sneak in and drop the once-dirty page on the floor
1531 * without writing it.
1533 * We have the pages locked and the extent range locked, so there's
1534 * no way someone can start IO on any dirty pages in this range.
1536 * We'll call btrfs_dirty_pages() later on, and that will flip around
1537 * delalloc bits and dirty the pages as required.
1539 for (i = 0; i < num_pages; i++) {
1540 set_page_extent_mapped(pages[i]);
1541 WARN_ON(!PageLocked(pages[i]));
1547 static noinline int check_can_nocow(struct btrfs_inode *inode, loff_t pos,
1548 size_t *write_bytes)
1550 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1551 struct btrfs_root *root = inode->root;
1552 u64 lockstart, lockend;
1556 ret = btrfs_start_write_no_snapshotting(root);
1560 lockstart = round_down(pos, fs_info->sectorsize);
1561 lockend = round_up(pos + *write_bytes,
1562 fs_info->sectorsize) - 1;
1564 btrfs_lock_and_flush_ordered_range(&inode->io_tree, inode, lockstart,
1567 num_bytes = lockend - lockstart + 1;
1568 ret = can_nocow_extent(&inode->vfs_inode, lockstart, &num_bytes,
1572 btrfs_end_write_no_snapshotting(root);
1574 *write_bytes = min_t(size_t, *write_bytes ,
1575 num_bytes - pos + lockstart);
1578 unlock_extent(&inode->io_tree, lockstart, lockend);
1583 static noinline ssize_t btrfs_buffered_write(struct kiocb *iocb,
1586 struct file *file = iocb->ki_filp;
1587 loff_t pos = iocb->ki_pos;
1588 struct inode *inode = file_inode(file);
1589 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1590 struct btrfs_root *root = BTRFS_I(inode)->root;
1591 struct page **pages = NULL;
1592 struct extent_changeset *data_reserved = NULL;
1593 u64 release_bytes = 0;
1596 size_t num_written = 0;
1599 bool only_release_metadata = false;
1600 bool force_page_uptodate = false;
1602 nrptrs = min(DIV_ROUND_UP(iov_iter_count(i), PAGE_SIZE),
1603 PAGE_SIZE / (sizeof(struct page *)));
1604 nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied);
1605 nrptrs = max(nrptrs, 8);
1606 pages = kmalloc_array(nrptrs, sizeof(struct page *), GFP_KERNEL);
1610 while (iov_iter_count(i) > 0) {
1611 struct extent_state *cached_state = NULL;
1612 size_t offset = offset_in_page(pos);
1613 size_t sector_offset;
1614 size_t write_bytes = min(iov_iter_count(i),
1615 nrptrs * (size_t)PAGE_SIZE -
1617 size_t num_pages = DIV_ROUND_UP(write_bytes + offset,
1619 size_t reserve_bytes;
1622 size_t dirty_sectors;
1626 WARN_ON(num_pages > nrptrs);
1629 * Fault pages before locking them in prepare_pages
1630 * to avoid recursive lock
1632 if (unlikely(iov_iter_fault_in_readable(i, write_bytes))) {
1637 only_release_metadata = false;
1638 sector_offset = pos & (fs_info->sectorsize - 1);
1639 reserve_bytes = round_up(write_bytes + sector_offset,
1640 fs_info->sectorsize);
1642 extent_changeset_release(data_reserved);
1643 ret = btrfs_check_data_free_space(inode, &data_reserved, pos,
1646 if ((BTRFS_I(inode)->flags & (BTRFS_INODE_NODATACOW |
1647 BTRFS_INODE_PREALLOC)) &&
1648 check_can_nocow(BTRFS_I(inode), pos,
1649 &write_bytes) > 0) {
1651 * For nodata cow case, no need to reserve
1654 only_release_metadata = true;
1656 * our prealloc extent may be smaller than
1657 * write_bytes, so scale down.
1659 num_pages = DIV_ROUND_UP(write_bytes + offset,
1661 reserve_bytes = round_up(write_bytes +
1663 fs_info->sectorsize);
1669 WARN_ON(reserve_bytes == 0);
1670 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
1673 if (!only_release_metadata)
1674 btrfs_free_reserved_data_space(inode,
1678 btrfs_end_write_no_snapshotting(root);
1682 release_bytes = reserve_bytes;
1685 * This is going to setup the pages array with the number of
1686 * pages we want, so we don't really need to worry about the
1687 * contents of pages from loop to loop
1689 ret = prepare_pages(inode, pages, num_pages,
1691 force_page_uptodate);
1693 btrfs_delalloc_release_extents(BTRFS_I(inode),
1698 extents_locked = lock_and_cleanup_extent_if_need(
1699 BTRFS_I(inode), pages,
1700 num_pages, pos, write_bytes, &lockstart,
1701 &lockend, &cached_state);
1702 if (extents_locked < 0) {
1703 if (extents_locked == -EAGAIN)
1705 btrfs_delalloc_release_extents(BTRFS_I(inode),
1707 ret = extents_locked;
1711 copied = btrfs_copy_from_user(pos, write_bytes, pages, i);
1713 num_sectors = BTRFS_BYTES_TO_BLKS(fs_info, reserve_bytes);
1714 dirty_sectors = round_up(copied + sector_offset,
1715 fs_info->sectorsize);
1716 dirty_sectors = BTRFS_BYTES_TO_BLKS(fs_info, dirty_sectors);
1719 * if we have trouble faulting in the pages, fall
1720 * back to one page at a time
1722 if (copied < write_bytes)
1726 force_page_uptodate = true;
1730 force_page_uptodate = false;
1731 dirty_pages = DIV_ROUND_UP(copied + offset,
1735 if (num_sectors > dirty_sectors) {
1736 /* release everything except the sectors we dirtied */
1737 release_bytes -= dirty_sectors <<
1738 fs_info->sb->s_blocksize_bits;
1739 if (only_release_metadata) {
1740 btrfs_delalloc_release_metadata(BTRFS_I(inode),
1741 release_bytes, true);
1745 __pos = round_down(pos,
1746 fs_info->sectorsize) +
1747 (dirty_pages << PAGE_SHIFT);
1748 btrfs_delalloc_release_space(inode,
1749 data_reserved, __pos,
1750 release_bytes, true);
1754 release_bytes = round_up(copied + sector_offset,
1755 fs_info->sectorsize);
1758 ret = btrfs_dirty_pages(inode, pages, dirty_pages,
1759 pos, copied, &cached_state);
1762 * If we have not locked the extent range, because the range's
1763 * start offset is >= i_size, we might still have a non-NULL
1764 * cached extent state, acquired while marking the extent range
1765 * as delalloc through btrfs_dirty_pages(). Therefore free any
1766 * possible cached extent state to avoid a memory leak.
1769 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1770 lockstart, lockend, &cached_state);
1772 free_extent_state(cached_state);
1774 btrfs_delalloc_release_extents(BTRFS_I(inode), reserve_bytes);
1776 btrfs_drop_pages(pages, num_pages);
1781 if (only_release_metadata)
1782 btrfs_end_write_no_snapshotting(root);
1784 if (only_release_metadata && copied > 0) {
1785 lockstart = round_down(pos,
1786 fs_info->sectorsize);
1787 lockend = round_up(pos + copied,
1788 fs_info->sectorsize) - 1;
1790 set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
1791 lockend, EXTENT_NORESERVE, NULL,
1795 btrfs_drop_pages(pages, num_pages);
1799 balance_dirty_pages_ratelimited(inode->i_mapping);
1800 if (dirty_pages < (fs_info->nodesize >> PAGE_SHIFT) + 1)
1801 btrfs_btree_balance_dirty(fs_info);
1804 num_written += copied;
1809 if (release_bytes) {
1810 if (only_release_metadata) {
1811 btrfs_end_write_no_snapshotting(root);
1812 btrfs_delalloc_release_metadata(BTRFS_I(inode),
1813 release_bytes, true);
1815 btrfs_delalloc_release_space(inode, data_reserved,
1816 round_down(pos, fs_info->sectorsize),
1817 release_bytes, true);
1821 extent_changeset_free(data_reserved);
1822 return num_written ? num_written : ret;
1825 static ssize_t __btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from)
1827 struct file *file = iocb->ki_filp;
1828 struct inode *inode = file_inode(file);
1831 ssize_t written_buffered;
1835 written = generic_file_direct_write(iocb, from);
1837 if (written < 0 || !iov_iter_count(from))
1841 written_buffered = btrfs_buffered_write(iocb, from);
1842 if (written_buffered < 0) {
1843 err = written_buffered;
1847 * Ensure all data is persisted. We want the next direct IO read to be
1848 * able to read what was just written.
1850 endbyte = pos + written_buffered - 1;
1851 err = btrfs_fdatawrite_range(inode, pos, endbyte);
1854 err = filemap_fdatawait_range(inode->i_mapping, pos, endbyte);
1857 written += written_buffered;
1858 iocb->ki_pos = pos + written_buffered;
1859 invalidate_mapping_pages(file->f_mapping, pos >> PAGE_SHIFT,
1860 endbyte >> PAGE_SHIFT);
1862 return written ? written : err;
1865 static void update_time_for_write(struct inode *inode)
1867 struct timespec64 now;
1869 if (IS_NOCMTIME(inode))
1872 now = current_time(inode);
1873 if (!timespec64_equal(&inode->i_mtime, &now))
1874 inode->i_mtime = now;
1876 if (!timespec64_equal(&inode->i_ctime, &now))
1877 inode->i_ctime = now;
1879 if (IS_I_VERSION(inode))
1880 inode_inc_iversion(inode);
1883 static ssize_t btrfs_file_write_iter(struct kiocb *iocb,
1884 struct iov_iter *from)
1886 struct file *file = iocb->ki_filp;
1887 struct inode *inode = file_inode(file);
1888 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1889 struct btrfs_root *root = BTRFS_I(inode)->root;
1892 ssize_t num_written = 0;
1893 const bool sync = iocb->ki_flags & IOCB_DSYNC;
1900 if (!(iocb->ki_flags & IOCB_DIRECT) &&
1901 (iocb->ki_flags & IOCB_NOWAIT))
1904 if (iocb->ki_flags & IOCB_NOWAIT) {
1905 if (!inode_trylock(inode))
1911 err = generic_write_checks(iocb, from);
1913 inode_unlock(inode);
1918 count = iov_iter_count(from);
1919 if (iocb->ki_flags & IOCB_NOWAIT) {
1921 * We will allocate space in case nodatacow is not set,
1924 if (!(BTRFS_I(inode)->flags & (BTRFS_INODE_NODATACOW |
1925 BTRFS_INODE_PREALLOC)) ||
1926 check_can_nocow(BTRFS_I(inode), pos, &count) <= 0) {
1927 inode_unlock(inode);
1932 current->backing_dev_info = inode_to_bdi(inode);
1933 err = file_remove_privs(file);
1935 inode_unlock(inode);
1940 * If BTRFS flips readonly due to some impossible error
1941 * (fs_info->fs_state now has BTRFS_SUPER_FLAG_ERROR),
1942 * although we have opened a file as writable, we have
1943 * to stop this write operation to ensure FS consistency.
1945 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
1946 inode_unlock(inode);
1952 * We reserve space for updating the inode when we reserve space for the
1953 * extent we are going to write, so we will enospc out there. We don't
1954 * need to start yet another transaction to update the inode as we will
1955 * update the inode when we finish writing whatever data we write.
1957 update_time_for_write(inode);
1959 start_pos = round_down(pos, fs_info->sectorsize);
1960 oldsize = i_size_read(inode);
1961 if (start_pos > oldsize) {
1962 /* Expand hole size to cover write data, preventing empty gap */
1963 end_pos = round_up(pos + count,
1964 fs_info->sectorsize);
1965 err = btrfs_cont_expand(inode, oldsize, end_pos);
1967 inode_unlock(inode);
1970 if (start_pos > round_up(oldsize, fs_info->sectorsize))
1975 atomic_inc(&BTRFS_I(inode)->sync_writers);
1977 if (iocb->ki_flags & IOCB_DIRECT) {
1978 num_written = __btrfs_direct_write(iocb, from);
1980 num_written = btrfs_buffered_write(iocb, from);
1981 if (num_written > 0)
1982 iocb->ki_pos = pos + num_written;
1984 pagecache_isize_extended(inode, oldsize,
1985 i_size_read(inode));
1988 inode_unlock(inode);
1991 * We also have to set last_sub_trans to the current log transid,
1992 * otherwise subsequent syncs to a file that's been synced in this
1993 * transaction will appear to have already occurred.
1995 spin_lock(&BTRFS_I(inode)->lock);
1996 BTRFS_I(inode)->last_sub_trans = root->log_transid;
1997 spin_unlock(&BTRFS_I(inode)->lock);
1998 if (num_written > 0)
1999 num_written = generic_write_sync(iocb, num_written);
2002 atomic_dec(&BTRFS_I(inode)->sync_writers);
2004 current->backing_dev_info = NULL;
2005 return num_written ? num_written : err;
2008 int btrfs_release_file(struct inode *inode, struct file *filp)
2010 struct btrfs_file_private *private = filp->private_data;
2012 if (private && private->filldir_buf)
2013 kfree(private->filldir_buf);
2015 filp->private_data = NULL;
2018 * ordered_data_close is set by setattr when we are about to truncate
2019 * a file from a non-zero size to a zero size. This tries to
2020 * flush down new bytes that may have been written if the
2021 * application were using truncate to replace a file in place.
2023 if (test_and_clear_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
2024 &BTRFS_I(inode)->runtime_flags))
2025 filemap_flush(inode->i_mapping);
2029 static int start_ordered_ops(struct inode *inode, loff_t start, loff_t end)
2032 struct blk_plug plug;
2035 * This is only called in fsync, which would do synchronous writes, so
2036 * a plug can merge adjacent IOs as much as possible. Esp. in case of
2037 * multiple disks using raid profile, a large IO can be split to
2038 * several segments of stripe length (currently 64K).
2040 blk_start_plug(&plug);
2041 atomic_inc(&BTRFS_I(inode)->sync_writers);
2042 ret = btrfs_fdatawrite_range(inode, start, end);
2043 atomic_dec(&BTRFS_I(inode)->sync_writers);
2044 blk_finish_plug(&plug);
2050 * fsync call for both files and directories. This logs the inode into
2051 * the tree log instead of forcing full commits whenever possible.
2053 * It needs to call filemap_fdatawait so that all ordered extent updates are
2054 * in the metadata btree are up to date for copying to the log.
2056 * It drops the inode mutex before doing the tree log commit. This is an
2057 * important optimization for directories because holding the mutex prevents
2058 * new operations on the dir while we write to disk.
2060 int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
2062 struct dentry *dentry = file_dentry(file);
2063 struct inode *inode = d_inode(dentry);
2064 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2065 struct btrfs_root *root = BTRFS_I(inode)->root;
2066 struct btrfs_trans_handle *trans;
2067 struct btrfs_log_ctx ctx;
2070 trace_btrfs_sync_file(file, datasync);
2072 btrfs_init_log_ctx(&ctx, inode);
2075 * We write the dirty pages in the range and wait until they complete
2076 * out of the ->i_mutex. If so, we can flush the dirty pages by
2077 * multi-task, and make the performance up. See
2078 * btrfs_wait_ordered_range for an explanation of the ASYNC check.
2080 ret = start_ordered_ops(inode, start, end);
2087 * We take the dio_sem here because the tree log stuff can race with
2088 * lockless dio writes and get an extent map logged for an extent we
2089 * never waited on. We need it this high up for lockdep reasons.
2091 down_write(&BTRFS_I(inode)->dio_sem);
2093 atomic_inc(&root->log_batch);
2096 * If the inode needs a full sync, make sure we use a full range to
2097 * avoid log tree corruption, due to hole detection racing with ordered
2098 * extent completion for adjacent ranges, and assertion failures during
2099 * hole detection. Do this while holding the inode lock, to avoid races
2102 if (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2103 &BTRFS_I(inode)->runtime_flags)) {
2109 * Before we acquired the inode's lock, someone may have dirtied more
2110 * pages in the target range. We need to make sure that writeback for
2111 * any such pages does not start while we are logging the inode, because
2112 * if it does, any of the following might happen when we are not doing a
2115 * 1) We log an extent after its writeback finishes but before its
2116 * checksums are added to the csum tree, leading to -EIO errors
2117 * when attempting to read the extent after a log replay.
2119 * 2) We can end up logging an extent before its writeback finishes.
2120 * Therefore after the log replay we will have a file extent item
2121 * pointing to an unwritten extent (and no data checksums as well).
2123 * So trigger writeback for any eventual new dirty pages and then we
2124 * wait for all ordered extents to complete below.
2126 ret = start_ordered_ops(inode, start, end);
2128 inode_unlock(inode);
2133 * We have to do this here to avoid the priority inversion of waiting on
2134 * IO of a lower priority task while holding a transaction open.
2136 * Also, the range length can be represented by u64, we have to do the
2137 * typecasts to avoid signed overflow if it's [0, LLONG_MAX].
2139 ret = btrfs_wait_ordered_range(inode, start, (u64)end - (u64)start + 1);
2141 up_write(&BTRFS_I(inode)->dio_sem);
2142 inode_unlock(inode);
2145 atomic_inc(&root->log_batch);
2148 if (btrfs_inode_in_log(BTRFS_I(inode), fs_info->generation) ||
2149 BTRFS_I(inode)->last_trans <= fs_info->last_trans_committed) {
2151 * We've had everything committed since the last time we were
2152 * modified so clear this flag in case it was set for whatever
2153 * reason, it's no longer relevant.
2155 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2156 &BTRFS_I(inode)->runtime_flags);
2158 * An ordered extent might have started before and completed
2159 * already with io errors, in which case the inode was not
2160 * updated and we end up here. So check the inode's mapping
2161 * for any errors that might have happened since we last
2162 * checked called fsync.
2164 ret = filemap_check_wb_err(inode->i_mapping, file->f_wb_err);
2165 up_write(&BTRFS_I(inode)->dio_sem);
2166 inode_unlock(inode);
2171 * We use start here because we will need to wait on the IO to complete
2172 * in btrfs_sync_log, which could require joining a transaction (for
2173 * example checking cross references in the nocow path). If we use join
2174 * here we could get into a situation where we're waiting on IO to
2175 * happen that is blocked on a transaction trying to commit. With start
2176 * we inc the extwriter counter, so we wait for all extwriters to exit
2177 * before we start blocking joiners. This comment is to keep somebody
2178 * from thinking they are super smart and changing this to
2179 * btrfs_join_transaction *cough*Josef*cough*.
2181 trans = btrfs_start_transaction(root, 0);
2182 if (IS_ERR(trans)) {
2183 ret = PTR_ERR(trans);
2184 up_write(&BTRFS_I(inode)->dio_sem);
2185 inode_unlock(inode);
2189 ret = btrfs_log_dentry_safe(trans, dentry, start, end, &ctx);
2191 /* Fallthrough and commit/free transaction. */
2195 /* we've logged all the items and now have a consistent
2196 * version of the file in the log. It is possible that
2197 * someone will come in and modify the file, but that's
2198 * fine because the log is consistent on disk, and we
2199 * have references to all of the file's extents
2201 * It is possible that someone will come in and log the
2202 * file again, but that will end up using the synchronization
2203 * inside btrfs_sync_log to keep things safe.
2205 up_write(&BTRFS_I(inode)->dio_sem);
2206 inode_unlock(inode);
2208 if (ret != BTRFS_NO_LOG_SYNC) {
2210 ret = btrfs_sync_log(trans, root, &ctx);
2212 ret = btrfs_end_transaction(trans);
2216 ret = btrfs_commit_transaction(trans);
2218 ret = btrfs_end_transaction(trans);
2221 ASSERT(list_empty(&ctx.list));
2222 err = file_check_and_advance_wb_err(file);
2225 return ret > 0 ? -EIO : ret;
2228 static const struct vm_operations_struct btrfs_file_vm_ops = {
2229 .fault = filemap_fault,
2230 .map_pages = filemap_map_pages,
2231 .page_mkwrite = btrfs_page_mkwrite,
2234 static int btrfs_file_mmap(struct file *filp, struct vm_area_struct *vma)
2236 struct address_space *mapping = filp->f_mapping;
2238 if (!mapping->a_ops->readpage)
2241 file_accessed(filp);
2242 vma->vm_ops = &btrfs_file_vm_ops;
2247 static int hole_mergeable(struct btrfs_inode *inode, struct extent_buffer *leaf,
2248 int slot, u64 start, u64 end)
2250 struct btrfs_file_extent_item *fi;
2251 struct btrfs_key key;
2253 if (slot < 0 || slot >= btrfs_header_nritems(leaf))
2256 btrfs_item_key_to_cpu(leaf, &key, slot);
2257 if (key.objectid != btrfs_ino(inode) ||
2258 key.type != BTRFS_EXTENT_DATA_KEY)
2261 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
2263 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2266 if (btrfs_file_extent_disk_bytenr(leaf, fi))
2269 if (key.offset == end)
2271 if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
2276 static int fill_holes(struct btrfs_trans_handle *trans,
2277 struct btrfs_inode *inode,
2278 struct btrfs_path *path, u64 offset, u64 end)
2280 struct btrfs_fs_info *fs_info = trans->fs_info;
2281 struct btrfs_root *root = inode->root;
2282 struct extent_buffer *leaf;
2283 struct btrfs_file_extent_item *fi;
2284 struct extent_map *hole_em;
2285 struct extent_map_tree *em_tree = &inode->extent_tree;
2286 struct btrfs_key key;
2289 if (btrfs_fs_incompat(fs_info, NO_HOLES))
2292 key.objectid = btrfs_ino(inode);
2293 key.type = BTRFS_EXTENT_DATA_KEY;
2294 key.offset = offset;
2296 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2299 * We should have dropped this offset, so if we find it then
2300 * something has gone horribly wrong.
2307 leaf = path->nodes[0];
2308 if (hole_mergeable(inode, leaf, path->slots[0] - 1, offset, end)) {
2312 fi = btrfs_item_ptr(leaf, path->slots[0],
2313 struct btrfs_file_extent_item);
2314 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
2316 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2317 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
2318 btrfs_set_file_extent_offset(leaf, fi, 0);
2319 btrfs_mark_buffer_dirty(leaf);
2323 if (hole_mergeable(inode, leaf, path->slots[0], offset, end)) {
2326 key.offset = offset;
2327 btrfs_set_item_key_safe(fs_info, path, &key);
2328 fi = btrfs_item_ptr(leaf, path->slots[0],
2329 struct btrfs_file_extent_item);
2330 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
2332 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2333 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
2334 btrfs_set_file_extent_offset(leaf, fi, 0);
2335 btrfs_mark_buffer_dirty(leaf);
2338 btrfs_release_path(path);
2340 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode),
2341 offset, 0, 0, end - offset, 0, end - offset, 0, 0, 0);
2346 btrfs_release_path(path);
2348 hole_em = alloc_extent_map();
2350 btrfs_drop_extent_cache(inode, offset, end - 1, 0);
2351 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
2353 hole_em->start = offset;
2354 hole_em->len = end - offset;
2355 hole_em->ram_bytes = hole_em->len;
2356 hole_em->orig_start = offset;
2358 hole_em->block_start = EXTENT_MAP_HOLE;
2359 hole_em->block_len = 0;
2360 hole_em->orig_block_len = 0;
2361 hole_em->compress_type = BTRFS_COMPRESS_NONE;
2362 hole_em->generation = trans->transid;
2365 btrfs_drop_extent_cache(inode, offset, end - 1, 0);
2366 write_lock(&em_tree->lock);
2367 ret = add_extent_mapping(em_tree, hole_em, 1);
2368 write_unlock(&em_tree->lock);
2369 } while (ret == -EEXIST);
2370 free_extent_map(hole_em);
2372 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2373 &inode->runtime_flags);
2380 * Find a hole extent on given inode and change start/len to the end of hole
2381 * extent.(hole/vacuum extent whose em->start <= start &&
2382 * em->start + em->len > start)
2383 * When a hole extent is found, return 1 and modify start/len.
2385 static int find_first_non_hole(struct inode *inode, u64 *start, u64 *len)
2387 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2388 struct extent_map *em;
2391 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0,
2392 round_down(*start, fs_info->sectorsize),
2393 round_up(*len, fs_info->sectorsize), 0);
2397 /* Hole or vacuum extent(only exists in no-hole mode) */
2398 if (em->block_start == EXTENT_MAP_HOLE) {
2400 *len = em->start + em->len > *start + *len ?
2401 0 : *start + *len - em->start - em->len;
2402 *start = em->start + em->len;
2404 free_extent_map(em);
2408 static int btrfs_punch_hole_lock_range(struct inode *inode,
2409 const u64 lockstart,
2411 struct extent_state **cached_state)
2414 struct btrfs_ordered_extent *ordered;
2417 truncate_pagecache_range(inode, lockstart, lockend);
2419 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2421 ordered = btrfs_lookup_first_ordered_extent(inode, lockend);
2424 * We need to make sure we have no ordered extents in this range
2425 * and nobody raced in and read a page in this range, if we did
2426 * we need to try again.
2429 (ordered->file_offset + ordered->len <= lockstart ||
2430 ordered->file_offset > lockend)) &&
2431 !filemap_range_has_page(inode->i_mapping,
2432 lockstart, lockend)) {
2434 btrfs_put_ordered_extent(ordered);
2438 btrfs_put_ordered_extent(ordered);
2439 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
2440 lockend, cached_state);
2441 ret = btrfs_wait_ordered_range(inode, lockstart,
2442 lockend - lockstart + 1);
2449 static int btrfs_insert_clone_extent(struct btrfs_trans_handle *trans,
2450 struct inode *inode,
2451 struct btrfs_path *path,
2452 struct btrfs_clone_extent_info *clone_info,
2453 const u64 clone_len)
2455 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2456 struct btrfs_root *root = BTRFS_I(inode)->root;
2457 struct btrfs_file_extent_item *extent;
2458 struct extent_buffer *leaf;
2459 struct btrfs_key key;
2461 struct btrfs_ref ref = { 0 };
2468 if (clone_info->disk_offset == 0 &&
2469 btrfs_fs_incompat(fs_info, NO_HOLES))
2472 key.objectid = btrfs_ino(BTRFS_I(inode));
2473 key.type = BTRFS_EXTENT_DATA_KEY;
2474 key.offset = clone_info->file_offset;
2475 ret = btrfs_insert_empty_item(trans, root, path, &key,
2476 clone_info->item_size);
2479 leaf = path->nodes[0];
2480 slot = path->slots[0];
2481 write_extent_buffer(leaf, clone_info->extent_buf,
2482 btrfs_item_ptr_offset(leaf, slot),
2483 clone_info->item_size);
2484 extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
2485 btrfs_set_file_extent_offset(leaf, extent, clone_info->data_offset);
2486 btrfs_set_file_extent_num_bytes(leaf, extent, clone_len);
2487 btrfs_mark_buffer_dirty(leaf);
2488 btrfs_release_path(path);
2490 /* If it's a hole, nothing more needs to be done. */
2491 if (clone_info->disk_offset == 0)
2494 inode_add_bytes(inode, clone_len);
2495 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF,
2496 clone_info->disk_offset,
2497 clone_info->disk_len, 0);
2498 ref_offset = clone_info->file_offset - clone_info->data_offset;
2499 btrfs_init_data_ref(&ref, root->root_key.objectid,
2500 btrfs_ino(BTRFS_I(inode)), ref_offset);
2501 ret = btrfs_inc_extent_ref(trans, &ref);
2507 * The respective range must have been previously locked, as well as the inode.
2508 * The end offset is inclusive (last byte of the range).
2509 * @clone_info is NULL for fallocate's hole punching and non-NULL for extent
2511 * When cloning, we don't want to end up in a state where we dropped extents
2512 * without inserting a new one, so we must abort the transaction to avoid a
2515 int btrfs_punch_hole_range(struct inode *inode, struct btrfs_path *path,
2516 const u64 start, const u64 end,
2517 struct btrfs_clone_extent_info *clone_info,
2518 struct btrfs_trans_handle **trans_out)
2520 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2521 u64 min_size = btrfs_calc_insert_metadata_size(fs_info, 1);
2522 u64 ino_size = round_up(inode->i_size, fs_info->sectorsize);
2523 struct btrfs_root *root = BTRFS_I(inode)->root;
2524 struct btrfs_trans_handle *trans = NULL;
2525 struct btrfs_block_rsv *rsv;
2526 unsigned int rsv_count;
2529 u64 len = end - start;
2535 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
2540 rsv->size = btrfs_calc_insert_metadata_size(fs_info, 1);
2544 * 1 - update the inode
2545 * 1 - removing the extents in the range
2546 * 1 - adding the hole extent if no_holes isn't set or if we are cloning
2549 if (!btrfs_fs_incompat(fs_info, NO_HOLES) || clone_info)
2554 trans = btrfs_start_transaction(root, rsv_count);
2555 if (IS_ERR(trans)) {
2556 ret = PTR_ERR(trans);
2561 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
2564 trans->block_rsv = rsv;
2567 while (cur_offset < end) {
2568 ret = __btrfs_drop_extents(trans, root, inode, path,
2569 cur_offset, end + 1, &drop_end,
2571 if (ret != -ENOSPC) {
2573 * When cloning we want to avoid transaction aborts when
2574 * nothing was done and we are attempting to clone parts
2575 * of inline extents, in such cases -EOPNOTSUPP is
2576 * returned by __btrfs_drop_extents() without having
2577 * changed anything in the file.
2579 if (clone_info && ret && ret != -EOPNOTSUPP)
2580 btrfs_abort_transaction(trans, ret);
2584 trans->block_rsv = &fs_info->trans_block_rsv;
2586 if (!clone_info && cur_offset < drop_end &&
2587 cur_offset < ino_size) {
2588 ret = fill_holes(trans, BTRFS_I(inode), path,
2589 cur_offset, drop_end);
2592 * If we failed then we didn't insert our hole
2593 * entries for the area we dropped, so now the
2594 * fs is corrupted, so we must abort the
2597 btrfs_abort_transaction(trans, ret);
2602 if (clone_info && drop_end > clone_info->file_offset) {
2603 u64 clone_len = drop_end - clone_info->file_offset;
2605 ret = btrfs_insert_clone_extent(trans, inode, path,
2606 clone_info, clone_len);
2608 btrfs_abort_transaction(trans, ret);
2611 clone_info->data_len -= clone_len;
2612 clone_info->data_offset += clone_len;
2613 clone_info->file_offset += clone_len;
2616 cur_offset = drop_end;
2618 ret = btrfs_update_inode(trans, root, inode);
2622 btrfs_end_transaction(trans);
2623 btrfs_btree_balance_dirty(fs_info);
2625 trans = btrfs_start_transaction(root, rsv_count);
2626 if (IS_ERR(trans)) {
2627 ret = PTR_ERR(trans);
2632 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
2633 rsv, min_size, false);
2634 BUG_ON(ret); /* shouldn't happen */
2635 trans->block_rsv = rsv;
2638 ret = find_first_non_hole(inode, &cur_offset, &len);
2639 if (unlikely(ret < 0))
2649 * If we were cloning, force the next fsync to be a full one since we
2650 * we replaced (or just dropped in the case of cloning holes when
2651 * NO_HOLES is enabled) extents and extent maps.
2652 * This is for the sake of simplicity, and cloning into files larger
2653 * than 16Mb would force the full fsync any way (when
2654 * try_release_extent_mapping() is invoked during page cache truncation.
2657 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2658 &BTRFS_I(inode)->runtime_flags);
2663 trans->block_rsv = &fs_info->trans_block_rsv;
2665 * If we are using the NO_HOLES feature we might have had already an
2666 * hole that overlaps a part of the region [lockstart, lockend] and
2667 * ends at (or beyond) lockend. Since we have no file extent items to
2668 * represent holes, drop_end can be less than lockend and so we must
2669 * make sure we have an extent map representing the existing hole (the
2670 * call to __btrfs_drop_extents() might have dropped the existing extent
2671 * map representing the existing hole), otherwise the fast fsync path
2672 * will not record the existence of the hole region
2673 * [existing_hole_start, lockend].
2675 if (drop_end <= end)
2678 * Don't insert file hole extent item if it's for a range beyond eof
2679 * (because it's useless) or if it represents a 0 bytes range (when
2680 * cur_offset == drop_end).
2682 if (!clone_info && cur_offset < ino_size && cur_offset < drop_end) {
2683 ret = fill_holes(trans, BTRFS_I(inode), path,
2684 cur_offset, drop_end);
2686 /* Same comment as above. */
2687 btrfs_abort_transaction(trans, ret);
2692 ret = btrfs_insert_clone_extent(trans, inode, path, clone_info,
2693 clone_info->data_len);
2695 btrfs_abort_transaction(trans, ret);
2704 trans->block_rsv = &fs_info->trans_block_rsv;
2706 btrfs_end_transaction(trans);
2710 btrfs_free_block_rsv(fs_info, rsv);
2715 static int btrfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
2717 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2718 struct btrfs_root *root = BTRFS_I(inode)->root;
2719 struct extent_state *cached_state = NULL;
2720 struct btrfs_path *path;
2721 struct btrfs_trans_handle *trans = NULL;
2726 u64 orig_start = offset;
2730 bool truncated_block = false;
2731 bool updated_inode = false;
2733 ret = btrfs_wait_ordered_range(inode, offset, len);
2738 ino_size = round_up(inode->i_size, fs_info->sectorsize);
2739 ret = find_first_non_hole(inode, &offset, &len);
2741 goto out_only_mutex;
2743 /* Already in a large hole */
2745 goto out_only_mutex;
2748 lockstart = round_up(offset, btrfs_inode_sectorsize(inode));
2749 lockend = round_down(offset + len,
2750 btrfs_inode_sectorsize(inode)) - 1;
2751 same_block = (BTRFS_BYTES_TO_BLKS(fs_info, offset))
2752 == (BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1));
2754 * We needn't truncate any block which is beyond the end of the file
2755 * because we are sure there is no data there.
2758 * Only do this if we are in the same block and we aren't doing the
2761 if (same_block && len < fs_info->sectorsize) {
2762 if (offset < ino_size) {
2763 truncated_block = true;
2764 ret = btrfs_truncate_block(inode, offset, len, 0);
2768 goto out_only_mutex;
2771 /* zero back part of the first block */
2772 if (offset < ino_size) {
2773 truncated_block = true;
2774 ret = btrfs_truncate_block(inode, offset, 0, 0);
2776 inode_unlock(inode);
2781 /* Check the aligned pages after the first unaligned page,
2782 * if offset != orig_start, which means the first unaligned page
2783 * including several following pages are already in holes,
2784 * the extra check can be skipped */
2785 if (offset == orig_start) {
2786 /* after truncate page, check hole again */
2787 len = offset + len - lockstart;
2789 ret = find_first_non_hole(inode, &offset, &len);
2791 goto out_only_mutex;
2794 goto out_only_mutex;
2799 /* Check the tail unaligned part is in a hole */
2800 tail_start = lockend + 1;
2801 tail_len = offset + len - tail_start;
2803 ret = find_first_non_hole(inode, &tail_start, &tail_len);
2804 if (unlikely(ret < 0))
2805 goto out_only_mutex;
2807 /* zero the front end of the last page */
2808 if (tail_start + tail_len < ino_size) {
2809 truncated_block = true;
2810 ret = btrfs_truncate_block(inode,
2811 tail_start + tail_len,
2814 goto out_only_mutex;
2819 if (lockend < lockstart) {
2821 goto out_only_mutex;
2824 ret = btrfs_punch_hole_lock_range(inode, lockstart, lockend,
2827 goto out_only_mutex;
2829 path = btrfs_alloc_path();
2835 ret = btrfs_punch_hole_range(inode, path, lockstart, lockend, NULL,
2837 btrfs_free_path(path);
2841 ASSERT(trans != NULL);
2842 inode_inc_iversion(inode);
2843 inode->i_mtime = inode->i_ctime = current_time(inode);
2844 ret = btrfs_update_inode(trans, root, inode);
2845 updated_inode = true;
2846 btrfs_end_transaction(trans);
2847 btrfs_btree_balance_dirty(fs_info);
2849 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2852 if (!updated_inode && truncated_block && !ret) {
2854 * If we only end up zeroing part of a page, we still need to
2855 * update the inode item, so that all the time fields are
2856 * updated as well as the necessary btrfs inode in memory fields
2857 * for detecting, at fsync time, if the inode isn't yet in the
2858 * log tree or it's there but not up to date.
2860 struct timespec64 now = current_time(inode);
2862 inode_inc_iversion(inode);
2863 inode->i_mtime = now;
2864 inode->i_ctime = now;
2865 trans = btrfs_start_transaction(root, 1);
2866 if (IS_ERR(trans)) {
2867 ret = PTR_ERR(trans);
2871 ret = btrfs_update_inode(trans, root, inode);
2872 ret2 = btrfs_end_transaction(trans);
2877 inode_unlock(inode);
2881 /* Helper structure to record which range is already reserved */
2882 struct falloc_range {
2883 struct list_head list;
2889 * Helper function to add falloc range
2891 * Caller should have locked the larger range of extent containing
2894 static int add_falloc_range(struct list_head *head, u64 start, u64 len)
2896 struct falloc_range *prev = NULL;
2897 struct falloc_range *range = NULL;
2899 if (list_empty(head))
2903 * As fallocate iterate by bytenr order, we only need to check
2906 prev = list_entry(head->prev, struct falloc_range, list);
2907 if (prev->start + prev->len == start) {
2912 range = kmalloc(sizeof(*range), GFP_KERNEL);
2915 range->start = start;
2917 list_add_tail(&range->list, head);
2921 static int btrfs_fallocate_update_isize(struct inode *inode,
2925 struct btrfs_trans_handle *trans;
2926 struct btrfs_root *root = BTRFS_I(inode)->root;
2930 if (mode & FALLOC_FL_KEEP_SIZE || end <= i_size_read(inode))
2933 trans = btrfs_start_transaction(root, 1);
2935 return PTR_ERR(trans);
2937 inode->i_ctime = current_time(inode);
2938 i_size_write(inode, end);
2939 btrfs_ordered_update_i_size(inode, end, NULL);
2940 ret = btrfs_update_inode(trans, root, inode);
2941 ret2 = btrfs_end_transaction(trans);
2943 return ret ? ret : ret2;
2947 RANGE_BOUNDARY_WRITTEN_EXTENT,
2948 RANGE_BOUNDARY_PREALLOC_EXTENT,
2949 RANGE_BOUNDARY_HOLE,
2952 static int btrfs_zero_range_check_range_boundary(struct inode *inode,
2955 const u64 sectorsize = btrfs_inode_sectorsize(inode);
2956 struct extent_map *em;
2959 offset = round_down(offset, sectorsize);
2960 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, offset, sectorsize, 0);
2964 if (em->block_start == EXTENT_MAP_HOLE)
2965 ret = RANGE_BOUNDARY_HOLE;
2966 else if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
2967 ret = RANGE_BOUNDARY_PREALLOC_EXTENT;
2969 ret = RANGE_BOUNDARY_WRITTEN_EXTENT;
2971 free_extent_map(em);
2975 static int btrfs_zero_range(struct inode *inode,
2980 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2981 struct extent_map *em;
2982 struct extent_changeset *data_reserved = NULL;
2985 const u64 sectorsize = btrfs_inode_sectorsize(inode);
2986 u64 alloc_start = round_down(offset, sectorsize);
2987 u64 alloc_end = round_up(offset + len, sectorsize);
2988 u64 bytes_to_reserve = 0;
2989 bool space_reserved = false;
2991 inode_dio_wait(inode);
2993 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0,
2994 alloc_start, alloc_end - alloc_start, 0);
3001 * Avoid hole punching and extent allocation for some cases. More cases
3002 * could be considered, but these are unlikely common and we keep things
3003 * as simple as possible for now. Also, intentionally, if the target
3004 * range contains one or more prealloc extents together with regular
3005 * extents and holes, we drop all the existing extents and allocate a
3006 * new prealloc extent, so that we get a larger contiguous disk extent.
3008 if (em->start <= alloc_start &&
3009 test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3010 const u64 em_end = em->start + em->len;
3012 if (em_end >= offset + len) {
3014 * The whole range is already a prealloc extent,
3015 * do nothing except updating the inode's i_size if
3018 free_extent_map(em);
3019 ret = btrfs_fallocate_update_isize(inode, offset + len,
3024 * Part of the range is already a prealloc extent, so operate
3025 * only on the remaining part of the range.
3027 alloc_start = em_end;
3028 ASSERT(IS_ALIGNED(alloc_start, sectorsize));
3029 len = offset + len - alloc_start;
3030 offset = alloc_start;
3031 alloc_hint = em->block_start + em->len;
3033 free_extent_map(em);
3035 if (BTRFS_BYTES_TO_BLKS(fs_info, offset) ==
3036 BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1)) {
3037 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0,
3038 alloc_start, sectorsize, 0);
3044 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3045 free_extent_map(em);
3046 ret = btrfs_fallocate_update_isize(inode, offset + len,
3050 if (len < sectorsize && em->block_start != EXTENT_MAP_HOLE) {
3051 free_extent_map(em);
3052 ret = btrfs_truncate_block(inode, offset, len, 0);
3054 ret = btrfs_fallocate_update_isize(inode,
3059 free_extent_map(em);
3060 alloc_start = round_down(offset, sectorsize);
3061 alloc_end = alloc_start + sectorsize;
3065 alloc_start = round_up(offset, sectorsize);
3066 alloc_end = round_down(offset + len, sectorsize);
3069 * For unaligned ranges, check the pages at the boundaries, they might
3070 * map to an extent, in which case we need to partially zero them, or
3071 * they might map to a hole, in which case we need our allocation range
3074 if (!IS_ALIGNED(offset, sectorsize)) {
3075 ret = btrfs_zero_range_check_range_boundary(inode, offset);
3078 if (ret == RANGE_BOUNDARY_HOLE) {
3079 alloc_start = round_down(offset, sectorsize);
3081 } else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) {
3082 ret = btrfs_truncate_block(inode, offset, 0, 0);
3090 if (!IS_ALIGNED(offset + len, sectorsize)) {
3091 ret = btrfs_zero_range_check_range_boundary(inode,
3095 if (ret == RANGE_BOUNDARY_HOLE) {
3096 alloc_end = round_up(offset + len, sectorsize);
3098 } else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) {
3099 ret = btrfs_truncate_block(inode, offset + len, 0, 1);
3108 if (alloc_start < alloc_end) {
3109 struct extent_state *cached_state = NULL;
3110 const u64 lockstart = alloc_start;
3111 const u64 lockend = alloc_end - 1;
3113 bytes_to_reserve = alloc_end - alloc_start;
3114 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
3118 space_reserved = true;
3119 ret = btrfs_qgroup_reserve_data(inode, &data_reserved,
3120 alloc_start, bytes_to_reserve);
3123 ret = btrfs_punch_hole_lock_range(inode, lockstart, lockend,
3127 ret = btrfs_prealloc_file_range(inode, mode, alloc_start,
3128 alloc_end - alloc_start,
3130 offset + len, &alloc_hint);
3131 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
3132 lockend, &cached_state);
3133 /* btrfs_prealloc_file_range releases reserved space on error */
3135 space_reserved = false;
3139 ret = btrfs_fallocate_update_isize(inode, offset + len, mode);
3141 if (ret && space_reserved)
3142 btrfs_free_reserved_data_space(inode, data_reserved,
3143 alloc_start, bytes_to_reserve);
3144 extent_changeset_free(data_reserved);
3149 static long btrfs_fallocate(struct file *file, int mode,
3150 loff_t offset, loff_t len)
3152 struct inode *inode = file_inode(file);
3153 struct extent_state *cached_state = NULL;
3154 struct extent_changeset *data_reserved = NULL;
3155 struct falloc_range *range;
3156 struct falloc_range *tmp;
3157 struct list_head reserve_list;
3165 struct extent_map *em;
3166 int blocksize = btrfs_inode_sectorsize(inode);
3169 alloc_start = round_down(offset, blocksize);
3170 alloc_end = round_up(offset + len, blocksize);
3171 cur_offset = alloc_start;
3173 /* Make sure we aren't being give some crap mode */
3174 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
3175 FALLOC_FL_ZERO_RANGE))
3178 if (mode & FALLOC_FL_PUNCH_HOLE)
3179 return btrfs_punch_hole(inode, offset, len);
3182 * Only trigger disk allocation, don't trigger qgroup reserve
3184 * For qgroup space, it will be checked later.
3186 if (!(mode & FALLOC_FL_ZERO_RANGE)) {
3187 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
3188 alloc_end - alloc_start);
3195 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size) {
3196 ret = inode_newsize_ok(inode, offset + len);
3202 * TODO: Move these two operations after we have checked
3203 * accurate reserved space, or fallocate can still fail but
3204 * with page truncated or size expanded.
3206 * But that's a minor problem and won't do much harm BTW.
3208 if (alloc_start > inode->i_size) {
3209 ret = btrfs_cont_expand(inode, i_size_read(inode),
3213 } else if (offset + len > inode->i_size) {
3215 * If we are fallocating from the end of the file onward we
3216 * need to zero out the end of the block if i_size lands in the
3217 * middle of a block.
3219 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
3225 * wait for ordered IO before we have any locks. We'll loop again
3226 * below with the locks held.
3228 ret = btrfs_wait_ordered_range(inode, alloc_start,
3229 alloc_end - alloc_start);
3233 if (mode & FALLOC_FL_ZERO_RANGE) {
3234 ret = btrfs_zero_range(inode, offset, len, mode);
3235 inode_unlock(inode);
3239 locked_end = alloc_end - 1;
3241 struct btrfs_ordered_extent *ordered;
3243 /* the extent lock is ordered inside the running
3246 lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
3247 locked_end, &cached_state);
3248 ordered = btrfs_lookup_first_ordered_extent(inode, locked_end);
3251 ordered->file_offset + ordered->len > alloc_start &&
3252 ordered->file_offset < alloc_end) {
3253 btrfs_put_ordered_extent(ordered);
3254 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
3255 alloc_start, locked_end,
3258 * we can't wait on the range with the transaction
3259 * running or with the extent lock held
3261 ret = btrfs_wait_ordered_range(inode, alloc_start,
3262 alloc_end - alloc_start);
3267 btrfs_put_ordered_extent(ordered);
3272 /* First, check if we exceed the qgroup limit */
3273 INIT_LIST_HEAD(&reserve_list);
3274 while (cur_offset < alloc_end) {
3275 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
3276 alloc_end - cur_offset, 0);
3281 last_byte = min(extent_map_end(em), alloc_end);
3282 actual_end = min_t(u64, extent_map_end(em), offset + len);
3283 last_byte = ALIGN(last_byte, blocksize);
3284 if (em->block_start == EXTENT_MAP_HOLE ||
3285 (cur_offset >= inode->i_size &&
3286 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
3287 ret = add_falloc_range(&reserve_list, cur_offset,
3288 last_byte - cur_offset);
3290 free_extent_map(em);
3293 ret = btrfs_qgroup_reserve_data(inode, &data_reserved,
3294 cur_offset, last_byte - cur_offset);
3296 cur_offset = last_byte;
3297 free_extent_map(em);
3302 * Do not need to reserve unwritten extent for this
3303 * range, free reserved data space first, otherwise
3304 * it'll result in false ENOSPC error.
3306 btrfs_free_reserved_data_space(inode, data_reserved,
3307 cur_offset, last_byte - cur_offset);
3309 free_extent_map(em);
3310 cur_offset = last_byte;
3314 * If ret is still 0, means we're OK to fallocate.
3315 * Or just cleanup the list and exit.
3317 list_for_each_entry_safe(range, tmp, &reserve_list, list) {
3319 ret = btrfs_prealloc_file_range(inode, mode,
3321 range->len, i_blocksize(inode),
3322 offset + len, &alloc_hint);
3324 btrfs_free_reserved_data_space(inode,
3325 data_reserved, range->start,
3327 list_del(&range->list);
3334 * We didn't need to allocate any more space, but we still extended the
3335 * size of the file so we need to update i_size and the inode item.
3337 ret = btrfs_fallocate_update_isize(inode, actual_end, mode);
3339 unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
3342 inode_unlock(inode);
3343 /* Let go of our reservation. */
3344 if (ret != 0 && !(mode & FALLOC_FL_ZERO_RANGE))
3345 btrfs_free_reserved_data_space(inode, data_reserved,
3346 cur_offset, alloc_end - cur_offset);
3347 extent_changeset_free(data_reserved);
3351 static loff_t find_desired_extent(struct inode *inode, loff_t offset,
3354 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3355 struct extent_map *em = NULL;
3356 struct extent_state *cached_state = NULL;
3357 loff_t i_size = inode->i_size;
3364 if (i_size == 0 || offset >= i_size)
3368 * offset can be negative, in this case we start finding DATA/HOLE from
3369 * the very start of the file.
3371 start = max_t(loff_t, 0, offset);
3373 lockstart = round_down(start, fs_info->sectorsize);
3374 lockend = round_up(i_size, fs_info->sectorsize);
3375 if (lockend <= lockstart)
3376 lockend = lockstart + fs_info->sectorsize;
3378 len = lockend - lockstart + 1;
3380 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
3383 while (start < i_size) {
3384 em = btrfs_get_extent_fiemap(BTRFS_I(inode), start, len);
3391 if (whence == SEEK_HOLE &&
3392 (em->block_start == EXTENT_MAP_HOLE ||
3393 test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
3395 else if (whence == SEEK_DATA &&
3396 (em->block_start != EXTENT_MAP_HOLE &&
3397 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
3400 start = em->start + em->len;
3401 free_extent_map(em);
3405 free_extent_map(em);
3406 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
3411 if (whence == SEEK_DATA && start >= i_size)
3414 offset = min_t(loff_t, start, i_size);
3420 static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
3422 struct inode *inode = file->f_mapping->host;
3426 return generic_file_llseek(file, offset, whence);
3429 inode_lock_shared(inode);
3430 offset = find_desired_extent(inode, offset, whence);
3431 inode_unlock_shared(inode);
3438 return vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
3441 static int btrfs_file_open(struct inode *inode, struct file *filp)
3443 filp->f_mode |= FMODE_NOWAIT;
3444 return generic_file_open(inode, filp);
3447 const struct file_operations btrfs_file_operations = {
3448 .llseek = btrfs_file_llseek,
3449 .read_iter = generic_file_read_iter,
3450 .splice_read = generic_file_splice_read,
3451 .write_iter = btrfs_file_write_iter,
3452 .mmap = btrfs_file_mmap,
3453 .open = btrfs_file_open,
3454 .release = btrfs_release_file,
3455 .fsync = btrfs_sync_file,
3456 .fallocate = btrfs_fallocate,
3457 .unlocked_ioctl = btrfs_ioctl,
3458 #ifdef CONFIG_COMPAT
3459 .compat_ioctl = btrfs_compat_ioctl,
3461 .remap_file_range = btrfs_remap_file_range,
3464 void __cold btrfs_auto_defrag_exit(void)
3466 kmem_cache_destroy(btrfs_inode_defrag_cachep);
3469 int __init btrfs_auto_defrag_init(void)
3471 btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
3472 sizeof(struct inode_defrag), 0,
3475 if (!btrfs_inode_defrag_cachep)
3481 int btrfs_fdatawrite_range(struct inode *inode, loff_t start, loff_t end)
3486 * So with compression we will find and lock a dirty page and clear the
3487 * first one as dirty, setup an async extent, and immediately return
3488 * with the entire range locked but with nobody actually marked with
3489 * writeback. So we can't just filemap_write_and_wait_range() and
3490 * expect it to work since it will just kick off a thread to do the
3491 * actual work. So we need to call filemap_fdatawrite_range _again_
3492 * since it will wait on the page lock, which won't be unlocked until
3493 * after the pages have been marked as writeback and so we're good to go
3494 * from there. We have to do this otherwise we'll miss the ordered
3495 * extents and that results in badness. Please Josef, do not think you
3496 * know better and pull this out at some point in the future, it is
3497 * right and you are wrong.
3499 ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
3500 if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
3501 &BTRFS_I(inode)->runtime_flags))
3502 ret = filemap_fdatawrite_range(inode->i_mapping, start, end);