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
, search_len
);
484 if (em
->block_start
!= EXTENT_MAP_HOLE
)
488 if (em
->start
< search_start
)
489 em_len
-= search_start
- em
->start
;
490 if (em_len
> search_len
)
493 ret
= set_extent_bit(&inode
->io_tree
, search_start
,
494 search_start
+ em_len
- 1,
496 NULL
, cached_state
, GFP_NOFS
);
498 search_start
= extent_map_end(em
);
507 * after copy_from_user, pages need to be dirtied and we need to make
508 * sure holes are created between the current EOF and the start of
509 * any next extents (if required).
511 * this also makes the decision about creating an inline extent vs
512 * doing real data extents, marking pages dirty and delalloc as required.
514 int btrfs_dirty_pages(struct inode
*inode
, struct page
**pages
,
515 size_t num_pages
, loff_t pos
, size_t write_bytes
,
516 struct extent_state
**cached
)
518 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
523 u64 end_of_last_block
;
524 u64 end_pos
= pos
+ write_bytes
;
525 loff_t isize
= i_size_read(inode
);
526 unsigned int extra_bits
= 0;
528 start_pos
= pos
& ~((u64
) fs_info
->sectorsize
- 1);
529 num_bytes
= round_up(write_bytes
+ pos
- start_pos
,
530 fs_info
->sectorsize
);
532 end_of_last_block
= start_pos
+ num_bytes
- 1;
535 * The pages may have already been dirty, clear out old accounting so
536 * we can set things up properly
538 clear_extent_bit(&BTRFS_I(inode
)->io_tree
, start_pos
, end_of_last_block
,
539 EXTENT_DELALLOC
| EXTENT_DO_ACCOUNTING
| EXTENT_DEFRAG
,
542 if (!btrfs_is_free_space_inode(BTRFS_I(inode
))) {
543 if (start_pos
>= isize
&&
544 !(BTRFS_I(inode
)->flags
& BTRFS_INODE_PREALLOC
)) {
546 * There can't be any extents following eof in this case
547 * so just set the delalloc new bit for the range
550 extra_bits
|= EXTENT_DELALLOC_NEW
;
552 err
= btrfs_find_new_delalloc_bytes(BTRFS_I(inode
),
560 err
= btrfs_set_extent_delalloc(inode
, start_pos
, end_of_last_block
,
565 for (i
= 0; i
< num_pages
; i
++) {
566 struct page
*p
= pages
[i
];
573 * we've only changed i_size in ram, and we haven't updated
574 * the disk i_size. There is no need to log the inode
578 i_size_write(inode
, end_pos
);
583 * this drops all the extents in the cache that intersect the range
584 * [start, end]. Existing extents are split as required.
586 void btrfs_drop_extent_cache(struct btrfs_inode
*inode
, u64 start
, u64 end
,
589 struct extent_map
*em
;
590 struct extent_map
*split
= NULL
;
591 struct extent_map
*split2
= NULL
;
592 struct extent_map_tree
*em_tree
= &inode
->extent_tree
;
593 u64 len
= end
- start
+ 1;
601 WARN_ON(end
< start
);
602 if (end
== (u64
)-1) {
611 split
= alloc_extent_map();
613 split2
= alloc_extent_map();
614 if (!split
|| !split2
)
617 write_lock(&em_tree
->lock
);
618 em
= lookup_extent_mapping(em_tree
, start
, len
);
620 write_unlock(&em_tree
->lock
);
624 gen
= em
->generation
;
625 if (skip_pinned
&& test_bit(EXTENT_FLAG_PINNED
, &em
->flags
)) {
626 if (testend
&& em
->start
+ em
->len
>= start
+ len
) {
628 write_unlock(&em_tree
->lock
);
631 start
= em
->start
+ em
->len
;
633 len
= start
+ len
- (em
->start
+ em
->len
);
635 write_unlock(&em_tree
->lock
);
638 compressed
= test_bit(EXTENT_FLAG_COMPRESSED
, &em
->flags
);
639 clear_bit(EXTENT_FLAG_PINNED
, &em
->flags
);
640 clear_bit(EXTENT_FLAG_LOGGING
, &flags
);
641 modified
= !list_empty(&em
->list
);
645 if (em
->start
< start
) {
646 split
->start
= em
->start
;
647 split
->len
= start
- em
->start
;
649 if (em
->block_start
< EXTENT_MAP_LAST_BYTE
) {
650 split
->orig_start
= em
->orig_start
;
651 split
->block_start
= em
->block_start
;
654 split
->block_len
= em
->block_len
;
656 split
->block_len
= split
->len
;
657 split
->orig_block_len
= max(split
->block_len
,
659 split
->ram_bytes
= em
->ram_bytes
;
661 split
->orig_start
= split
->start
;
662 split
->block_len
= 0;
663 split
->block_start
= em
->block_start
;
664 split
->orig_block_len
= 0;
665 split
->ram_bytes
= split
->len
;
668 split
->generation
= gen
;
669 split
->flags
= flags
;
670 split
->compress_type
= em
->compress_type
;
671 replace_extent_mapping(em_tree
, em
, split
, modified
);
672 free_extent_map(split
);
676 if (testend
&& em
->start
+ em
->len
> start
+ len
) {
677 u64 diff
= start
+ len
- em
->start
;
679 split
->start
= start
+ len
;
680 split
->len
= em
->start
+ em
->len
- (start
+ len
);
681 split
->flags
= flags
;
682 split
->compress_type
= em
->compress_type
;
683 split
->generation
= gen
;
685 if (em
->block_start
< EXTENT_MAP_LAST_BYTE
) {
686 split
->orig_block_len
= max(em
->block_len
,
689 split
->ram_bytes
= em
->ram_bytes
;
691 split
->block_len
= em
->block_len
;
692 split
->block_start
= em
->block_start
;
693 split
->orig_start
= em
->orig_start
;
695 split
->block_len
= split
->len
;
696 split
->block_start
= em
->block_start
698 split
->orig_start
= em
->orig_start
;
701 split
->ram_bytes
= split
->len
;
702 split
->orig_start
= split
->start
;
703 split
->block_len
= 0;
704 split
->block_start
= em
->block_start
;
705 split
->orig_block_len
= 0;
708 if (extent_map_in_tree(em
)) {
709 replace_extent_mapping(em_tree
, em
, split
,
712 ret
= add_extent_mapping(em_tree
, split
,
714 ASSERT(ret
== 0); /* Logic error */
716 free_extent_map(split
);
720 if (extent_map_in_tree(em
))
721 remove_extent_mapping(em_tree
, em
);
722 write_unlock(&em_tree
->lock
);
726 /* once for the tree*/
730 free_extent_map(split
);
732 free_extent_map(split2
);
736 * this is very complex, but the basic idea is to drop all extents
737 * in the range start - end. hint_block is filled in with a block number
738 * that would be a good hint to the block allocator for this file.
740 * If an extent intersects the range but is not entirely inside the range
741 * it is either truncated or split. Anything entirely inside the range
742 * is deleted from the tree.
744 int __btrfs_drop_extents(struct btrfs_trans_handle
*trans
,
745 struct btrfs_root
*root
, struct inode
*inode
,
746 struct btrfs_path
*path
, u64 start
, u64 end
,
747 u64
*drop_end
, int drop_cache
,
749 u32 extent_item_size
,
752 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
753 struct extent_buffer
*leaf
;
754 struct btrfs_file_extent_item
*fi
;
755 struct btrfs_ref ref
= { 0 };
756 struct btrfs_key key
;
757 struct btrfs_key new_key
;
758 u64 ino
= btrfs_ino(BTRFS_I(inode
));
759 u64 search_start
= start
;
762 u64 extent_offset
= 0;
764 u64 last_end
= start
;
770 int modify_tree
= -1;
773 int leafs_visited
= 0;
776 btrfs_drop_extent_cache(BTRFS_I(inode
), start
, end
- 1, 0);
778 if (start
>= BTRFS_I(inode
)->disk_i_size
&& !replace_extent
)
781 update_refs
= (test_bit(BTRFS_ROOT_REF_COWS
, &root
->state
) ||
782 root
== fs_info
->tree_root
);
785 ret
= btrfs_lookup_file_extent(trans
, root
, path
, ino
,
786 search_start
, modify_tree
);
789 if (ret
> 0 && path
->slots
[0] > 0 && search_start
== start
) {
790 leaf
= path
->nodes
[0];
791 btrfs_item_key_to_cpu(leaf
, &key
, path
->slots
[0] - 1);
792 if (key
.objectid
== ino
&&
793 key
.type
== BTRFS_EXTENT_DATA_KEY
)
799 leaf
= path
->nodes
[0];
800 if (path
->slots
[0] >= btrfs_header_nritems(leaf
)) {
802 ret
= btrfs_next_leaf(root
, path
);
810 leaf
= path
->nodes
[0];
814 btrfs_item_key_to_cpu(leaf
, &key
, path
->slots
[0]);
816 if (key
.objectid
> ino
)
818 if (WARN_ON_ONCE(key
.objectid
< ino
) ||
819 key
.type
< BTRFS_EXTENT_DATA_KEY
) {
824 if (key
.type
> BTRFS_EXTENT_DATA_KEY
|| key
.offset
>= end
)
827 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
828 struct btrfs_file_extent_item
);
829 extent_type
= btrfs_file_extent_type(leaf
, fi
);
831 if (extent_type
== BTRFS_FILE_EXTENT_REG
||
832 extent_type
== BTRFS_FILE_EXTENT_PREALLOC
) {
833 disk_bytenr
= btrfs_file_extent_disk_bytenr(leaf
, fi
);
834 num_bytes
= btrfs_file_extent_disk_num_bytes(leaf
, fi
);
835 extent_offset
= btrfs_file_extent_offset(leaf
, fi
);
836 extent_end
= key
.offset
+
837 btrfs_file_extent_num_bytes(leaf
, fi
);
838 } else if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
839 extent_end
= key
.offset
+
840 btrfs_file_extent_ram_bytes(leaf
, fi
);
847 * Don't skip extent items representing 0 byte lengths. They
848 * used to be created (bug) if while punching holes we hit
849 * -ENOSPC condition. So if we find one here, just ensure we
850 * delete it, otherwise we would insert a new file extent item
851 * with the same key (offset) as that 0 bytes length file
852 * extent item in the call to setup_items_for_insert() later
855 if (extent_end
== key
.offset
&& extent_end
>= search_start
) {
856 last_end
= extent_end
;
857 goto delete_extent_item
;
860 if (extent_end
<= search_start
) {
866 search_start
= max(key
.offset
, start
);
867 if (recow
|| !modify_tree
) {
869 btrfs_release_path(path
);
874 * | - range to drop - |
875 * | -------- extent -------- |
877 if (start
> key
.offset
&& end
< extent_end
) {
879 if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
884 memcpy(&new_key
, &key
, sizeof(new_key
));
885 new_key
.offset
= start
;
886 ret
= btrfs_duplicate_item(trans
, root
, path
,
888 if (ret
== -EAGAIN
) {
889 btrfs_release_path(path
);
895 leaf
= path
->nodes
[0];
896 fi
= btrfs_item_ptr(leaf
, path
->slots
[0] - 1,
897 struct btrfs_file_extent_item
);
898 btrfs_set_file_extent_num_bytes(leaf
, fi
,
901 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
902 struct btrfs_file_extent_item
);
904 extent_offset
+= start
- key
.offset
;
905 btrfs_set_file_extent_offset(leaf
, fi
, extent_offset
);
906 btrfs_set_file_extent_num_bytes(leaf
, fi
,
908 btrfs_mark_buffer_dirty(leaf
);
910 if (update_refs
&& disk_bytenr
> 0) {
911 btrfs_init_generic_ref(&ref
,
912 BTRFS_ADD_DELAYED_REF
,
913 disk_bytenr
, num_bytes
, 0);
914 btrfs_init_data_ref(&ref
,
915 root
->root_key
.objectid
,
917 start
- extent_offset
);
918 ret
= btrfs_inc_extent_ref(trans
, &ref
);
919 BUG_ON(ret
); /* -ENOMEM */
924 * From here on out we will have actually dropped something, so
925 * last_end can be updated.
927 last_end
= extent_end
;
930 * | ---- range to drop ----- |
931 * | -------- extent -------- |
933 if (start
<= key
.offset
&& end
< extent_end
) {
934 if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
939 memcpy(&new_key
, &key
, sizeof(new_key
));
940 new_key
.offset
= end
;
941 btrfs_set_item_key_safe(fs_info
, path
, &new_key
);
943 extent_offset
+= end
- key
.offset
;
944 btrfs_set_file_extent_offset(leaf
, fi
, extent_offset
);
945 btrfs_set_file_extent_num_bytes(leaf
, fi
,
947 btrfs_mark_buffer_dirty(leaf
);
948 if (update_refs
&& disk_bytenr
> 0)
949 inode_sub_bytes(inode
, end
- key
.offset
);
953 search_start
= extent_end
;
955 * | ---- range to drop ----- |
956 * | -------- extent -------- |
958 if (start
> key
.offset
&& end
>= extent_end
) {
960 if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
965 btrfs_set_file_extent_num_bytes(leaf
, fi
,
967 btrfs_mark_buffer_dirty(leaf
);
968 if (update_refs
&& disk_bytenr
> 0)
969 inode_sub_bytes(inode
, extent_end
- start
);
970 if (end
== extent_end
)
978 * | ---- range to drop ----- |
979 * | ------ extent ------ |
981 if (start
<= key
.offset
&& end
>= extent_end
) {
984 del_slot
= path
->slots
[0];
987 BUG_ON(del_slot
+ del_nr
!= path
->slots
[0]);
992 extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
993 inode_sub_bytes(inode
,
994 extent_end
- key
.offset
);
995 extent_end
= ALIGN(extent_end
,
996 fs_info
->sectorsize
);
997 } else if (update_refs
&& disk_bytenr
> 0) {
998 btrfs_init_generic_ref(&ref
,
999 BTRFS_DROP_DELAYED_REF
,
1000 disk_bytenr
, num_bytes
, 0);
1001 btrfs_init_data_ref(&ref
,
1002 root
->root_key
.objectid
,
1004 key
.offset
- extent_offset
);
1005 ret
= btrfs_free_extent(trans
, &ref
);
1006 BUG_ON(ret
); /* -ENOMEM */
1007 inode_sub_bytes(inode
,
1008 extent_end
- key
.offset
);
1011 if (end
== extent_end
)
1014 if (path
->slots
[0] + 1 < btrfs_header_nritems(leaf
)) {
1019 ret
= btrfs_del_items(trans
, root
, path
, del_slot
,
1022 btrfs_abort_transaction(trans
, ret
);
1029 btrfs_release_path(path
);
1036 if (!ret
&& del_nr
> 0) {
1038 * Set path->slots[0] to first slot, so that after the delete
1039 * if items are move off from our leaf to its immediate left or
1040 * right neighbor leafs, we end up with a correct and adjusted
1041 * path->slots[0] for our insertion (if replace_extent != 0).
1043 path
->slots
[0] = del_slot
;
1044 ret
= btrfs_del_items(trans
, root
, path
, del_slot
, del_nr
);
1046 btrfs_abort_transaction(trans
, ret
);
1049 leaf
= path
->nodes
[0];
1051 * If btrfs_del_items() was called, it might have deleted a leaf, in
1052 * which case it unlocked our path, so check path->locks[0] matches a
1055 if (!ret
&& replace_extent
&& leafs_visited
== 1 &&
1056 (path
->locks
[0] == BTRFS_WRITE_LOCK_BLOCKING
||
1057 path
->locks
[0] == BTRFS_WRITE_LOCK
) &&
1058 btrfs_leaf_free_space(leaf
) >=
1059 sizeof(struct btrfs_item
) + extent_item_size
) {
1062 key
.type
= BTRFS_EXTENT_DATA_KEY
;
1064 if (!del_nr
&& path
->slots
[0] < btrfs_header_nritems(leaf
)) {
1065 struct btrfs_key slot_key
;
1067 btrfs_item_key_to_cpu(leaf
, &slot_key
, path
->slots
[0]);
1068 if (btrfs_comp_cpu_keys(&key
, &slot_key
) > 0)
1071 setup_items_for_insert(root
, path
, &key
,
1074 sizeof(struct btrfs_item
) +
1075 extent_item_size
, 1);
1079 if (!replace_extent
|| !(*key_inserted
))
1080 btrfs_release_path(path
);
1082 *drop_end
= found
? min(end
, last_end
) : end
;
1086 int btrfs_drop_extents(struct btrfs_trans_handle
*trans
,
1087 struct btrfs_root
*root
, struct inode
*inode
, u64 start
,
1088 u64 end
, int drop_cache
)
1090 struct btrfs_path
*path
;
1093 path
= btrfs_alloc_path();
1096 ret
= __btrfs_drop_extents(trans
, root
, inode
, path
, start
, end
, NULL
,
1097 drop_cache
, 0, 0, NULL
);
1098 btrfs_free_path(path
);
1102 static int extent_mergeable(struct extent_buffer
*leaf
, int slot
,
1103 u64 objectid
, u64 bytenr
, u64 orig_offset
,
1104 u64
*start
, u64
*end
)
1106 struct btrfs_file_extent_item
*fi
;
1107 struct btrfs_key key
;
1110 if (slot
< 0 || slot
>= btrfs_header_nritems(leaf
))
1113 btrfs_item_key_to_cpu(leaf
, &key
, slot
);
1114 if (key
.objectid
!= objectid
|| key
.type
!= BTRFS_EXTENT_DATA_KEY
)
1117 fi
= btrfs_item_ptr(leaf
, slot
, struct btrfs_file_extent_item
);
1118 if (btrfs_file_extent_type(leaf
, fi
) != BTRFS_FILE_EXTENT_REG
||
1119 btrfs_file_extent_disk_bytenr(leaf
, fi
) != bytenr
||
1120 btrfs_file_extent_offset(leaf
, fi
) != key
.offset
- orig_offset
||
1121 btrfs_file_extent_compression(leaf
, fi
) ||
1122 btrfs_file_extent_encryption(leaf
, fi
) ||
1123 btrfs_file_extent_other_encoding(leaf
, fi
))
1126 extent_end
= key
.offset
+ btrfs_file_extent_num_bytes(leaf
, fi
);
1127 if ((*start
&& *start
!= key
.offset
) || (*end
&& *end
!= extent_end
))
1130 *start
= key
.offset
;
1136 * Mark extent in the range start - end as written.
1138 * This changes extent type from 'pre-allocated' to 'regular'. If only
1139 * part of extent is marked as written, the extent will be split into
1142 int btrfs_mark_extent_written(struct btrfs_trans_handle
*trans
,
1143 struct btrfs_inode
*inode
, u64 start
, u64 end
)
1145 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
1146 struct btrfs_root
*root
= inode
->root
;
1147 struct extent_buffer
*leaf
;
1148 struct btrfs_path
*path
;
1149 struct btrfs_file_extent_item
*fi
;
1150 struct btrfs_ref ref
= { 0 };
1151 struct btrfs_key key
;
1152 struct btrfs_key new_key
;
1164 u64 ino
= btrfs_ino(inode
);
1166 path
= btrfs_alloc_path();
1173 key
.type
= BTRFS_EXTENT_DATA_KEY
;
1176 ret
= btrfs_search_slot(trans
, root
, &key
, path
, -1, 1);
1179 if (ret
> 0 && path
->slots
[0] > 0)
1182 leaf
= path
->nodes
[0];
1183 btrfs_item_key_to_cpu(leaf
, &key
, path
->slots
[0]);
1184 if (key
.objectid
!= ino
||
1185 key
.type
!= BTRFS_EXTENT_DATA_KEY
) {
1187 btrfs_abort_transaction(trans
, ret
);
1190 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
1191 struct btrfs_file_extent_item
);
1192 if (btrfs_file_extent_type(leaf
, fi
) != BTRFS_FILE_EXTENT_PREALLOC
) {
1194 btrfs_abort_transaction(trans
, ret
);
1197 extent_end
= key
.offset
+ btrfs_file_extent_num_bytes(leaf
, fi
);
1198 if (key
.offset
> start
|| extent_end
< end
) {
1200 btrfs_abort_transaction(trans
, ret
);
1204 bytenr
= btrfs_file_extent_disk_bytenr(leaf
, fi
);
1205 num_bytes
= btrfs_file_extent_disk_num_bytes(leaf
, fi
);
1206 orig_offset
= key
.offset
- btrfs_file_extent_offset(leaf
, fi
);
1207 memcpy(&new_key
, &key
, sizeof(new_key
));
1209 if (start
== key
.offset
&& end
< extent_end
) {
1212 if (extent_mergeable(leaf
, path
->slots
[0] - 1,
1213 ino
, bytenr
, orig_offset
,
1214 &other_start
, &other_end
)) {
1215 new_key
.offset
= end
;
1216 btrfs_set_item_key_safe(fs_info
, path
, &new_key
);
1217 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
1218 struct btrfs_file_extent_item
);
1219 btrfs_set_file_extent_generation(leaf
, fi
,
1221 btrfs_set_file_extent_num_bytes(leaf
, fi
,
1223 btrfs_set_file_extent_offset(leaf
, fi
,
1225 fi
= btrfs_item_ptr(leaf
, path
->slots
[0] - 1,
1226 struct btrfs_file_extent_item
);
1227 btrfs_set_file_extent_generation(leaf
, fi
,
1229 btrfs_set_file_extent_num_bytes(leaf
, fi
,
1231 btrfs_mark_buffer_dirty(leaf
);
1236 if (start
> key
.offset
&& end
== extent_end
) {
1239 if (extent_mergeable(leaf
, path
->slots
[0] + 1,
1240 ino
, bytenr
, orig_offset
,
1241 &other_start
, &other_end
)) {
1242 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
1243 struct btrfs_file_extent_item
);
1244 btrfs_set_file_extent_num_bytes(leaf
, fi
,
1245 start
- key
.offset
);
1246 btrfs_set_file_extent_generation(leaf
, fi
,
1249 new_key
.offset
= start
;
1250 btrfs_set_item_key_safe(fs_info
, path
, &new_key
);
1252 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
1253 struct btrfs_file_extent_item
);
1254 btrfs_set_file_extent_generation(leaf
, fi
,
1256 btrfs_set_file_extent_num_bytes(leaf
, fi
,
1258 btrfs_set_file_extent_offset(leaf
, fi
,
1259 start
- orig_offset
);
1260 btrfs_mark_buffer_dirty(leaf
);
1265 while (start
> key
.offset
|| end
< extent_end
) {
1266 if (key
.offset
== start
)
1269 new_key
.offset
= split
;
1270 ret
= btrfs_duplicate_item(trans
, root
, path
, &new_key
);
1271 if (ret
== -EAGAIN
) {
1272 btrfs_release_path(path
);
1276 btrfs_abort_transaction(trans
, ret
);
1280 leaf
= path
->nodes
[0];
1281 fi
= btrfs_item_ptr(leaf
, path
->slots
[0] - 1,
1282 struct btrfs_file_extent_item
);
1283 btrfs_set_file_extent_generation(leaf
, fi
, trans
->transid
);
1284 btrfs_set_file_extent_num_bytes(leaf
, fi
,
1285 split
- key
.offset
);
1287 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
1288 struct btrfs_file_extent_item
);
1290 btrfs_set_file_extent_generation(leaf
, fi
, trans
->transid
);
1291 btrfs_set_file_extent_offset(leaf
, fi
, split
- orig_offset
);
1292 btrfs_set_file_extent_num_bytes(leaf
, fi
,
1293 extent_end
- split
);
1294 btrfs_mark_buffer_dirty(leaf
);
1296 btrfs_init_generic_ref(&ref
, BTRFS_ADD_DELAYED_REF
, bytenr
,
1298 btrfs_init_data_ref(&ref
, root
->root_key
.objectid
, ino
,
1300 ret
= btrfs_inc_extent_ref(trans
, &ref
);
1302 btrfs_abort_transaction(trans
, ret
);
1306 if (split
== start
) {
1309 if (start
!= key
.offset
) {
1311 btrfs_abort_transaction(trans
, ret
);
1322 btrfs_init_generic_ref(&ref
, BTRFS_DROP_DELAYED_REF
, bytenr
,
1324 btrfs_init_data_ref(&ref
, root
->root_key
.objectid
, ino
, orig_offset
);
1325 if (extent_mergeable(leaf
, path
->slots
[0] + 1,
1326 ino
, bytenr
, orig_offset
,
1327 &other_start
, &other_end
)) {
1329 btrfs_release_path(path
);
1332 extent_end
= other_end
;
1333 del_slot
= path
->slots
[0] + 1;
1335 ret
= btrfs_free_extent(trans
, &ref
);
1337 btrfs_abort_transaction(trans
, ret
);
1343 if (extent_mergeable(leaf
, path
->slots
[0] - 1,
1344 ino
, bytenr
, orig_offset
,
1345 &other_start
, &other_end
)) {
1347 btrfs_release_path(path
);
1350 key
.offset
= other_start
;
1351 del_slot
= path
->slots
[0];
1353 ret
= btrfs_free_extent(trans
, &ref
);
1355 btrfs_abort_transaction(trans
, ret
);
1360 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
1361 struct btrfs_file_extent_item
);
1362 btrfs_set_file_extent_type(leaf
, fi
,
1363 BTRFS_FILE_EXTENT_REG
);
1364 btrfs_set_file_extent_generation(leaf
, fi
, trans
->transid
);
1365 btrfs_mark_buffer_dirty(leaf
);
1367 fi
= btrfs_item_ptr(leaf
, del_slot
- 1,
1368 struct btrfs_file_extent_item
);
1369 btrfs_set_file_extent_type(leaf
, fi
,
1370 BTRFS_FILE_EXTENT_REG
);
1371 btrfs_set_file_extent_generation(leaf
, fi
, trans
->transid
);
1372 btrfs_set_file_extent_num_bytes(leaf
, fi
,
1373 extent_end
- key
.offset
);
1374 btrfs_mark_buffer_dirty(leaf
);
1376 ret
= btrfs_del_items(trans
, root
, path
, del_slot
, del_nr
);
1378 btrfs_abort_transaction(trans
, ret
);
1383 btrfs_free_path(path
);
1388 * on error we return an unlocked page and the error value
1389 * on success we return a locked page and 0
1391 static int prepare_uptodate_page(struct inode
*inode
,
1392 struct page
*page
, u64 pos
,
1393 bool force_uptodate
)
1397 if (((pos
& (PAGE_SIZE
- 1)) || force_uptodate
) &&
1398 !PageUptodate(page
)) {
1399 ret
= btrfs_readpage(NULL
, page
);
1403 if (!PageUptodate(page
)) {
1407 if (page
->mapping
!= inode
->i_mapping
) {
1416 * this just gets pages into the page cache and locks them down.
1418 static noinline
int prepare_pages(struct inode
*inode
, struct page
**pages
,
1419 size_t num_pages
, loff_t pos
,
1420 size_t write_bytes
, bool force_uptodate
)
1423 unsigned long index
= pos
>> PAGE_SHIFT
;
1424 gfp_t mask
= btrfs_alloc_write_mask(inode
->i_mapping
);
1428 for (i
= 0; i
< num_pages
; i
++) {
1430 pages
[i
] = find_or_create_page(inode
->i_mapping
, index
+ i
,
1431 mask
| __GFP_WRITE
);
1439 err
= prepare_uptodate_page(inode
, pages
[i
], pos
,
1441 if (!err
&& i
== num_pages
- 1)
1442 err
= prepare_uptodate_page(inode
, pages
[i
],
1443 pos
+ write_bytes
, false);
1446 if (err
== -EAGAIN
) {
1453 wait_on_page_writeback(pages
[i
]);
1458 while (faili
>= 0) {
1459 unlock_page(pages
[faili
]);
1460 put_page(pages
[faili
]);
1468 * This function locks the extent and properly waits for data=ordered extents
1469 * to finish before allowing the pages to be modified if need.
1472 * 1 - the extent is locked
1473 * 0 - the extent is not locked, and everything is OK
1474 * -EAGAIN - need re-prepare the pages
1475 * the other < 0 number - Something wrong happens
1478 lock_and_cleanup_extent_if_need(struct btrfs_inode
*inode
, struct page
**pages
,
1479 size_t num_pages
, loff_t pos
,
1481 u64
*lockstart
, u64
*lockend
,
1482 struct extent_state
**cached_state
)
1484 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
1490 start_pos
= round_down(pos
, fs_info
->sectorsize
);
1491 last_pos
= start_pos
1492 + round_up(pos
+ write_bytes
- start_pos
,
1493 fs_info
->sectorsize
) - 1;
1495 if (start_pos
< inode
->vfs_inode
.i_size
) {
1496 struct btrfs_ordered_extent
*ordered
;
1498 lock_extent_bits(&inode
->io_tree
, start_pos
, last_pos
,
1500 ordered
= btrfs_lookup_ordered_range(inode
, start_pos
,
1501 last_pos
- start_pos
+ 1);
1503 ordered
->file_offset
+ ordered
->num_bytes
> start_pos
&&
1504 ordered
->file_offset
<= last_pos
) {
1505 unlock_extent_cached(&inode
->io_tree
, start_pos
,
1506 last_pos
, cached_state
);
1507 for (i
= 0; i
< num_pages
; i
++) {
1508 unlock_page(pages
[i
]);
1511 btrfs_start_ordered_extent(&inode
->vfs_inode
,
1513 btrfs_put_ordered_extent(ordered
);
1517 btrfs_put_ordered_extent(ordered
);
1519 *lockstart
= start_pos
;
1520 *lockend
= last_pos
;
1525 * It's possible the pages are dirty right now, but we don't want
1526 * to clean them yet because copy_from_user may catch a page fault
1527 * and we might have to fall back to one page at a time. If that
1528 * happens, we'll unlock these pages and we'd have a window where
1529 * reclaim could sneak in and drop the once-dirty page on the floor
1530 * without writing it.
1532 * We have the pages locked and the extent range locked, so there's
1533 * no way someone can start IO on any dirty pages in this range.
1535 * We'll call btrfs_dirty_pages() later on, and that will flip around
1536 * delalloc bits and dirty the pages as required.
1538 for (i
= 0; i
< num_pages
; i
++) {
1539 set_page_extent_mapped(pages
[i
]);
1540 WARN_ON(!PageLocked(pages
[i
]));
1546 static noinline
int check_can_nocow(struct btrfs_inode
*inode
, loff_t pos
,
1547 size_t *write_bytes
)
1549 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
1550 struct btrfs_root
*root
= inode
->root
;
1551 u64 lockstart
, lockend
;
1555 ret
= btrfs_start_write_no_snapshotting(root
);
1559 lockstart
= round_down(pos
, fs_info
->sectorsize
);
1560 lockend
= round_up(pos
+ *write_bytes
,
1561 fs_info
->sectorsize
) - 1;
1563 btrfs_lock_and_flush_ordered_range(&inode
->io_tree
, inode
, lockstart
,
1566 num_bytes
= lockend
- lockstart
+ 1;
1567 ret
= can_nocow_extent(&inode
->vfs_inode
, lockstart
, &num_bytes
,
1571 btrfs_end_write_no_snapshotting(root
);
1573 *write_bytes
= min_t(size_t, *write_bytes
,
1574 num_bytes
- pos
+ lockstart
);
1577 unlock_extent(&inode
->io_tree
, lockstart
, lockend
);
1582 static noinline ssize_t
btrfs_buffered_write(struct kiocb
*iocb
,
1585 struct file
*file
= iocb
->ki_filp
;
1586 loff_t pos
= iocb
->ki_pos
;
1587 struct inode
*inode
= file_inode(file
);
1588 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
1589 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
1590 struct page
**pages
= NULL
;
1591 struct extent_changeset
*data_reserved
= NULL
;
1592 u64 release_bytes
= 0;
1595 size_t num_written
= 0;
1598 bool only_release_metadata
= false;
1599 bool force_page_uptodate
= false;
1601 nrptrs
= min(DIV_ROUND_UP(iov_iter_count(i
), PAGE_SIZE
),
1602 PAGE_SIZE
/ (sizeof(struct page
*)));
1603 nrptrs
= min(nrptrs
, current
->nr_dirtied_pause
- current
->nr_dirtied
);
1604 nrptrs
= max(nrptrs
, 8);
1605 pages
= kmalloc_array(nrptrs
, sizeof(struct page
*), GFP_KERNEL
);
1609 while (iov_iter_count(i
) > 0) {
1610 struct extent_state
*cached_state
= NULL
;
1611 size_t offset
= offset_in_page(pos
);
1612 size_t sector_offset
;
1613 size_t write_bytes
= min(iov_iter_count(i
),
1614 nrptrs
* (size_t)PAGE_SIZE
-
1616 size_t num_pages
= DIV_ROUND_UP(write_bytes
+ offset
,
1618 size_t reserve_bytes
;
1621 size_t dirty_sectors
;
1625 WARN_ON(num_pages
> nrptrs
);
1628 * Fault pages before locking them in prepare_pages
1629 * to avoid recursive lock
1631 if (unlikely(iov_iter_fault_in_readable(i
, write_bytes
))) {
1636 only_release_metadata
= false;
1637 sector_offset
= pos
& (fs_info
->sectorsize
- 1);
1638 reserve_bytes
= round_up(write_bytes
+ sector_offset
,
1639 fs_info
->sectorsize
);
1641 extent_changeset_release(data_reserved
);
1642 ret
= btrfs_check_data_free_space(inode
, &data_reserved
, pos
,
1645 if ((BTRFS_I(inode
)->flags
& (BTRFS_INODE_NODATACOW
|
1646 BTRFS_INODE_PREALLOC
)) &&
1647 check_can_nocow(BTRFS_I(inode
), pos
,
1648 &write_bytes
) > 0) {
1650 * For nodata cow case, no need to reserve
1653 only_release_metadata
= true;
1655 * our prealloc extent may be smaller than
1656 * write_bytes, so scale down.
1658 num_pages
= DIV_ROUND_UP(write_bytes
+ offset
,
1660 reserve_bytes
= round_up(write_bytes
+
1662 fs_info
->sectorsize
);
1668 WARN_ON(reserve_bytes
== 0);
1669 ret
= btrfs_delalloc_reserve_metadata(BTRFS_I(inode
),
1672 if (!only_release_metadata
)
1673 btrfs_free_reserved_data_space(inode
,
1677 btrfs_end_write_no_snapshotting(root
);
1681 release_bytes
= reserve_bytes
;
1684 * This is going to setup the pages array with the number of
1685 * pages we want, so we don't really need to worry about the
1686 * contents of pages from loop to loop
1688 ret
= prepare_pages(inode
, pages
, num_pages
,
1690 force_page_uptodate
);
1692 btrfs_delalloc_release_extents(BTRFS_I(inode
),
1697 extents_locked
= lock_and_cleanup_extent_if_need(
1698 BTRFS_I(inode
), pages
,
1699 num_pages
, pos
, write_bytes
, &lockstart
,
1700 &lockend
, &cached_state
);
1701 if (extents_locked
< 0) {
1702 if (extents_locked
== -EAGAIN
)
1704 btrfs_delalloc_release_extents(BTRFS_I(inode
),
1706 ret
= extents_locked
;
1710 copied
= btrfs_copy_from_user(pos
, write_bytes
, pages
, i
);
1712 num_sectors
= BTRFS_BYTES_TO_BLKS(fs_info
, reserve_bytes
);
1713 dirty_sectors
= round_up(copied
+ sector_offset
,
1714 fs_info
->sectorsize
);
1715 dirty_sectors
= BTRFS_BYTES_TO_BLKS(fs_info
, dirty_sectors
);
1718 * if we have trouble faulting in the pages, fall
1719 * back to one page at a time
1721 if (copied
< write_bytes
)
1725 force_page_uptodate
= true;
1729 force_page_uptodate
= false;
1730 dirty_pages
= DIV_ROUND_UP(copied
+ offset
,
1734 if (num_sectors
> dirty_sectors
) {
1735 /* release everything except the sectors we dirtied */
1736 release_bytes
-= dirty_sectors
<<
1737 fs_info
->sb
->s_blocksize_bits
;
1738 if (only_release_metadata
) {
1739 btrfs_delalloc_release_metadata(BTRFS_I(inode
),
1740 release_bytes
, true);
1744 __pos
= round_down(pos
,
1745 fs_info
->sectorsize
) +
1746 (dirty_pages
<< PAGE_SHIFT
);
1747 btrfs_delalloc_release_space(inode
,
1748 data_reserved
, __pos
,
1749 release_bytes
, true);
1753 release_bytes
= round_up(copied
+ sector_offset
,
1754 fs_info
->sectorsize
);
1757 ret
= btrfs_dirty_pages(inode
, pages
, dirty_pages
,
1758 pos
, copied
, &cached_state
);
1761 * If we have not locked the extent range, because the range's
1762 * start offset is >= i_size, we might still have a non-NULL
1763 * cached extent state, acquired while marking the extent range
1764 * as delalloc through btrfs_dirty_pages(). Therefore free any
1765 * possible cached extent state to avoid a memory leak.
1768 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
,
1769 lockstart
, lockend
, &cached_state
);
1771 free_extent_state(cached_state
);
1773 btrfs_delalloc_release_extents(BTRFS_I(inode
), reserve_bytes
);
1775 btrfs_drop_pages(pages
, num_pages
);
1780 if (only_release_metadata
)
1781 btrfs_end_write_no_snapshotting(root
);
1783 if (only_release_metadata
&& copied
> 0) {
1784 lockstart
= round_down(pos
,
1785 fs_info
->sectorsize
);
1786 lockend
= round_up(pos
+ copied
,
1787 fs_info
->sectorsize
) - 1;
1789 set_extent_bit(&BTRFS_I(inode
)->io_tree
, lockstart
,
1790 lockend
, EXTENT_NORESERVE
, NULL
,
1794 btrfs_drop_pages(pages
, num_pages
);
1798 balance_dirty_pages_ratelimited(inode
->i_mapping
);
1799 if (dirty_pages
< (fs_info
->nodesize
>> PAGE_SHIFT
) + 1)
1800 btrfs_btree_balance_dirty(fs_info
);
1803 num_written
+= copied
;
1808 if (release_bytes
) {
1809 if (only_release_metadata
) {
1810 btrfs_end_write_no_snapshotting(root
);
1811 btrfs_delalloc_release_metadata(BTRFS_I(inode
),
1812 release_bytes
, true);
1814 btrfs_delalloc_release_space(inode
, data_reserved
,
1815 round_down(pos
, fs_info
->sectorsize
),
1816 release_bytes
, true);
1820 extent_changeset_free(data_reserved
);
1821 return num_written
? num_written
: ret
;
1824 static ssize_t
__btrfs_direct_write(struct kiocb
*iocb
, struct iov_iter
*from
)
1826 struct file
*file
= iocb
->ki_filp
;
1827 struct inode
*inode
= file_inode(file
);
1830 ssize_t written_buffered
;
1834 written
= generic_file_direct_write(iocb
, from
);
1836 if (written
< 0 || !iov_iter_count(from
))
1840 written_buffered
= btrfs_buffered_write(iocb
, from
);
1841 if (written_buffered
< 0) {
1842 err
= written_buffered
;
1846 * Ensure all data is persisted. We want the next direct IO read to be
1847 * able to read what was just written.
1849 endbyte
= pos
+ written_buffered
- 1;
1850 err
= btrfs_fdatawrite_range(inode
, pos
, endbyte
);
1853 err
= filemap_fdatawait_range(inode
->i_mapping
, pos
, endbyte
);
1856 written
+= written_buffered
;
1857 iocb
->ki_pos
= pos
+ written_buffered
;
1858 invalidate_mapping_pages(file
->f_mapping
, pos
>> PAGE_SHIFT
,
1859 endbyte
>> PAGE_SHIFT
);
1861 return written
? written
: err
;
1864 static void update_time_for_write(struct inode
*inode
)
1866 struct timespec64 now
;
1868 if (IS_NOCMTIME(inode
))
1871 now
= current_time(inode
);
1872 if (!timespec64_equal(&inode
->i_mtime
, &now
))
1873 inode
->i_mtime
= now
;
1875 if (!timespec64_equal(&inode
->i_ctime
, &now
))
1876 inode
->i_ctime
= now
;
1878 if (IS_I_VERSION(inode
))
1879 inode_inc_iversion(inode
);
1882 static ssize_t
btrfs_file_write_iter(struct kiocb
*iocb
,
1883 struct iov_iter
*from
)
1885 struct file
*file
= iocb
->ki_filp
;
1886 struct inode
*inode
= file_inode(file
);
1887 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
1888 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
1891 ssize_t num_written
= 0;
1892 const bool sync
= iocb
->ki_flags
& IOCB_DSYNC
;
1899 if (!(iocb
->ki_flags
& IOCB_DIRECT
) &&
1900 (iocb
->ki_flags
& IOCB_NOWAIT
))
1903 if (iocb
->ki_flags
& IOCB_NOWAIT
) {
1904 if (!inode_trylock(inode
))
1910 err
= generic_write_checks(iocb
, from
);
1912 inode_unlock(inode
);
1917 count
= iov_iter_count(from
);
1918 if (iocb
->ki_flags
& IOCB_NOWAIT
) {
1920 * We will allocate space in case nodatacow is not set,
1923 if (!(BTRFS_I(inode
)->flags
& (BTRFS_INODE_NODATACOW
|
1924 BTRFS_INODE_PREALLOC
)) ||
1925 check_can_nocow(BTRFS_I(inode
), pos
, &count
) <= 0) {
1926 inode_unlock(inode
);
1931 current
->backing_dev_info
= inode_to_bdi(inode
);
1932 err
= file_remove_privs(file
);
1934 inode_unlock(inode
);
1939 * If BTRFS flips readonly due to some impossible error
1940 * (fs_info->fs_state now has BTRFS_SUPER_FLAG_ERROR),
1941 * although we have opened a file as writable, we have
1942 * to stop this write operation to ensure FS consistency.
1944 if (test_bit(BTRFS_FS_STATE_ERROR
, &fs_info
->fs_state
)) {
1945 inode_unlock(inode
);
1951 * We reserve space for updating the inode when we reserve space for the
1952 * extent we are going to write, so we will enospc out there. We don't
1953 * need to start yet another transaction to update the inode as we will
1954 * update the inode when we finish writing whatever data we write.
1956 update_time_for_write(inode
);
1958 start_pos
= round_down(pos
, fs_info
->sectorsize
);
1959 oldsize
= i_size_read(inode
);
1960 if (start_pos
> oldsize
) {
1961 /* Expand hole size to cover write data, preventing empty gap */
1962 end_pos
= round_up(pos
+ count
,
1963 fs_info
->sectorsize
);
1964 err
= btrfs_cont_expand(inode
, oldsize
, end_pos
);
1966 inode_unlock(inode
);
1969 if (start_pos
> round_up(oldsize
, fs_info
->sectorsize
))
1974 atomic_inc(&BTRFS_I(inode
)->sync_writers
);
1976 if (iocb
->ki_flags
& IOCB_DIRECT
) {
1977 num_written
= __btrfs_direct_write(iocb
, from
);
1979 num_written
= btrfs_buffered_write(iocb
, from
);
1980 if (num_written
> 0)
1981 iocb
->ki_pos
= pos
+ num_written
;
1983 pagecache_isize_extended(inode
, oldsize
,
1984 i_size_read(inode
));
1987 inode_unlock(inode
);
1990 * We also have to set last_sub_trans to the current log transid,
1991 * otherwise subsequent syncs to a file that's been synced in this
1992 * transaction will appear to have already occurred.
1994 spin_lock(&BTRFS_I(inode
)->lock
);
1995 BTRFS_I(inode
)->last_sub_trans
= root
->log_transid
;
1996 spin_unlock(&BTRFS_I(inode
)->lock
);
1997 if (num_written
> 0)
1998 num_written
= generic_write_sync(iocb
, num_written
);
2001 atomic_dec(&BTRFS_I(inode
)->sync_writers
);
2003 current
->backing_dev_info
= NULL
;
2004 return num_written
? num_written
: err
;
2007 int btrfs_release_file(struct inode
*inode
, struct file
*filp
)
2009 struct btrfs_file_private
*private = filp
->private_data
;
2011 if (private && private->filldir_buf
)
2012 kfree(private->filldir_buf
);
2014 filp
->private_data
= NULL
;
2017 * ordered_data_close is set by setattr when we are about to truncate
2018 * a file from a non-zero size to a zero size. This tries to
2019 * flush down new bytes that may have been written if the
2020 * application were using truncate to replace a file in place.
2022 if (test_and_clear_bit(BTRFS_INODE_ORDERED_DATA_CLOSE
,
2023 &BTRFS_I(inode
)->runtime_flags
))
2024 filemap_flush(inode
->i_mapping
);
2028 static int start_ordered_ops(struct inode
*inode
, loff_t start
, loff_t end
)
2031 struct blk_plug plug
;
2034 * This is only called in fsync, which would do synchronous writes, so
2035 * a plug can merge adjacent IOs as much as possible. Esp. in case of
2036 * multiple disks using raid profile, a large IO can be split to
2037 * several segments of stripe length (currently 64K).
2039 blk_start_plug(&plug
);
2040 atomic_inc(&BTRFS_I(inode
)->sync_writers
);
2041 ret
= btrfs_fdatawrite_range(inode
, start
, end
);
2042 atomic_dec(&BTRFS_I(inode
)->sync_writers
);
2043 blk_finish_plug(&plug
);
2049 * fsync call for both files and directories. This logs the inode into
2050 * the tree log instead of forcing full commits whenever possible.
2052 * It needs to call filemap_fdatawait so that all ordered extent updates are
2053 * in the metadata btree are up to date for copying to the log.
2055 * It drops the inode mutex before doing the tree log commit. This is an
2056 * important optimization for directories because holding the mutex prevents
2057 * new operations on the dir while we write to disk.
2059 int btrfs_sync_file(struct file
*file
, loff_t start
, loff_t end
, int datasync
)
2061 struct dentry
*dentry
= file_dentry(file
);
2062 struct inode
*inode
= d_inode(dentry
);
2063 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2064 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
2065 struct btrfs_trans_handle
*trans
;
2066 struct btrfs_log_ctx ctx
;
2069 trace_btrfs_sync_file(file
, datasync
);
2071 btrfs_init_log_ctx(&ctx
, inode
);
2074 * We write the dirty pages in the range and wait until they complete
2075 * out of the ->i_mutex. If so, we can flush the dirty pages by
2076 * multi-task, and make the performance up. See
2077 * btrfs_wait_ordered_range for an explanation of the ASYNC check.
2079 ret
= start_ordered_ops(inode
, start
, end
);
2086 * We take the dio_sem here because the tree log stuff can race with
2087 * lockless dio writes and get an extent map logged for an extent we
2088 * never waited on. We need it this high up for lockdep reasons.
2090 down_write(&BTRFS_I(inode
)->dio_sem
);
2092 atomic_inc(&root
->log_batch
);
2095 * If the inode needs a full sync, make sure we use a full range to
2096 * avoid log tree corruption, due to hole detection racing with ordered
2097 * extent completion for adjacent ranges, and assertion failures during
2098 * hole detection. Do this while holding the inode lock, to avoid races
2101 if (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC
,
2102 &BTRFS_I(inode
)->runtime_flags
)) {
2108 * Before we acquired the inode's lock, someone may have dirtied more
2109 * pages in the target range. We need to make sure that writeback for
2110 * any such pages does not start while we are logging the inode, because
2111 * if it does, any of the following might happen when we are not doing a
2114 * 1) We log an extent after its writeback finishes but before its
2115 * checksums are added to the csum tree, leading to -EIO errors
2116 * when attempting to read the extent after a log replay.
2118 * 2) We can end up logging an extent before its writeback finishes.
2119 * Therefore after the log replay we will have a file extent item
2120 * pointing to an unwritten extent (and no data checksums as well).
2122 * So trigger writeback for any eventual new dirty pages and then we
2123 * wait for all ordered extents to complete below.
2125 ret
= start_ordered_ops(inode
, start
, end
);
2127 inode_unlock(inode
);
2132 * We have to do this here to avoid the priority inversion of waiting on
2133 * IO of a lower priority task while holding a transaction open.
2135 * Also, the range length can be represented by u64, we have to do the
2136 * typecasts to avoid signed overflow if it's [0, LLONG_MAX].
2138 ret
= btrfs_wait_ordered_range(inode
, start
, (u64
)end
- (u64
)start
+ 1);
2140 up_write(&BTRFS_I(inode
)->dio_sem
);
2141 inode_unlock(inode
);
2144 atomic_inc(&root
->log_batch
);
2147 if (btrfs_inode_in_log(BTRFS_I(inode
), fs_info
->generation
) ||
2148 BTRFS_I(inode
)->last_trans
<= fs_info
->last_trans_committed
) {
2150 * We've had everything committed since the last time we were
2151 * modified so clear this flag in case it was set for whatever
2152 * reason, it's no longer relevant.
2154 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC
,
2155 &BTRFS_I(inode
)->runtime_flags
);
2157 * An ordered extent might have started before and completed
2158 * already with io errors, in which case the inode was not
2159 * updated and we end up here. So check the inode's mapping
2160 * for any errors that might have happened since we last
2161 * checked called fsync.
2163 ret
= filemap_check_wb_err(inode
->i_mapping
, file
->f_wb_err
);
2164 up_write(&BTRFS_I(inode
)->dio_sem
);
2165 inode_unlock(inode
);
2170 * We use start here because we will need to wait on the IO to complete
2171 * in btrfs_sync_log, which could require joining a transaction (for
2172 * example checking cross references in the nocow path). If we use join
2173 * here we could get into a situation where we're waiting on IO to
2174 * happen that is blocked on a transaction trying to commit. With start
2175 * we inc the extwriter counter, so we wait for all extwriters to exit
2176 * before we start blocking joiners. This comment is to keep somebody
2177 * from thinking they are super smart and changing this to
2178 * btrfs_join_transaction *cough*Josef*cough*.
2180 trans
= btrfs_start_transaction(root
, 0);
2181 if (IS_ERR(trans
)) {
2182 ret
= PTR_ERR(trans
);
2183 up_write(&BTRFS_I(inode
)->dio_sem
);
2184 inode_unlock(inode
);
2188 ret
= btrfs_log_dentry_safe(trans
, dentry
, start
, end
, &ctx
);
2190 /* Fallthrough and commit/free transaction. */
2194 /* we've logged all the items and now have a consistent
2195 * version of the file in the log. It is possible that
2196 * someone will come in and modify the file, but that's
2197 * fine because the log is consistent on disk, and we
2198 * have references to all of the file's extents
2200 * It is possible that someone will come in and log the
2201 * file again, but that will end up using the synchronization
2202 * inside btrfs_sync_log to keep things safe.
2204 up_write(&BTRFS_I(inode
)->dio_sem
);
2205 inode_unlock(inode
);
2207 if (ret
!= BTRFS_NO_LOG_SYNC
) {
2209 ret
= btrfs_sync_log(trans
, root
, &ctx
);
2211 ret
= btrfs_end_transaction(trans
);
2215 ret
= btrfs_commit_transaction(trans
);
2217 ret
= btrfs_end_transaction(trans
);
2220 ASSERT(list_empty(&ctx
.list
));
2221 err
= file_check_and_advance_wb_err(file
);
2224 return ret
> 0 ? -EIO
: ret
;
2227 static const struct vm_operations_struct btrfs_file_vm_ops
= {
2228 .fault
= filemap_fault
,
2229 .map_pages
= filemap_map_pages
,
2230 .page_mkwrite
= btrfs_page_mkwrite
,
2233 static int btrfs_file_mmap(struct file
*filp
, struct vm_area_struct
*vma
)
2235 struct address_space
*mapping
= filp
->f_mapping
;
2237 if (!mapping
->a_ops
->readpage
)
2240 file_accessed(filp
);
2241 vma
->vm_ops
= &btrfs_file_vm_ops
;
2246 static int hole_mergeable(struct btrfs_inode
*inode
, struct extent_buffer
*leaf
,
2247 int slot
, u64 start
, u64 end
)
2249 struct btrfs_file_extent_item
*fi
;
2250 struct btrfs_key key
;
2252 if (slot
< 0 || slot
>= btrfs_header_nritems(leaf
))
2255 btrfs_item_key_to_cpu(leaf
, &key
, slot
);
2256 if (key
.objectid
!= btrfs_ino(inode
) ||
2257 key
.type
!= BTRFS_EXTENT_DATA_KEY
)
2260 fi
= btrfs_item_ptr(leaf
, slot
, struct btrfs_file_extent_item
);
2262 if (btrfs_file_extent_type(leaf
, fi
) != BTRFS_FILE_EXTENT_REG
)
2265 if (btrfs_file_extent_disk_bytenr(leaf
, fi
))
2268 if (key
.offset
== end
)
2270 if (key
.offset
+ btrfs_file_extent_num_bytes(leaf
, fi
) == start
)
2275 static int fill_holes(struct btrfs_trans_handle
*trans
,
2276 struct btrfs_inode
*inode
,
2277 struct btrfs_path
*path
, u64 offset
, u64 end
)
2279 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
2280 struct btrfs_root
*root
= inode
->root
;
2281 struct extent_buffer
*leaf
;
2282 struct btrfs_file_extent_item
*fi
;
2283 struct extent_map
*hole_em
;
2284 struct extent_map_tree
*em_tree
= &inode
->extent_tree
;
2285 struct btrfs_key key
;
2288 if (btrfs_fs_incompat(fs_info
, NO_HOLES
))
2291 key
.objectid
= btrfs_ino(inode
);
2292 key
.type
= BTRFS_EXTENT_DATA_KEY
;
2293 key
.offset
= offset
;
2295 ret
= btrfs_search_slot(trans
, root
, &key
, path
, 0, 1);
2298 * We should have dropped this offset, so if we find it then
2299 * something has gone horribly wrong.
2306 leaf
= path
->nodes
[0];
2307 if (hole_mergeable(inode
, leaf
, path
->slots
[0] - 1, offset
, end
)) {
2311 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
2312 struct btrfs_file_extent_item
);
2313 num_bytes
= btrfs_file_extent_num_bytes(leaf
, fi
) +
2315 btrfs_set_file_extent_num_bytes(leaf
, fi
, num_bytes
);
2316 btrfs_set_file_extent_ram_bytes(leaf
, fi
, num_bytes
);
2317 btrfs_set_file_extent_offset(leaf
, fi
, 0);
2318 btrfs_mark_buffer_dirty(leaf
);
2322 if (hole_mergeable(inode
, leaf
, path
->slots
[0], offset
, end
)) {
2325 key
.offset
= offset
;
2326 btrfs_set_item_key_safe(fs_info
, path
, &key
);
2327 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
2328 struct btrfs_file_extent_item
);
2329 num_bytes
= btrfs_file_extent_num_bytes(leaf
, fi
) + end
-
2331 btrfs_set_file_extent_num_bytes(leaf
, fi
, num_bytes
);
2332 btrfs_set_file_extent_ram_bytes(leaf
, fi
, num_bytes
);
2333 btrfs_set_file_extent_offset(leaf
, fi
, 0);
2334 btrfs_mark_buffer_dirty(leaf
);
2337 btrfs_release_path(path
);
2339 ret
= btrfs_insert_file_extent(trans
, root
, btrfs_ino(inode
),
2340 offset
, 0, 0, end
- offset
, 0, end
- offset
, 0, 0, 0);
2345 btrfs_release_path(path
);
2347 hole_em
= alloc_extent_map();
2349 btrfs_drop_extent_cache(inode
, offset
, end
- 1, 0);
2350 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC
, &inode
->runtime_flags
);
2352 hole_em
->start
= offset
;
2353 hole_em
->len
= end
- offset
;
2354 hole_em
->ram_bytes
= hole_em
->len
;
2355 hole_em
->orig_start
= offset
;
2357 hole_em
->block_start
= EXTENT_MAP_HOLE
;
2358 hole_em
->block_len
= 0;
2359 hole_em
->orig_block_len
= 0;
2360 hole_em
->compress_type
= BTRFS_COMPRESS_NONE
;
2361 hole_em
->generation
= trans
->transid
;
2364 btrfs_drop_extent_cache(inode
, offset
, end
- 1, 0);
2365 write_lock(&em_tree
->lock
);
2366 ret
= add_extent_mapping(em_tree
, hole_em
, 1);
2367 write_unlock(&em_tree
->lock
);
2368 } while (ret
== -EEXIST
);
2369 free_extent_map(hole_em
);
2371 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC
,
2372 &inode
->runtime_flags
);
2379 * Find a hole extent on given inode and change start/len to the end of hole
2380 * extent.(hole/vacuum extent whose em->start <= start &&
2381 * em->start + em->len > start)
2382 * When a hole extent is found, return 1 and modify start/len.
2384 static int find_first_non_hole(struct inode
*inode
, u64
*start
, u64
*len
)
2386 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2387 struct extent_map
*em
;
2390 em
= btrfs_get_extent(BTRFS_I(inode
), NULL
, 0,
2391 round_down(*start
, fs_info
->sectorsize
),
2392 round_up(*len
, fs_info
->sectorsize
));
2396 /* Hole or vacuum extent(only exists in no-hole mode) */
2397 if (em
->block_start
== EXTENT_MAP_HOLE
) {
2399 *len
= em
->start
+ em
->len
> *start
+ *len
?
2400 0 : *start
+ *len
- em
->start
- em
->len
;
2401 *start
= em
->start
+ em
->len
;
2403 free_extent_map(em
);
2407 static int btrfs_punch_hole_lock_range(struct inode
*inode
,
2408 const u64 lockstart
,
2410 struct extent_state
**cached_state
)
2413 struct btrfs_ordered_extent
*ordered
;
2416 truncate_pagecache_range(inode
, lockstart
, lockend
);
2418 lock_extent_bits(&BTRFS_I(inode
)->io_tree
, lockstart
, lockend
,
2420 ordered
= btrfs_lookup_first_ordered_extent(inode
, lockend
);
2423 * We need to make sure we have no ordered extents in this range
2424 * and nobody raced in and read a page in this range, if we did
2425 * we need to try again.
2428 (ordered
->file_offset
+ ordered
->num_bytes
<= lockstart
||
2429 ordered
->file_offset
> lockend
)) &&
2430 !filemap_range_has_page(inode
->i_mapping
,
2431 lockstart
, lockend
)) {
2433 btrfs_put_ordered_extent(ordered
);
2437 btrfs_put_ordered_extent(ordered
);
2438 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
, lockstart
,
2439 lockend
, cached_state
);
2440 ret
= btrfs_wait_ordered_range(inode
, lockstart
,
2441 lockend
- lockstart
+ 1);
2448 static int btrfs_insert_clone_extent(struct btrfs_trans_handle
*trans
,
2449 struct inode
*inode
,
2450 struct btrfs_path
*path
,
2451 struct btrfs_clone_extent_info
*clone_info
,
2452 const u64 clone_len
)
2454 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2455 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
2456 struct btrfs_file_extent_item
*extent
;
2457 struct extent_buffer
*leaf
;
2458 struct btrfs_key key
;
2460 struct btrfs_ref ref
= { 0 };
2467 if (clone_info
->disk_offset
== 0 &&
2468 btrfs_fs_incompat(fs_info
, NO_HOLES
))
2471 key
.objectid
= btrfs_ino(BTRFS_I(inode
));
2472 key
.type
= BTRFS_EXTENT_DATA_KEY
;
2473 key
.offset
= clone_info
->file_offset
;
2474 ret
= btrfs_insert_empty_item(trans
, root
, path
, &key
,
2475 clone_info
->item_size
);
2478 leaf
= path
->nodes
[0];
2479 slot
= path
->slots
[0];
2480 write_extent_buffer(leaf
, clone_info
->extent_buf
,
2481 btrfs_item_ptr_offset(leaf
, slot
),
2482 clone_info
->item_size
);
2483 extent
= btrfs_item_ptr(leaf
, slot
, struct btrfs_file_extent_item
);
2484 btrfs_set_file_extent_offset(leaf
, extent
, clone_info
->data_offset
);
2485 btrfs_set_file_extent_num_bytes(leaf
, extent
, clone_len
);
2486 btrfs_mark_buffer_dirty(leaf
);
2487 btrfs_release_path(path
);
2489 /* If it's a hole, nothing more needs to be done. */
2490 if (clone_info
->disk_offset
== 0)
2493 inode_add_bytes(inode
, clone_len
);
2494 btrfs_init_generic_ref(&ref
, BTRFS_ADD_DELAYED_REF
,
2495 clone_info
->disk_offset
,
2496 clone_info
->disk_len
, 0);
2497 ref_offset
= clone_info
->file_offset
- clone_info
->data_offset
;
2498 btrfs_init_data_ref(&ref
, root
->root_key
.objectid
,
2499 btrfs_ino(BTRFS_I(inode
)), ref_offset
);
2500 ret
= btrfs_inc_extent_ref(trans
, &ref
);
2506 * The respective range must have been previously locked, as well as the inode.
2507 * The end offset is inclusive (last byte of the range).
2508 * @clone_info is NULL for fallocate's hole punching and non-NULL for extent
2510 * When cloning, we don't want to end up in a state where we dropped extents
2511 * without inserting a new one, so we must abort the transaction to avoid a
2514 int btrfs_punch_hole_range(struct inode
*inode
, struct btrfs_path
*path
,
2515 const u64 start
, const u64 end
,
2516 struct btrfs_clone_extent_info
*clone_info
,
2517 struct btrfs_trans_handle
**trans_out
)
2519 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2520 u64 min_size
= btrfs_calc_insert_metadata_size(fs_info
, 1);
2521 u64 ino_size
= round_up(inode
->i_size
, fs_info
->sectorsize
);
2522 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
2523 struct btrfs_trans_handle
*trans
= NULL
;
2524 struct btrfs_block_rsv
*rsv
;
2525 unsigned int rsv_count
;
2528 u64 len
= end
- start
;
2534 rsv
= btrfs_alloc_block_rsv(fs_info
, BTRFS_BLOCK_RSV_TEMP
);
2539 rsv
->size
= btrfs_calc_insert_metadata_size(fs_info
, 1);
2543 * 1 - update the inode
2544 * 1 - removing the extents in the range
2545 * 1 - adding the hole extent if no_holes isn't set or if we are cloning
2548 if (!btrfs_fs_incompat(fs_info
, NO_HOLES
) || clone_info
)
2553 trans
= btrfs_start_transaction(root
, rsv_count
);
2554 if (IS_ERR(trans
)) {
2555 ret
= PTR_ERR(trans
);
2560 ret
= btrfs_block_rsv_migrate(&fs_info
->trans_block_rsv
, rsv
,
2563 trans
->block_rsv
= rsv
;
2566 while (cur_offset
< end
) {
2567 ret
= __btrfs_drop_extents(trans
, root
, inode
, path
,
2568 cur_offset
, end
+ 1, &drop_end
,
2570 if (ret
!= -ENOSPC
) {
2572 * When cloning we want to avoid transaction aborts when
2573 * nothing was done and we are attempting to clone parts
2574 * of inline extents, in such cases -EOPNOTSUPP is
2575 * returned by __btrfs_drop_extents() without having
2576 * changed anything in the file.
2578 if (clone_info
&& ret
&& ret
!= -EOPNOTSUPP
)
2579 btrfs_abort_transaction(trans
, ret
);
2583 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
2585 if (!clone_info
&& cur_offset
< drop_end
&&
2586 cur_offset
< ino_size
) {
2587 ret
= fill_holes(trans
, BTRFS_I(inode
), path
,
2588 cur_offset
, drop_end
);
2591 * If we failed then we didn't insert our hole
2592 * entries for the area we dropped, so now the
2593 * fs is corrupted, so we must abort the
2596 btrfs_abort_transaction(trans
, ret
);
2601 if (clone_info
&& drop_end
> clone_info
->file_offset
) {
2602 u64 clone_len
= drop_end
- clone_info
->file_offset
;
2604 ret
= btrfs_insert_clone_extent(trans
, inode
, path
,
2605 clone_info
, clone_len
);
2607 btrfs_abort_transaction(trans
, ret
);
2610 clone_info
->data_len
-= clone_len
;
2611 clone_info
->data_offset
+= clone_len
;
2612 clone_info
->file_offset
+= clone_len
;
2615 cur_offset
= drop_end
;
2617 ret
= btrfs_update_inode(trans
, root
, inode
);
2621 btrfs_end_transaction(trans
);
2622 btrfs_btree_balance_dirty(fs_info
);
2624 trans
= btrfs_start_transaction(root
, rsv_count
);
2625 if (IS_ERR(trans
)) {
2626 ret
= PTR_ERR(trans
);
2631 ret
= btrfs_block_rsv_migrate(&fs_info
->trans_block_rsv
,
2632 rsv
, min_size
, false);
2633 BUG_ON(ret
); /* shouldn't happen */
2634 trans
->block_rsv
= rsv
;
2637 ret
= find_first_non_hole(inode
, &cur_offset
, &len
);
2638 if (unlikely(ret
< 0))
2648 * If we were cloning, force the next fsync to be a full one since we
2649 * we replaced (or just dropped in the case of cloning holes when
2650 * NO_HOLES is enabled) extents and extent maps.
2651 * This is for the sake of simplicity, and cloning into files larger
2652 * than 16Mb would force the full fsync any way (when
2653 * try_release_extent_mapping() is invoked during page cache truncation.
2656 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC
,
2657 &BTRFS_I(inode
)->runtime_flags
);
2662 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
2664 * If we are using the NO_HOLES feature we might have had already an
2665 * hole that overlaps a part of the region [lockstart, lockend] and
2666 * ends at (or beyond) lockend. Since we have no file extent items to
2667 * represent holes, drop_end can be less than lockend and so we must
2668 * make sure we have an extent map representing the existing hole (the
2669 * call to __btrfs_drop_extents() might have dropped the existing extent
2670 * map representing the existing hole), otherwise the fast fsync path
2671 * will not record the existence of the hole region
2672 * [existing_hole_start, lockend].
2674 if (drop_end
<= end
)
2677 * Don't insert file hole extent item if it's for a range beyond eof
2678 * (because it's useless) or if it represents a 0 bytes range (when
2679 * cur_offset == drop_end).
2681 if (!clone_info
&& cur_offset
< ino_size
&& cur_offset
< drop_end
) {
2682 ret
= fill_holes(trans
, BTRFS_I(inode
), path
,
2683 cur_offset
, drop_end
);
2685 /* Same comment as above. */
2686 btrfs_abort_transaction(trans
, ret
);
2691 ret
= btrfs_insert_clone_extent(trans
, inode
, path
, clone_info
,
2692 clone_info
->data_len
);
2694 btrfs_abort_transaction(trans
, ret
);
2703 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
2705 btrfs_end_transaction(trans
);
2709 btrfs_free_block_rsv(fs_info
, rsv
);
2714 static int btrfs_punch_hole(struct inode
*inode
, loff_t offset
, loff_t len
)
2716 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2717 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
2718 struct extent_state
*cached_state
= NULL
;
2719 struct btrfs_path
*path
;
2720 struct btrfs_trans_handle
*trans
= NULL
;
2725 u64 orig_start
= offset
;
2729 bool truncated_block
= false;
2730 bool updated_inode
= false;
2732 ret
= btrfs_wait_ordered_range(inode
, offset
, len
);
2737 ino_size
= round_up(inode
->i_size
, fs_info
->sectorsize
);
2738 ret
= find_first_non_hole(inode
, &offset
, &len
);
2740 goto out_only_mutex
;
2742 /* Already in a large hole */
2744 goto out_only_mutex
;
2747 lockstart
= round_up(offset
, btrfs_inode_sectorsize(inode
));
2748 lockend
= round_down(offset
+ len
,
2749 btrfs_inode_sectorsize(inode
)) - 1;
2750 same_block
= (BTRFS_BYTES_TO_BLKS(fs_info
, offset
))
2751 == (BTRFS_BYTES_TO_BLKS(fs_info
, offset
+ len
- 1));
2753 * We needn't truncate any block which is beyond the end of the file
2754 * because we are sure there is no data there.
2757 * Only do this if we are in the same block and we aren't doing the
2760 if (same_block
&& len
< fs_info
->sectorsize
) {
2761 if (offset
< ino_size
) {
2762 truncated_block
= true;
2763 ret
= btrfs_truncate_block(inode
, offset
, len
, 0);
2767 goto out_only_mutex
;
2770 /* zero back part of the first block */
2771 if (offset
< ino_size
) {
2772 truncated_block
= true;
2773 ret
= btrfs_truncate_block(inode
, offset
, 0, 0);
2775 inode_unlock(inode
);
2780 /* Check the aligned pages after the first unaligned page,
2781 * if offset != orig_start, which means the first unaligned page
2782 * including several following pages are already in holes,
2783 * the extra check can be skipped */
2784 if (offset
== orig_start
) {
2785 /* after truncate page, check hole again */
2786 len
= offset
+ len
- lockstart
;
2788 ret
= find_first_non_hole(inode
, &offset
, &len
);
2790 goto out_only_mutex
;
2793 goto out_only_mutex
;
2798 /* Check the tail unaligned part is in a hole */
2799 tail_start
= lockend
+ 1;
2800 tail_len
= offset
+ len
- tail_start
;
2802 ret
= find_first_non_hole(inode
, &tail_start
, &tail_len
);
2803 if (unlikely(ret
< 0))
2804 goto out_only_mutex
;
2806 /* zero the front end of the last page */
2807 if (tail_start
+ tail_len
< ino_size
) {
2808 truncated_block
= true;
2809 ret
= btrfs_truncate_block(inode
,
2810 tail_start
+ tail_len
,
2813 goto out_only_mutex
;
2818 if (lockend
< lockstart
) {
2820 goto out_only_mutex
;
2823 ret
= btrfs_punch_hole_lock_range(inode
, lockstart
, lockend
,
2826 goto out_only_mutex
;
2828 path
= btrfs_alloc_path();
2834 ret
= btrfs_punch_hole_range(inode
, path
, lockstart
, lockend
, NULL
,
2836 btrfs_free_path(path
);
2840 ASSERT(trans
!= NULL
);
2841 inode_inc_iversion(inode
);
2842 inode
->i_mtime
= inode
->i_ctime
= current_time(inode
);
2843 ret
= btrfs_update_inode(trans
, root
, inode
);
2844 updated_inode
= true;
2845 btrfs_end_transaction(trans
);
2846 btrfs_btree_balance_dirty(fs_info
);
2848 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
, lockstart
, lockend
,
2851 if (!updated_inode
&& truncated_block
&& !ret
) {
2853 * If we only end up zeroing part of a page, we still need to
2854 * update the inode item, so that all the time fields are
2855 * updated as well as the necessary btrfs inode in memory fields
2856 * for detecting, at fsync time, if the inode isn't yet in the
2857 * log tree or it's there but not up to date.
2859 struct timespec64 now
= current_time(inode
);
2861 inode_inc_iversion(inode
);
2862 inode
->i_mtime
= now
;
2863 inode
->i_ctime
= now
;
2864 trans
= btrfs_start_transaction(root
, 1);
2865 if (IS_ERR(trans
)) {
2866 ret
= PTR_ERR(trans
);
2870 ret
= btrfs_update_inode(trans
, root
, inode
);
2871 ret2
= btrfs_end_transaction(trans
);
2876 inode_unlock(inode
);
2880 /* Helper structure to record which range is already reserved */
2881 struct falloc_range
{
2882 struct list_head list
;
2888 * Helper function to add falloc range
2890 * Caller should have locked the larger range of extent containing
2893 static int add_falloc_range(struct list_head
*head
, u64 start
, u64 len
)
2895 struct falloc_range
*prev
= NULL
;
2896 struct falloc_range
*range
= NULL
;
2898 if (list_empty(head
))
2902 * As fallocate iterate by bytenr order, we only need to check
2905 prev
= list_entry(head
->prev
, struct falloc_range
, list
);
2906 if (prev
->start
+ prev
->len
== start
) {
2911 range
= kmalloc(sizeof(*range
), GFP_KERNEL
);
2914 range
->start
= start
;
2916 list_add_tail(&range
->list
, head
);
2920 static int btrfs_fallocate_update_isize(struct inode
*inode
,
2924 struct btrfs_trans_handle
*trans
;
2925 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
2929 if (mode
& FALLOC_FL_KEEP_SIZE
|| end
<= i_size_read(inode
))
2932 trans
= btrfs_start_transaction(root
, 1);
2934 return PTR_ERR(trans
);
2936 inode
->i_ctime
= current_time(inode
);
2937 i_size_write(inode
, end
);
2938 btrfs_ordered_update_i_size(inode
, end
, NULL
);
2939 ret
= btrfs_update_inode(trans
, root
, inode
);
2940 ret2
= btrfs_end_transaction(trans
);
2942 return ret
? ret
: ret2
;
2946 RANGE_BOUNDARY_WRITTEN_EXTENT
,
2947 RANGE_BOUNDARY_PREALLOC_EXTENT
,
2948 RANGE_BOUNDARY_HOLE
,
2951 static int btrfs_zero_range_check_range_boundary(struct inode
*inode
,
2954 const u64 sectorsize
= btrfs_inode_sectorsize(inode
);
2955 struct extent_map
*em
;
2958 offset
= round_down(offset
, sectorsize
);
2959 em
= btrfs_get_extent(BTRFS_I(inode
), NULL
, 0, offset
, sectorsize
);
2963 if (em
->block_start
== EXTENT_MAP_HOLE
)
2964 ret
= RANGE_BOUNDARY_HOLE
;
2965 else if (test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
))
2966 ret
= RANGE_BOUNDARY_PREALLOC_EXTENT
;
2968 ret
= RANGE_BOUNDARY_WRITTEN_EXTENT
;
2970 free_extent_map(em
);
2974 static int btrfs_zero_range(struct inode
*inode
,
2979 struct btrfs_fs_info
*fs_info
= BTRFS_I(inode
)->root
->fs_info
;
2980 struct extent_map
*em
;
2981 struct extent_changeset
*data_reserved
= NULL
;
2984 const u64 sectorsize
= btrfs_inode_sectorsize(inode
);
2985 u64 alloc_start
= round_down(offset
, sectorsize
);
2986 u64 alloc_end
= round_up(offset
+ len
, sectorsize
);
2987 u64 bytes_to_reserve
= 0;
2988 bool space_reserved
= false;
2990 inode_dio_wait(inode
);
2992 em
= btrfs_get_extent(BTRFS_I(inode
), NULL
, 0, alloc_start
,
2993 alloc_end
- alloc_start
);
3000 * Avoid hole punching and extent allocation for some cases. More cases
3001 * could be considered, but these are unlikely common and we keep things
3002 * as simple as possible for now. Also, intentionally, if the target
3003 * range contains one or more prealloc extents together with regular
3004 * extents and holes, we drop all the existing extents and allocate a
3005 * new prealloc extent, so that we get a larger contiguous disk extent.
3007 if (em
->start
<= alloc_start
&&
3008 test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
)) {
3009 const u64 em_end
= em
->start
+ em
->len
;
3011 if (em_end
>= offset
+ len
) {
3013 * The whole range is already a prealloc extent,
3014 * do nothing except updating the inode's i_size if
3017 free_extent_map(em
);
3018 ret
= btrfs_fallocate_update_isize(inode
, offset
+ len
,
3023 * Part of the range is already a prealloc extent, so operate
3024 * only on the remaining part of the range.
3026 alloc_start
= em_end
;
3027 ASSERT(IS_ALIGNED(alloc_start
, sectorsize
));
3028 len
= offset
+ len
- alloc_start
;
3029 offset
= alloc_start
;
3030 alloc_hint
= em
->block_start
+ em
->len
;
3032 free_extent_map(em
);
3034 if (BTRFS_BYTES_TO_BLKS(fs_info
, offset
) ==
3035 BTRFS_BYTES_TO_BLKS(fs_info
, offset
+ len
- 1)) {
3036 em
= btrfs_get_extent(BTRFS_I(inode
), NULL
, 0, alloc_start
,
3043 if (test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
)) {
3044 free_extent_map(em
);
3045 ret
= btrfs_fallocate_update_isize(inode
, offset
+ len
,
3049 if (len
< sectorsize
&& em
->block_start
!= EXTENT_MAP_HOLE
) {
3050 free_extent_map(em
);
3051 ret
= btrfs_truncate_block(inode
, offset
, len
, 0);
3053 ret
= btrfs_fallocate_update_isize(inode
,
3058 free_extent_map(em
);
3059 alloc_start
= round_down(offset
, sectorsize
);
3060 alloc_end
= alloc_start
+ sectorsize
;
3064 alloc_start
= round_up(offset
, sectorsize
);
3065 alloc_end
= round_down(offset
+ len
, sectorsize
);
3068 * For unaligned ranges, check the pages at the boundaries, they might
3069 * map to an extent, in which case we need to partially zero them, or
3070 * they might map to a hole, in which case we need our allocation range
3073 if (!IS_ALIGNED(offset
, sectorsize
)) {
3074 ret
= btrfs_zero_range_check_range_boundary(inode
, offset
);
3077 if (ret
== RANGE_BOUNDARY_HOLE
) {
3078 alloc_start
= round_down(offset
, sectorsize
);
3080 } else if (ret
== RANGE_BOUNDARY_WRITTEN_EXTENT
) {
3081 ret
= btrfs_truncate_block(inode
, offset
, 0, 0);
3089 if (!IS_ALIGNED(offset
+ len
, sectorsize
)) {
3090 ret
= btrfs_zero_range_check_range_boundary(inode
,
3094 if (ret
== RANGE_BOUNDARY_HOLE
) {
3095 alloc_end
= round_up(offset
+ len
, sectorsize
);
3097 } else if (ret
== RANGE_BOUNDARY_WRITTEN_EXTENT
) {
3098 ret
= btrfs_truncate_block(inode
, offset
+ len
, 0, 1);
3107 if (alloc_start
< alloc_end
) {
3108 struct extent_state
*cached_state
= NULL
;
3109 const u64 lockstart
= alloc_start
;
3110 const u64 lockend
= alloc_end
- 1;
3112 bytes_to_reserve
= alloc_end
- alloc_start
;
3113 ret
= btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode
),
3117 space_reserved
= true;
3118 ret
= btrfs_qgroup_reserve_data(inode
, &data_reserved
,
3119 alloc_start
, bytes_to_reserve
);
3122 ret
= btrfs_punch_hole_lock_range(inode
, lockstart
, lockend
,
3126 ret
= btrfs_prealloc_file_range(inode
, mode
, alloc_start
,
3127 alloc_end
- alloc_start
,
3129 offset
+ len
, &alloc_hint
);
3130 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
, lockstart
,
3131 lockend
, &cached_state
);
3132 /* btrfs_prealloc_file_range releases reserved space on error */
3134 space_reserved
= false;
3138 ret
= btrfs_fallocate_update_isize(inode
, offset
+ len
, mode
);
3140 if (ret
&& space_reserved
)
3141 btrfs_free_reserved_data_space(inode
, data_reserved
,
3142 alloc_start
, bytes_to_reserve
);
3143 extent_changeset_free(data_reserved
);
3148 static long btrfs_fallocate(struct file
*file
, int mode
,
3149 loff_t offset
, loff_t len
)
3151 struct inode
*inode
= file_inode(file
);
3152 struct extent_state
*cached_state
= NULL
;
3153 struct extent_changeset
*data_reserved
= NULL
;
3154 struct falloc_range
*range
;
3155 struct falloc_range
*tmp
;
3156 struct list_head reserve_list
;
3164 struct extent_map
*em
;
3165 int blocksize
= btrfs_inode_sectorsize(inode
);
3168 alloc_start
= round_down(offset
, blocksize
);
3169 alloc_end
= round_up(offset
+ len
, blocksize
);
3170 cur_offset
= alloc_start
;
3172 /* Make sure we aren't being give some crap mode */
3173 if (mode
& ~(FALLOC_FL_KEEP_SIZE
| FALLOC_FL_PUNCH_HOLE
|
3174 FALLOC_FL_ZERO_RANGE
))
3177 if (mode
& FALLOC_FL_PUNCH_HOLE
)
3178 return btrfs_punch_hole(inode
, offset
, len
);
3181 * Only trigger disk allocation, don't trigger qgroup reserve
3183 * For qgroup space, it will be checked later.
3185 if (!(mode
& FALLOC_FL_ZERO_RANGE
)) {
3186 ret
= btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode
),
3187 alloc_end
- alloc_start
);
3194 if (!(mode
& FALLOC_FL_KEEP_SIZE
) && offset
+ len
> inode
->i_size
) {
3195 ret
= inode_newsize_ok(inode
, offset
+ len
);
3201 * TODO: Move these two operations after we have checked
3202 * accurate reserved space, or fallocate can still fail but
3203 * with page truncated or size expanded.
3205 * But that's a minor problem and won't do much harm BTW.
3207 if (alloc_start
> inode
->i_size
) {
3208 ret
= btrfs_cont_expand(inode
, i_size_read(inode
),
3212 } else if (offset
+ len
> inode
->i_size
) {
3214 * If we are fallocating from the end of the file onward we
3215 * need to zero out the end of the block if i_size lands in the
3216 * middle of a block.
3218 ret
= btrfs_truncate_block(inode
, inode
->i_size
, 0, 0);
3224 * wait for ordered IO before we have any locks. We'll loop again
3225 * below with the locks held.
3227 ret
= btrfs_wait_ordered_range(inode
, alloc_start
,
3228 alloc_end
- alloc_start
);
3232 if (mode
& FALLOC_FL_ZERO_RANGE
) {
3233 ret
= btrfs_zero_range(inode
, offset
, len
, mode
);
3234 inode_unlock(inode
);
3238 locked_end
= alloc_end
- 1;
3240 struct btrfs_ordered_extent
*ordered
;
3242 /* the extent lock is ordered inside the running
3245 lock_extent_bits(&BTRFS_I(inode
)->io_tree
, alloc_start
,
3246 locked_end
, &cached_state
);
3247 ordered
= btrfs_lookup_first_ordered_extent(inode
, locked_end
);
3250 ordered
->file_offset
+ ordered
->num_bytes
> alloc_start
&&
3251 ordered
->file_offset
< alloc_end
) {
3252 btrfs_put_ordered_extent(ordered
);
3253 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
,
3254 alloc_start
, locked_end
,
3257 * we can't wait on the range with the transaction
3258 * running or with the extent lock held
3260 ret
= btrfs_wait_ordered_range(inode
, alloc_start
,
3261 alloc_end
- alloc_start
);
3266 btrfs_put_ordered_extent(ordered
);
3271 /* First, check if we exceed the qgroup limit */
3272 INIT_LIST_HEAD(&reserve_list
);
3273 while (cur_offset
< alloc_end
) {
3274 em
= btrfs_get_extent(BTRFS_I(inode
), NULL
, 0, cur_offset
,
3275 alloc_end
- cur_offset
);
3280 last_byte
= min(extent_map_end(em
), alloc_end
);
3281 actual_end
= min_t(u64
, extent_map_end(em
), offset
+ len
);
3282 last_byte
= ALIGN(last_byte
, blocksize
);
3283 if (em
->block_start
== EXTENT_MAP_HOLE
||
3284 (cur_offset
>= inode
->i_size
&&
3285 !test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
))) {
3286 ret
= add_falloc_range(&reserve_list
, cur_offset
,
3287 last_byte
- cur_offset
);
3289 free_extent_map(em
);
3292 ret
= btrfs_qgroup_reserve_data(inode
, &data_reserved
,
3293 cur_offset
, last_byte
- cur_offset
);
3295 cur_offset
= last_byte
;
3296 free_extent_map(em
);
3301 * Do not need to reserve unwritten extent for this
3302 * range, free reserved data space first, otherwise
3303 * it'll result in false ENOSPC error.
3305 btrfs_free_reserved_data_space(inode
, data_reserved
,
3306 cur_offset
, last_byte
- cur_offset
);
3308 free_extent_map(em
);
3309 cur_offset
= last_byte
;
3313 * If ret is still 0, means we're OK to fallocate.
3314 * Or just cleanup the list and exit.
3316 list_for_each_entry_safe(range
, tmp
, &reserve_list
, list
) {
3318 ret
= btrfs_prealloc_file_range(inode
, mode
,
3320 range
->len
, i_blocksize(inode
),
3321 offset
+ len
, &alloc_hint
);
3323 btrfs_free_reserved_data_space(inode
,
3324 data_reserved
, range
->start
,
3326 list_del(&range
->list
);
3333 * We didn't need to allocate any more space, but we still extended the
3334 * size of the file so we need to update i_size and the inode item.
3336 ret
= btrfs_fallocate_update_isize(inode
, actual_end
, mode
);
3338 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
, alloc_start
, locked_end
,
3341 inode_unlock(inode
);
3342 /* Let go of our reservation. */
3343 if (ret
!= 0 && !(mode
& FALLOC_FL_ZERO_RANGE
))
3344 btrfs_free_reserved_data_space(inode
, data_reserved
,
3345 cur_offset
, alloc_end
- cur_offset
);
3346 extent_changeset_free(data_reserved
);
3350 static loff_t
find_desired_extent(struct inode
*inode
, loff_t offset
,
3353 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
3354 struct extent_map
*em
= NULL
;
3355 struct extent_state
*cached_state
= NULL
;
3356 loff_t i_size
= inode
->i_size
;
3363 if (i_size
== 0 || offset
>= i_size
)
3367 * offset can be negative, in this case we start finding DATA/HOLE from
3368 * the very start of the file.
3370 start
= max_t(loff_t
, 0, offset
);
3372 lockstart
= round_down(start
, fs_info
->sectorsize
);
3373 lockend
= round_up(i_size
, fs_info
->sectorsize
);
3374 if (lockend
<= lockstart
)
3375 lockend
= lockstart
+ fs_info
->sectorsize
;
3377 len
= lockend
- lockstart
+ 1;
3379 lock_extent_bits(&BTRFS_I(inode
)->io_tree
, lockstart
, lockend
,
3382 while (start
< i_size
) {
3383 em
= btrfs_get_extent_fiemap(BTRFS_I(inode
), start
, len
);
3390 if (whence
== SEEK_HOLE
&&
3391 (em
->block_start
== EXTENT_MAP_HOLE
||
3392 test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
)))
3394 else if (whence
== SEEK_DATA
&&
3395 (em
->block_start
!= EXTENT_MAP_HOLE
&&
3396 !test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
)))
3399 start
= em
->start
+ em
->len
;
3400 free_extent_map(em
);
3404 free_extent_map(em
);
3405 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
, lockstart
, lockend
,
3410 if (whence
== SEEK_DATA
&& start
>= i_size
)
3413 offset
= min_t(loff_t
, start
, i_size
);
3419 static loff_t
btrfs_file_llseek(struct file
*file
, loff_t offset
, int whence
)
3421 struct inode
*inode
= file
->f_mapping
->host
;
3425 return generic_file_llseek(file
, offset
, whence
);
3428 inode_lock_shared(inode
);
3429 offset
= find_desired_extent(inode
, offset
, whence
);
3430 inode_unlock_shared(inode
);
3437 return vfs_setpos(file
, offset
, inode
->i_sb
->s_maxbytes
);
3440 static int btrfs_file_open(struct inode
*inode
, struct file
*filp
)
3442 filp
->f_mode
|= FMODE_NOWAIT
;
3443 return generic_file_open(inode
, filp
);
3446 const struct file_operations btrfs_file_operations
= {
3447 .llseek
= btrfs_file_llseek
,
3448 .read_iter
= generic_file_read_iter
,
3449 .splice_read
= generic_file_splice_read
,
3450 .write_iter
= btrfs_file_write_iter
,
3451 .mmap
= btrfs_file_mmap
,
3452 .open
= btrfs_file_open
,
3453 .release
= btrfs_release_file
,
3454 .fsync
= btrfs_sync_file
,
3455 .fallocate
= btrfs_fallocate
,
3456 .unlocked_ioctl
= btrfs_ioctl
,
3457 #ifdef CONFIG_COMPAT
3458 .compat_ioctl
= btrfs_compat_ioctl
,
3460 .remap_file_range
= btrfs_remap_file_range
,
3463 void __cold
btrfs_auto_defrag_exit(void)
3465 kmem_cache_destroy(btrfs_inode_defrag_cachep
);
3468 int __init
btrfs_auto_defrag_init(void)
3470 btrfs_inode_defrag_cachep
= kmem_cache_create("btrfs_inode_defrag",
3471 sizeof(struct inode_defrag
), 0,
3474 if (!btrfs_inode_defrag_cachep
)
3480 int btrfs_fdatawrite_range(struct inode
*inode
, loff_t start
, loff_t end
)
3485 * So with compression we will find and lock a dirty page and clear the
3486 * first one as dirty, setup an async extent, and immediately return
3487 * with the entire range locked but with nobody actually marked with
3488 * writeback. So we can't just filemap_write_and_wait_range() and
3489 * expect it to work since it will just kick off a thread to do the
3490 * actual work. So we need to call filemap_fdatawrite_range _again_
3491 * since it will wait on the page lock, which won't be unlocked until
3492 * after the pages have been marked as writeback and so we're good to go
3493 * from there. We have to do this otherwise we'll miss the ordered
3494 * extents and that results in badness. Please Josef, do not think you
3495 * know better and pull this out at some point in the future, it is
3496 * right and you are wrong.
3498 ret
= filemap_fdatawrite_range(inode
->i_mapping
, start
, end
);
3499 if (!ret
&& test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT
,
3500 &BTRFS_I(inode
)->runtime_flags
))
3501 ret
= filemap_fdatawrite_range(inode
->i_mapping
, start
, end
);