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"
32 static struct kmem_cache
*btrfs_inode_defrag_cachep
;
34 * when auto defrag is enabled we
35 * queue up these defrag structs to remember which
36 * inodes need defragging passes
39 struct rb_node rb_node
;
43 * transid where the defrag was added, we search for
44 * extents newer than this
51 /* last offset we were able to defrag */
54 /* if we've wrapped around back to zero once already */
58 static int __compare_inode_defrag(struct inode_defrag
*defrag1
,
59 struct inode_defrag
*defrag2
)
61 if (defrag1
->root
> defrag2
->root
)
63 else if (defrag1
->root
< defrag2
->root
)
65 else if (defrag1
->ino
> defrag2
->ino
)
67 else if (defrag1
->ino
< defrag2
->ino
)
73 /* pop a record for an inode into the defrag tree. The lock
74 * must be held already
76 * If you're inserting a record for an older transid than an
77 * existing record, the transid already in the tree is lowered
79 * If an existing record is found the defrag item you
82 static int __btrfs_add_inode_defrag(struct btrfs_inode
*inode
,
83 struct inode_defrag
*defrag
)
85 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
86 struct inode_defrag
*entry
;
88 struct rb_node
*parent
= NULL
;
91 p
= &fs_info
->defrag_inodes
.rb_node
;
94 entry
= rb_entry(parent
, struct inode_defrag
, rb_node
);
96 ret
= __compare_inode_defrag(defrag
, entry
);
100 p
= &parent
->rb_right
;
102 /* if we're reinserting an entry for
103 * an old defrag run, make sure to
104 * lower the transid of our existing record
106 if (defrag
->transid
< entry
->transid
)
107 entry
->transid
= defrag
->transid
;
108 if (defrag
->last_offset
> entry
->last_offset
)
109 entry
->last_offset
= defrag
->last_offset
;
113 set_bit(BTRFS_INODE_IN_DEFRAG
, &inode
->runtime_flags
);
114 rb_link_node(&defrag
->rb_node
, parent
, p
);
115 rb_insert_color(&defrag
->rb_node
, &fs_info
->defrag_inodes
);
119 static inline int __need_auto_defrag(struct btrfs_fs_info
*fs_info
)
121 if (!btrfs_test_opt(fs_info
, AUTO_DEFRAG
))
124 if (btrfs_fs_closing(fs_info
))
131 * insert a defrag record for this inode if auto defrag is
134 int btrfs_add_inode_defrag(struct btrfs_trans_handle
*trans
,
135 struct btrfs_inode
*inode
)
137 struct btrfs_root
*root
= inode
->root
;
138 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
139 struct inode_defrag
*defrag
;
143 if (!__need_auto_defrag(fs_info
))
146 if (test_bit(BTRFS_INODE_IN_DEFRAG
, &inode
->runtime_flags
))
150 transid
= trans
->transid
;
152 transid
= inode
->root
->last_trans
;
154 defrag
= kmem_cache_zalloc(btrfs_inode_defrag_cachep
, GFP_NOFS
);
158 defrag
->ino
= btrfs_ino(inode
);
159 defrag
->transid
= transid
;
160 defrag
->root
= root
->root_key
.objectid
;
162 spin_lock(&fs_info
->defrag_inodes_lock
);
163 if (!test_bit(BTRFS_INODE_IN_DEFRAG
, &inode
->runtime_flags
)) {
165 * If we set IN_DEFRAG flag and evict the inode from memory,
166 * and then re-read this inode, this new inode doesn't have
167 * IN_DEFRAG flag. At the case, we may find the existed defrag.
169 ret
= __btrfs_add_inode_defrag(inode
, defrag
);
171 kmem_cache_free(btrfs_inode_defrag_cachep
, defrag
);
173 kmem_cache_free(btrfs_inode_defrag_cachep
, defrag
);
175 spin_unlock(&fs_info
->defrag_inodes_lock
);
180 * Requeue the defrag object. If there is a defrag object that points to
181 * the same inode in the tree, we will merge them together (by
182 * __btrfs_add_inode_defrag()) and free the one that we want to requeue.
184 static void btrfs_requeue_inode_defrag(struct btrfs_inode
*inode
,
185 struct inode_defrag
*defrag
)
187 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
190 if (!__need_auto_defrag(fs_info
))
194 * Here we don't check the IN_DEFRAG flag, because we need merge
197 spin_lock(&fs_info
->defrag_inodes_lock
);
198 ret
= __btrfs_add_inode_defrag(inode
, defrag
);
199 spin_unlock(&fs_info
->defrag_inodes_lock
);
204 kmem_cache_free(btrfs_inode_defrag_cachep
, defrag
);
208 * pick the defragable inode that we want, if it doesn't exist, we will get
211 static struct inode_defrag
*
212 btrfs_pick_defrag_inode(struct btrfs_fs_info
*fs_info
, u64 root
, u64 ino
)
214 struct inode_defrag
*entry
= NULL
;
215 struct inode_defrag tmp
;
217 struct rb_node
*parent
= NULL
;
223 spin_lock(&fs_info
->defrag_inodes_lock
);
224 p
= fs_info
->defrag_inodes
.rb_node
;
227 entry
= rb_entry(parent
, struct inode_defrag
, rb_node
);
229 ret
= __compare_inode_defrag(&tmp
, entry
);
233 p
= parent
->rb_right
;
238 if (parent
&& __compare_inode_defrag(&tmp
, entry
) > 0) {
239 parent
= rb_next(parent
);
241 entry
= rb_entry(parent
, struct inode_defrag
, rb_node
);
247 rb_erase(parent
, &fs_info
->defrag_inodes
);
248 spin_unlock(&fs_info
->defrag_inodes_lock
);
252 void btrfs_cleanup_defrag_inodes(struct btrfs_fs_info
*fs_info
)
254 struct inode_defrag
*defrag
;
255 struct rb_node
*node
;
257 spin_lock(&fs_info
->defrag_inodes_lock
);
258 node
= rb_first(&fs_info
->defrag_inodes
);
260 rb_erase(node
, &fs_info
->defrag_inodes
);
261 defrag
= rb_entry(node
, struct inode_defrag
, rb_node
);
262 kmem_cache_free(btrfs_inode_defrag_cachep
, defrag
);
264 cond_resched_lock(&fs_info
->defrag_inodes_lock
);
266 node
= rb_first(&fs_info
->defrag_inodes
);
268 spin_unlock(&fs_info
->defrag_inodes_lock
);
271 #define BTRFS_DEFRAG_BATCH 1024
273 static int __btrfs_run_defrag_inode(struct btrfs_fs_info
*fs_info
,
274 struct inode_defrag
*defrag
)
276 struct btrfs_root
*inode_root
;
278 struct btrfs_ioctl_defrag_range_args range
;
283 inode_root
= btrfs_get_fs_root(fs_info
, defrag
->root
, true);
284 if (IS_ERR(inode_root
)) {
285 ret
= PTR_ERR(inode_root
);
289 inode
= btrfs_iget(fs_info
->sb
, defrag
->ino
, inode_root
);
290 btrfs_put_root(inode_root
);
292 ret
= PTR_ERR(inode
);
296 /* do a chunk of defrag */
297 clear_bit(BTRFS_INODE_IN_DEFRAG
, &BTRFS_I(inode
)->runtime_flags
);
298 memset(&range
, 0, sizeof(range
));
300 range
.start
= defrag
->last_offset
;
302 sb_start_write(fs_info
->sb
);
303 num_defrag
= btrfs_defrag_file(inode
, NULL
, &range
, defrag
->transid
,
305 sb_end_write(fs_info
->sb
);
307 * if we filled the whole defrag batch, there
308 * must be more work to do. Queue this defrag
311 if (num_defrag
== BTRFS_DEFRAG_BATCH
) {
312 defrag
->last_offset
= range
.start
;
313 btrfs_requeue_inode_defrag(BTRFS_I(inode
), defrag
);
314 } else if (defrag
->last_offset
&& !defrag
->cycled
) {
316 * we didn't fill our defrag batch, but
317 * we didn't start at zero. Make sure we loop
318 * around to the start of the file.
320 defrag
->last_offset
= 0;
322 btrfs_requeue_inode_defrag(BTRFS_I(inode
), defrag
);
324 kmem_cache_free(btrfs_inode_defrag_cachep
, defrag
);
330 kmem_cache_free(btrfs_inode_defrag_cachep
, defrag
);
335 * run through the list of inodes in the FS that need
338 int btrfs_run_defrag_inodes(struct btrfs_fs_info
*fs_info
)
340 struct inode_defrag
*defrag
;
342 u64 root_objectid
= 0;
344 atomic_inc(&fs_info
->defrag_running
);
346 /* Pause the auto defragger. */
347 if (test_bit(BTRFS_FS_STATE_REMOUNTING
,
351 if (!__need_auto_defrag(fs_info
))
354 /* find an inode to defrag */
355 defrag
= btrfs_pick_defrag_inode(fs_info
, root_objectid
,
358 if (root_objectid
|| first_ino
) {
367 first_ino
= defrag
->ino
+ 1;
368 root_objectid
= defrag
->root
;
370 __btrfs_run_defrag_inode(fs_info
, defrag
);
372 atomic_dec(&fs_info
->defrag_running
);
375 * during unmount, we use the transaction_wait queue to
376 * wait for the defragger to stop
378 wake_up(&fs_info
->transaction_wait
);
382 /* simple helper to fault in pages and copy. This should go away
383 * and be replaced with calls into generic code.
385 static noinline
int btrfs_copy_from_user(loff_t pos
, size_t write_bytes
,
386 struct page
**prepared_pages
,
390 size_t total_copied
= 0;
392 int offset
= offset_in_page(pos
);
394 while (write_bytes
> 0) {
395 size_t count
= min_t(size_t,
396 PAGE_SIZE
- offset
, write_bytes
);
397 struct page
*page
= prepared_pages
[pg
];
399 * Copy data from userspace to the current page
401 copied
= iov_iter_copy_from_user_atomic(page
, i
, offset
, count
);
403 /* Flush processor's dcache for this page */
404 flush_dcache_page(page
);
407 * if we get a partial write, we can end up with
408 * partially up to date pages. These add
409 * a lot of complexity, so make sure they don't
410 * happen by forcing this copy to be retried.
412 * The rest of the btrfs_file_write code will fall
413 * back to page at a time copies after we return 0.
415 if (!PageUptodate(page
) && copied
< count
)
418 iov_iter_advance(i
, copied
);
419 write_bytes
-= copied
;
420 total_copied
+= copied
;
422 /* Return to btrfs_file_write_iter to fault page */
423 if (unlikely(copied
== 0))
426 if (copied
< PAGE_SIZE
- offset
) {
437 * unlocks pages after btrfs_file_write is done with them
439 static void btrfs_drop_pages(struct page
**pages
, size_t num_pages
)
442 for (i
= 0; i
< num_pages
; i
++) {
443 /* page checked is some magic around finding pages that
444 * have been modified without going through btrfs_set_page_dirty
445 * clear it here. There should be no need to mark the pages
446 * accessed as prepare_pages should have marked them accessed
447 * in prepare_pages via find_or_create_page()
449 ClearPageChecked(pages
[i
]);
450 unlock_page(pages
[i
]);
456 * after copy_from_user, pages need to be dirtied and we need to make
457 * sure holes are created between the current EOF and the start of
458 * any next extents (if required).
460 * this also makes the decision about creating an inline extent vs
461 * doing real data extents, marking pages dirty and delalloc as required.
463 int btrfs_dirty_pages(struct btrfs_inode
*inode
, struct page
**pages
,
464 size_t num_pages
, loff_t pos
, size_t write_bytes
,
465 struct extent_state
**cached
, bool noreserve
)
467 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
472 u64 end_of_last_block
;
473 u64 end_pos
= pos
+ write_bytes
;
474 loff_t isize
= i_size_read(&inode
->vfs_inode
);
475 unsigned int extra_bits
= 0;
477 if (write_bytes
== 0)
481 extra_bits
|= EXTENT_NORESERVE
;
483 start_pos
= round_down(pos
, fs_info
->sectorsize
);
484 num_bytes
= round_up(write_bytes
+ pos
- start_pos
,
485 fs_info
->sectorsize
);
487 end_of_last_block
= start_pos
+ num_bytes
- 1;
490 * The pages may have already been dirty, clear out old accounting so
491 * we can set things up properly
493 clear_extent_bit(&inode
->io_tree
, start_pos
, end_of_last_block
,
494 EXTENT_DELALLOC
| EXTENT_DO_ACCOUNTING
| EXTENT_DEFRAG
,
497 err
= btrfs_set_extent_delalloc(inode
, start_pos
, end_of_last_block
,
502 for (i
= 0; i
< num_pages
; i
++) {
503 struct page
*p
= pages
[i
];
510 * we've only changed i_size in ram, and we haven't updated
511 * the disk i_size. There is no need to log the inode
515 i_size_write(&inode
->vfs_inode
, end_pos
);
520 * this drops all the extents in the cache that intersect the range
521 * [start, end]. Existing extents are split as required.
523 void btrfs_drop_extent_cache(struct btrfs_inode
*inode
, u64 start
, u64 end
,
526 struct extent_map
*em
;
527 struct extent_map
*split
= NULL
;
528 struct extent_map
*split2
= NULL
;
529 struct extent_map_tree
*em_tree
= &inode
->extent_tree
;
530 u64 len
= end
- start
+ 1;
538 WARN_ON(end
< start
);
539 if (end
== (u64
)-1) {
548 split
= alloc_extent_map();
550 split2
= alloc_extent_map();
551 if (!split
|| !split2
)
554 write_lock(&em_tree
->lock
);
555 em
= lookup_extent_mapping(em_tree
, start
, len
);
557 write_unlock(&em_tree
->lock
);
561 gen
= em
->generation
;
562 if (skip_pinned
&& test_bit(EXTENT_FLAG_PINNED
, &em
->flags
)) {
563 if (testend
&& em
->start
+ em
->len
>= start
+ len
) {
565 write_unlock(&em_tree
->lock
);
568 start
= em
->start
+ em
->len
;
570 len
= start
+ len
- (em
->start
+ em
->len
);
572 write_unlock(&em_tree
->lock
);
575 compressed
= test_bit(EXTENT_FLAG_COMPRESSED
, &em
->flags
);
576 clear_bit(EXTENT_FLAG_PINNED
, &em
->flags
);
577 clear_bit(EXTENT_FLAG_LOGGING
, &flags
);
578 modified
= !list_empty(&em
->list
);
582 if (em
->start
< start
) {
583 split
->start
= em
->start
;
584 split
->len
= start
- em
->start
;
586 if (em
->block_start
< EXTENT_MAP_LAST_BYTE
) {
587 split
->orig_start
= em
->orig_start
;
588 split
->block_start
= em
->block_start
;
591 split
->block_len
= em
->block_len
;
593 split
->block_len
= split
->len
;
594 split
->orig_block_len
= max(split
->block_len
,
596 split
->ram_bytes
= em
->ram_bytes
;
598 split
->orig_start
= split
->start
;
599 split
->block_len
= 0;
600 split
->block_start
= em
->block_start
;
601 split
->orig_block_len
= 0;
602 split
->ram_bytes
= split
->len
;
605 split
->generation
= gen
;
606 split
->flags
= flags
;
607 split
->compress_type
= em
->compress_type
;
608 replace_extent_mapping(em_tree
, em
, split
, modified
);
609 free_extent_map(split
);
613 if (testend
&& em
->start
+ em
->len
> start
+ len
) {
614 u64 diff
= start
+ len
- em
->start
;
616 split
->start
= start
+ len
;
617 split
->len
= em
->start
+ em
->len
- (start
+ len
);
618 split
->flags
= flags
;
619 split
->compress_type
= em
->compress_type
;
620 split
->generation
= gen
;
622 if (em
->block_start
< EXTENT_MAP_LAST_BYTE
) {
623 split
->orig_block_len
= max(em
->block_len
,
626 split
->ram_bytes
= em
->ram_bytes
;
628 split
->block_len
= em
->block_len
;
629 split
->block_start
= em
->block_start
;
630 split
->orig_start
= em
->orig_start
;
632 split
->block_len
= split
->len
;
633 split
->block_start
= em
->block_start
635 split
->orig_start
= em
->orig_start
;
638 split
->ram_bytes
= split
->len
;
639 split
->orig_start
= split
->start
;
640 split
->block_len
= 0;
641 split
->block_start
= em
->block_start
;
642 split
->orig_block_len
= 0;
645 if (extent_map_in_tree(em
)) {
646 replace_extent_mapping(em_tree
, em
, split
,
649 ret
= add_extent_mapping(em_tree
, split
,
651 ASSERT(ret
== 0); /* Logic error */
653 free_extent_map(split
);
657 if (extent_map_in_tree(em
))
658 remove_extent_mapping(em_tree
, em
);
659 write_unlock(&em_tree
->lock
);
663 /* once for the tree*/
667 free_extent_map(split
);
669 free_extent_map(split2
);
673 * this is very complex, but the basic idea is to drop all extents
674 * in the range start - end. hint_block is filled in with a block number
675 * that would be a good hint to the block allocator for this file.
677 * If an extent intersects the range but is not entirely inside the range
678 * it is either truncated or split. Anything entirely inside the range
679 * is deleted from the tree.
681 * Note: the VFS' inode number of bytes is not updated, it's up to the caller
682 * to deal with that. We set the field 'bytes_found' of the arguments structure
683 * with the number of allocated bytes found in the target range, so that the
684 * caller can update the inode's number of bytes in an atomic way when
685 * replacing extents in a range to avoid races with stat(2).
687 int btrfs_drop_extents(struct btrfs_trans_handle
*trans
,
688 struct btrfs_root
*root
, struct btrfs_inode
*inode
,
689 struct btrfs_drop_extents_args
*args
)
691 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
692 struct extent_buffer
*leaf
;
693 struct btrfs_file_extent_item
*fi
;
694 struct btrfs_ref ref
= { 0 };
695 struct btrfs_key key
;
696 struct btrfs_key new_key
;
697 u64 ino
= btrfs_ino(inode
);
698 u64 search_start
= args
->start
;
701 u64 extent_offset
= 0;
703 u64 last_end
= args
->start
;
709 int modify_tree
= -1;
712 int leafs_visited
= 0;
713 struct btrfs_path
*path
= args
->path
;
715 args
->bytes_found
= 0;
716 args
->extent_inserted
= false;
718 /* Must always have a path if ->replace_extent is true */
719 ASSERT(!(args
->replace_extent
&& !args
->path
));
722 path
= btrfs_alloc_path();
729 if (args
->drop_cache
)
730 btrfs_drop_extent_cache(inode
, args
->start
, args
->end
- 1, 0);
732 if (args
->start
>= inode
->disk_i_size
&& !args
->replace_extent
)
735 update_refs
= (test_bit(BTRFS_ROOT_SHAREABLE
, &root
->state
) ||
736 root
== fs_info
->tree_root
);
739 ret
= btrfs_lookup_file_extent(trans
, root
, path
, ino
,
740 search_start
, modify_tree
);
743 if (ret
> 0 && path
->slots
[0] > 0 && search_start
== args
->start
) {
744 leaf
= path
->nodes
[0];
745 btrfs_item_key_to_cpu(leaf
, &key
, path
->slots
[0] - 1);
746 if (key
.objectid
== ino
&&
747 key
.type
== BTRFS_EXTENT_DATA_KEY
)
753 leaf
= path
->nodes
[0];
754 if (path
->slots
[0] >= btrfs_header_nritems(leaf
)) {
756 ret
= btrfs_next_leaf(root
, path
);
764 leaf
= path
->nodes
[0];
768 btrfs_item_key_to_cpu(leaf
, &key
, path
->slots
[0]);
770 if (key
.objectid
> ino
)
772 if (WARN_ON_ONCE(key
.objectid
< ino
) ||
773 key
.type
< BTRFS_EXTENT_DATA_KEY
) {
778 if (key
.type
> BTRFS_EXTENT_DATA_KEY
|| key
.offset
>= args
->end
)
781 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
782 struct btrfs_file_extent_item
);
783 extent_type
= btrfs_file_extent_type(leaf
, fi
);
785 if (extent_type
== BTRFS_FILE_EXTENT_REG
||
786 extent_type
== BTRFS_FILE_EXTENT_PREALLOC
) {
787 disk_bytenr
= btrfs_file_extent_disk_bytenr(leaf
, fi
);
788 num_bytes
= btrfs_file_extent_disk_num_bytes(leaf
, fi
);
789 extent_offset
= btrfs_file_extent_offset(leaf
, fi
);
790 extent_end
= key
.offset
+
791 btrfs_file_extent_num_bytes(leaf
, fi
);
792 } else if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
793 extent_end
= key
.offset
+
794 btrfs_file_extent_ram_bytes(leaf
, fi
);
801 * Don't skip extent items representing 0 byte lengths. They
802 * used to be created (bug) if while punching holes we hit
803 * -ENOSPC condition. So if we find one here, just ensure we
804 * delete it, otherwise we would insert a new file extent item
805 * with the same key (offset) as that 0 bytes length file
806 * extent item in the call to setup_items_for_insert() later
809 if (extent_end
== key
.offset
&& extent_end
>= search_start
) {
810 last_end
= extent_end
;
811 goto delete_extent_item
;
814 if (extent_end
<= search_start
) {
820 search_start
= max(key
.offset
, args
->start
);
821 if (recow
|| !modify_tree
) {
823 btrfs_release_path(path
);
828 * | - range to drop - |
829 * | -------- extent -------- |
831 if (args
->start
> key
.offset
&& args
->end
< extent_end
) {
833 if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
838 memcpy(&new_key
, &key
, sizeof(new_key
));
839 new_key
.offset
= args
->start
;
840 ret
= btrfs_duplicate_item(trans
, root
, path
,
842 if (ret
== -EAGAIN
) {
843 btrfs_release_path(path
);
849 leaf
= path
->nodes
[0];
850 fi
= btrfs_item_ptr(leaf
, path
->slots
[0] - 1,
851 struct btrfs_file_extent_item
);
852 btrfs_set_file_extent_num_bytes(leaf
, fi
,
853 args
->start
- key
.offset
);
855 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
856 struct btrfs_file_extent_item
);
858 extent_offset
+= args
->start
- key
.offset
;
859 btrfs_set_file_extent_offset(leaf
, fi
, extent_offset
);
860 btrfs_set_file_extent_num_bytes(leaf
, fi
,
861 extent_end
- args
->start
);
862 btrfs_mark_buffer_dirty(leaf
);
864 if (update_refs
&& disk_bytenr
> 0) {
865 btrfs_init_generic_ref(&ref
,
866 BTRFS_ADD_DELAYED_REF
,
867 disk_bytenr
, num_bytes
, 0);
868 btrfs_init_data_ref(&ref
,
869 root
->root_key
.objectid
,
871 args
->start
- extent_offset
);
872 ret
= btrfs_inc_extent_ref(trans
, &ref
);
873 BUG_ON(ret
); /* -ENOMEM */
875 key
.offset
= args
->start
;
878 * From here on out we will have actually dropped something, so
879 * last_end can be updated.
881 last_end
= extent_end
;
884 * | ---- range to drop ----- |
885 * | -------- extent -------- |
887 if (args
->start
<= key
.offset
&& args
->end
< extent_end
) {
888 if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
893 memcpy(&new_key
, &key
, sizeof(new_key
));
894 new_key
.offset
= args
->end
;
895 btrfs_set_item_key_safe(fs_info
, path
, &new_key
);
897 extent_offset
+= args
->end
- key
.offset
;
898 btrfs_set_file_extent_offset(leaf
, fi
, extent_offset
);
899 btrfs_set_file_extent_num_bytes(leaf
, fi
,
900 extent_end
- args
->end
);
901 btrfs_mark_buffer_dirty(leaf
);
902 if (update_refs
&& disk_bytenr
> 0)
903 args
->bytes_found
+= args
->end
- key
.offset
;
907 search_start
= extent_end
;
909 * | ---- range to drop ----- |
910 * | -------- extent -------- |
912 if (args
->start
> key
.offset
&& args
->end
>= extent_end
) {
914 if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
919 btrfs_set_file_extent_num_bytes(leaf
, fi
,
920 args
->start
- key
.offset
);
921 btrfs_mark_buffer_dirty(leaf
);
922 if (update_refs
&& disk_bytenr
> 0)
923 args
->bytes_found
+= extent_end
- args
->start
;
924 if (args
->end
== extent_end
)
932 * | ---- range to drop ----- |
933 * | ------ extent ------ |
935 if (args
->start
<= key
.offset
&& args
->end
>= extent_end
) {
938 del_slot
= path
->slots
[0];
941 BUG_ON(del_slot
+ del_nr
!= path
->slots
[0]);
946 extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
947 args
->bytes_found
+= extent_end
- key
.offset
;
948 extent_end
= ALIGN(extent_end
,
949 fs_info
->sectorsize
);
950 } else if (update_refs
&& disk_bytenr
> 0) {
951 btrfs_init_generic_ref(&ref
,
952 BTRFS_DROP_DELAYED_REF
,
953 disk_bytenr
, num_bytes
, 0);
954 btrfs_init_data_ref(&ref
,
955 root
->root_key
.objectid
,
957 key
.offset
- extent_offset
);
958 ret
= btrfs_free_extent(trans
, &ref
);
959 BUG_ON(ret
); /* -ENOMEM */
960 args
->bytes_found
+= extent_end
- key
.offset
;
963 if (args
->end
== extent_end
)
966 if (path
->slots
[0] + 1 < btrfs_header_nritems(leaf
)) {
971 ret
= btrfs_del_items(trans
, root
, path
, del_slot
,
974 btrfs_abort_transaction(trans
, ret
);
981 btrfs_release_path(path
);
988 if (!ret
&& del_nr
> 0) {
990 * Set path->slots[0] to first slot, so that after the delete
991 * if items are move off from our leaf to its immediate left or
992 * right neighbor leafs, we end up with a correct and adjusted
993 * path->slots[0] for our insertion (if args->replace_extent).
995 path
->slots
[0] = del_slot
;
996 ret
= btrfs_del_items(trans
, root
, path
, del_slot
, del_nr
);
998 btrfs_abort_transaction(trans
, ret
);
1001 leaf
= path
->nodes
[0];
1003 * If btrfs_del_items() was called, it might have deleted a leaf, in
1004 * which case it unlocked our path, so check path->locks[0] matches a
1007 if (!ret
&& args
->replace_extent
&& leafs_visited
== 1 &&
1008 path
->locks
[0] == BTRFS_WRITE_LOCK
&&
1009 btrfs_leaf_free_space(leaf
) >=
1010 sizeof(struct btrfs_item
) + args
->extent_item_size
) {
1013 key
.type
= BTRFS_EXTENT_DATA_KEY
;
1014 key
.offset
= args
->start
;
1015 if (!del_nr
&& path
->slots
[0] < btrfs_header_nritems(leaf
)) {
1016 struct btrfs_key slot_key
;
1018 btrfs_item_key_to_cpu(leaf
, &slot_key
, path
->slots
[0]);
1019 if (btrfs_comp_cpu_keys(&key
, &slot_key
) > 0)
1022 setup_items_for_insert(root
, path
, &key
,
1023 &args
->extent_item_size
, 1);
1024 args
->extent_inserted
= true;
1028 btrfs_free_path(path
);
1029 else if (!args
->extent_inserted
)
1030 btrfs_release_path(path
);
1032 args
->drop_end
= found
? min(args
->end
, last_end
) : args
->end
;
1037 static int extent_mergeable(struct extent_buffer
*leaf
, int slot
,
1038 u64 objectid
, u64 bytenr
, u64 orig_offset
,
1039 u64
*start
, u64
*end
)
1041 struct btrfs_file_extent_item
*fi
;
1042 struct btrfs_key key
;
1045 if (slot
< 0 || slot
>= btrfs_header_nritems(leaf
))
1048 btrfs_item_key_to_cpu(leaf
, &key
, slot
);
1049 if (key
.objectid
!= objectid
|| key
.type
!= BTRFS_EXTENT_DATA_KEY
)
1052 fi
= btrfs_item_ptr(leaf
, slot
, struct btrfs_file_extent_item
);
1053 if (btrfs_file_extent_type(leaf
, fi
) != BTRFS_FILE_EXTENT_REG
||
1054 btrfs_file_extent_disk_bytenr(leaf
, fi
) != bytenr
||
1055 btrfs_file_extent_offset(leaf
, fi
) != key
.offset
- orig_offset
||
1056 btrfs_file_extent_compression(leaf
, fi
) ||
1057 btrfs_file_extent_encryption(leaf
, fi
) ||
1058 btrfs_file_extent_other_encoding(leaf
, fi
))
1061 extent_end
= key
.offset
+ btrfs_file_extent_num_bytes(leaf
, fi
);
1062 if ((*start
&& *start
!= key
.offset
) || (*end
&& *end
!= extent_end
))
1065 *start
= key
.offset
;
1071 * Mark extent in the range start - end as written.
1073 * This changes extent type from 'pre-allocated' to 'regular'. If only
1074 * part of extent is marked as written, the extent will be split into
1077 int btrfs_mark_extent_written(struct btrfs_trans_handle
*trans
,
1078 struct btrfs_inode
*inode
, u64 start
, u64 end
)
1080 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
1081 struct btrfs_root
*root
= inode
->root
;
1082 struct extent_buffer
*leaf
;
1083 struct btrfs_path
*path
;
1084 struct btrfs_file_extent_item
*fi
;
1085 struct btrfs_ref ref
= { 0 };
1086 struct btrfs_key key
;
1087 struct btrfs_key new_key
;
1099 u64 ino
= btrfs_ino(inode
);
1101 path
= btrfs_alloc_path();
1108 key
.type
= BTRFS_EXTENT_DATA_KEY
;
1111 ret
= btrfs_search_slot(trans
, root
, &key
, path
, -1, 1);
1114 if (ret
> 0 && path
->slots
[0] > 0)
1117 leaf
= path
->nodes
[0];
1118 btrfs_item_key_to_cpu(leaf
, &key
, path
->slots
[0]);
1119 if (key
.objectid
!= ino
||
1120 key
.type
!= BTRFS_EXTENT_DATA_KEY
) {
1122 btrfs_abort_transaction(trans
, ret
);
1125 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
1126 struct btrfs_file_extent_item
);
1127 if (btrfs_file_extent_type(leaf
, fi
) != BTRFS_FILE_EXTENT_PREALLOC
) {
1129 btrfs_abort_transaction(trans
, ret
);
1132 extent_end
= key
.offset
+ btrfs_file_extent_num_bytes(leaf
, fi
);
1133 if (key
.offset
> start
|| extent_end
< end
) {
1135 btrfs_abort_transaction(trans
, ret
);
1139 bytenr
= btrfs_file_extent_disk_bytenr(leaf
, fi
);
1140 num_bytes
= btrfs_file_extent_disk_num_bytes(leaf
, fi
);
1141 orig_offset
= key
.offset
- btrfs_file_extent_offset(leaf
, fi
);
1142 memcpy(&new_key
, &key
, sizeof(new_key
));
1144 if (start
== key
.offset
&& end
< extent_end
) {
1147 if (extent_mergeable(leaf
, path
->slots
[0] - 1,
1148 ino
, bytenr
, orig_offset
,
1149 &other_start
, &other_end
)) {
1150 new_key
.offset
= end
;
1151 btrfs_set_item_key_safe(fs_info
, path
, &new_key
);
1152 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
1153 struct btrfs_file_extent_item
);
1154 btrfs_set_file_extent_generation(leaf
, fi
,
1156 btrfs_set_file_extent_num_bytes(leaf
, fi
,
1158 btrfs_set_file_extent_offset(leaf
, fi
,
1160 fi
= btrfs_item_ptr(leaf
, path
->slots
[0] - 1,
1161 struct btrfs_file_extent_item
);
1162 btrfs_set_file_extent_generation(leaf
, fi
,
1164 btrfs_set_file_extent_num_bytes(leaf
, fi
,
1166 btrfs_mark_buffer_dirty(leaf
);
1171 if (start
> key
.offset
&& end
== extent_end
) {
1174 if (extent_mergeable(leaf
, path
->slots
[0] + 1,
1175 ino
, bytenr
, orig_offset
,
1176 &other_start
, &other_end
)) {
1177 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
1178 struct btrfs_file_extent_item
);
1179 btrfs_set_file_extent_num_bytes(leaf
, fi
,
1180 start
- key
.offset
);
1181 btrfs_set_file_extent_generation(leaf
, fi
,
1184 new_key
.offset
= start
;
1185 btrfs_set_item_key_safe(fs_info
, path
, &new_key
);
1187 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
1188 struct btrfs_file_extent_item
);
1189 btrfs_set_file_extent_generation(leaf
, fi
,
1191 btrfs_set_file_extent_num_bytes(leaf
, fi
,
1193 btrfs_set_file_extent_offset(leaf
, fi
,
1194 start
- orig_offset
);
1195 btrfs_mark_buffer_dirty(leaf
);
1200 while (start
> key
.offset
|| end
< extent_end
) {
1201 if (key
.offset
== start
)
1204 new_key
.offset
= split
;
1205 ret
= btrfs_duplicate_item(trans
, root
, path
, &new_key
);
1206 if (ret
== -EAGAIN
) {
1207 btrfs_release_path(path
);
1211 btrfs_abort_transaction(trans
, ret
);
1215 leaf
= path
->nodes
[0];
1216 fi
= btrfs_item_ptr(leaf
, path
->slots
[0] - 1,
1217 struct btrfs_file_extent_item
);
1218 btrfs_set_file_extent_generation(leaf
, fi
, trans
->transid
);
1219 btrfs_set_file_extent_num_bytes(leaf
, fi
,
1220 split
- key
.offset
);
1222 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
1223 struct btrfs_file_extent_item
);
1225 btrfs_set_file_extent_generation(leaf
, fi
, trans
->transid
);
1226 btrfs_set_file_extent_offset(leaf
, fi
, split
- orig_offset
);
1227 btrfs_set_file_extent_num_bytes(leaf
, fi
,
1228 extent_end
- split
);
1229 btrfs_mark_buffer_dirty(leaf
);
1231 btrfs_init_generic_ref(&ref
, BTRFS_ADD_DELAYED_REF
, bytenr
,
1233 btrfs_init_data_ref(&ref
, root
->root_key
.objectid
, ino
,
1235 ret
= btrfs_inc_extent_ref(trans
, &ref
);
1237 btrfs_abort_transaction(trans
, ret
);
1241 if (split
== start
) {
1244 if (start
!= key
.offset
) {
1246 btrfs_abort_transaction(trans
, ret
);
1257 btrfs_init_generic_ref(&ref
, BTRFS_DROP_DELAYED_REF
, bytenr
,
1259 btrfs_init_data_ref(&ref
, root
->root_key
.objectid
, ino
, orig_offset
);
1260 if (extent_mergeable(leaf
, path
->slots
[0] + 1,
1261 ino
, bytenr
, orig_offset
,
1262 &other_start
, &other_end
)) {
1264 btrfs_release_path(path
);
1267 extent_end
= other_end
;
1268 del_slot
= path
->slots
[0] + 1;
1270 ret
= btrfs_free_extent(trans
, &ref
);
1272 btrfs_abort_transaction(trans
, ret
);
1278 if (extent_mergeable(leaf
, path
->slots
[0] - 1,
1279 ino
, bytenr
, orig_offset
,
1280 &other_start
, &other_end
)) {
1282 btrfs_release_path(path
);
1285 key
.offset
= other_start
;
1286 del_slot
= path
->slots
[0];
1288 ret
= btrfs_free_extent(trans
, &ref
);
1290 btrfs_abort_transaction(trans
, ret
);
1295 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
1296 struct btrfs_file_extent_item
);
1297 btrfs_set_file_extent_type(leaf
, fi
,
1298 BTRFS_FILE_EXTENT_REG
);
1299 btrfs_set_file_extent_generation(leaf
, fi
, trans
->transid
);
1300 btrfs_mark_buffer_dirty(leaf
);
1302 fi
= btrfs_item_ptr(leaf
, del_slot
- 1,
1303 struct btrfs_file_extent_item
);
1304 btrfs_set_file_extent_type(leaf
, fi
,
1305 BTRFS_FILE_EXTENT_REG
);
1306 btrfs_set_file_extent_generation(leaf
, fi
, trans
->transid
);
1307 btrfs_set_file_extent_num_bytes(leaf
, fi
,
1308 extent_end
- key
.offset
);
1309 btrfs_mark_buffer_dirty(leaf
);
1311 ret
= btrfs_del_items(trans
, root
, path
, del_slot
, del_nr
);
1313 btrfs_abort_transaction(trans
, ret
);
1318 btrfs_free_path(path
);
1323 * on error we return an unlocked page and the error value
1324 * on success we return a locked page and 0
1326 static int prepare_uptodate_page(struct inode
*inode
,
1327 struct page
*page
, u64 pos
,
1328 bool force_uptodate
)
1332 if (((pos
& (PAGE_SIZE
- 1)) || force_uptodate
) &&
1333 !PageUptodate(page
)) {
1334 ret
= btrfs_readpage(NULL
, page
);
1338 if (!PageUptodate(page
)) {
1342 if (page
->mapping
!= inode
->i_mapping
) {
1351 * this just gets pages into the page cache and locks them down.
1353 static noinline
int prepare_pages(struct inode
*inode
, struct page
**pages
,
1354 size_t num_pages
, loff_t pos
,
1355 size_t write_bytes
, bool force_uptodate
)
1358 unsigned long index
= pos
>> PAGE_SHIFT
;
1359 gfp_t mask
= btrfs_alloc_write_mask(inode
->i_mapping
);
1363 for (i
= 0; i
< num_pages
; i
++) {
1365 pages
[i
] = find_or_create_page(inode
->i_mapping
, index
+ i
,
1366 mask
| __GFP_WRITE
);
1374 err
= prepare_uptodate_page(inode
, pages
[i
], pos
,
1376 if (!err
&& i
== num_pages
- 1)
1377 err
= prepare_uptodate_page(inode
, pages
[i
],
1378 pos
+ write_bytes
, false);
1381 if (err
== -EAGAIN
) {
1388 wait_on_page_writeback(pages
[i
]);
1393 while (faili
>= 0) {
1394 unlock_page(pages
[faili
]);
1395 put_page(pages
[faili
]);
1403 * This function locks the extent and properly waits for data=ordered extents
1404 * to finish before allowing the pages to be modified if need.
1407 * 1 - the extent is locked
1408 * 0 - the extent is not locked, and everything is OK
1409 * -EAGAIN - need re-prepare the pages
1410 * the other < 0 number - Something wrong happens
1413 lock_and_cleanup_extent_if_need(struct btrfs_inode
*inode
, struct page
**pages
,
1414 size_t num_pages
, loff_t pos
,
1416 u64
*lockstart
, u64
*lockend
,
1417 struct extent_state
**cached_state
)
1419 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
1425 start_pos
= round_down(pos
, fs_info
->sectorsize
);
1426 last_pos
= round_up(pos
+ write_bytes
, fs_info
->sectorsize
) - 1;
1428 if (start_pos
< inode
->vfs_inode
.i_size
) {
1429 struct btrfs_ordered_extent
*ordered
;
1431 lock_extent_bits(&inode
->io_tree
, start_pos
, last_pos
,
1433 ordered
= btrfs_lookup_ordered_range(inode
, start_pos
,
1434 last_pos
- start_pos
+ 1);
1436 ordered
->file_offset
+ ordered
->num_bytes
> start_pos
&&
1437 ordered
->file_offset
<= last_pos
) {
1438 unlock_extent_cached(&inode
->io_tree
, start_pos
,
1439 last_pos
, cached_state
);
1440 for (i
= 0; i
< num_pages
; i
++) {
1441 unlock_page(pages
[i
]);
1444 btrfs_start_ordered_extent(ordered
, 1);
1445 btrfs_put_ordered_extent(ordered
);
1449 btrfs_put_ordered_extent(ordered
);
1451 *lockstart
= start_pos
;
1452 *lockend
= last_pos
;
1457 * It's possible the pages are dirty right now, but we don't want
1458 * to clean them yet because copy_from_user may catch a page fault
1459 * and we might have to fall back to one page at a time. If that
1460 * happens, we'll unlock these pages and we'd have a window where
1461 * reclaim could sneak in and drop the once-dirty page on the floor
1462 * without writing it.
1464 * We have the pages locked and the extent range locked, so there's
1465 * no way someone can start IO on any dirty pages in this range.
1467 * We'll call btrfs_dirty_pages() later on, and that will flip around
1468 * delalloc bits and dirty the pages as required.
1470 for (i
= 0; i
< num_pages
; i
++) {
1471 set_page_extent_mapped(pages
[i
]);
1472 WARN_ON(!PageLocked(pages
[i
]));
1478 static int check_can_nocow(struct btrfs_inode
*inode
, loff_t pos
,
1479 size_t *write_bytes
, bool nowait
)
1481 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
1482 struct btrfs_root
*root
= inode
->root
;
1483 u64 lockstart
, lockend
;
1487 if (!(inode
->flags
& (BTRFS_INODE_NODATACOW
| BTRFS_INODE_PREALLOC
)))
1490 if (!nowait
&& !btrfs_drew_try_write_lock(&root
->snapshot_lock
))
1493 lockstart
= round_down(pos
, fs_info
->sectorsize
);
1494 lockend
= round_up(pos
+ *write_bytes
,
1495 fs_info
->sectorsize
) - 1;
1496 num_bytes
= lockend
- lockstart
+ 1;
1499 struct btrfs_ordered_extent
*ordered
;
1501 if (!try_lock_extent(&inode
->io_tree
, lockstart
, lockend
))
1504 ordered
= btrfs_lookup_ordered_range(inode
, lockstart
,
1507 btrfs_put_ordered_extent(ordered
);
1512 btrfs_lock_and_flush_ordered_range(inode
, lockstart
,
1516 ret
= can_nocow_extent(&inode
->vfs_inode
, lockstart
, &num_bytes
,
1517 NULL
, NULL
, NULL
, false);
1521 btrfs_drew_write_unlock(&root
->snapshot_lock
);
1523 *write_bytes
= min_t(size_t, *write_bytes
,
1524 num_bytes
- pos
+ lockstart
);
1527 unlock_extent(&inode
->io_tree
, lockstart
, lockend
);
1532 static int check_nocow_nolock(struct btrfs_inode
*inode
, loff_t pos
,
1533 size_t *write_bytes
)
1535 return check_can_nocow(inode
, pos
, write_bytes
, true);
1539 * Check if we can do nocow write into the range [@pos, @pos + @write_bytes)
1542 * @write_bytes: The length to write, will be updated to the nocow writeable
1545 * This function will flush ordered extents in the range to ensure proper
1549 * >0 and update @write_bytes if we can do nocow write
1550 * 0 if we can't do nocow write
1551 * -EAGAIN if we can't get the needed lock or there are ordered extents
1552 * for * (nowait == true) case
1553 * <0 if other error happened
1555 * NOTE: Callers need to release the lock by btrfs_check_nocow_unlock().
1557 int btrfs_check_nocow_lock(struct btrfs_inode
*inode
, loff_t pos
,
1558 size_t *write_bytes
)
1560 return check_can_nocow(inode
, pos
, write_bytes
, false);
1563 void btrfs_check_nocow_unlock(struct btrfs_inode
*inode
)
1565 btrfs_drew_write_unlock(&inode
->root
->snapshot_lock
);
1568 static void update_time_for_write(struct inode
*inode
)
1570 struct timespec64 now
;
1572 if (IS_NOCMTIME(inode
))
1575 now
= current_time(inode
);
1576 if (!timespec64_equal(&inode
->i_mtime
, &now
))
1577 inode
->i_mtime
= now
;
1579 if (!timespec64_equal(&inode
->i_ctime
, &now
))
1580 inode
->i_ctime
= now
;
1582 if (IS_I_VERSION(inode
))
1583 inode_inc_iversion(inode
);
1586 static int btrfs_write_check(struct kiocb
*iocb
, struct iov_iter
*from
,
1589 struct file
*file
= iocb
->ki_filp
;
1590 struct inode
*inode
= file_inode(file
);
1591 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
1592 loff_t pos
= iocb
->ki_pos
;
1597 if (iocb
->ki_flags
& IOCB_NOWAIT
) {
1598 size_t nocow_bytes
= count
;
1600 /* We will allocate space in case nodatacow is not set, so bail */
1601 if (check_nocow_nolock(BTRFS_I(inode
), pos
, &nocow_bytes
) <= 0)
1604 * There are holes in the range or parts of the range that must
1605 * be COWed (shared extents, RO block groups, etc), so just bail
1608 if (nocow_bytes
< count
)
1612 current
->backing_dev_info
= inode_to_bdi(inode
);
1613 ret
= file_remove_privs(file
);
1618 * We reserve space for updating the inode when we reserve space for the
1619 * extent we are going to write, so we will enospc out there. We don't
1620 * need to start yet another transaction to update the inode as we will
1621 * update the inode when we finish writing whatever data we write.
1623 update_time_for_write(inode
);
1625 start_pos
= round_down(pos
, fs_info
->sectorsize
);
1626 oldsize
= i_size_read(inode
);
1627 if (start_pos
> oldsize
) {
1628 /* Expand hole size to cover write data, preventing empty gap */
1629 loff_t end_pos
= round_up(pos
+ count
, fs_info
->sectorsize
);
1631 ret
= btrfs_cont_expand(BTRFS_I(inode
), oldsize
, end_pos
);
1633 current
->backing_dev_info
= NULL
;
1641 static noinline ssize_t
btrfs_buffered_write(struct kiocb
*iocb
,
1644 struct file
*file
= iocb
->ki_filp
;
1646 struct inode
*inode
= file_inode(file
);
1647 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
1648 struct page
**pages
= NULL
;
1649 struct extent_changeset
*data_reserved
= NULL
;
1650 u64 release_bytes
= 0;
1653 size_t num_written
= 0;
1656 bool only_release_metadata
= false;
1657 bool force_page_uptodate
= false;
1658 loff_t old_isize
= i_size_read(inode
);
1659 unsigned int ilock_flags
= 0;
1661 if (iocb
->ki_flags
& IOCB_NOWAIT
)
1662 ilock_flags
|= BTRFS_ILOCK_TRY
;
1664 ret
= btrfs_inode_lock(inode
, ilock_flags
);
1668 ret
= generic_write_checks(iocb
, i
);
1672 ret
= btrfs_write_check(iocb
, i
, ret
);
1677 nrptrs
= min(DIV_ROUND_UP(iov_iter_count(i
), PAGE_SIZE
),
1678 PAGE_SIZE
/ (sizeof(struct page
*)));
1679 nrptrs
= min(nrptrs
, current
->nr_dirtied_pause
- current
->nr_dirtied
);
1680 nrptrs
= max(nrptrs
, 8);
1681 pages
= kmalloc_array(nrptrs
, sizeof(struct page
*), GFP_KERNEL
);
1687 while (iov_iter_count(i
) > 0) {
1688 struct extent_state
*cached_state
= NULL
;
1689 size_t offset
= offset_in_page(pos
);
1690 size_t sector_offset
;
1691 size_t write_bytes
= min(iov_iter_count(i
),
1692 nrptrs
* (size_t)PAGE_SIZE
-
1695 size_t reserve_bytes
;
1698 size_t dirty_sectors
;
1703 * Fault pages before locking them in prepare_pages
1704 * to avoid recursive lock
1706 if (unlikely(iov_iter_fault_in_readable(i
, write_bytes
))) {
1711 only_release_metadata
= false;
1712 sector_offset
= pos
& (fs_info
->sectorsize
- 1);
1714 extent_changeset_release(data_reserved
);
1715 ret
= btrfs_check_data_free_space(BTRFS_I(inode
),
1716 &data_reserved
, pos
,
1720 * If we don't have to COW at the offset, reserve
1721 * metadata only. write_bytes may get smaller than
1724 if (btrfs_check_nocow_lock(BTRFS_I(inode
), pos
,
1726 only_release_metadata
= true;
1731 num_pages
= DIV_ROUND_UP(write_bytes
+ offset
, PAGE_SIZE
);
1732 WARN_ON(num_pages
> nrptrs
);
1733 reserve_bytes
= round_up(write_bytes
+ sector_offset
,
1734 fs_info
->sectorsize
);
1735 WARN_ON(reserve_bytes
== 0);
1736 ret
= btrfs_delalloc_reserve_metadata(BTRFS_I(inode
),
1739 if (!only_release_metadata
)
1740 btrfs_free_reserved_data_space(BTRFS_I(inode
),
1744 btrfs_check_nocow_unlock(BTRFS_I(inode
));
1748 release_bytes
= reserve_bytes
;
1751 * This is going to setup the pages array with the number of
1752 * pages we want, so we don't really need to worry about the
1753 * contents of pages from loop to loop
1755 ret
= prepare_pages(inode
, pages
, num_pages
,
1757 force_page_uptodate
);
1759 btrfs_delalloc_release_extents(BTRFS_I(inode
),
1764 extents_locked
= lock_and_cleanup_extent_if_need(
1765 BTRFS_I(inode
), pages
,
1766 num_pages
, pos
, write_bytes
, &lockstart
,
1767 &lockend
, &cached_state
);
1768 if (extents_locked
< 0) {
1769 if (extents_locked
== -EAGAIN
)
1771 btrfs_delalloc_release_extents(BTRFS_I(inode
),
1773 ret
= extents_locked
;
1777 copied
= btrfs_copy_from_user(pos
, write_bytes
, pages
, i
);
1779 num_sectors
= BTRFS_BYTES_TO_BLKS(fs_info
, reserve_bytes
);
1780 dirty_sectors
= round_up(copied
+ sector_offset
,
1781 fs_info
->sectorsize
);
1782 dirty_sectors
= BTRFS_BYTES_TO_BLKS(fs_info
, dirty_sectors
);
1785 * if we have trouble faulting in the pages, fall
1786 * back to one page at a time
1788 if (copied
< write_bytes
)
1792 force_page_uptodate
= true;
1796 force_page_uptodate
= false;
1797 dirty_pages
= DIV_ROUND_UP(copied
+ offset
,
1801 if (num_sectors
> dirty_sectors
) {
1802 /* release everything except the sectors we dirtied */
1803 release_bytes
-= dirty_sectors
<< fs_info
->sectorsize_bits
;
1804 if (only_release_metadata
) {
1805 btrfs_delalloc_release_metadata(BTRFS_I(inode
),
1806 release_bytes
, true);
1810 __pos
= round_down(pos
,
1811 fs_info
->sectorsize
) +
1812 (dirty_pages
<< PAGE_SHIFT
);
1813 btrfs_delalloc_release_space(BTRFS_I(inode
),
1814 data_reserved
, __pos
,
1815 release_bytes
, true);
1819 release_bytes
= round_up(copied
+ sector_offset
,
1820 fs_info
->sectorsize
);
1822 ret
= btrfs_dirty_pages(BTRFS_I(inode
), pages
,
1823 dirty_pages
, pos
, copied
,
1824 &cached_state
, only_release_metadata
);
1827 * If we have not locked the extent range, because the range's
1828 * start offset is >= i_size, we might still have a non-NULL
1829 * cached extent state, acquired while marking the extent range
1830 * as delalloc through btrfs_dirty_pages(). Therefore free any
1831 * possible cached extent state to avoid a memory leak.
1834 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
,
1835 lockstart
, lockend
, &cached_state
);
1837 free_extent_state(cached_state
);
1839 btrfs_delalloc_release_extents(BTRFS_I(inode
), reserve_bytes
);
1841 btrfs_drop_pages(pages
, num_pages
);
1846 if (only_release_metadata
)
1847 btrfs_check_nocow_unlock(BTRFS_I(inode
));
1849 btrfs_drop_pages(pages
, num_pages
);
1853 balance_dirty_pages_ratelimited(inode
->i_mapping
);
1856 num_written
+= copied
;
1861 if (release_bytes
) {
1862 if (only_release_metadata
) {
1863 btrfs_check_nocow_unlock(BTRFS_I(inode
));
1864 btrfs_delalloc_release_metadata(BTRFS_I(inode
),
1865 release_bytes
, true);
1867 btrfs_delalloc_release_space(BTRFS_I(inode
),
1869 round_down(pos
, fs_info
->sectorsize
),
1870 release_bytes
, true);
1874 extent_changeset_free(data_reserved
);
1875 if (num_written
> 0) {
1876 pagecache_isize_extended(inode
, old_isize
, iocb
->ki_pos
);
1877 iocb
->ki_pos
+= num_written
;
1880 btrfs_inode_unlock(inode
, ilock_flags
);
1881 return num_written
? num_written
: ret
;
1884 static ssize_t
check_direct_IO(struct btrfs_fs_info
*fs_info
,
1885 const struct iov_iter
*iter
, loff_t offset
)
1887 const u32 blocksize_mask
= fs_info
->sectorsize
- 1;
1889 if (offset
& blocksize_mask
)
1892 if (iov_iter_alignment(iter
) & blocksize_mask
)
1898 static ssize_t
btrfs_direct_write(struct kiocb
*iocb
, struct iov_iter
*from
)
1900 struct file
*file
= iocb
->ki_filp
;
1901 struct inode
*inode
= file_inode(file
);
1902 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
1904 ssize_t written
= 0;
1905 ssize_t written_buffered
;
1908 unsigned int ilock_flags
= 0;
1909 struct iomap_dio
*dio
= NULL
;
1911 if (iocb
->ki_flags
& IOCB_NOWAIT
)
1912 ilock_flags
|= BTRFS_ILOCK_TRY
;
1914 /* If the write DIO is within EOF, use a shared lock */
1915 if (iocb
->ki_pos
+ iov_iter_count(from
) <= i_size_read(inode
))
1916 ilock_flags
|= BTRFS_ILOCK_SHARED
;
1919 err
= btrfs_inode_lock(inode
, ilock_flags
);
1923 err
= generic_write_checks(iocb
, from
);
1925 btrfs_inode_unlock(inode
, ilock_flags
);
1929 err
= btrfs_write_check(iocb
, from
, err
);
1931 btrfs_inode_unlock(inode
, ilock_flags
);
1937 * Re-check since file size may have changed just before taking the
1938 * lock or pos may have changed because of O_APPEND in generic_write_check()
1940 if ((ilock_flags
& BTRFS_ILOCK_SHARED
) &&
1941 pos
+ iov_iter_count(from
) > i_size_read(inode
)) {
1942 btrfs_inode_unlock(inode
, ilock_flags
);
1943 ilock_flags
&= ~BTRFS_ILOCK_SHARED
;
1947 if (check_direct_IO(fs_info
, from
, pos
)) {
1948 btrfs_inode_unlock(inode
, ilock_flags
);
1952 dio
= __iomap_dio_rw(iocb
, from
, &btrfs_dio_iomap_ops
,
1953 &btrfs_dio_ops
, is_sync_kiocb(iocb
));
1955 btrfs_inode_unlock(inode
, ilock_flags
);
1957 if (IS_ERR_OR_NULL(dio
)) {
1958 err
= PTR_ERR_OR_ZERO(dio
);
1959 if (err
< 0 && err
!= -ENOTBLK
)
1962 written
= iomap_dio_complete(dio
);
1965 if (written
< 0 || !iov_iter_count(from
)) {
1972 written_buffered
= btrfs_buffered_write(iocb
, from
);
1973 if (written_buffered
< 0) {
1974 err
= written_buffered
;
1978 * Ensure all data is persisted. We want the next direct IO read to be
1979 * able to read what was just written.
1981 endbyte
= pos
+ written_buffered
- 1;
1982 err
= btrfs_fdatawrite_range(inode
, pos
, endbyte
);
1985 err
= filemap_fdatawait_range(inode
->i_mapping
, pos
, endbyte
);
1988 written
+= written_buffered
;
1989 iocb
->ki_pos
= pos
+ written_buffered
;
1990 invalidate_mapping_pages(file
->f_mapping
, pos
>> PAGE_SHIFT
,
1991 endbyte
>> PAGE_SHIFT
);
1993 return written
? written
: err
;
1996 static ssize_t
btrfs_file_write_iter(struct kiocb
*iocb
,
1997 struct iov_iter
*from
)
1999 struct file
*file
= iocb
->ki_filp
;
2000 struct inode
*inode
= file_inode(file
);
2001 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2002 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
2003 ssize_t num_written
= 0;
2004 const bool sync
= iocb
->ki_flags
& IOCB_DSYNC
;
2007 * If the fs flips readonly due to some impossible error, although we
2008 * have opened a file as writable, we have to stop this write operation
2009 * to ensure consistency.
2011 if (test_bit(BTRFS_FS_STATE_ERROR
, &fs_info
->fs_state
))
2014 if (!(iocb
->ki_flags
& IOCB_DIRECT
) &&
2015 (iocb
->ki_flags
& IOCB_NOWAIT
))
2019 atomic_inc(&BTRFS_I(inode
)->sync_writers
);
2021 if (iocb
->ki_flags
& IOCB_DIRECT
)
2022 num_written
= btrfs_direct_write(iocb
, from
);
2024 num_written
= btrfs_buffered_write(iocb
, from
);
2027 * We also have to set last_sub_trans to the current log transid,
2028 * otherwise subsequent syncs to a file that's been synced in this
2029 * transaction will appear to have already occurred.
2031 spin_lock(&BTRFS_I(inode
)->lock
);
2032 BTRFS_I(inode
)->last_sub_trans
= root
->log_transid
;
2033 spin_unlock(&BTRFS_I(inode
)->lock
);
2034 if (num_written
> 0)
2035 num_written
= generic_write_sync(iocb
, num_written
);
2038 atomic_dec(&BTRFS_I(inode
)->sync_writers
);
2040 current
->backing_dev_info
= NULL
;
2044 int btrfs_release_file(struct inode
*inode
, struct file
*filp
)
2046 struct btrfs_file_private
*private = filp
->private_data
;
2048 if (private && private->filldir_buf
)
2049 kfree(private->filldir_buf
);
2051 filp
->private_data
= NULL
;
2054 * Set by setattr when we are about to truncate a file from a non-zero
2055 * size to a zero size. This tries to flush down new bytes that may
2056 * have been written if the application were using truncate to replace
2059 if (test_and_clear_bit(BTRFS_INODE_FLUSH_ON_CLOSE
,
2060 &BTRFS_I(inode
)->runtime_flags
))
2061 filemap_flush(inode
->i_mapping
);
2065 static int start_ordered_ops(struct inode
*inode
, loff_t start
, loff_t end
)
2068 struct blk_plug plug
;
2071 * This is only called in fsync, which would do synchronous writes, so
2072 * a plug can merge adjacent IOs as much as possible. Esp. in case of
2073 * multiple disks using raid profile, a large IO can be split to
2074 * several segments of stripe length (currently 64K).
2076 blk_start_plug(&plug
);
2077 atomic_inc(&BTRFS_I(inode
)->sync_writers
);
2078 ret
= btrfs_fdatawrite_range(inode
, start
, end
);
2079 atomic_dec(&BTRFS_I(inode
)->sync_writers
);
2080 blk_finish_plug(&plug
);
2086 * fsync call for both files and directories. This logs the inode into
2087 * the tree log instead of forcing full commits whenever possible.
2089 * It needs to call filemap_fdatawait so that all ordered extent updates are
2090 * in the metadata btree are up to date for copying to the log.
2092 * It drops the inode mutex before doing the tree log commit. This is an
2093 * important optimization for directories because holding the mutex prevents
2094 * new operations on the dir while we write to disk.
2096 int btrfs_sync_file(struct file
*file
, loff_t start
, loff_t end
, int datasync
)
2098 struct dentry
*dentry
= file_dentry(file
);
2099 struct inode
*inode
= d_inode(dentry
);
2100 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2101 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
2102 struct btrfs_trans_handle
*trans
;
2103 struct btrfs_log_ctx ctx
;
2108 trace_btrfs_sync_file(file
, datasync
);
2110 btrfs_init_log_ctx(&ctx
, inode
);
2113 * Always set the range to a full range, otherwise we can get into
2114 * several problems, from missing file extent items to represent holes
2115 * when not using the NO_HOLES feature, to log tree corruption due to
2116 * races between hole detection during logging and completion of ordered
2117 * extents outside the range, to missing checksums due to ordered extents
2118 * for which we flushed only a subset of their pages.
2122 len
= (u64
)LLONG_MAX
+ 1;
2125 * We write the dirty pages in the range and wait until they complete
2126 * out of the ->i_mutex. If so, we can flush the dirty pages by
2127 * multi-task, and make the performance up. See
2128 * btrfs_wait_ordered_range for an explanation of the ASYNC check.
2130 ret
= start_ordered_ops(inode
, start
, end
);
2136 atomic_inc(&root
->log_batch
);
2139 * Always check for the full sync flag while holding the inode's lock,
2140 * to avoid races with other tasks. The flag must be either set all the
2141 * time during logging or always off all the time while logging.
2143 full_sync
= test_bit(BTRFS_INODE_NEEDS_FULL_SYNC
,
2144 &BTRFS_I(inode
)->runtime_flags
);
2147 * Before we acquired the inode's lock, someone may have dirtied more
2148 * pages in the target range. We need to make sure that writeback for
2149 * any such pages does not start while we are logging the inode, because
2150 * if it does, any of the following might happen when we are not doing a
2153 * 1) We log an extent after its writeback finishes but before its
2154 * checksums are added to the csum tree, leading to -EIO errors
2155 * when attempting to read the extent after a log replay.
2157 * 2) We can end up logging an extent before its writeback finishes.
2158 * Therefore after the log replay we will have a file extent item
2159 * pointing to an unwritten extent (and no data checksums as well).
2161 * So trigger writeback for any eventual new dirty pages and then we
2162 * wait for all ordered extents to complete below.
2164 ret
= start_ordered_ops(inode
, start
, end
);
2166 inode_unlock(inode
);
2171 * We have to do this here to avoid the priority inversion of waiting on
2172 * IO of a lower priority task while holding a transaction open.
2174 * For a full fsync we wait for the ordered extents to complete while
2175 * for a fast fsync we wait just for writeback to complete, and then
2176 * attach the ordered extents to the transaction so that a transaction
2177 * commit waits for their completion, to avoid data loss if we fsync,
2178 * the current transaction commits before the ordered extents complete
2179 * and a power failure happens right after that.
2182 ret
= btrfs_wait_ordered_range(inode
, start
, len
);
2185 * Get our ordered extents as soon as possible to avoid doing
2186 * checksum lookups in the csum tree, and use instead the
2187 * checksums attached to the ordered extents.
2189 btrfs_get_ordered_extents_for_logging(BTRFS_I(inode
),
2190 &ctx
.ordered_extents
);
2191 ret
= filemap_fdatawait_range(inode
->i_mapping
, start
, end
);
2195 goto out_release_extents
;
2197 atomic_inc(&root
->log_batch
);
2200 * If we are doing a fast fsync we can not bail out if the inode's
2201 * last_trans is <= then the last committed transaction, because we only
2202 * update the last_trans of the inode during ordered extent completion,
2203 * and for a fast fsync we don't wait for that, we only wait for the
2204 * writeback to complete.
2207 if (btrfs_inode_in_log(BTRFS_I(inode
), fs_info
->generation
) ||
2208 (BTRFS_I(inode
)->last_trans
<= fs_info
->last_trans_committed
&&
2209 (full_sync
|| list_empty(&ctx
.ordered_extents
)))) {
2211 * We've had everything committed since the last time we were
2212 * modified so clear this flag in case it was set for whatever
2213 * reason, it's no longer relevant.
2215 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC
,
2216 &BTRFS_I(inode
)->runtime_flags
);
2218 * An ordered extent might have started before and completed
2219 * already with io errors, in which case the inode was not
2220 * updated and we end up here. So check the inode's mapping
2221 * for any errors that might have happened since we last
2222 * checked called fsync.
2224 ret
= filemap_check_wb_err(inode
->i_mapping
, file
->f_wb_err
);
2225 goto out_release_extents
;
2229 * We use start here because we will need to wait on the IO to complete
2230 * in btrfs_sync_log, which could require joining a transaction (for
2231 * example checking cross references in the nocow path). If we use join
2232 * here we could get into a situation where we're waiting on IO to
2233 * happen that is blocked on a transaction trying to commit. With start
2234 * we inc the extwriter counter, so we wait for all extwriters to exit
2235 * before we start blocking joiners. This comment is to keep somebody
2236 * from thinking they are super smart and changing this to
2237 * btrfs_join_transaction *cough*Josef*cough*.
2239 trans
= btrfs_start_transaction(root
, 0);
2240 if (IS_ERR(trans
)) {
2241 ret
= PTR_ERR(trans
);
2242 goto out_release_extents
;
2245 ret
= btrfs_log_dentry_safe(trans
, dentry
, &ctx
);
2246 btrfs_release_log_ctx_extents(&ctx
);
2248 /* Fallthrough and commit/free transaction. */
2252 /* we've logged all the items and now have a consistent
2253 * version of the file in the log. It is possible that
2254 * someone will come in and modify the file, but that's
2255 * fine because the log is consistent on disk, and we
2256 * have references to all of the file's extents
2258 * It is possible that someone will come in and log the
2259 * file again, but that will end up using the synchronization
2260 * inside btrfs_sync_log to keep things safe.
2262 inode_unlock(inode
);
2264 if (ret
!= BTRFS_NO_LOG_SYNC
) {
2266 ret
= btrfs_sync_log(trans
, root
, &ctx
);
2268 ret
= btrfs_end_transaction(trans
);
2273 ret
= btrfs_wait_ordered_range(inode
, start
, len
);
2275 btrfs_end_transaction(trans
);
2279 ret
= btrfs_commit_transaction(trans
);
2281 ret
= btrfs_end_transaction(trans
);
2284 ASSERT(list_empty(&ctx
.list
));
2285 err
= file_check_and_advance_wb_err(file
);
2288 return ret
> 0 ? -EIO
: ret
;
2290 out_release_extents
:
2291 btrfs_release_log_ctx_extents(&ctx
);
2292 inode_unlock(inode
);
2296 static const struct vm_operations_struct btrfs_file_vm_ops
= {
2297 .fault
= filemap_fault
,
2298 .map_pages
= filemap_map_pages
,
2299 .page_mkwrite
= btrfs_page_mkwrite
,
2302 static int btrfs_file_mmap(struct file
*filp
, struct vm_area_struct
*vma
)
2304 struct address_space
*mapping
= filp
->f_mapping
;
2306 if (!mapping
->a_ops
->readpage
)
2309 file_accessed(filp
);
2310 vma
->vm_ops
= &btrfs_file_vm_ops
;
2315 static int hole_mergeable(struct btrfs_inode
*inode
, struct extent_buffer
*leaf
,
2316 int slot
, u64 start
, u64 end
)
2318 struct btrfs_file_extent_item
*fi
;
2319 struct btrfs_key key
;
2321 if (slot
< 0 || slot
>= btrfs_header_nritems(leaf
))
2324 btrfs_item_key_to_cpu(leaf
, &key
, slot
);
2325 if (key
.objectid
!= btrfs_ino(inode
) ||
2326 key
.type
!= BTRFS_EXTENT_DATA_KEY
)
2329 fi
= btrfs_item_ptr(leaf
, slot
, struct btrfs_file_extent_item
);
2331 if (btrfs_file_extent_type(leaf
, fi
) != BTRFS_FILE_EXTENT_REG
)
2334 if (btrfs_file_extent_disk_bytenr(leaf
, fi
))
2337 if (key
.offset
== end
)
2339 if (key
.offset
+ btrfs_file_extent_num_bytes(leaf
, fi
) == start
)
2344 static int fill_holes(struct btrfs_trans_handle
*trans
,
2345 struct btrfs_inode
*inode
,
2346 struct btrfs_path
*path
, u64 offset
, u64 end
)
2348 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
2349 struct btrfs_root
*root
= inode
->root
;
2350 struct extent_buffer
*leaf
;
2351 struct btrfs_file_extent_item
*fi
;
2352 struct extent_map
*hole_em
;
2353 struct extent_map_tree
*em_tree
= &inode
->extent_tree
;
2354 struct btrfs_key key
;
2357 if (btrfs_fs_incompat(fs_info
, NO_HOLES
))
2360 key
.objectid
= btrfs_ino(inode
);
2361 key
.type
= BTRFS_EXTENT_DATA_KEY
;
2362 key
.offset
= offset
;
2364 ret
= btrfs_search_slot(trans
, root
, &key
, path
, 0, 1);
2367 * We should have dropped this offset, so if we find it then
2368 * something has gone horribly wrong.
2375 leaf
= path
->nodes
[0];
2376 if (hole_mergeable(inode
, leaf
, path
->slots
[0] - 1, offset
, end
)) {
2380 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
2381 struct btrfs_file_extent_item
);
2382 num_bytes
= btrfs_file_extent_num_bytes(leaf
, fi
) +
2384 btrfs_set_file_extent_num_bytes(leaf
, fi
, num_bytes
);
2385 btrfs_set_file_extent_ram_bytes(leaf
, fi
, num_bytes
);
2386 btrfs_set_file_extent_offset(leaf
, fi
, 0);
2387 btrfs_mark_buffer_dirty(leaf
);
2391 if (hole_mergeable(inode
, leaf
, path
->slots
[0], offset
, end
)) {
2394 key
.offset
= offset
;
2395 btrfs_set_item_key_safe(fs_info
, path
, &key
);
2396 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
2397 struct btrfs_file_extent_item
);
2398 num_bytes
= btrfs_file_extent_num_bytes(leaf
, fi
) + end
-
2400 btrfs_set_file_extent_num_bytes(leaf
, fi
, num_bytes
);
2401 btrfs_set_file_extent_ram_bytes(leaf
, fi
, num_bytes
);
2402 btrfs_set_file_extent_offset(leaf
, fi
, 0);
2403 btrfs_mark_buffer_dirty(leaf
);
2406 btrfs_release_path(path
);
2408 ret
= btrfs_insert_file_extent(trans
, root
, btrfs_ino(inode
),
2409 offset
, 0, 0, end
- offset
, 0, end
- offset
, 0, 0, 0);
2414 btrfs_release_path(path
);
2416 hole_em
= alloc_extent_map();
2418 btrfs_drop_extent_cache(inode
, offset
, end
- 1, 0);
2419 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC
, &inode
->runtime_flags
);
2421 hole_em
->start
= offset
;
2422 hole_em
->len
= end
- offset
;
2423 hole_em
->ram_bytes
= hole_em
->len
;
2424 hole_em
->orig_start
= offset
;
2426 hole_em
->block_start
= EXTENT_MAP_HOLE
;
2427 hole_em
->block_len
= 0;
2428 hole_em
->orig_block_len
= 0;
2429 hole_em
->compress_type
= BTRFS_COMPRESS_NONE
;
2430 hole_em
->generation
= trans
->transid
;
2433 btrfs_drop_extent_cache(inode
, offset
, end
- 1, 0);
2434 write_lock(&em_tree
->lock
);
2435 ret
= add_extent_mapping(em_tree
, hole_em
, 1);
2436 write_unlock(&em_tree
->lock
);
2437 } while (ret
== -EEXIST
);
2438 free_extent_map(hole_em
);
2440 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC
,
2441 &inode
->runtime_flags
);
2448 * Find a hole extent on given inode and change start/len to the end of hole
2449 * extent.(hole/vacuum extent whose em->start <= start &&
2450 * em->start + em->len > start)
2451 * When a hole extent is found, return 1 and modify start/len.
2453 static int find_first_non_hole(struct btrfs_inode
*inode
, u64
*start
, u64
*len
)
2455 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
2456 struct extent_map
*em
;
2459 em
= btrfs_get_extent(inode
, NULL
, 0,
2460 round_down(*start
, fs_info
->sectorsize
),
2461 round_up(*len
, fs_info
->sectorsize
));
2465 /* Hole or vacuum extent(only exists in no-hole mode) */
2466 if (em
->block_start
== EXTENT_MAP_HOLE
) {
2468 *len
= em
->start
+ em
->len
> *start
+ *len
?
2469 0 : *start
+ *len
- em
->start
- em
->len
;
2470 *start
= em
->start
+ em
->len
;
2472 free_extent_map(em
);
2476 static int btrfs_punch_hole_lock_range(struct inode
*inode
,
2477 const u64 lockstart
,
2479 struct extent_state
**cached_state
)
2482 struct btrfs_ordered_extent
*ordered
;
2485 truncate_pagecache_range(inode
, lockstart
, lockend
);
2487 lock_extent_bits(&BTRFS_I(inode
)->io_tree
, lockstart
, lockend
,
2489 ordered
= btrfs_lookup_first_ordered_extent(BTRFS_I(inode
),
2493 * We need to make sure we have no ordered extents in this range
2494 * and nobody raced in and read a page in this range, if we did
2495 * we need to try again.
2498 (ordered
->file_offset
+ ordered
->num_bytes
<= lockstart
||
2499 ordered
->file_offset
> lockend
)) &&
2500 !filemap_range_has_page(inode
->i_mapping
,
2501 lockstart
, lockend
)) {
2503 btrfs_put_ordered_extent(ordered
);
2507 btrfs_put_ordered_extent(ordered
);
2508 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
, lockstart
,
2509 lockend
, cached_state
);
2510 ret
= btrfs_wait_ordered_range(inode
, lockstart
,
2511 lockend
- lockstart
+ 1);
2518 static int btrfs_insert_replace_extent(struct btrfs_trans_handle
*trans
,
2519 struct btrfs_inode
*inode
,
2520 struct btrfs_path
*path
,
2521 struct btrfs_replace_extent_info
*extent_info
,
2522 const u64 replace_len
,
2523 const u64 bytes_to_drop
)
2525 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
2526 struct btrfs_root
*root
= inode
->root
;
2527 struct btrfs_file_extent_item
*extent
;
2528 struct extent_buffer
*leaf
;
2529 struct btrfs_key key
;
2531 struct btrfs_ref ref
= { 0 };
2534 if (replace_len
== 0)
2537 if (extent_info
->disk_offset
== 0 &&
2538 btrfs_fs_incompat(fs_info
, NO_HOLES
)) {
2539 btrfs_update_inode_bytes(inode
, 0, bytes_to_drop
);
2543 key
.objectid
= btrfs_ino(inode
);
2544 key
.type
= BTRFS_EXTENT_DATA_KEY
;
2545 key
.offset
= extent_info
->file_offset
;
2546 ret
= btrfs_insert_empty_item(trans
, root
, path
, &key
,
2547 sizeof(struct btrfs_file_extent_item
));
2550 leaf
= path
->nodes
[0];
2551 slot
= path
->slots
[0];
2552 write_extent_buffer(leaf
, extent_info
->extent_buf
,
2553 btrfs_item_ptr_offset(leaf
, slot
),
2554 sizeof(struct btrfs_file_extent_item
));
2555 extent
= btrfs_item_ptr(leaf
, slot
, struct btrfs_file_extent_item
);
2556 ASSERT(btrfs_file_extent_type(leaf
, extent
) != BTRFS_FILE_EXTENT_INLINE
);
2557 btrfs_set_file_extent_offset(leaf
, extent
, extent_info
->data_offset
);
2558 btrfs_set_file_extent_num_bytes(leaf
, extent
, replace_len
);
2559 if (extent_info
->is_new_extent
)
2560 btrfs_set_file_extent_generation(leaf
, extent
, trans
->transid
);
2561 btrfs_mark_buffer_dirty(leaf
);
2562 btrfs_release_path(path
);
2564 ret
= btrfs_inode_set_file_extent_range(inode
, extent_info
->file_offset
,
2569 /* If it's a hole, nothing more needs to be done. */
2570 if (extent_info
->disk_offset
== 0) {
2571 btrfs_update_inode_bytes(inode
, 0, bytes_to_drop
);
2575 btrfs_update_inode_bytes(inode
, replace_len
, bytes_to_drop
);
2577 if (extent_info
->is_new_extent
&& extent_info
->insertions
== 0) {
2578 key
.objectid
= extent_info
->disk_offset
;
2579 key
.type
= BTRFS_EXTENT_ITEM_KEY
;
2580 key
.offset
= extent_info
->disk_len
;
2581 ret
= btrfs_alloc_reserved_file_extent(trans
, root
,
2583 extent_info
->file_offset
,
2584 extent_info
->qgroup_reserved
,
2589 btrfs_init_generic_ref(&ref
, BTRFS_ADD_DELAYED_REF
,
2590 extent_info
->disk_offset
,
2591 extent_info
->disk_len
, 0);
2592 ref_offset
= extent_info
->file_offset
- extent_info
->data_offset
;
2593 btrfs_init_data_ref(&ref
, root
->root_key
.objectid
,
2594 btrfs_ino(inode
), ref_offset
);
2595 ret
= btrfs_inc_extent_ref(trans
, &ref
);
2598 extent_info
->insertions
++;
2604 * The respective range must have been previously locked, as well as the inode.
2605 * The end offset is inclusive (last byte of the range).
2606 * @extent_info is NULL for fallocate's hole punching and non-NULL when replacing
2607 * the file range with an extent.
2608 * When not punching a hole, we don't want to end up in a state where we dropped
2609 * extents without inserting a new one, so we must abort the transaction to avoid
2612 int btrfs_replace_file_extents(struct inode
*inode
, struct btrfs_path
*path
,
2613 const u64 start
, const u64 end
,
2614 struct btrfs_replace_extent_info
*extent_info
,
2615 struct btrfs_trans_handle
**trans_out
)
2617 struct btrfs_drop_extents_args drop_args
= { 0 };
2618 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2619 u64 min_size
= btrfs_calc_insert_metadata_size(fs_info
, 1);
2620 u64 ino_size
= round_up(inode
->i_size
, fs_info
->sectorsize
);
2621 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
2622 struct btrfs_trans_handle
*trans
= NULL
;
2623 struct btrfs_block_rsv
*rsv
;
2624 unsigned int rsv_count
;
2626 u64 len
= end
- start
;
2632 rsv
= btrfs_alloc_block_rsv(fs_info
, BTRFS_BLOCK_RSV_TEMP
);
2637 rsv
->size
= btrfs_calc_insert_metadata_size(fs_info
, 1);
2641 * 1 - update the inode
2642 * 1 - removing the extents in the range
2643 * 1 - adding the hole extent if no_holes isn't set or if we are
2644 * replacing the range with a new extent
2646 if (!btrfs_fs_incompat(fs_info
, NO_HOLES
) || extent_info
)
2651 trans
= btrfs_start_transaction(root
, rsv_count
);
2652 if (IS_ERR(trans
)) {
2653 ret
= PTR_ERR(trans
);
2658 ret
= btrfs_block_rsv_migrate(&fs_info
->trans_block_rsv
, rsv
,
2661 trans
->block_rsv
= rsv
;
2664 drop_args
.path
= path
;
2665 drop_args
.end
= end
+ 1;
2666 drop_args
.drop_cache
= true;
2667 while (cur_offset
< end
) {
2668 drop_args
.start
= cur_offset
;
2669 ret
= btrfs_drop_extents(trans
, root
, BTRFS_I(inode
), &drop_args
);
2670 /* If we are punching a hole decrement the inode's byte count */
2672 btrfs_update_inode_bytes(BTRFS_I(inode
), 0,
2673 drop_args
.bytes_found
);
2674 if (ret
!= -ENOSPC
) {
2676 * When cloning we want to avoid transaction aborts when
2677 * nothing was done and we are attempting to clone parts
2678 * of inline extents, in such cases -EOPNOTSUPP is
2679 * returned by __btrfs_drop_extents() without having
2680 * changed anything in the file.
2682 if (extent_info
&& !extent_info
->is_new_extent
&&
2683 ret
&& ret
!= -EOPNOTSUPP
)
2684 btrfs_abort_transaction(trans
, ret
);
2688 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
2690 if (!extent_info
&& cur_offset
< drop_args
.drop_end
&&
2691 cur_offset
< ino_size
) {
2692 ret
= fill_holes(trans
, BTRFS_I(inode
), path
,
2693 cur_offset
, drop_args
.drop_end
);
2696 * If we failed then we didn't insert our hole
2697 * entries for the area we dropped, so now the
2698 * fs is corrupted, so we must abort the
2701 btrfs_abort_transaction(trans
, ret
);
2704 } else if (!extent_info
&& cur_offset
< drop_args
.drop_end
) {
2706 * We are past the i_size here, but since we didn't
2707 * insert holes we need to clear the mapped area so we
2708 * know to not set disk_i_size in this area until a new
2709 * file extent is inserted here.
2711 ret
= btrfs_inode_clear_file_extent_range(BTRFS_I(inode
),
2713 drop_args
.drop_end
- cur_offset
);
2716 * We couldn't clear our area, so we could
2717 * presumably adjust up and corrupt the fs, so
2720 btrfs_abort_transaction(trans
, ret
);
2726 drop_args
.drop_end
> extent_info
->file_offset
) {
2727 u64 replace_len
= drop_args
.drop_end
-
2728 extent_info
->file_offset
;
2730 ret
= btrfs_insert_replace_extent(trans
, BTRFS_I(inode
),
2731 path
, extent_info
, replace_len
,
2732 drop_args
.bytes_found
);
2734 btrfs_abort_transaction(trans
, ret
);
2737 extent_info
->data_len
-= replace_len
;
2738 extent_info
->data_offset
+= replace_len
;
2739 extent_info
->file_offset
+= replace_len
;
2742 cur_offset
= drop_args
.drop_end
;
2744 ret
= btrfs_update_inode(trans
, root
, BTRFS_I(inode
));
2748 btrfs_end_transaction(trans
);
2749 btrfs_btree_balance_dirty(fs_info
);
2751 trans
= btrfs_start_transaction(root
, rsv_count
);
2752 if (IS_ERR(trans
)) {
2753 ret
= PTR_ERR(trans
);
2758 ret
= btrfs_block_rsv_migrate(&fs_info
->trans_block_rsv
,
2759 rsv
, min_size
, false);
2760 BUG_ON(ret
); /* shouldn't happen */
2761 trans
->block_rsv
= rsv
;
2764 ret
= find_first_non_hole(BTRFS_I(inode
), &cur_offset
,
2766 if (unlikely(ret
< 0))
2776 * If we were cloning, force the next fsync to be a full one since we
2777 * we replaced (or just dropped in the case of cloning holes when
2778 * NO_HOLES is enabled) extents and extent maps.
2779 * This is for the sake of simplicity, and cloning into files larger
2780 * than 16Mb would force the full fsync any way (when
2781 * try_release_extent_mapping() is invoked during page cache truncation.
2783 if (extent_info
&& !extent_info
->is_new_extent
)
2784 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC
,
2785 &BTRFS_I(inode
)->runtime_flags
);
2790 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
2792 * If we are using the NO_HOLES feature we might have had already an
2793 * hole that overlaps a part of the region [lockstart, lockend] and
2794 * ends at (or beyond) lockend. Since we have no file extent items to
2795 * represent holes, drop_end can be less than lockend and so we must
2796 * make sure we have an extent map representing the existing hole (the
2797 * call to __btrfs_drop_extents() might have dropped the existing extent
2798 * map representing the existing hole), otherwise the fast fsync path
2799 * will not record the existence of the hole region
2800 * [existing_hole_start, lockend].
2802 if (drop_args
.drop_end
<= end
)
2803 drop_args
.drop_end
= end
+ 1;
2805 * Don't insert file hole extent item if it's for a range beyond eof
2806 * (because it's useless) or if it represents a 0 bytes range (when
2807 * cur_offset == drop_end).
2809 if (!extent_info
&& cur_offset
< ino_size
&&
2810 cur_offset
< drop_args
.drop_end
) {
2811 ret
= fill_holes(trans
, BTRFS_I(inode
), path
,
2812 cur_offset
, drop_args
.drop_end
);
2814 /* Same comment as above. */
2815 btrfs_abort_transaction(trans
, ret
);
2818 } else if (!extent_info
&& cur_offset
< drop_args
.drop_end
) {
2819 /* See the comment in the loop above for the reasoning here. */
2820 ret
= btrfs_inode_clear_file_extent_range(BTRFS_I(inode
),
2821 cur_offset
, drop_args
.drop_end
- cur_offset
);
2823 btrfs_abort_transaction(trans
, ret
);
2829 ret
= btrfs_insert_replace_extent(trans
, BTRFS_I(inode
), path
,
2830 extent_info
, extent_info
->data_len
,
2831 drop_args
.bytes_found
);
2833 btrfs_abort_transaction(trans
, ret
);
2842 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
2844 btrfs_end_transaction(trans
);
2848 btrfs_free_block_rsv(fs_info
, rsv
);
2853 static int btrfs_punch_hole(struct inode
*inode
, loff_t offset
, loff_t len
)
2855 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2856 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
2857 struct extent_state
*cached_state
= NULL
;
2858 struct btrfs_path
*path
;
2859 struct btrfs_trans_handle
*trans
= NULL
;
2864 u64 orig_start
= offset
;
2868 bool truncated_block
= false;
2869 bool updated_inode
= false;
2871 ret
= btrfs_wait_ordered_range(inode
, offset
, len
);
2876 ino_size
= round_up(inode
->i_size
, fs_info
->sectorsize
);
2877 ret
= find_first_non_hole(BTRFS_I(inode
), &offset
, &len
);
2879 goto out_only_mutex
;
2881 /* Already in a large hole */
2883 goto out_only_mutex
;
2886 lockstart
= round_up(offset
, btrfs_inode_sectorsize(BTRFS_I(inode
)));
2887 lockend
= round_down(offset
+ len
,
2888 btrfs_inode_sectorsize(BTRFS_I(inode
))) - 1;
2889 same_block
= (BTRFS_BYTES_TO_BLKS(fs_info
, offset
))
2890 == (BTRFS_BYTES_TO_BLKS(fs_info
, offset
+ len
- 1));
2892 * We needn't truncate any block which is beyond the end of the file
2893 * because we are sure there is no data there.
2896 * Only do this if we are in the same block and we aren't doing the
2899 if (same_block
&& len
< fs_info
->sectorsize
) {
2900 if (offset
< ino_size
) {
2901 truncated_block
= true;
2902 ret
= btrfs_truncate_block(BTRFS_I(inode
), offset
, len
,
2907 goto out_only_mutex
;
2910 /* zero back part of the first block */
2911 if (offset
< ino_size
) {
2912 truncated_block
= true;
2913 ret
= btrfs_truncate_block(BTRFS_I(inode
), offset
, 0, 0);
2915 inode_unlock(inode
);
2920 /* Check the aligned pages after the first unaligned page,
2921 * if offset != orig_start, which means the first unaligned page
2922 * including several following pages are already in holes,
2923 * the extra check can be skipped */
2924 if (offset
== orig_start
) {
2925 /* after truncate page, check hole again */
2926 len
= offset
+ len
- lockstart
;
2928 ret
= find_first_non_hole(BTRFS_I(inode
), &offset
, &len
);
2930 goto out_only_mutex
;
2933 goto out_only_mutex
;
2938 /* Check the tail unaligned part is in a hole */
2939 tail_start
= lockend
+ 1;
2940 tail_len
= offset
+ len
- tail_start
;
2942 ret
= find_first_non_hole(BTRFS_I(inode
), &tail_start
, &tail_len
);
2943 if (unlikely(ret
< 0))
2944 goto out_only_mutex
;
2946 /* zero the front end of the last page */
2947 if (tail_start
+ tail_len
< ino_size
) {
2948 truncated_block
= true;
2949 ret
= btrfs_truncate_block(BTRFS_I(inode
),
2950 tail_start
+ tail_len
,
2953 goto out_only_mutex
;
2958 if (lockend
< lockstart
) {
2960 goto out_only_mutex
;
2963 ret
= btrfs_punch_hole_lock_range(inode
, lockstart
, lockend
,
2966 goto out_only_mutex
;
2968 path
= btrfs_alloc_path();
2974 ret
= btrfs_replace_file_extents(inode
, path
, lockstart
, lockend
, NULL
,
2976 btrfs_free_path(path
);
2980 ASSERT(trans
!= NULL
);
2981 inode_inc_iversion(inode
);
2982 inode
->i_mtime
= inode
->i_ctime
= current_time(inode
);
2983 ret
= btrfs_update_inode(trans
, root
, BTRFS_I(inode
));
2984 updated_inode
= true;
2985 btrfs_end_transaction(trans
);
2986 btrfs_btree_balance_dirty(fs_info
);
2988 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
, lockstart
, lockend
,
2991 if (!updated_inode
&& truncated_block
&& !ret
) {
2993 * If we only end up zeroing part of a page, we still need to
2994 * update the inode item, so that all the time fields are
2995 * updated as well as the necessary btrfs inode in memory fields
2996 * for detecting, at fsync time, if the inode isn't yet in the
2997 * log tree or it's there but not up to date.
2999 struct timespec64 now
= current_time(inode
);
3001 inode_inc_iversion(inode
);
3002 inode
->i_mtime
= now
;
3003 inode
->i_ctime
= now
;
3004 trans
= btrfs_start_transaction(root
, 1);
3005 if (IS_ERR(trans
)) {
3006 ret
= PTR_ERR(trans
);
3010 ret
= btrfs_update_inode(trans
, root
, BTRFS_I(inode
));
3011 ret2
= btrfs_end_transaction(trans
);
3016 inode_unlock(inode
);
3020 /* Helper structure to record which range is already reserved */
3021 struct falloc_range
{
3022 struct list_head list
;
3028 * Helper function to add falloc range
3030 * Caller should have locked the larger range of extent containing
3033 static int add_falloc_range(struct list_head
*head
, u64 start
, u64 len
)
3035 struct falloc_range
*prev
= NULL
;
3036 struct falloc_range
*range
= NULL
;
3038 if (list_empty(head
))
3042 * As fallocate iterate by bytenr order, we only need to check
3045 prev
= list_entry(head
->prev
, struct falloc_range
, list
);
3046 if (prev
->start
+ prev
->len
== start
) {
3051 range
= kmalloc(sizeof(*range
), GFP_KERNEL
);
3054 range
->start
= start
;
3056 list_add_tail(&range
->list
, head
);
3060 static int btrfs_fallocate_update_isize(struct inode
*inode
,
3064 struct btrfs_trans_handle
*trans
;
3065 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
3069 if (mode
& FALLOC_FL_KEEP_SIZE
|| end
<= i_size_read(inode
))
3072 trans
= btrfs_start_transaction(root
, 1);
3074 return PTR_ERR(trans
);
3076 inode
->i_ctime
= current_time(inode
);
3077 i_size_write(inode
, end
);
3078 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode
), 0);
3079 ret
= btrfs_update_inode(trans
, root
, BTRFS_I(inode
));
3080 ret2
= btrfs_end_transaction(trans
);
3082 return ret
? ret
: ret2
;
3086 RANGE_BOUNDARY_WRITTEN_EXTENT
,
3087 RANGE_BOUNDARY_PREALLOC_EXTENT
,
3088 RANGE_BOUNDARY_HOLE
,
3091 static int btrfs_zero_range_check_range_boundary(struct btrfs_inode
*inode
,
3094 const u64 sectorsize
= btrfs_inode_sectorsize(inode
);
3095 struct extent_map
*em
;
3098 offset
= round_down(offset
, sectorsize
);
3099 em
= btrfs_get_extent(inode
, NULL
, 0, offset
, sectorsize
);
3103 if (em
->block_start
== EXTENT_MAP_HOLE
)
3104 ret
= RANGE_BOUNDARY_HOLE
;
3105 else if (test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
))
3106 ret
= RANGE_BOUNDARY_PREALLOC_EXTENT
;
3108 ret
= RANGE_BOUNDARY_WRITTEN_EXTENT
;
3110 free_extent_map(em
);
3114 static int btrfs_zero_range(struct inode
*inode
,
3119 struct btrfs_fs_info
*fs_info
= BTRFS_I(inode
)->root
->fs_info
;
3120 struct extent_map
*em
;
3121 struct extent_changeset
*data_reserved
= NULL
;
3124 const u64 sectorsize
= btrfs_inode_sectorsize(BTRFS_I(inode
));
3125 u64 alloc_start
= round_down(offset
, sectorsize
);
3126 u64 alloc_end
= round_up(offset
+ len
, sectorsize
);
3127 u64 bytes_to_reserve
= 0;
3128 bool space_reserved
= false;
3130 inode_dio_wait(inode
);
3132 em
= btrfs_get_extent(BTRFS_I(inode
), NULL
, 0, alloc_start
,
3133 alloc_end
- alloc_start
);
3140 * Avoid hole punching and extent allocation for some cases. More cases
3141 * could be considered, but these are unlikely common and we keep things
3142 * as simple as possible for now. Also, intentionally, if the target
3143 * range contains one or more prealloc extents together with regular
3144 * extents and holes, we drop all the existing extents and allocate a
3145 * new prealloc extent, so that we get a larger contiguous disk extent.
3147 if (em
->start
<= alloc_start
&&
3148 test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
)) {
3149 const u64 em_end
= em
->start
+ em
->len
;
3151 if (em_end
>= offset
+ len
) {
3153 * The whole range is already a prealloc extent,
3154 * do nothing except updating the inode's i_size if
3157 free_extent_map(em
);
3158 ret
= btrfs_fallocate_update_isize(inode
, offset
+ len
,
3163 * Part of the range is already a prealloc extent, so operate
3164 * only on the remaining part of the range.
3166 alloc_start
= em_end
;
3167 ASSERT(IS_ALIGNED(alloc_start
, sectorsize
));
3168 len
= offset
+ len
- alloc_start
;
3169 offset
= alloc_start
;
3170 alloc_hint
= em
->block_start
+ em
->len
;
3172 free_extent_map(em
);
3174 if (BTRFS_BYTES_TO_BLKS(fs_info
, offset
) ==
3175 BTRFS_BYTES_TO_BLKS(fs_info
, offset
+ len
- 1)) {
3176 em
= btrfs_get_extent(BTRFS_I(inode
), NULL
, 0, alloc_start
,
3183 if (test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
)) {
3184 free_extent_map(em
);
3185 ret
= btrfs_fallocate_update_isize(inode
, offset
+ len
,
3189 if (len
< sectorsize
&& em
->block_start
!= EXTENT_MAP_HOLE
) {
3190 free_extent_map(em
);
3191 ret
= btrfs_truncate_block(BTRFS_I(inode
), offset
, len
,
3194 ret
= btrfs_fallocate_update_isize(inode
,
3199 free_extent_map(em
);
3200 alloc_start
= round_down(offset
, sectorsize
);
3201 alloc_end
= alloc_start
+ sectorsize
;
3205 alloc_start
= round_up(offset
, sectorsize
);
3206 alloc_end
= round_down(offset
+ len
, sectorsize
);
3209 * For unaligned ranges, check the pages at the boundaries, they might
3210 * map to an extent, in which case we need to partially zero them, or
3211 * they might map to a hole, in which case we need our allocation range
3214 if (!IS_ALIGNED(offset
, sectorsize
)) {
3215 ret
= btrfs_zero_range_check_range_boundary(BTRFS_I(inode
),
3219 if (ret
== RANGE_BOUNDARY_HOLE
) {
3220 alloc_start
= round_down(offset
, sectorsize
);
3222 } else if (ret
== RANGE_BOUNDARY_WRITTEN_EXTENT
) {
3223 ret
= btrfs_truncate_block(BTRFS_I(inode
), offset
, 0, 0);
3231 if (!IS_ALIGNED(offset
+ len
, sectorsize
)) {
3232 ret
= btrfs_zero_range_check_range_boundary(BTRFS_I(inode
),
3236 if (ret
== RANGE_BOUNDARY_HOLE
) {
3237 alloc_end
= round_up(offset
+ len
, sectorsize
);
3239 } else if (ret
== RANGE_BOUNDARY_WRITTEN_EXTENT
) {
3240 ret
= btrfs_truncate_block(BTRFS_I(inode
), offset
+ len
,
3250 if (alloc_start
< alloc_end
) {
3251 struct extent_state
*cached_state
= NULL
;
3252 const u64 lockstart
= alloc_start
;
3253 const u64 lockend
= alloc_end
- 1;
3255 bytes_to_reserve
= alloc_end
- alloc_start
;
3256 ret
= btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode
),
3260 space_reserved
= true;
3261 ret
= btrfs_punch_hole_lock_range(inode
, lockstart
, lockend
,
3265 ret
= btrfs_qgroup_reserve_data(BTRFS_I(inode
), &data_reserved
,
3266 alloc_start
, bytes_to_reserve
);
3269 ret
= btrfs_prealloc_file_range(inode
, mode
, alloc_start
,
3270 alloc_end
- alloc_start
,
3272 offset
+ len
, &alloc_hint
);
3273 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
, lockstart
,
3274 lockend
, &cached_state
);
3275 /* btrfs_prealloc_file_range releases reserved space on error */
3277 space_reserved
= false;
3281 ret
= btrfs_fallocate_update_isize(inode
, offset
+ len
, mode
);
3283 if (ret
&& space_reserved
)
3284 btrfs_free_reserved_data_space(BTRFS_I(inode
), data_reserved
,
3285 alloc_start
, bytes_to_reserve
);
3286 extent_changeset_free(data_reserved
);
3291 static long btrfs_fallocate(struct file
*file
, int mode
,
3292 loff_t offset
, loff_t len
)
3294 struct inode
*inode
= file_inode(file
);
3295 struct extent_state
*cached_state
= NULL
;
3296 struct extent_changeset
*data_reserved
= NULL
;
3297 struct falloc_range
*range
;
3298 struct falloc_range
*tmp
;
3299 struct list_head reserve_list
;
3307 struct extent_map
*em
;
3308 int blocksize
= btrfs_inode_sectorsize(BTRFS_I(inode
));
3311 /* Do not allow fallocate in ZONED mode */
3312 if (btrfs_is_zoned(btrfs_sb(inode
->i_sb
)))
3315 alloc_start
= round_down(offset
, blocksize
);
3316 alloc_end
= round_up(offset
+ len
, blocksize
);
3317 cur_offset
= alloc_start
;
3319 /* Make sure we aren't being give some crap mode */
3320 if (mode
& ~(FALLOC_FL_KEEP_SIZE
| FALLOC_FL_PUNCH_HOLE
|
3321 FALLOC_FL_ZERO_RANGE
))
3324 if (mode
& FALLOC_FL_PUNCH_HOLE
)
3325 return btrfs_punch_hole(inode
, offset
, len
);
3328 * Only trigger disk allocation, don't trigger qgroup reserve
3330 * For qgroup space, it will be checked later.
3332 if (!(mode
& FALLOC_FL_ZERO_RANGE
)) {
3333 ret
= btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode
),
3334 alloc_end
- alloc_start
);
3339 btrfs_inode_lock(inode
, 0);
3341 if (!(mode
& FALLOC_FL_KEEP_SIZE
) && offset
+ len
> inode
->i_size
) {
3342 ret
= inode_newsize_ok(inode
, offset
+ len
);
3348 * TODO: Move these two operations after we have checked
3349 * accurate reserved space, or fallocate can still fail but
3350 * with page truncated or size expanded.
3352 * But that's a minor problem and won't do much harm BTW.
3354 if (alloc_start
> inode
->i_size
) {
3355 ret
= btrfs_cont_expand(BTRFS_I(inode
), i_size_read(inode
),
3359 } else if (offset
+ len
> inode
->i_size
) {
3361 * If we are fallocating from the end of the file onward we
3362 * need to zero out the end of the block if i_size lands in the
3363 * middle of a block.
3365 ret
= btrfs_truncate_block(BTRFS_I(inode
), inode
->i_size
, 0, 0);
3371 * wait for ordered IO before we have any locks. We'll loop again
3372 * below with the locks held.
3374 ret
= btrfs_wait_ordered_range(inode
, alloc_start
,
3375 alloc_end
- alloc_start
);
3379 if (mode
& FALLOC_FL_ZERO_RANGE
) {
3380 ret
= btrfs_zero_range(inode
, offset
, len
, mode
);
3381 inode_unlock(inode
);
3385 locked_end
= alloc_end
- 1;
3387 struct btrfs_ordered_extent
*ordered
;
3389 /* the extent lock is ordered inside the running
3392 lock_extent_bits(&BTRFS_I(inode
)->io_tree
, alloc_start
,
3393 locked_end
, &cached_state
);
3394 ordered
= btrfs_lookup_first_ordered_extent(BTRFS_I(inode
),
3398 ordered
->file_offset
+ ordered
->num_bytes
> alloc_start
&&
3399 ordered
->file_offset
< alloc_end
) {
3400 btrfs_put_ordered_extent(ordered
);
3401 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
,
3402 alloc_start
, locked_end
,
3405 * we can't wait on the range with the transaction
3406 * running or with the extent lock held
3408 ret
= btrfs_wait_ordered_range(inode
, alloc_start
,
3409 alloc_end
- alloc_start
);
3414 btrfs_put_ordered_extent(ordered
);
3419 /* First, check if we exceed the qgroup limit */
3420 INIT_LIST_HEAD(&reserve_list
);
3421 while (cur_offset
< alloc_end
) {
3422 em
= btrfs_get_extent(BTRFS_I(inode
), NULL
, 0, cur_offset
,
3423 alloc_end
- cur_offset
);
3428 last_byte
= min(extent_map_end(em
), alloc_end
);
3429 actual_end
= min_t(u64
, extent_map_end(em
), offset
+ len
);
3430 last_byte
= ALIGN(last_byte
, blocksize
);
3431 if (em
->block_start
== EXTENT_MAP_HOLE
||
3432 (cur_offset
>= inode
->i_size
&&
3433 !test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
))) {
3434 ret
= add_falloc_range(&reserve_list
, cur_offset
,
3435 last_byte
- cur_offset
);
3437 free_extent_map(em
);
3440 ret
= btrfs_qgroup_reserve_data(BTRFS_I(inode
),
3441 &data_reserved
, cur_offset
,
3442 last_byte
- cur_offset
);
3444 cur_offset
= last_byte
;
3445 free_extent_map(em
);
3450 * Do not need to reserve unwritten extent for this
3451 * range, free reserved data space first, otherwise
3452 * it'll result in false ENOSPC error.
3454 btrfs_free_reserved_data_space(BTRFS_I(inode
),
3455 data_reserved
, cur_offset
,
3456 last_byte
- cur_offset
);
3458 free_extent_map(em
);
3459 cur_offset
= last_byte
;
3463 * If ret is still 0, means we're OK to fallocate.
3464 * Or just cleanup the list and exit.
3466 list_for_each_entry_safe(range
, tmp
, &reserve_list
, list
) {
3468 ret
= btrfs_prealloc_file_range(inode
, mode
,
3470 range
->len
, i_blocksize(inode
),
3471 offset
+ len
, &alloc_hint
);
3473 btrfs_free_reserved_data_space(BTRFS_I(inode
),
3474 data_reserved
, range
->start
,
3476 list_del(&range
->list
);
3483 * We didn't need to allocate any more space, but we still extended the
3484 * size of the file so we need to update i_size and the inode item.
3486 ret
= btrfs_fallocate_update_isize(inode
, actual_end
, mode
);
3488 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
, alloc_start
, locked_end
,
3491 inode_unlock(inode
);
3492 /* Let go of our reservation. */
3493 if (ret
!= 0 && !(mode
& FALLOC_FL_ZERO_RANGE
))
3494 btrfs_free_reserved_data_space(BTRFS_I(inode
), data_reserved
,
3495 cur_offset
, alloc_end
- cur_offset
);
3496 extent_changeset_free(data_reserved
);
3500 static loff_t
find_desired_extent(struct inode
*inode
, loff_t offset
,
3503 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
3504 struct extent_map
*em
= NULL
;
3505 struct extent_state
*cached_state
= NULL
;
3506 loff_t i_size
= inode
->i_size
;
3513 if (i_size
== 0 || offset
>= i_size
)
3517 * offset can be negative, in this case we start finding DATA/HOLE from
3518 * the very start of the file.
3520 start
= max_t(loff_t
, 0, offset
);
3522 lockstart
= round_down(start
, fs_info
->sectorsize
);
3523 lockend
= round_up(i_size
, fs_info
->sectorsize
);
3524 if (lockend
<= lockstart
)
3525 lockend
= lockstart
+ fs_info
->sectorsize
;
3527 len
= lockend
- lockstart
+ 1;
3529 lock_extent_bits(&BTRFS_I(inode
)->io_tree
, lockstart
, lockend
,
3532 while (start
< i_size
) {
3533 em
= btrfs_get_extent_fiemap(BTRFS_I(inode
), start
, len
);
3540 if (whence
== SEEK_HOLE
&&
3541 (em
->block_start
== EXTENT_MAP_HOLE
||
3542 test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
)))
3544 else if (whence
== SEEK_DATA
&&
3545 (em
->block_start
!= EXTENT_MAP_HOLE
&&
3546 !test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
)))
3549 start
= em
->start
+ em
->len
;
3550 free_extent_map(em
);
3554 free_extent_map(em
);
3555 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
, lockstart
, lockend
,
3560 if (whence
== SEEK_DATA
&& start
>= i_size
)
3563 offset
= min_t(loff_t
, start
, i_size
);
3569 static loff_t
btrfs_file_llseek(struct file
*file
, loff_t offset
, int whence
)
3571 struct inode
*inode
= file
->f_mapping
->host
;
3575 return generic_file_llseek(file
, offset
, whence
);
3578 btrfs_inode_lock(inode
, BTRFS_ILOCK_SHARED
);
3579 offset
= find_desired_extent(inode
, offset
, whence
);
3580 btrfs_inode_unlock(inode
, BTRFS_ILOCK_SHARED
);
3587 return vfs_setpos(file
, offset
, inode
->i_sb
->s_maxbytes
);
3590 static int btrfs_file_open(struct inode
*inode
, struct file
*filp
)
3592 filp
->f_mode
|= FMODE_NOWAIT
| FMODE_BUF_RASYNC
;
3593 return generic_file_open(inode
, filp
);
3596 static int check_direct_read(struct btrfs_fs_info
*fs_info
,
3597 const struct iov_iter
*iter
, loff_t offset
)
3602 ret
= check_direct_IO(fs_info
, iter
, offset
);
3606 if (!iter_is_iovec(iter
))
3609 for (seg
= 0; seg
< iter
->nr_segs
; seg
++)
3610 for (i
= seg
+ 1; i
< iter
->nr_segs
; i
++)
3611 if (iter
->iov
[seg
].iov_base
== iter
->iov
[i
].iov_base
)
3616 static ssize_t
btrfs_direct_read(struct kiocb
*iocb
, struct iov_iter
*to
)
3618 struct inode
*inode
= file_inode(iocb
->ki_filp
);
3621 if (check_direct_read(btrfs_sb(inode
->i_sb
), to
, iocb
->ki_pos
))
3624 btrfs_inode_lock(inode
, BTRFS_ILOCK_SHARED
);
3625 ret
= iomap_dio_rw(iocb
, to
, &btrfs_dio_iomap_ops
, &btrfs_dio_ops
,
3626 is_sync_kiocb(iocb
));
3627 btrfs_inode_unlock(inode
, BTRFS_ILOCK_SHARED
);
3631 static ssize_t
btrfs_file_read_iter(struct kiocb
*iocb
, struct iov_iter
*to
)
3635 if (iocb
->ki_flags
& IOCB_DIRECT
) {
3636 ret
= btrfs_direct_read(iocb
, to
);
3637 if (ret
< 0 || !iov_iter_count(to
) ||
3638 iocb
->ki_pos
>= i_size_read(file_inode(iocb
->ki_filp
)))
3642 return generic_file_buffered_read(iocb
, to
, ret
);
3645 const struct file_operations btrfs_file_operations
= {
3646 .llseek
= btrfs_file_llseek
,
3647 .read_iter
= btrfs_file_read_iter
,
3648 .splice_read
= generic_file_splice_read
,
3649 .write_iter
= btrfs_file_write_iter
,
3650 .splice_write
= iter_file_splice_write
,
3651 .mmap
= btrfs_file_mmap
,
3652 .open
= btrfs_file_open
,
3653 .release
= btrfs_release_file
,
3654 .fsync
= btrfs_sync_file
,
3655 .fallocate
= btrfs_fallocate
,
3656 .unlocked_ioctl
= btrfs_ioctl
,
3657 #ifdef CONFIG_COMPAT
3658 .compat_ioctl
= btrfs_compat_ioctl
,
3660 .remap_file_range
= btrfs_remap_file_range
,
3663 void __cold
btrfs_auto_defrag_exit(void)
3665 kmem_cache_destroy(btrfs_inode_defrag_cachep
);
3668 int __init
btrfs_auto_defrag_init(void)
3670 btrfs_inode_defrag_cachep
= kmem_cache_create("btrfs_inode_defrag",
3671 sizeof(struct inode_defrag
), 0,
3674 if (!btrfs_inode_defrag_cachep
)
3680 int btrfs_fdatawrite_range(struct inode
*inode
, loff_t start
, loff_t end
)
3685 * So with compression we will find and lock a dirty page and clear the
3686 * first one as dirty, setup an async extent, and immediately return
3687 * with the entire range locked but with nobody actually marked with
3688 * writeback. So we can't just filemap_write_and_wait_range() and
3689 * expect it to work since it will just kick off a thread to do the
3690 * actual work. So we need to call filemap_fdatawrite_range _again_
3691 * since it will wait on the page lock, which won't be unlocked until
3692 * after the pages have been marked as writeback and so we're good to go
3693 * from there. We have to do this otherwise we'll miss the ordered
3694 * extents and that results in badness. Please Josef, do not think you
3695 * know better and pull this out at some point in the future, it is
3696 * right and you are wrong.
3698 ret
= filemap_fdatawrite_range(inode
->i_mapping
, start
, end
);
3699 if (!ret
&& test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT
,
3700 &BTRFS_I(inode
)->runtime_flags
))
3701 ret
= filemap_fdatawrite_range(inode
->i_mapping
, start
, end
);