f2fs: support & optimize large folios for writable files
Subsystems (2)
v6 cover f2fs: support & optimize large folios for writable files
From: Nanzhe Zhao <[email protected]>
This series supports large folios for most readable/writable files in buffered I/O paths, including normal files, block-layer encrypted files, and atomic files except for inline-data files, compressed files, and quota files.
It also extends f2fs_folio_state to coexist with f2fs page-private flags and to handle large folio write path and partial truncate of large folios correctly. A valid large folio always carries a f2fs_folio_state at its folio->private in the current implementation.
Benchmark details can be found in the RFC v2 cover letter:
https://lore.kernel.org/r/[email protected]
Changes in v6:
- Rebased onto the f2fs dev branch (fd106ada4dee).
- v5 12/16 ("f2fs: wait for folio writeback before ffs_detach_free") is dropped, because the lkp warning reported by [1] was caused by a write_pages_pending leak on the GC truncate path.
- Improve large-folio support in the f2fs_do_write_data_page() path used by GC:
- 05/15: use __folio_start_writeback(folio, folio_test_dirty(folio)) in both the IPU and OPU paths, so a single-subpage GC write does not clear PAGECACHE_TAG_TOWRITE while other subpages are still dirty [3].
- 05/15: add f2fs_ffs_put_write_pending() as the common writeback completion helper; do_write_block() only ends writeback for order-0 folios.
- 08/15: move the write_pages_pending increment from move_data_page() into f2fs_do_write_data_page(), take it only after __folio_start_writeback(), and drop it on every error path. move_data_page() no longer adjusts write_pages_pending or clears gcing on error [1].
- 02/15: compute bio_offset/bio_len against the folio actually added to the bio [5].
- 05/15, 06/15: fix the order-0 dirty accounting leak in the cp_error path [2].
- 10/15: allocate ffs before f2fs_truncate_read_extent() [4].
- 11/15: move the existing truncated-page handling into f2fs_clear_truncated_page_state() and reuse it for the subpage-aware large-folio writeback path, including the -ENOENT/NULL_ADDR case [2].
Link to v5: [6]
Many thanks to Chao, Daeho and Jaegeuk for the reviews, and to the kernel test robot for the report.
[1] https://lore.kernel.org/oe-lkp/[email protected]
[2] https://lore.kernel.org/r/[email protected]
[3] https://lore.kernel.org/r/[email protected]
[4] https://lore.kernel.org/r/[email protected]
[5] https://lore.kernel.org/r/[email protected]
[6] https://lore.kernel.org/r/[email protected]/
Nanzhe Zhao (15):
f2fs: extend folio state for large folio write path
f2fs: carry subpage offset and count in write IO
f2fs: support regular file buffered writes on large folios
f2fs: support atomic file large folios buffered write
f2fs: support large folio writeback
f2fs: account large folio dirty data at block granularity
f2fs: prepare mmap write faults for large folios
f2fs: make GC migration large-folio aware
f2fs: optimize small block size large folio read
f2fs: support partial uptodate large folio read
f2fs: handle partial truncate of large folio dirty subpages
f2fs: fix zeroing paths for large folios
f2fs: handle block cloning within the same large folio
f2fs: allow large folio support to writeable files
f2fs: make compressed files compatible with large folio
Documentation/filesystems/f2fs.rst | 10 + fs/f2fs/checkpoint.c | 40 +- fs/f2fs/compress.c | 7 +- fs/f2fs/data.c | 1486 +++++++++++++++++++++++++--- fs/f2fs/dir.c | 2 +- fs/f2fs/f2fs.h | 170 +++- fs/f2fs/file.c | 226 +++-- fs/f2fs/gc.c | 32 +- fs/f2fs/inline.c | 9 +- fs/f2fs/inode.c | 4 +- fs/f2fs/namei.c | 1 + fs/f2fs/node.c | 2 +- fs/f2fs/segment.c | 13 +- 13 files changed, 1742 insertions(+), 260 deletions(-)
Signature · 1 line
2.43.0
PATCH v6 1/15 f2fs: extend folio state for large folio write path
From: Nanzhe Zhao <[email protected]>
Large folio write path needs a subpage status bitmap and write pages pending counter, while keeping compatible with f2fs private flags.
Move struct f2fs_folio_state to f2fs.h, add private_flags and subpage state bitmap, and change PAGE_PRIVATE functions to be compatible with f2fs_folio_state. Allocate f2fs_folio_state via kzalloc instead of kmem_cache, since the state size depends on the folio order.
Note: Now if a path wants to use f2fs_folio_state, it must call folio_has_ffs instead of `folio_test_large`` to make check.
--- fs/f2fs/data.c | 52 ++++++++++++++++++++----------------- fs/f2fs/f2fs.h | 70 +++++++++++++++++++++++++++++++++++++------------- 2 files changed, 80 insertions(+), 42 deletions(-)
fs/f2fs/data.c +28 -24
@@ -32,15 +32,9 @@static struct kmem_cache *bio_post_read_ctx_cache;static struct kmem_cache *bio_entry_slab; -static struct kmem_cache *ffs_entry_slab;static mempool_t *bio_post_read_ctx_pool;static struct bio_set f2fs_bioset; -struct f2fs_folio_state { -spinlock_t state_lock; -unsigned int read_pages_pending; -}; -#define F2FS_BIO_POOL_SIZE NR_CURSEG_TYPEint __init f2fs_init_bioset (void )
@@ -2717,17 +2711,31 @@ int f2fs_read_multi_pages(struct compress_ctx *cc, struct bio **bio_ret, }#endif -static struct f2fs_folio_state *ffs_find_or_alloc (struct folio *folio) +struct f2fs_folio_state *f2fs_ffs_find_or_alloc (struct folio *folio) { -struct f2fs_folio_state *ffs = folio->private; +struct f2fs_folio_state *ffs; +unsigned int nr_subpages =folio_nr_pages (folio); +unsigned long private = (unsigned long )folio->private; -if (ffs) -return ffs; +f2fs_bug_on (F2FS_F_SB (folio), !folio_test_large (folio)); +f2fs_bug_on (F2FS_F_SB (folio), +test_bit (PAGE_PRIVATE_NOT_POINTER , &private)); - ffs =f2fs_kmem_cache_alloc (ffs_entry_slab, -GFP_NOIO | __GFP_ZERO, true,NULL ); +if (f2fs_folio_has_ffs (folio)) +return (struct f2fs_folio_state *)folio->private; + + ffs =f2fs_kmalloc (F2FS_F_SB (folio), +struct_size (ffs, state,BITS_TO_LONGS (2 * nr_subpages)), +GFP_NOFS | __GFP_ZERO); +if (!ffs) +return NULL ;spin_lock_init (&ffs->state_lock); +if (folio_test_uptodate (folio)) +bitmap_set (ffs->state,0 , nr_subpages); +if (folio_test_dirty (folio)) +bitmap_set (ffs->state, nr_subpages, nr_subpages); +folio_attach_private (folio, ffs);return ffs; }
@@ -2736,7 +2744,7 @@ static void ffs_detach_free(struct folio *folio) {struct f2fs_folio_state *ffs; -if (!folio_test_large (folio)) { +if (!f2fs_folio_has_ffs (folio)) {folio_detach_private (folio);return ; }
@@ -2746,7 +2754,8 @@ static void ffs_detach_free(struct folio *folio)return ;WARN_ON_ONCE (ffs->read_pages_pending !=0 ); -kmem_cache_free (ffs_entry_slab, ffs); +WARN_ON_ONCE (atomic_read (&ffs->write_pages_pending)); +kfree (ffs); } static int f2fs_read_data_large_folio(struct inode *inode,
@@ -2835,7 +2844,11 @@ static int f2fs_read_data_large_folio(struct inode *inode,* to prevent from premature folio_end_read() call on folio */ if (folio_test_large (folio)) { - ffs =ffs_find_or_alloc (folio); + ffs =f2fs_ffs_find_or_alloc (folio); +if (!ffs) { + ret = -ENOMEM ; + goto err_out; + }/* set the bitmap to wait */ spin_lock_irq (&ffs->state_lock);
@@ -4750,21 +4763,12 @@ int __init f2fs_init_bio_entry_cache(void)if (!bio_entry_slab)return -ENOMEM ; - ffs_entry_slab =f2fs_kmem_cache_create ("f2fs_ffs_slab" , -sizeof (struct f2fs_folio_state )); - -if (!ffs_entry_slab) { -kmem_cache_destroy (bio_entry_slab); -return -ENOMEM ; - } -return 0 ; }void f2fs_destroy_bio_entry_cache (void ) {kmem_cache_destroy (bio_entry_slab); -kmem_cache_destroy (ffs_entry_slab); } static int f2fs_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
fs/f2fs/f2fs.h +52 -18
111 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH v6 2/15 f2fs: carry subpage offset and count in write IO
In reply to Nanzhe ZhaoFrom: Nanzhe Zhao <[email protected]>
Large folio write paths need to submit I/O for a range inside a folio instead of always submitting the whole folio from offset zero. Add folio_offset and folio_blkcnt to f2fs_io_info to describe the block offset inside the folio and the number of contiguous blocks covered by the I/O.
Apply the new fields to the bio submit paths that need the subpage offset or contiguous block count.
--- fs/f2fs/checkpoint.c | 2 ++ fs/f2fs/compress.c | 1 + fs/f2fs/data.c | 78 ++++++++++++++++++++++++++++++++------------ fs/f2fs/f2fs.h | 11 +++++++ fs/f2fs/gc.c | 3 ++ fs/f2fs/inline.c | 1 + fs/f2fs/segment.c | 3 +- 7 files changed, 78 insertions(+), 21 deletions(-)
fs/f2fs/checkpoint.c +2 -0
@@ -264,6 +264,7 @@ static struct f2fs_cached_block *__get_meta_cache(struct f2fs_sb_info *sbi, .op_flags = REQ_META | REQ_PRIO, .old_blkaddr = index, .new_blkaddr = index, + .folio_blkcnt = 1, .encrypted_page = NULL, .is_por = !is_meta ? 1 : 0, .is_cache = 1,
@@ -462,6 +463,7 @@ int f2fs_ra_meta_caches(struct f2fs_sb_info *sbi, block_t start, .type = META, .op = REQ_OP_READ, .op_flags = sync ? (REQ_META | REQ_PRIO) : REQ_RAHEAD, + .folio_blkcnt = 1, .encrypted_page = NULL, .in_list = 0, .is_por = (type == META_POR) ? 1 : 0,
fs/f2fs/compress.c +1 -0
@@ -1282,6 +1282,7 @@ static int f2fs_write_compressed_pages(struct compress_ctx *cc, .op_flags = wbc_to_write_flags(wbc), .old_blkaddr = NEW_ADDR, .page = NULL, + .folio_blkcnt = 1, .encrypted_page = NULL, .compressed_page = NULL, .io_type = io_type,
fs/f2fs/data.c +58 -20
190 lines not on this page · raw message
fs/f2fs/f2fs.h +11 -0
@@ -1350,6 +1350,8 @@ struct f2fs_io_info {blk_opf_t op_flags;/* req_flag_bits */ block_t new_blkaddr;/* new block address to be written */ block_t old_blkaddr;/* old block address before Cow */ +pgoff_t folio_offset;/* offset in large folio */ +unsigned int folio_blkcnt;/* block count in large folio */ union {struct page *page;/* page to be written */ struct folio *folio;
@@ -1372,6 +1374,15 @@ struct f2fs_io_info {sector_t *last_block;/* last block number in bio */ }; +#define F2FS_FIO_LBLK (fio) \ + (((fio)->folio)->index + (fio)->folio_offset) +#define F2FS_FIO_BLKCNT (fio) \ + ((fio)->folio_blkcnt) +#define F2FS_FIO_BIO_OFFSET (fio) \ + ((fio)->folio_offset << PAGE_SHIFT) +#define F2FS_FIO_BIO_SIZE (fio) \ + F2FS_BLK_TO_BYTES((fio)->sbi, F2FS_FIO_BLKCNT(fio)) +struct bio_entry {struct bio *bio;struct list_head list;
fs/f2fs/gc.c +3 -0
@@ -1228,6 +1228,7 @@ static int ra_data_block(struct inode *inode, pgoff_t index) .temp = COLD, .op = REQ_OP_READ, .op_flags = 0, + .folio_blkcnt = 1, .encrypted_page = NULL, .in_list = 0, .is_cache = 1,
@@ -1338,6 +1339,7 @@ static int move_data_block(struct inode *inode, block_t bidx, .temp = COLD, .op = REQ_OP_READ, .op_flags = 0, + .folio_blkcnt = 1, .encrypted_page = NULL, .in_list = 0, .is_cache = 1,
@@ -1550,6 +1552,7 @@ static int move_data_page(struct inode *inode, block_t bidx, int gc_type, .op_flags = REQ_SYNC, .old_blkaddr = NULL_ADDR, .folio = folio, + .folio_blkcnt = 1, .encrypted_page = NULL, .need_lock = LOCK_REQ, .io_type = FS_GC_DATA_IO,
fs/f2fs/inline.c +1 -0
@@ -151,6 +151,7 @@ int f2fs_convert_inline_folio(struct dnode_of_data *dn, struct folio *folio) .op = REQ_OP_WRITE, .op_flags = REQ_SYNC | REQ_PRIO, .folio = folio, + .folio_blkcnt = 1, .encrypted_page = NULL, .io_type = FS_DATA_IO, };
fs/f2fs/segment.c +2 -1
@@ -3876,7 +3876,8 @@ static int __get_segment_type_6(struct f2fs_io_info *fio)if (file_is_cold (inode) ||f2fs_need_compress_data (inode))return CURSEG_COLD_DATA ; - type =__get_age_segment_type (inode, fio->folio->index); + type =__get_age_segment_type (inode, +F2FS_FIO_LBLK (fio));if (type !=NO_CHECK_TYPE )return type;
Signature · 1 line
2.43.0
PATCH v6 3/15 f2fs: support regular file buffered writes on large folios
In reply to Nanzhe ZhaoFrom: Nanzhe Zhao <[email protected]>
To avoid the complexity of unlocking a large folio in write_begin, preallocate partial blocks for inodes that can use large folios. During write_begin, read only the partial head and tail 4K subpages that need read-before-write, and skip read I/O for the full middle subpages covered by the write.
--- fs/f2fs/data.c | 431 +++++++++++++++++++++++++++++++++++++++++++++---- fs/f2fs/f2fs.h | 1 + fs/f2fs/file.c | 17 +- 3 files changed, 412 insertions(+), 37 deletions(-)
fs/f2fs/data.c +397 -34
@@ -93,6 +93,20 @@ struct bio_post_read_ctx {block_t fs_blkaddr; }; +static bool __ffs_mark_subrange_uptodate (struct folio *folio, +struct f2fs_folio_state *ffs,size_t offset,size_t len) +{ +unsigned int nr_subpages =folio_nr_pages (folio); +unsigned int start, end; + + start = offset >>PAGE_SHIFT ; + end = (offset + len +PAGE_SIZE -1 ) >>PAGE_SHIFT ; + end =min (end, nr_subpages); + +bitmap_set (ffs->state, start, end - start); +return bitmap_full (ffs->state, nr_subpages); +} +/* * Update and unlock a bio's pages, and free the bio. *
@@ -107,6 +121,23 @@ struct bio_post_read_ctx {* called (i.e., I/O error or decryption error, but *not* verity error), and * release the bio's reference to the decompress_io_ctx of the page's cluster. */ +/* +* Update read_pages_pending. +*/ +static inline void f2fs_update_read_folio_pending (struct folio *folio,int nr) +{ +struct f2fs_folio_state *ffs; +unsigned long flags; + +if (!f2fs_folio_has_ffs (folio)) +return ; + + ffs = (struct f2fs_folio_state *)folio->private; +spin_lock_irqsave (&ffs->state_lock, flags); + ffs->read_pages_pending += nr; +spin_unlock_irqrestore (&ffs->state_lock, flags); +} +static void f2fs_finish_read_bio (struct bio *bio,bool in_task) {struct folio_iter fi;
@@ -128,7 +159,8 @@ static void f2fs_finish_read_bio(struct bio *bio, bool in_task) }if (folio_test_large (folio)) { -struct f2fs_folio_state *ffs = folio->private; +struct f2fs_folio_state *ffs = + (struct f2fs_folio_state *)folio->private;spin_lock_irqsave (&ffs->state_lock, flags); ffs->read_pages_pending -= nr_pages;
@@ -1437,19 +1469,26 @@ static struct bio *f2fs_grab_read_bio(struct inode *inode,/* This can handle encryption stuffs */ static void f2fs_submit_page_read (struct inode *inode,struct fsverity_info *vi, -struct folio *folio,block_t blkaddr, -blk_opf_t op_flags,bool for_write) +struct folio *folio,pgoff_t index, +block_t blkaddr,blk_opf_t op_flags, +bool for_write) {struct f2fs_sb_info *sbi =F2FS_I_SB (inode);struct bio *bio; +size_t offset =0 ; + +if (f2fs_folio_has_ffs (folio)) { + offset =offset_in_folio (folio, (loff_t )index <<PAGE_SHIFT ); +f2fs_update_read_folio_pending (folio,1 ); + } - bio =f2fs_grab_read_bio (inode, vi, blkaddr,1 , op_flags, folio->index, + bio =f2fs_grab_read_bio (inode, vi, blkaddr,1 , op_flags, index, for_write);/* wait for GCed page writeback via generic cache */ f2fs_wait_on_block_writeback (inode, blkaddr); -if (!bio_add_folio (bio, folio,PAGE_SIZE ,0 )) +if (!bio_add_folio (bio, folio,PAGE_SIZE , offset))f2fs_bug_on (sbi,1 );inc_cache_count (sbi,F2FS_RD_DATA );
@@ -1457,6 +1496,40 @@ static void f2fs_submit_page_read(struct inode *inode, struct fsverity_info *vi,f2fs_submit_read_bio (sbi, bio,DATA ); } +/* +* Synchronously read a single 4K subpage by reusing f2fs_submit_page_read() +* so that iostat, trace, blk-crypto and post-read handling are all preserved. +* The caller must have already allocated ffs for the folio. +*/ +static int f2fs_submit_page_read_sync (struct inode *inode,struct folio *folio, +pgoff_t index,block_t blkaddr) +{ +struct f2fs_folio_state *ffs = + (struct f2fs_folio_state *)folio->private; + +/* Add bias so end_io does not call folio_end_read(). */ +f2fs_update_read_folio_pending (folio,1 ); + +/* +* We are holding the folio lock, so use GFP_NOIO for the bio +* allocation to avoid entering mm reclaim. +*/ +f2fs_submit_page_read (inode,NULL , folio, index, blkaddr, +REQ_OP_READ , true); + +/* Wait until all bios have completed (pending drops back to our bias). */ +while (READ_ONCE (ffs->read_pages_pending) !=1 ) +f2fs_io_schedule_timeout (DEFAULT_SCHEDULE_TIMEOUT ); + +/* Remove the bias. */ +f2fs_update_read_folio_pending (folio,-1 ); + +if (!f2fs_ffs_test_blk_uptodate (folio, index)) +return -EIO ; + +return 0 ; +} +static void __set_data_blkaddr (struct dnode_of_data *dn,block_t blkaddr) {__le32 *addr =get_dnode_addr (dn->inode, dn->node_entry);
@@ -1630,8 +1703,8 @@ struct folio *f2fs_get_read_data_folio(struct inode *inode, pgoff_t index,return folio; } -f2fs_submit_page_read (inode,f2fs_need_verity (inode, folio->index), - folio, dn.data_blkaddr, op_flags, for_write); +f2fs_submit_page_read (inode,f2fs_need_verity (inode, index), + folio, index, dn.data_blkaddr, op_flags, for_write);return folio; put_err:
@@ -2793,6 +2866,110 @@ static void ffs_detach_free(struct folio *folio)kfree (ffs); } +bool f2fs_ffs_test_blk_uptodate (const struct folio *folio,pgoff_t index) +{ +struct f2fs_folio_state *ffs; +unsigned int idx; + +f2fs_bug_on (F2FS_F_SB (folio), !folio_contains (folio, index)); + +if (folio_test_uptodate (folio)) +return true; + +if (!f2fs_folio_has_ffs (folio)) +return false; + + ffs = (struct f2fs_folio_state *)folio->private; + idx = index - folio->index; +return test_bit (idx, ffs->state); +} + +static void f2fs_ffs_mark_subrange_uptodate (struct folio *folio,size_t offset, +size_t len) +{ +struct f2fs_folio_state *ffs; +unsigned long flags; +bool mark_uptodate = false; + +f2fs_bug_on (F2FS_F_SB (folio), offset + len >folio_size (folio)); + +if (!f2fs_folio_has_ffs (folio)) { +folio_mark_uptodate (folio); +return ; + } + + ffs = (struct f2fs_folio_state *)folio->private; +spin_lock_irqsave (&ffs->state_lock, flags); + mark_uptodate =__ffs_mark_subrange_uptodate (folio, ffs, offset, len) && + !ffs->read_pages_pending; +spin_unlock_irqrestore (&ffs->state_lock, flags); +if (mark_uptodate) +folio_mark_uptodate (folio); +} + +static unsigned int __ffs_mark_subrange_dirty (struct folio *folio, +struct f2fs_folio_state *ffs,size_t offset,size_t len) +{ +unsigned int nr_subpages =folio_nr_pages (folio); +unsigned int start, end, before; + + start = offset >>PAGE_SHIFT ; + end = (offset + len +PAGE_SIZE -1 ) >>PAGE_SHIFT ; + end =min (end, nr_subpages); + + before =bitmap_weight (ffs->state,2 * nr_subpages); +bitmap_set (ffs->state, nr_subpages + start, end - start); +return bitmap_weight (ffs->state,2 * nr_subpages) - before; +} + +static void f2fs_ffs_mark_subrange_dirty (struct folio *folio, +size_t offset,size_t len) +{ +struct f2fs_folio_state *ffs; +unsigned long flags; + +f2fs_bug_on (F2FS_F_SB (folio), offset + len >folio_size (folio)); + +if (!f2fs_folio_has_ffs (folio)) +return ; + + ffs = (struct f2fs_folio_state *)folio->private; + +spin_lock_irqsave (&ffs->state_lock, flags); +__ffs_mark_subrange_dirty (folio, ffs, offset, len); +spin_unlock_irqrestore (&ffs->state_lock, flags); +} + +static bool find_next_valid_block (const struct folio *folio, +size_t orig_off,size_t *need_off, +size_t len) +{ +size_t start = orig_off; +size_t end = start + len; +size_t head, tail; +pgoff_t index; + +if (start & (PAGE_SIZE -1 )) { + head =round_down (start,PAGE_SIZE ); + index = folio->index + (head >>PAGE_SHIFT ); +if (!f2fs_ffs_test_blk_uptodate (folio, index)) { + *need_off = head; +return true; + } + } + +if (end & (PAGE_SIZE -1 )) { + tail =round_down (end,PAGE_SIZE ); + index = folio->index + (tail >>PAGE_SHIFT ); +if (!f2fs_ffs_test_blk_uptodate (folio, index)) { + *need_off = tail; +return true; + } + } + +return false; +} +static int f2fs_read_data_large_folio (struct inode *inode,struct fsverity_info *vi,struct readahead_control *rac,struct folio *folio)
@@ -4158,6 +4335,151 @@ static int prepare_atomic_write_begin(struct f2fs_sb_info *sbi,return 0 ; } +/* +* Drop the folio lock when a node was changed, then balance the +* filesystem and reacquire the lock. +* +* Return: true if the folio became unusable while unlocked (being +* truncated), false if the folio is still usable. +*/ +static bool f2fs_balance_fs_folio_locked (struct folio *folio, +struct address_space *mapping,bool node_changed) +{ +struct inode *inode = folio->mapping->host; +struct f2fs_sb_info *sbi =F2FS_I_SB (inode); +unsigned int orig_order; +bool had_ffs; + +if (!node_changed ||IS_NOQUOTA (inode) || + !has_not_enough_free_secs (sbi,0 ,0 )) +return false; + + had_ffs =f2fs_folio_has_ffs (folio); + orig_order =folio_order (folio); +folio_unlock (folio); +f2fs_balance_fs (sbi, true); +folio_lock (folio); + +/* +* Writeback may have started on the folio during the unlock +* window, so wait for it before the caller proceeds. +*/ +f2fs_folio_wait_writeback (folio, true, true); + +if (folio->mapping != mapping) +return true; + +if (folio_order (folio) != orig_order) +return true; + +/* large folio was released */ +if (had_ffs && !f2fs_folio_has_ffs (folio)) +return true; + +return false; +} + +static int prepare_large_folio_write_begin (struct inode *inode, +struct folio *folio,loff_t pos, +unsigned int len) +{ +struct f2fs_sb_info *sbi =F2FS_I_SB (inode); +struct f2fs_folio_state *ffs; +size_t ori_off =offset_in_folio (folio, pos); +size_t need_off = ori_off; +int err =0 ; + +/* +* when the write did not come through f2fs_write_iter, we preallocate all +* blocks in the write range here. +*/ +if (!is_inode_flag_set (inode,FI_PREALLOCATED_ALL ) && + !IS_DEVICE_ALIASING (inode)) { +pgoff_t first =F2FS_BYTES_TO_BLK (sbi, pos); +pgoff_t last =F2FS_BLK_ALIGN (sbi, pos + len); +pgoff_t idx; + +for (idx = first; idx < last; idx++) { +block_t blkaddr =NULL_ADDR ; +bool node_changed = false; + + err =__reserve_data_block (inode, idx, &blkaddr, + &node_changed); +if (err) +return err; +if (f2fs_balance_fs_folio_locked (folio, folio->mapping, + node_changed)) +return -EAGAIN ; + } + } + + ffs =f2fs_ffs_find_or_alloc (folio); +if (!ffs) +return -ENOMEM ; + +/* Skip read if the folio is already fully uptodate or the write +* covers the entire folio. +*/ +if (folio_test_uptodate (folio) || len ==folio_size (folio)) +return 0 ; + +if (!f2fs_verity_in_progress (inode) && + !(pos & (PAGE_SIZE -1 )) && (pos + len) >=i_size_read (inode)) { +size_t zoff = ori_off + len; + +if (zoff <folio_size (folio)) +folio_zero_segment (folio, zoff,folio_size (folio)); +return 0 ; + } + +/* Inline data must have been converted before reaching here. */ +f2fs_bug_on (sbi,f2fs_has_inline_data (inode)); + +while (find_next_valid_block (folio, ori_off, + &need_off, len)) { +struct dnode_of_data dn; +pgoff_t index = folio->index + (need_off >>PAGE_SHIFT ); +block_t blkaddr; + +if (!f2fs_lookup_read_extent_cache_block (inode, index, + &blkaddr)) { +if (IS_DEVICE_ALIASING (inode)) +return -ENODATA ; + +set_new_dnode (&dn, inode,NULL ,NULL ,0 ); + err =f2fs_get_dnode_of_data (&dn, index,LOOKUP_NODE ); +if (err) +return err; + blkaddr = dn.data_blkaddr; +f2fs_put_dnode (&dn); + +if (blkaddr ==NEW_ADDR ) { +size_t off =offset_in_folio (folio, + (loff_t )index <<PAGE_SHIFT ); + +folio_zero_segment (folio, off, off +PAGE_SIZE ); +f2fs_ffs_mark_subrange_uptodate (folio, off, +PAGE_SIZE ); +continue ; + } + } + +/* +* The read extent cache only validates the first and last +* block of i_ext, so check both the cached and dnode paths. +*/ +if (!f2fs_is_valid_blkaddr (sbi, blkaddr, +DATA_GENERIC_ENHANCE_READ )) +return -EFSCORRUPTED ; + + err =f2fs_submit_page_read_sync (inode, folio, index, blkaddr); +if (err) +return err; + } + +return 0 ; +} + static int f2fs_write_begin(const struct kiocb *iocb, struct address_space *mapping, loff_t pos, unsigned len, struct folio **foliop,
@@ -4169,6 +4491,8 @@ static int f2fs_write_begin(const struct kiocb *iocb,pgoff_t index = pos >>PAGE_SHIFT ;bool need_balance = false;block_t blkaddr =NULL_ADDR ; +fgf_t fgp =FGP_LOCK |FGP_WRITE |FGP_CREAT ; +unsigned int blen;int err =0 ;trace_f2fs_write_begin (inode, pos, len);
@@ -4216,9 +4540,15 @@ static int f2fs_write_begin(const struct kiocb *iocb,* Do not use FGP_STABLE to avoid deadlock. * Will wait that below with our IO control. */ - folio =f2fs_filemap_get_folio (mapping, index, -FGP_LOCK |FGP_WRITE |FGP_CREAT , -mapping_gfp_mask (mapping)); +/* +* Inline data is carried in the first subpage. Keep the index #0 +* folio order-0 so that the existing inline read/convert paths +* (prepare_write_begin()) still apply; large folios are used from +* the second folio on. +*/ + fgp |=fgf_set_order (f2fs_has_inline_data (inode) ?PAGE_SIZE : len); + folio =f2fs_filemap_get_folio (mapping, index, fgp, +mapping_gfp_mask (mapping));if (IS_ERR (folio)) { err =PTR_ERR (folio); goto fail;
@@ -4228,31 +4558,42 @@ static int f2fs_write_begin(const struct kiocb *iocb, *foliop = folio; +/* Clamp the write length to the folio size. */ + blen = min_t(unsigned int, len, +folio_size (folio) -offset_in_folio (folio, pos)); + +/* +* Flush the cached IO of this folio before touching it, especially +* for the large folio prepare below which reads and updates subpage +* states. +*/ +f2fs_folio_wait_writeback (folio, false, true); +if (f2fs_is_atomic_file (inode)) err =prepare_atomic_write_begin (sbi, folio, pos, len, &blkaddr, &need_balance); -else - err =prepare_write_begin (sbi, folio, pos, len, +else if (!folio_test_large (folio)) + err =prepare_write_begin (sbi, folio, pos, blen, &blkaddr, &need_balance); -if (err) - goto put_folio; - -if (need_balance && !IS_NOQUOTA (inode) && -has_not_enough_free_secs (sbi,0 ,0 )) { -folio_unlock (folio); -f2fs_balance_fs (sbi, true); -folio_lock (folio); -if (folio->mapping != mapping) { -/* The folio got truncated from under us */ -folio_unlock (folio); -folio_put (folio); +else + err =prepare_large_folio_write_begin (inode, folio, pos, blen); +if (err) { +if (err == -EAGAIN ) { +f2fs_folio_put (folio, true); goto repeat; } + goto put_folio; } -f2fs_folio_wait_writeback (folio, false, true); +if (f2fs_balance_fs_folio_locked (folio, mapping, need_balance)) { +f2fs_folio_put (folio, true); + goto repeat; + } + +if (folio_test_large (folio)) +return 0 ; -if (len ==folio_size (folio) ||folio_test_uptodate (folio)) +if (blen ==folio_size (folio) ||folio_test_uptodate (folio))return 0 ; if (!(pos & (PAGE_SIZE - 1)) && (pos + len) >= i_size_read(inode) &&
@@ -4280,7 +4621,7 @@ static int f2fs_write_begin(const struct kiocb *iocb,*/ f2fs_submit_page_read (inode,NULL ,/* can't write to fsverity files */ - folio, blkaddr,0 , true); + folio, index, blkaddr,0 , true);folio_lock (folio);if (unlikely (folio->mapping != mapping)) {
@@ -4312,15 +4653,20 @@ static int f2fs_write_end(const struct kiocb *iocb,trace_f2fs_write_end (inode, pos, len, copied);/* -* This should be come from len == PAGE_SIZE, and we expect copied -* should be PAGE_SIZE. Otherwise, we treat it with zero copied and -* let generic_perform_write() try to copy data again through copied=0. +* If a short copy happens on a folio that isn't uptodate, we treat +* it with zero copied and let generic_perform_write() try to copy +* data again through copied=0. */ if (!folio_test_uptodate (folio)) { -if (unlikely (copied != len)) +if (unlikely (copied != len)) { copied =0 ; -else + }else if (folio_test_large (folio)) { +f2fs_ffs_mark_subrange_uptodate (folio, +offset_in_folio (folio, pos), len); + }else { +/* This should be come from len == PAGE_SIZE */ folio_mark_uptodate (folio); + } }#ifdef CONFIG_F2FS_FS_COMPRESSION
@@ -4339,6 +4685,9 @@ static int f2fs_write_end(const struct kiocb *iocb,if (!copied) goto unlock_out; +if (folio_test_large (folio)) +f2fs_ffs_mark_subrange_dirty (folio,offset_in_folio (folio, pos), + copied);folio_mark_dirty (folio);if (f2fs_is_atomic_file (inode))
@@ -4395,8 +4744,22 @@ static bool f2fs_dirty_data_folio(struct address_space *mapping,trace_f2fs_set_page_dirty (folio,DATA ); -if (!folio_test_uptodate (folio)) -folio_mark_uptodate (folio); +if (!folio_test_uptodate (folio)) { +bool uptodate = true; + +if (f2fs_folio_has_ffs (folio)) { +struct f2fs_folio_state *ffs = + (struct f2fs_folio_state *)folio->private; +unsigned long flags; + +spin_lock_irqsave (&ffs->state_lock, flags); + uptodate =bitmap_full (ffs->state,folio_nr_pages (folio)) && + !ffs->read_pages_pending; +spin_unlock_irqrestore (&ffs->state_lock, flags); + } +if (uptodate) +folio_mark_uptodate (folio); + }BUG_ON (folio_test_swapcache (folio));if (filemap_dirty_folio (mapping, folio)) {
fs/f2fs/f2fs.h +1 -0
@@ -4454,6 +4454,7 @@ int f2fs_write_single_data_page(struct folio *folio, int *submitted,struct writeback_control *wbc, enum iostat_type io_type, int compr_blocks, bool allow_balance); +bool f2fs_ffs_test_blk_uptodate (const struct folio *folio,pgoff_t index);void f2fs_write_failed (struct inode *inode,loff_t to);void f2fs_invalidate_folio (struct folio *folio,size_t offset,size_t length);bool f2fs_release_folio (struct folio *folio,gfp_t wait);
fs/f2fs/file.c +14 -3
@@ -5420,9 +5420,20 @@ static int f2fs_preallocate_blocks(struct kiocb *iocb, struct iov_iter *iter,return ret; } -/* Do not preallocate blocks that will be written partially in 4KB. */ - map.m_lblk =F2FS_BLK_ALIGN (sbi, pos); - map.m_len =F2FS_BYTES_TO_BLK (sbi, pos + count); +if (!dio &&mapping_large_folio_support (inode->i_mapping)) { +/* +* Preallocate all blocks touched by a large-folio buffered write so +* the regular write_begin path does not need to unlock the folio for +* f2fs_balance_fs(). Rechecking large-folio state after unlock is +* unreliable since partial truncation can split the folio. +*/ + map.m_lblk =F2FS_BYTES_TO_BLK (sbi, pos); + map.m_len =F2FS_BLK_ALIGN (sbi, pos + count); + }else { +/* Do not preallocate blocks that will be written partially in 4KB. */ + map.m_lblk =F2FS_BLK_ALIGN (sbi, pos); + map.m_len =F2FS_BYTES_TO_BLK (sbi, pos + count); + }if (map.m_len > map.m_lblk) map.m_len -= map.m_lblk;else
Signature · 1 line
2.43.0
PATCH v6 4/15 f2fs: support atomic file large folios buffered write
In reply to Nanzhe ZhaoFrom: Nanzhe Zhao <[email protected]>
ioctl can convert an inode with large folio support into an atomic file. Support large folio buffered writes for atomic files as well.
Add a large folio atomic write_begin helper that reserves COW mappings for the write range. For partial head and tail subpages, read the existing data from either the COW inode or the original inode before marking the subpage uptodate.
--- fs/f2fs/data.c | 70 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 63 insertions(+), 7 deletions(-)
fs/f2fs/data.c +63 -7
@@ -4287,18 +4287,16 @@ static int __reserve_data_block(struct inode *inode, pgoff_t index, }static int prepare_atomic_write_begin (struct f2fs_sb_info *sbi, -struct folio *folio,loff_t pos,unsigned int len, +struct inode *inode,pgoff_t index,block_t *blk_addr,bool *node_changed) { -struct inode *inode = folio->mapping->host;struct inode *cow_inode =F2FS_I (inode)->cow_inode; -pgoff_t index = folio->index;int err =0 ;block_t ori_blk_addr =NULL_ADDR ;bool cow_has_reserved_block = false; -/* If pos is beyond the end of file, reserve a new block in COW inode */ -if ((pos &PAGE_MASK ) >=i_size_read (inode)) +/* If index is beyond the end of file, reserve a new block in COW inode */ +if (((loff_t )index <<PAGE_SHIFT ) >=i_size_read (inode)) goto reserve_block;/* Look for the block in COW inode first */
@@ -4480,6 +4478,61 @@ static int prepare_large_folio_write_begin(struct inode *inode,return 0 ; } +static int prepare_large_folio_atomic_write_begin (struct inode *inode, +struct address_space *mapping,struct folio *folio,loff_t pos, +unsigned int len) +{ +struct f2fs_sb_info *sbi =F2FS_I_SB (inode); +size_t ori_off =offset_in_folio (folio, pos); +pgoff_t start, end, index; +int err =0 ; + + len = min_t(unsigned int, len, folio_size(folio) - ori_off); + +if (!f2fs_ffs_find_or_alloc (folio)) +return -ENOMEM ; + +/* Inline data must have been converted before reaching here. */ +f2fs_bug_on (sbi,f2fs_has_inline_data (inode)); + + start = folio->index + (ori_off >>PAGE_SHIFT ); + end = folio->index + ((ori_off + len -1 ) >>PAGE_SHIFT ); + +for (index = start; index <= end; index++) { +block_t blkaddr =NULL_ADDR ; +bool node_changed = false; +size_t off = (index - folio->index) <<PAGE_SHIFT ; + + err =prepare_atomic_write_begin (sbi, inode, index, + &blkaddr, &node_changed); +if (err) +return err; + +if (f2fs_ffs_test_blk_uptodate (folio, index)) + goto balance; + +if (blkaddr ==NEW_ADDR ) { +folio_zero_segment (folio, off, off +PAGE_SIZE ); +f2fs_ffs_mark_subrange_uptodate (folio, off,PAGE_SIZE ); + goto balance; + } + +if (!f2fs_is_valid_blkaddr (sbi, blkaddr, +DATA_GENERIC_ENHANCE_READ )) +return -EFSCORRUPTED ; + + err =f2fs_submit_page_read_sync (inode, folio, index, + blkaddr); +if (err) +return err; +balance: +if (f2fs_balance_fs_folio_locked (folio, mapping, node_changed)) +return -EAGAIN ; + } + +return 0 ; +} + static int f2fs_write_begin(const struct kiocb *iocb, struct address_space *mapping, loff_t pos, unsigned len, struct folio **foliop,
@@ -4569,12 +4622,15 @@ static int f2fs_write_begin(const struct kiocb *iocb,*/ f2fs_folio_wait_writeback (folio, false, true); -if (f2fs_is_atomic_file (inode)) - err =prepare_atomic_write_begin (sbi, folio, pos, len, +if (f2fs_is_atomic_file (inode) && !folio_test_large (folio)) + err =prepare_atomic_write_begin (sbi, inode, folio->index, &blkaddr, &need_balance);else if (!folio_test_large (folio)) err =prepare_write_begin (sbi, folio, pos, blen, &blkaddr, &need_balance); +else if (f2fs_is_atomic_file (inode)) + err =prepare_large_folio_atomic_write_begin (inode, + mapping, folio, pos, len);else err =prepare_large_folio_write_begin (inode, folio, pos, blen);if (err) {
Signature · 1 line
2.43.0
PATCH v6 5/15 f2fs: support large folio writeback
In reply to Nanzhe ZhaoFrom: Nanzhe Zhao <[email protected]>
Large folio can contain multiple dirty ranges.
Add a folio-based writeback path for large-folio mapping files and keep the legacy f2fs_write_cache_pages() path unchanged for non large-folio mapping files.
--- fs/f2fs/data.c | 521 +++++++++++++++++++++++++++++++++++++++++++++- fs/f2fs/segment.c | 8 +- 2 files changed, 521 insertions(+), 8 deletions(-)
fs/f2fs/data.c +514 -7
@@ -358,6 +358,49 @@ static void f2fs_cache_write_end_bio(struct bio *bio)bio_put (bio); } +static bool f2fs_ffs_has_dirty_subpage (struct folio *folio) +{ +struct f2fs_folio_state *ffs; +unsigned long flags; +unsigned int nr_subpages; +bool dirty; + +if (!f2fs_folio_has_ffs (folio)) +return false; + + ffs = (struct f2fs_folio_state *)folio->private; + nr_subpages =folio_nr_pages (folio); + +spin_lock_irqsave (&ffs->state_lock, flags); + dirty =find_next_bit (ffs->state,2 * nr_subpages, + nr_subpages) <2 * nr_subpages; +spin_unlock_irqrestore (&ffs->state_lock, flags); + +return dirty; +} + +/* +* Drop a write page pending of @folio. When the last pending is gone, +* clear PAGE_PRIVATE_GCING if no dirty subpage is left, and end +* writeback if it was started. +*/ +static void f2fs_ffs_put_write_pending (struct folio *folio,unsigned int nr) +{ +struct f2fs_folio_state *ffs; + +if (!f2fs_folio_has_ffs (folio)) + goto release; + + ffs = (struct f2fs_folio_state *)folio->private; +if (!atomic_sub_and_test (nr, &ffs->write_pages_pending)) +return ; +release: +if (!f2fs_ffs_has_dirty_subpage (folio)) +folio_clear_f2fs_gcing (folio); +if (folio_test_writeback (folio)) +folio_end_writeback (folio); +} +static void f2fs_write_end_bio (struct bio *bio) {struct f2fs_sb_info *sbi = bio->bi_private;
@@ -373,6 +416,8 @@ static void f2fs_write_end_bio(struct bio *bio)bio_for_each_folio_all (fi, bio) {struct folio *folio = fi.folio; +unsigned int nr_pages = fi.length >>PAGE_SHIFT ; +unsigned int npages = nr_pages;enum count_type type;#ifdef CONFIG_F2FS_FS_COMPRESSION
@@ -392,7 +437,8 @@ static void f2fs_write_end_bio(struct bio *bio) } } -dec_cache_count (sbi, type); +while (nr_pages--) +dec_cache_count (sbi, type);/* * we should access sbi before folio_end_writeback() to
@@ -402,8 +448,7 @@ static void f2fs_write_end_bio(struct bio *bio) wq_has_sleeper(&sbi->cp_wait))wake_up (&sbi->cp_wait); -folio_clear_f2fs_gcing (folio); -folio_end_writeback (folio); +f2fs_ffs_put_write_pending (folio, npages); }bio_put (bio);
@@ -2922,7 +2967,7 @@ static unsigned int __ffs_mark_subrange_dirty(struct folio *folio,return bitmap_weight (ffs->state,2 * nr_subpages) - before; } -static void f2fs_ffs_mark_subrange_dirty (struct folio *folio, +void f2fs_ffs_mark_subrange_dirty (struct folio *folio,size_t offset,size_t len) {struct f2fs_folio_state *ffs;
@@ -2940,6 +2985,99 @@ static void f2fs_ffs_mark_subrange_dirty(struct folio *folio,spin_unlock_irqrestore (&ffs->state_lock, flags); } +static bool __ffs_clear_subrange_dirty (struct folio *folio, +struct f2fs_folio_state *ffs,size_t offset,size_t len) +{ +unsigned int nr_subpages =folio_nr_pages (folio); +unsigned int start, end; + + start = offset >>PAGE_SHIFT ; + end = (offset + len +PAGE_SIZE -1 ) >>PAGE_SHIFT ; + end =min (end, nr_subpages); + +bitmap_clear (ffs->state, nr_subpages + start, end - start); +return find_next_bit (ffs->state,2 * nr_subpages, nr_subpages) < +2 * nr_subpages; +} + +/** +* f2fs_ffs_clear_subrange_dirty_and_test - clear dirty bits and test remaining +* @folio: the large folio +* @offset: start byte offset within the folio +* @len: byte length of the subrange +* +* Clear the dirty bits of the 4K subpages covered by [offset, offset + len), +* and return whether the folio still has any dirty subpage left. +*/ +bool f2fs_ffs_clear_subrange_dirty_and_test (struct folio *folio,size_t offset, +size_t len) +{ +struct f2fs_folio_state *ffs; +unsigned long flags; +bool dirty; + +if (!f2fs_folio_has_ffs (folio)) +return false; + + ffs = (struct f2fs_folio_state *)folio->private; +spin_lock_irqsave (&ffs->state_lock, flags); + dirty =__ffs_clear_subrange_dirty (folio, ffs, offset, len); +spin_unlock_irqrestore (&ffs->state_lock, flags); + +return dirty; +} + +static unsigned int ffs_next_dirty_subpage (struct f2fs_folio_state *ffs, +const struct folio *folio,unsigned int start, +unsigned int end) +{ +unsigned int nr_subpages =folio_nr_pages (folio); + +return find_next_bit (ffs->state, nr_subpages + end +1 , + nr_subpages + start) - nr_subpages; +} + +static unsigned int ffs_next_clean_subpage (struct f2fs_folio_state *ffs, +const struct folio *folio,unsigned int start, +unsigned int end) +{ +unsigned int nr_subpages =folio_nr_pages (folio); + +return find_next_zero_bit (ffs->state, nr_subpages + end +1 , + nr_subpages + start) - nr_subpages; +} + +static unsigned int ffs_find_dirty_range (struct folio *folio, +u64 *range_start,u64 range_end) +{ +struct f2fs_folio_state *ffs; +unsigned int start, end, nr_pages; + +if (*range_start >= range_end) +return 0 ; + +if (!f2fs_folio_has_ffs (folio)) +return range_end - *range_start; + + ffs = (struct f2fs_folio_state *)folio->private; + start =offset_in_folio (folio, *range_start) >>PAGE_SHIFT ; + end =DIV_ROUND_UP (min_not_zero (offset_in_folio (folio, range_end), +folio_size (folio)),PAGE_SIZE ) -1 ; + + start =ffs_next_dirty_subpage (ffs, folio, start, end); +if (start > end) +return 0 ; + +if (start == end) + nr_pages =1 ; +else + nr_pages =ffs_next_clean_subpage (ffs, folio, + start +1 , end) - start; + + *range_start =folio_pos (folio) + ((u64 )start <<PAGE_SHIFT ); +return (u64 )nr_pages <<PAGE_SHIFT ; +} +static bool find_next_valid_block (const struct folio *folio,size_t orig_off,size_t *need_off,size_t len)
@@ -3477,7 +3615,7 @@ int f2fs_do_write_data_page(struct f2fs_io_info *fio)if (ipu_force || (__is_valid_data_blkaddr (fio->old_blkaddr) &&need_inplace_update (fio))) { -folio_start_writeback (folio); +__folio_start_writeback (folio,folio_test_dirty (folio));f2fs_put_dnode (&dn);if (fio->need_lock ==LOCK_REQ )f2fs_unlock_op (fio->sbi, &lc);
@@ -3504,7 +3642,7 @@ int f2fs_do_write_data_page(struct f2fs_io_info *fio) fio->version = ni.version; -folio_start_writeback (folio); +__folio_start_writeback (folio,folio_test_dirty (folio));if (fio->compr_blocks && fio->old_blkaddr ==COMPRESS_ADDR )f2fs_i_compr_blocks_update (inode, fio->compr_blocks -1 , false);
@@ -3512,6 +3650,13 @@ int f2fs_do_write_data_page(struct f2fs_io_info *fio)/* LFS mode write path */ f2fs_outplace_write_data (&dn, fio);trace_f2fs_do_write_data_page (folio,OPU ); +/* +* The outplace write path failed to submit this block. +*/ +if (!fio->submitted) { + err = -EIO ; + goto out_writepage; + }set_inode_flag (inode,FI_APPEND_WRITE );if (atomic_commit)folio_clear_f2fs_atomic (folio);
@@ -3523,6 +3668,144 @@ int f2fs_do_write_data_page(struct f2fs_io_info *fio)return err; } +static int f2fs_write_folio_dirty_range (struct folio *folio,int *submitted, +struct writeback_control *wbc, +enum iostat_type io_type, +u64 *pos,u64 len) +{ +struct inode *inode = folio->mapping->host; +struct f2fs_sb_info *sbi =F2FS_I_SB (inode); +bool atomic_commit =f2fs_is_atomic_file (inode) && +folio_test_f2fs_atomic (folio); +struct inode *dn_inode = atomic_commit ? +F2FS_I (inode)->cow_inode : inode; +struct f2fs_folio_state *ffs =NULL ; +u64 folio_start =folio_pos (folio); +pgoff_t start_idx = (*pos - folio_start) >>PAGE_SHIFT ; +pgoff_t end_idx = (*pos - folio_start + len -1 ) >>PAGE_SHIFT ; +int err =0 ; + +for (pgoff_t i = start_idx; i <= end_idx && !err; i++) { +struct dnode_of_data dn; +struct node_info ni; +pgoff_t data_idx = folio->index + i; +bool ipu_force = false; +bool dn_held = false; +bool submitted_blk = false; +struct f2fs_io_info fio = { + .sbi = sbi, + .ino = inode->i_ino, + .type =DATA , + .op =REQ_OP_WRITE , + .op_flags =wbc_to_write_flags (wbc), + .old_blkaddr =NULL_ADDR , + .folio = folio, + .folio_offset = i, + .folio_blkcnt =1 , + .encrypted_page =NULL , + .submitted =0 , + .need_lock =LOCK_DONE , + .meta_gc =f2fs_meta_inode_gc_required (inode) ?1 :0 , + .io_type = io_type, + .io_wbc = wbc, + }; + +if (f2fs_folio_has_ffs (folio)) { + ffs = (struct f2fs_folio_state *)folio->private; +atomic_inc (&ffs->write_pages_pending); + } + +set_new_dnode (&dn, dn_inode,NULL ,NULL ,0 ); + +if (need_inplace_update (&fio) && +f2fs_lookup_read_extent_cache_block (inode, data_idx, + &fio.old_blkaddr)) { +if (!f2fs_is_valid_blkaddr (sbi, fio.old_blkaddr, +DATA_GENERIC_ENHANCE )) { + err = -EFSCORRUPTED ; + goto block_done; + } + ipu_force = true; + goto got_it; + } + + err =f2fs_get_dnode_of_data (&dn, data_idx,LOOKUP_NODE ); +if (err) + goto block_done; + dn_held = true; + + fio.old_blkaddr = dn.data_blkaddr; + +got_it: +if (__is_valid_data_blkaddr (fio.old_blkaddr) && + !f2fs_is_valid_blkaddr (sbi, fio.old_blkaddr, +DATA_GENERIC_ENHANCE )) { + err = -EFSCORRUPTED ; + goto block_done; + } + +if (fio.meta_gc) +f2fs_wait_on_block_writeback (inode, fio.old_blkaddr); + +if (ipu_force || + (__is_valid_data_blkaddr (fio.old_blkaddr) && +need_inplace_update (&fio))) { +f2fs_put_dnode (&dn); + dn_held = false; + err =f2fs_inplace_write_data (&fio); +trace_f2fs_do_write_data_page (folio,IPU ); +if (err) + goto block_done; + +if (submitted) + (*submitted)++; + submitted_blk = true; +set_inode_flag (inode,FI_UPDATE_WRITE ); + goto block_done; + } + + err =f2fs_get_node_info (sbi, dn.nid, &ni, false); +if (err) + goto block_done; + + fio.version = ni.version; + +f2fs_outplace_write_data (&dn, &fio); +/* +* The outplace write path failed to submit this block. +*/ +if (!fio.submitted) { + err = -EIO ; + goto block_done; + } +if (submitted) + (*submitted)++; + submitted_blk = true; +set_inode_flag (inode,FI_APPEND_WRITE ); +trace_f2fs_do_write_data_page (folio,OPU ); +block_done: +if (dn_held) +f2fs_put_dnode (&dn); +/* +* If this block was not submitted, roll back its +* write pages pending. +*/ +if (!submitted_blk && ffs) +f2fs_ffs_put_write_pending (folio,1 ); +if (!err) { + *pos = ((loff_t )data_idx +1 ) <<PAGE_SHIFT ; +spin_lock (&F2FS_I (inode)->i_size_lock); +if (F2FS_I (inode)->last_disk_size < *pos) +F2FS_I (inode)->last_disk_size = *pos; +spin_unlock (&F2FS_I (inode)->i_size_lock); + }else { +file_set_keep_isize (inode); + } + } + +return err; +} + int f2fs_write_single_data_page(struct folio *folio, int *submitted, struct bio **bio, sector_t *last_block,
@@ -3972,6 +4255,226 @@ static int f2fs_write_cache_pages(struct address_space *mapping,return ret; } +static int f2fs_write_cache_folios (struct address_space *mapping, +struct writeback_control *wbc, +enum iostat_type io_type) +{ +struct folio *folio =NULL ; +struct inode *inode = mapping->host; +struct f2fs_sb_info *sbi =F2FS_I_SB (inode); +struct f2fs_lock_context lc; +u64 pos =0 ; +u64 end_pos =0 ; +u32 r_len =0 ; +int err =0 ; +int submitted =0 ; +int nwritten =0 ; +bool op_locked = false; +bool retry = false; + +if (get_dirty_pages (inode) <=SM_I (sbi)->min_hot_blocks) +set_inode_flag (inode,FI_HOT_DATA ); +else +clear_inode_flag (inode,FI_HOT_DATA ); + +while ((folio =writeback_iter (mapping, wbc, folio, &err))) { +struct f2fs_folio_state *ffs =NULL ; +u64 isize; +size_t poff; +pgoff_t end_index; +bool verity_in_progress; +int folio_submitted =0 ; +bool bias_added = false; + + submitted =0 ; + retry = false; + +if (err) { +folio_redirty_for_writepage (wbc, folio); + goto retry_out; + } + +if (atomic_read (&sbi->wb_sync_req[DATA ]) && + wbc->sync_mode ==WB_SYNC_NONE ) { +folio_redirty_for_writepage (wbc, folio); +/* +* A WB_SYNC_ALL writeback is in progress, so defer +* this writeback. Mark the error as -EBUSY to let +* writeback_iter() stop iterating. +*/ + err = -EBUSY ; + goto retry_out; + } + +/* +* If cp_error is set, all subpages of this folio are not written +* back unless the filesystem is mounted with errors=remount-ro. +*/ +if (unlikely (f2fs_cp_error (sbi))) { +mapping_set_error (folio->mapping, -EIO ); +if (F2FS_OPTION (sbi).errors ==MOUNT_ERRORS_READONLY ) { +folio_redirty_for_writepage (wbc, folio); + }else { +if (f2fs_folio_has_ffs (folio)) +f2fs_ffs_clear_subrange_dirty_and_test (folio,0 , +folio_size (folio)); +inode_dec_dirty_pages (inode); + } + goto retry_out; + } + +/* +* Writing back one large folio performs multiple block allocations, so +* best-effort balance the filesystem before writing it back. +*/ +if (!F2FS_I (inode)->wb_task &&has_not_enough_free_secs (sbi,0 ,0 )) { +folio_redirty_for_writepage (wbc, folio); + retry = true; +folio_unlock (folio); +f2fs_balance_fs (sbi, true); +folio_lock (folio); + goto retry; + } +retry: + pos =folio_pos (folio); + end_pos = pos +folio_size (folio); + isize =i_size_read (inode); + verity_in_progress =f2fs_verity_in_progress (inode); + poff =0 ; + end_index =0 ; + +if (retry) { + +if (unlikely (folio->mapping != mapping)) + goto retry_out; + +if (!folio_test_dirty (folio)) + goto retry_out; + +if (folio_test_writeback (folio)) { +if (wbc->sync_mode ==WB_SYNC_NONE ) + goto retry_out; +f2fs_folio_wait_writeback (folio, true, true); + } + +if (!folio_clear_dirty_for_io (folio)) + goto retry_out; + } + +/* To avoid dealing with the complexity for one subrange is in bio +* while we trylock_op failed before writing another subrange. +* Try to lock_op before any subrange write for the folio. +*/ +if (!op_locked) { +if (!f2fs_trylock_op (sbi, &lc)) { +folio_redirty_for_writepage (wbc, folio); + err =0 ; +if (wbc->sync_mode !=WB_SYNC_ALL ) + goto retry_out; + + retry = true; +folio_unlock (folio); +f2fs_io_schedule_timeout (DEFAULT_SCHEDULE_TIMEOUT ); +folio_lock (folio); + goto retry; + } + op_locked = true; + } + +if (!verity_in_progress) { + poff =offset_in_folio (folio, isize); + end_index = isize >>PAGE_SHIFT ; + +if (folio->index > end_index || + (folio->index == end_index && poff ==0 )) + goto out; + +if (end_pos > isize) { +folio_zero_segment (folio, poff,folio_size (folio)); + end_pos = isize; + } + } + +folio_start_writeback (folio); + +/* +* Large folios can be submitted as multiple bios, which may +* complete while we are still submitting the remaining dirty +* ranges. Hold a bias on write_pages_pending to prevent +* folio_end_writeback() from being called early. +*/ +if (!bias_added &&f2fs_folio_has_ffs (folio)) { + ffs = (struct f2fs_folio_state *)folio->private; +WARN_ON_ONCE (atomic_read (&ffs->write_pages_pending) !=0 ); +atomic_inc (&ffs->write_pages_pending); + bias_added = true; + } + +while ((r_len =ffs_find_dirty_range (folio, &pos, end_pos))) { + err =f2fs_write_folio_dirty_range (folio, &submitted, + wbc, io_type, &pos, r_len); + folio_submitted += submitted; + nwritten += submitted; +if (err) + goto out; + } + +/* If none of the subpages of a folio is submitted, keep the atomic flag */ +if (folio_submitted && +f2fs_is_atomic_file (inode) && +folio_test_f2fs_atomic (folio)) +folio_clear_f2fs_atomic (folio); + +out: +/* +* Clear the dirty state of the subranges that were written back. +* If some subranges are still dirty (e.g. the folio was only +* partially written back), or if the writeback failed, the +* folio must stay dirty so that the remaining subranges are +* written back later. +*/ +if (f2fs_ffs_clear_subrange_dirty_and_test (folio,0 , + (err ? pos : end_pos) -folio_pos (folio)) || err) +folio_redirty_for_writepage (wbc, folio); +else +inode_dec_dirty_pages (inode); + +/* +* Release the bias taken above and we end writeback here if +* no write bio is in flight. +*/ +if (bias_added) { +f2fs_ffs_put_write_pending (folio,1 ); + }else if (!folio_submitted &&folio_test_writeback (folio)) { +/* +* Order-0 folios take no bias, so end the writeback +* if nothing was submitted. +*/ +folio_end_writeback (folio); + } + +retry_out: +if (op_locked) { +f2fs_unlock_op (sbi, &lc); + op_locked = false; + } + +folio_unlock (folio); + } + +if (nwritten) +f2fs_submit_merged_write_cond (F2FS_M_SB (mapping), mapping->host, +NULL ); + +/* +* Prevent the -EBUSY error that stopped writeback_iter() from +* propagating to the user. +*/ +if (err == -EBUSY ) + err =0 ; +return err; +} +static inline bool __should_serialize_io (struct inode *inode,struct writeback_control *wbc) {
@@ -4066,7 +4569,11 @@ static int __f2fs_write_data_pages(struct address_space *mapping,account_writeback (inode, true);blk_start_plug (&plug); - ret =f2fs_write_cache_pages (mapping, wbc, io_type); +if (mapping_large_folio_support (inode->i_mapping) && + !f2fs_has_inline_data (inode)) + ret =f2fs_write_cache_folios (mapping, wbc, io_type); +else + ret =f2fs_write_cache_pages (mapping, wbc, io_type);blk_finish_plug (&plug);account_writeback (inode, false);
fs/f2fs/segment.c +7 -1
@@ -4173,7 +4173,13 @@ static void do_write_block(struct f2fs_summary *sum, struct f2fs_io_info *fio)"%s Failed to allocate data block, ino:%u, index:%lu, type:%d, old_blkaddr:0x%x, new_blkaddr:0x%x, err:%d" , __func__, fio->ino, folio->index, type, fio->old_blkaddr, fio->new_blkaddr, err); -folio_end_writeback (folio); +/* +* For a large folio, the caller rolls back +* write_pages_pending and ends writeback when the last +* pending write is gone. +*/ +if (!f2fs_folio_has_ffs (folio)) +folio_end_writeback (folio); }f2fs_bug_on (fio->sbi, !is_set_ckpt_flags (fio->sbi,CP_ERROR_FLAG ));
Signature · 1 line
2.43.0
PATCH v6 6/15 f2fs: account large folio dirty data at block granularity
In reply to Nanzhe ZhaoFrom: Nanzhe Zhao <[email protected]>
Originally inode->dirty_pages was accounted once per folio, but f2fs needs the counter to be accounted in blocks.
This introduces batch dirty page add/sub accounting; for a large folio the changed dirty page count is computed from the dirty bitmap bit changes.
Found by f2fs/006 (lfs + checkpoint=disable) and generic/363.
--- fs/f2fs/checkpoint.c | 38 ++++++++++++++++++++++---- fs/f2fs/compress.c | 4 +-- fs/f2fs/data.c | 50 +++++++++++++++++++++++----------- fs/f2fs/dir.c | 2 +- fs/f2fs/f2fs.h | 65 ++++++++++++++++++++++++++++++++++---------- fs/f2fs/gc.c | 2 +- fs/f2fs/inline.c | 2 +- fs/f2fs/node.c | 2 +- 8 files changed, 123 insertions(+), 42 deletions(-)
fs/f2fs/checkpoint.c +32 -6
@@ -1324,20 +1324,46 @@ static void __remove_dirty_inode(struct inode *inode, enum inode_type type)stat_dec_dirty_inode (F2FS_I_SB (inode), type); } -void f2fs_update_dirty_folio (struct inode *inode,struct folio *folio) +/* +* Account @nr dirty pages (negative when dirtiness is cleared) for @inode. +*/ +void f2fs_account_dirty_blocks (struct inode *inode,int nr) {struct f2fs_sb_info *sbi =F2FS_I_SB (inode);enum inode_type type =S_ISDIR (inode->i_mode) ?DIR_INODE :FILE_INODE ; -if (!S_ISDIR (inode->i_mode) && !S_ISREG (inode->i_mode) && - !S_ISLNK (inode->i_mode)) +if (!nr)return ;spin_lock (&sbi->inode_lock[type]); -if (type !=FILE_INODE ||test_opt (sbi,DATA_FLUSH )) -__add_dirty_inode (inode, type); -inode_inc_dirty_pages (inode); +if (nr >0 ) { +if (type !=FILE_INODE ||test_opt (sbi,DATA_FLUSH )) +__add_dirty_inode (inode, type); +inode_add_dirty_blocks (inode, nr); + }else { +inode_sub_dirty_blocks (inode, -nr); +__remove_dirty_inode (inode, type); + }spin_unlock (&sbi->inode_lock[type]); +} + +void f2fs_update_dirty_folio (struct inode *inode,struct folio *folio) +{ +if (!S_ISDIR (inode->i_mode) && !S_ISREG (inode->i_mode) && + !S_ISLNK (inode->i_mode)) +return ; + +/* +* Large folios have a subpage dirty bitmap, so defer their dirty accounting +* to the f2fs_ffs_*subrange_dirty*() helpers. This avoids nesting +* ffs->state_lock with the inode dirty list lock. +*/ +if (f2fs_folio_has_ffs (folio)) { +folio_set_f2fs_reference (folio); +return ; + } + +f2fs_account_dirty_blocks (inode,1 );folio_set_f2fs_reference (folio); }
fs/f2fs/compress.c +2 -2
@@ -1065,7 +1065,7 @@ static void cancel_cluster_writeback(struct compress_ctx *cc,/* Cancel writeback and stay locked. */ for (i =0 ; i < cc->cluster_size; i++) {if (i < submitted) { -inode_inc_dirty_pages (cc->inode); +inode_inc_dirty_block (cc->inode);lock_page (cc->rpages[i]); }clear_page_private_gcing (cc->rpages[i]);
@@ -1409,7 +1409,7 @@ static int f2fs_write_compressed_pages(struct compress_ctx *cc, } (*submitted)++; unlock_continue: -inode_dec_dirty_pages (cc->inode); +inode_dec_dirty_block (cc->inode);folio_unlock (fio.folio); }
fs/f2fs/data.c +34 -16
123 lines not on this page · raw message
fs/f2fs/dir.c +1 -1
@@ -937,7 +937,7 @@ void f2fs_delete_entry(struct f2fs_dir_entry *dentry, void *dentry_block,folio_clear_uptodate (folio);folio_detach_private (folio); -inode_dec_dirty_pages (dir); +inode_dec_dirty_block (dir);f2fs_remove_dirty_inode (dir); }f2fs_folio_put (folio, true);
fs/f2fs/f2fs.h +51 -14
97 lines not on this page · raw message
fs/f2fs/gc.c +1 -1
@@ -1564,7 +1564,7 @@ static int move_data_page(struct inode *inode, block_t bidx, int gc_type,folio_mark_dirty (folio);if (folio_clear_dirty_for_io (folio)) { -inode_dec_dirty_pages (inode); +inode_dec_dirty_block (inode);f2fs_remove_dirty_inode (inode); }
fs/f2fs/inline.c +1 -1
@@ -199,7 +199,7 @@ int f2fs_convert_inline_folio(struct dnode_of_data *dn, struct folio *folio)f2fs_outplace_write_data (dn, &fio);f2fs_folio_wait_writeback (folio, true, true);if (dirty) { -inode_dec_dirty_pages (dn->inode); +inode_dec_dirty_block (dn->inode);f2fs_remove_dirty_inode (dn->inode); }
fs/f2fs/node.c +1 -1
@@ -1699,7 +1699,7 @@ static void flush_inline_data(struct f2fs_sb_info *sbi, nid_t ino) goto folio_out; ret =f2fs_write_inline_data (inode, folio); -inode_dec_dirty_pages (inode); +inode_dec_dirty_block (inode);f2fs_remove_dirty_inode (inode);if (ret)folio_mark_dirty (folio);
Signature · 1 line
2.43.0
PATCH v6 7/15 f2fs: prepare mmap write faults for large folios
In reply to Nanzhe ZhaoFrom: Nanzhe Zhao <[email protected]>
Now write protect mmap also need to support large folio, Change f2fs_vm_page_mkwrite to achieve that.
Note it currently marks the whole large folio dirty to avoid data loss which causes write amplification. Further optimization is welcome.
The folio_zero_segment() in mkwrite is extended to zero the post-EOF part of the faulted folio for both order-0 and large folios, so the f2fs_zero_post_eof_page() call that was added to cover the removed shortcut is no longer needed.
--- fs/f2fs/f2fs.h | 4 +++ fs/f2fs/file.c | 96 ++++++++++++++++++++++++++++++++------------------ 2 files changed, 65 insertions(+), 35 deletions(-)
fs/f2fs/f2fs.h +4 -0
@@ -4492,6 +4492,10 @@ int f2fs_write_single_data_page(struct folio *folio, int *submitted,enum iostat_type io_type, int compr_blocks, bool allow_balance);bool f2fs_ffs_test_blk_uptodate (const struct folio *folio,pgoff_t index); +struct f2fs_folio_state *f2fs_ffs_find_or_alloc (struct folio *folio); +void f2fs_ffs_mark_subrange_dirty (struct folio *folio,size_t offset,size_t len); +bool f2fs_ffs_clear_subrange_dirty_and_test (struct folio *folio,size_t offset, +size_t len);void f2fs_write_failed (struct inode *inode,loff_t to);void f2fs_invalidate_folio (struct folio *folio,size_t offset,size_t length);bool f2fs_release_folio (struct folio *folio,gfp_t wait);
fs/f2fs/file.c +61 -35
155 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH v6 8/15 f2fs: make GC migration large-folio aware
In reply to Nanzhe ZhaoFrom: Nanzhe Zhao <[email protected]>
GC can operate on a 4K block that is cached inside a large folio. The data lookup helpers therefore need to test and update uptodate state for the addressed subpage instead of rejecting large folios or treating the whole folio as the target block.
Let f2fs_get_read_data_folio() and f2fs_get_lock_data_folio() to use subpage uptodate state. Submit single-block reads at the requested folio offset and zero only the addressed 4K range for NEW_ADDR.
Also update move_data_page to mark, clear, and restore dirty state for the target subpage, and submit write I/O with the subpage offset recorded in f2fs_io_info.
The write_pages_pending reference is taken by f2fs_do_write_data_page() and dropped from its common error path, so a block that is truncated concurrently no longer leaks the counter.
--- fs/f2fs/data.c | 63 ++++++++++++++++++++++++++++++++++------------- fs/f2fs/f2fs.h | 1 + fs/f2fs/gc.c | 29 ++++++++++++++++++---- fs/f2fs/segment.c | 2 +- 4 files changed, 72 insertions(+), 23 deletions(-)
fs/f2fs/data.c +46 -17
@@ -1679,20 +1679,16 @@ struct folio *f2fs_get_read_data_folio(struct inode *inode, pgoff_t index,struct dnode_of_data dn;struct folio *folio;int err; -retry: + folio =f2fs_grab_cache_folio (mapping, index, for_write);if (IS_ERR (folio))return folio;if (folio_test_large (folio)) { -pgoff_t folio_index =mapping_align_index (mapping, index); -unsigned long nr_pages =folio_nr_pages (folio); - -f2fs_folio_put (folio, true); -invalidate_inode_pages2_range (mapping, folio_index, - folio_index + nr_pages -1 ); -f2fs_schedule_timeout (DEFAULT_SCHEDULE_TIMEOUT ); - goto retry; +if (!f2fs_ffs_find_or_alloc (folio)) { + err = -ENOMEM ; + goto put_err; + } } if (f2fs_lookup_read_extent_cache_block(inode, index,
@@ -1728,7 +1724,7 @@ struct folio *f2fs_get_read_data_folio(struct inode *inode, pgoff_t index, goto put_err; } got_it: -if (folio_test_uptodate (folio)) { +if (f2fs_ffs_test_blk_uptodate (folio, index)) {folio_unlock (folio);return folio; }
@@ -1741,9 +1737,11 @@ struct folio *f2fs_get_read_data_folio(struct inode *inode, pgoff_t index,* f2fs_init_inode_metadata. */ if (dn.data_blkaddr ==NEW_ADDR ) { -folio_zero_segment (folio,0 ,folio_size (folio)); -if (!folio_test_uptodate (folio)) -folio_mark_uptodate (folio); +size_t offset =offset_in_folio (folio, + (loff_t )index <<PAGE_SHIFT ); + +folio_zero_segment (folio, offset, offset +PAGE_SIZE ); +f2fs_ffs_mark_subrange_uptodate (folio, offset,PAGE_SIZE );folio_unlock (folio);return folio; }
@@ -1803,7 +1801,8 @@ struct folio *f2fs_get_lock_data_folio(struct inode *inode, pgoff_t index,/* wait for read completion */ folio_lock (folio); -if (unlikely (folio->mapping != mapping || !folio_test_uptodate (folio))) { +if (unlikely (folio->mapping != mapping || + !f2fs_ffs_test_blk_uptodate (folio, index))) {f2fs_folio_put (folio, true);return ERR_PTR (-EIO ); }
@@ -2952,6 +2951,22 @@ static void f2fs_ffs_mark_subrange_uptodate(struct folio *folio, size_t offset,folio_mark_uptodate (folio); } +bool f2fs_ffs_test_blk_dirty (const struct folio *folio,pgoff_t index) +{ +struct f2fs_folio_state *ffs; +unsigned int idx, nr_subpages; + +f2fs_bug_on (F2FS_F_SB (folio), !folio_contains (folio, index)); + +if (!f2fs_folio_has_ffs (folio)) +return folio_test_dirty (folio); + + ffs = (struct f2fs_folio_state *)folio->private; + nr_subpages =folio_nr_pages (folio); + idx = index - folio->index; +return test_bit (nr_subpages + idx, ffs->state); +} +static unsigned int __ffs_mark_subrange_dirty (struct folio *folio,struct f2fs_folio_state *ffs,size_t offset,size_t len) {
@@ -3045,7 +3060,6 @@ bool f2fs_ffs_clear_subrange_dirty_and_test(struct folio *folio, size_t offset,return dirty; } -static unsigned int ffs_next_dirty_subpage (struct f2fs_folio_state *ffs,const struct folio *folio,unsigned int start,unsigned int end)
@@ -3543,7 +3557,7 @@ bool f2fs_should_update_outplace(struct inode *inode, struct f2fs_io_info *fio)return true;if (fio) { -if (page_private_gcing (fio->page)) +if (folio_test_f2fs_gcing (fio->folio))return true;if (unlikely (is_sbi_flag_set (sbi,SBI_CP_DISABLED ) &&f2fs_is_checkpointed_data (sbi, fio->old_blkaddr)))
@@ -3569,8 +3583,11 @@ int f2fs_do_write_data_page(struct f2fs_io_info *fio)struct dnode_of_data dn;struct node_info ni;struct f2fs_lock_context lc; +struct f2fs_folio_state *ffs;bool ipu_force = false;bool atomic_commit; +bool pending_added = false; +bool submitted = false;int err =0 ;/* Use COW inode to make dnode_of_data for atomic write */
@@ -3612,7 +3629,6 @@ int f2fs_do_write_data_page(struct f2fs_io_info *fio)/* This page is already truncated */ if (fio->old_blkaddr ==NULL_ADDR ) {folio_clear_uptodate (folio); -folio_clear_f2fs_gcing (folio); goto out_writepage; } got_it:
@@ -3662,6 +3678,11 @@ int f2fs_do_write_data_page(struct f2fs_io_info *fio) fio->version = ni.version;__folio_start_writeback (folio,folio_test_dirty (folio)); +if (f2fs_folio_has_ffs (folio)) { + ffs = (struct f2fs_folio_state *)folio->private; +atomic_inc (&ffs->write_pages_pending); + pending_added = true; + }if (fio->compr_blocks && fio->old_blkaddr ==COMPRESS_ADDR )f2fs_i_compr_blocks_update (inode, fio->compr_blocks -1 , false);
@@ -3676,6 +3697,7 @@ int f2fs_do_write_data_page(struct f2fs_io_info *fio) err = -EIO ; goto out_writepage; } + submitted = true;set_inode_flag (inode,FI_APPEND_WRITE );if (atomic_commit)folio_clear_f2fs_atomic (folio);
@@ -3684,6 +3706,13 @@ int f2fs_do_write_data_page(struct f2fs_io_info *fio) out:if (fio->need_lock ==LOCK_REQ )f2fs_unlock_op (fio->sbi, &lc); +if (!submitted) { +if (pending_added) { +f2fs_ffs_put_write_pending (folio,1 ); + }else if (!f2fs_ffs_has_dirty_subpage (folio)) { +folio_clear_f2fs_gcing (folio); + } + }return err; }
fs/f2fs/f2fs.h +1 -0
@@ -4493,6 +4493,7 @@ int f2fs_write_single_data_page(struct folio *folio, int *submitted, int compr_blocks, bool allow_balance);bool f2fs_ffs_test_blk_uptodate (const struct folio *folio,pgoff_t index);struct f2fs_folio_state *f2fs_ffs_find_or_alloc (struct folio *folio); +bool f2fs_ffs_test_blk_dirty (const struct folio *folio,pgoff_t index);void f2fs_ffs_mark_subrange_dirty (struct folio *folio,size_t offset,size_t len);bool f2fs_ffs_clear_subrange_dirty_and_test (struct folio *folio,size_t offset,size_t len);
fs/f2fs/gc.c +24 -5
@@ -1520,12 +1520,19 @@ static int move_data_page(struct inode *inode, block_t bidx, int gc_type, unsigned int segno, int off) {struct folio *folio; +size_t foff =0 ; +bool large = false;int err =0 ; folio =f2fs_get_lock_data_folio (inode, bidx, true);if (IS_ERR (folio))return PTR_ERR (folio); +if (f2fs_folio_has_ffs (folio)) { + large = true; + foff =offset_in_folio (folio, (loff_t )bidx <<PAGE_SHIFT ); + } +if (!check_valid_map (F2FS_I_SB (inode), segno, off)) { err = -ENOENT ; goto out;
@@ -1540,6 +1547,8 @@ static int move_data_page(struct inode *inode, block_t bidx, int gc_type, err = -EAGAIN ; goto out; } +if (large) +f2fs_ffs_mark_subrange_dirty (folio, foff,PAGE_SIZE );folio_mark_dirty (folio);folio_set_f2fs_gcing (folio); }else {
@@ -1552,33 +1561,43 @@ static int move_data_page(struct inode *inode, block_t bidx, int gc_type, .op_flags = REQ_SYNC, .old_blkaddr = NULL_ADDR, .folio = folio, + .folio_offset = bidx - folio->index, .folio_blkcnt = 1, .encrypted_page = NULL, .need_lock = LOCK_REQ, .io_type = FS_GC_DATA_IO, }; -bool is_dirty =folio_test_dirty (folio); +bool is_dirty =f2fs_ffs_test_blk_dirty (folio, bidx); retry:f2fs_folio_wait_writeback (folio, true, true); +if (large) +f2fs_ffs_mark_subrange_dirty (folio, foff,PAGE_SIZE );folio_mark_dirty (folio);if (folio_clear_dirty_for_io (folio)) { -inode_dec_dirty_block (inode); -f2fs_remove_dirty_inode (inode); +if (!large) { +inode_dec_dirty_block (inode); +f2fs_remove_dirty_inode (inode); + }else if (f2fs_ffs_clear_subrange_dirty_and_test (folio, + foff,PAGE_SIZE )) { +folio_mark_dirty (folio); + } }folio_set_f2fs_gcing (folio); err =f2fs_do_write_data_page (&fio);if (err) { -folio_clear_f2fs_gcing (folio);if (err == -ENOMEM ) {memalloc_retry_wait (GFP_NOFS ); goto retry; } -if (is_dirty) +if (is_dirty) { +if (large) +f2fs_ffs_mark_subrange_dirty (folio, foff,PAGE_SIZE );folio_mark_dirty (folio); + } } } out:
fs/f2fs/segment.c +1 -1
@@ -3863,7 +3863,7 @@ static int __get_segment_type_6(struct f2fs_io_info *fio)if (is_inode_flag_set (inode,FI_ALIGNED_WRITE ))return CURSEG_COLD_DATA_PINNED ; -if (page_private_gcing (fio->page)) { +if (folio_test_f2fs_gcing (fio->folio)) { if (fio->sbi->am.atgc_enabled && (fio->io_type == FS_DATA_IO) && (fio->sbi->gc_mode != GC_URGENT_HIGH) &&
Signature · 1 line
2.43.0
PATCH v6 9/15 f2fs: optimize small block size large folio read
In reply to Nanzhe ZhaoFrom: Nanzhe Zhao <[email protected]>
The original f2fs_read_data_large_folio() implementation has limited benefit with a 4KB block size, mainly because updating read_pages_pending greatly increases the number of spinlock operations.
Use len_blks to batch read_pages_pending and iostat updates for contiguous mapped blocks.
--- fs/f2fs/data.c | 46 +++++++++++++++++++++++++++++++--------------- 1 file changed, 31 insertions(+), 15 deletions(-)
fs/f2fs/data.c +31 -15
@@ -158,7 +158,7 @@ static void f2fs_finish_read_bio(struct bio *bio, bool in_task)continue ; } -if (folio_test_large (folio)) { +if (f2fs_folio_has_ffs (folio)) {struct f2fs_folio_state *ffs = (struct f2fs_folio_state *)folio->private;
@@ -3151,7 +3151,7 @@ static int f2fs_read_data_large_folio(struct inode *inode,pgoff_t index, offset, next_pgofs =0 ;unsigned max_nr_pages = rac ?readahead_count (rac) :folio_nr_pages (folio); -unsigned nrpages; +unsigned nrpages, len_blks;struct f2fs_folio_state *ffs;int ret =0 ;bool folio_in_bio = false;
@@ -3175,11 +3175,16 @@ static int f2fs_read_data_large_folio(struct inode *inode, folio_in_bio = false; index = folio->index; offset =0 ; - ffs =NULL ; nrpages =folio_nr_pages (folio); -for (; nrpages; nrpages--, max_nr_pages--, index++, offset++) { +for (; nrpages; + nrpages -= len_blks, max_nr_pages -= len_blks, + index += len_blks, offset += len_blks) {sector_t block_nr; +unsigned int i; + + len_blks =1 ; +/* * Map blocks using the previous result first. */
@@ -3208,13 +3213,23 @@ static int f2fs_read_data_large_folio(struct inode *inode, got_it:if ((map.m_flags &F2FS_MAP_MAPPED )) { block_nr = map.m_pblk + index - map.m_lblk; -if (!f2fs_is_valid_blkaddr (F2FS_I_SB (inode), block_nr, + + len_blks = min_t(unsigned int, nrpages, max_nr_pages); + len_blks = min_t(unsigned int, len_blks, + (unsigned int )(map.m_lblk + map.m_len - index)); + +for (i =0 ; i < len_blks; i++) { +if (!f2fs_is_valid_blkaddr (F2FS_I_SB (inode), + block_nr + i,DATA_GENERIC_ENHANCE_READ )) { - ret = -EFSCORRUPTED ; - goto err_out; + ret = -EFSCORRUPTED ; + goto err_out; + } } + }else {size_t page_offset = offset <<PAGE_SHIFT ; +folio_zero_range (folio, page_offset,PAGE_SIZE );if (vi && !fsverity_verify_blocks (vi, folio,PAGE_SIZE , page_offset)) { ret = -EIO ;
@@ -3234,9 +3249,7 @@ static int f2fs_read_data_large_folio(struct inode *inode, }/* set the bitmap to wait */ -spin_lock_irq (&ffs->state_lock); - ffs->read_pages_pending++; -spin_unlock_irq (&ffs->state_lock); +f2fs_update_read_folio_pending (folio, len_blks); }/*
@@ -3260,17 +3273,20 @@ static int f2fs_read_data_large_folio(struct inode *inode,* If the page is under writeback, we need to wait for * its completion to see the correct decrypted data. */ -f2fs_wait_on_block_writeback (inode, block_nr); +for (i =0 ; i < len_blks; i++) +f2fs_wait_on_block_writeback (inode, block_nr + i); -if (!bio_add_folio (bio, folio,F2FS_BLKSIZE (F2FS_I_SB (inode)), +if (!bio_add_folio (bio, folio, + len_blks *F2FS_BLKSIZE (F2FS_I_SB (inode)), offset <<PAGE_SHIFT )) goto submit_and_realloc; folio_in_bio = true; -inc_cache_count (F2FS_I_SB (inode),F2FS_RD_DATA ); +for (i =0 ; i < len_blks; i++) +inc_cache_count (F2FS_I_SB (inode),F2FS_RD_DATA );f2fs_update_iostat (F2FS_I_SB (inode),NULL ,FS_DATA_READ_IO , -F2FS_BLKSIZE (F2FS_I_SB (inode))); - last_block_in_bio = block_nr; + len_blks *F2FS_BLKSIZE (F2FS_I_SB (inode))); + last_block_in_bio = block_nr + len_blks -1 ; }trace_f2fs_read_folio (folio,DATA ); err_out:
Signature · 1 line
2.43.0
PATCH v6 10/15 f2fs: support partial uptodate large folio read
In reply to Nanzhe ZhaoFrom: Nanzhe Zhao <[email protected]>
Buffered write can have write bytes smaller than folio size for cases when folio minimum order is not zero. This can left partially uptodate folio in page cache. So we skip uptodate subpage read in read_data_large_folio. Also mark hole subpage uptodate in uptodate bitmap.
--- fs/f2fs/data.c | 102 +++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 95 insertions(+), 7 deletions(-)
fs/f2fs/data.c +95 -7
@@ -148,6 +148,7 @@ static void f2fs_finish_read_bio(struct bio *bio, bool in_task)struct folio *folio = fi.folio;unsigned nr_pages = fi.length >>PAGE_SHIFT ;bool finished = true; +bool uptodate = bio->bi_status ==BLK_STS_OK ;if (!folio_test_large (folio) &&f2fs_is_compressed_page (folio)) {
@@ -163,6 +164,9 @@ static void f2fs_finish_read_bio(struct bio *bio, bool in_task) (struct f2fs_folio_state *)folio->private;spin_lock_irqsave (&ffs->state_lock, flags); +if (uptodate) + uptodate =__ffs_mark_subrange_uptodate (folio, ffs, + fi.offset, fi.length); ffs->read_pages_pending -= nr_pages; finished = !ffs->read_pages_pending;spin_unlock_irqrestore (&ffs->state_lock, flags);
@@ -172,7 +176,7 @@ static void f2fs_finish_read_bio(struct bio *bio, bool in_task)dec_cache_count (F2FS_F_SB (folio),F2FS_RD_DATA );if (finished) -folio_end_read (folio, bio->bi_status ==BLK_STS_OK ); +folio_end_read (folio, uptodate); }if (ctx)
@@ -3141,6 +3145,70 @@ static bool find_next_valid_block(const struct folio *folio,return false; } +static unsigned int ffs_next_uptodate_subpage (struct f2fs_folio_state *ffs, +unsigned int start,unsigned int end) +{ +return find_next_bit (ffs->state, end +1 , start); +} + +static unsigned int ffs_next_nonuptodate_subpage (struct f2fs_folio_state *ffs, +unsigned int start,unsigned int end) +{ +return find_next_zero_bit (ffs->state, end +1 , start); +} + +static void f2fs_skip_fully_uptodate_front (struct folio *folio, +pgoff_t *index,pgoff_t *offset,unsigned int *nrpages, +unsigned int *max_nr_pages) +{ +struct f2fs_folio_state *ffs; +unsigned int next, skipped; + +if (!f2fs_folio_has_ffs (folio) || !*nrpages) +return ; + + ffs = (struct f2fs_folio_state *)folio->private; + next =ffs_next_nonuptodate_subpage (ffs, *offset, + *offset + *nrpages -1 ); + skipped = next - *offset; +if (!skipped) +return ; + + *index += skipped; + *offset += skipped; + *nrpages -= skipped; + *max_nr_pages -= skipped; +} + +static void f2fs_truncate_read_extent (struct inode *inode,struct folio *folio, +pgoff_t offset,block_t block_nr, +unsigned int *len_blks) +{ +struct f2fs_sb_info *sbi =F2FS_I_SB (inode); +struct f2fs_folio_state *ffs; +unsigned int next, end; + +if (!f2fs_folio_has_ffs (folio) || *len_blks <=1 ) +return ; + +if (f2fs_is_multi_device (sbi)) { +int bidx =f2fs_target_device_index (sbi, block_nr); + + *len_blks = min_t(unsigned int, *len_blks, +FDEV (bidx).end_blk +1 - block_nr); + } + *len_blks = min_t(unsigned int, *len_blks, + (unsigned int )fscrypt_limit_io_blocks (inode, + folio->index + offset, + *len_blks)); + + ffs = (struct f2fs_folio_state *)folio->private; + end = offset + *len_blks -1 ; + next =ffs_next_uptodate_subpage (ffs, offset +1 , end); +if (next <= end) + *len_blks = next - offset; +} +static int f2fs_read_data_large_folio (struct inode *inode,struct fsverity_info *vi,struct readahead_control *rac,struct folio *folio)
@@ -3173,6 +3241,19 @@ static int f2fs_read_data_large_folio(struct inode *inode,f2fs_update_read_folio_count (F2FS_I_SB (inode), folio); folio_in_bio = false; + ffs =NULL ; +if (folio_test_large (folio)) { +/* +* Allocate the folio state before doing anything with the +* folio, so that the block mapping helpers below can rely on +* it, and fail early if memory is not available. +*/ + ffs =f2fs_ffs_find_or_alloc (folio); +if (!ffs) { + ret = -ENOMEM ; + goto err_out; + } + } index = folio->index; offset =0 ; nrpages =folio_nr_pages (folio);
@@ -3185,6 +3266,11 @@ static int f2fs_read_data_large_folio(struct inode *inode, len_blks =1 ; +f2fs_skip_fully_uptodate_front (folio, &index, &offset, + &nrpages, &max_nr_pages); +if (!nrpages) +break ; +/* * Map blocks using the previous result first. */
@@ -3217,6 +3303,8 @@ static int f2fs_read_data_large_folio(struct inode *inode, len_blks = min_t(unsigned int, nrpages, max_nr_pages); len_blks = min_t(unsigned int, len_blks, (unsigned int )(map.m_lblk + map.m_len - index)); +f2fs_truncate_read_extent (inode, folio, offset, + block_nr, &len_blks); for (i = 0; i < len_blks; i++) { if (!f2fs_is_valid_blkaddr(F2FS_I_SB(inode),
@@ -3235,6 +3323,12 @@ static int f2fs_read_data_large_folio(struct inode *inode, ret = -EIO ; goto err_out; } +if (folio_test_large (folio)) { +spin_lock_irq (&ffs->state_lock); +__ffs_mark_subrange_uptodate (folio, ffs, + page_offset,PAGE_SIZE ); +spin_unlock_irq (&ffs->state_lock); + }continue ; }
@@ -3242,12 +3336,6 @@ static int f2fs_read_data_large_folio(struct inode *inode,* to prevent from premature folio_end_read() call on folio */ if (folio_test_large (folio)) { - ffs =f2fs_ffs_find_or_alloc (folio); -if (!ffs) { - ret = -ENOMEM ; - goto err_out; - } -/* set the bitmap to wait */ f2fs_update_read_folio_pending (folio, len_blks); }
Signature · 1 line
2.43.0
PATCH v6 11/15 f2fs: handle partial truncate of large folio dirty subpages
In reply to Nanzhe ZhaoFrom: Nanzhe Zhao <[email protected]>
A large folio can be partial truncated and stays in folio mapping, we need to clear the subrange dirty bits and uptodate bits that the partial truncate covers. If this partial truncate happens to clear the last subrange dirty bits, then cancel the whole folio dirty state.
Also add a guard in f2fs_write_folio_dirty_range() so a large folio subpage whose disk block was already truncated (NULL_ADDR) is skipped
--- fs/f2fs/data.c | 94 +++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 89 insertions(+), 5 deletions(-)
fs/f2fs/data.c +89 -5
@@ -404,7 +404,6 @@ static void f2fs_ffs_put_write_pending(struct folio *folio, unsigned int nr)if (folio_test_writeback (folio))folio_end_writeback (folio); } -static void f2fs_write_end_bio (struct bio *bio) {struct f2fs_sb_info *sbi = bio->bi_private;
@@ -2955,6 +2954,41 @@ static void f2fs_ffs_mark_subrange_uptodate(struct folio *folio, size_t offset,folio_mark_uptodate (folio); } +static void ffs_clear_subrange_uptodate (struct folio *folio, +size_t offset,size_t len) +{ +struct f2fs_folio_state *ffs; +unsigned int nr_subpages, start, end; +unsigned long flags; + +f2fs_bug_on (F2FS_F_SB (folio), offset + len >folio_size (folio)); + +if (!f2fs_folio_has_ffs (folio)) +return ; + + ffs = (struct f2fs_folio_state *)folio->private; + nr_subpages =folio_nr_pages (folio); + start = offset >>PAGE_SHIFT ; + end = (offset + len +PAGE_SIZE -1 ) >>PAGE_SHIFT ; + end =min (end, nr_subpages); + +spin_lock_irqsave (&ffs->state_lock, flags); +bitmap_clear (ffs->state, start, end - start); +spin_unlock_irqrestore (&ffs->state_lock, flags); +} + +static void f2fs_clear_truncated_page_state (struct folio *folio,pgoff_t i) +{ +if (f2fs_folio_has_ffs (folio)) { +ffs_clear_subrange_uptodate (folio, + (loff_t )i <<PAGE_SHIFT ,PAGE_SIZE ); +folio_clear_uptodate (folio); + }else { +folio_clear_uptodate (folio); +folio_clear_f2fs_gcing (folio); + } +} +bool f2fs_ffs_test_blk_dirty (const struct folio *folio,pgoff_t index) {struct f2fs_folio_state *ffs;
@@ -3732,7 +3766,7 @@ int f2fs_do_write_data_page(struct f2fs_io_info *fio)/* This page is already truncated */ if (fio->old_blkaddr ==NULL_ADDR ) { -folio_clear_uptodate (folio); +f2fs_clear_truncated_page_state (folio, fio->folio_offset); goto out_writepage; } got_it:
@@ -3882,12 +3916,31 @@ static int f2fs_write_folio_dirty_range(struct folio *folio, int *submitted, } err =f2fs_get_dnode_of_data (&dn, data_idx,LOOKUP_NODE ); -if (err) +/* +* If a subpage of folio for a cow file is dirtied but not +* reserve a cow block, fallback to original inode to lookup +* block address +*/ +if (atomic_commit && (err == -ENOENT || + (!err && dn.data_blkaddr ==NULL_ADDR ))) { +f2fs_put_dnode (&dn); +set_new_dnode (&dn, inode,NULL ,NULL ,0 ); + err =f2fs_get_dnode_of_data (&dn, data_idx, +LOOKUP_NODE ); + } +if (err && err != -ENOENT ) goto block_done; dn_held = true; fio.old_blkaddr = dn.data_blkaddr; +/* This page is already truncated */ +if (err == -ENOENT || fio.old_blkaddr ==NULL_ADDR ) { +f2fs_clear_truncated_page_state (folio, i); + err =0 ; + goto block_done; + } + got_it:if (__is_valid_data_blkaddr (fio.old_blkaddr) && !f2fs_is_valid_blkaddr(sbi, fio.old_blkaddr,
@@ -5426,10 +5479,41 @@ void f2fs_invalidate_folio(struct folio *folio, size_t offset, size_t length)struct f2fs_sb_info *sbi =F2FS_I_SB (inode);if (inode->i_ino >=F2FS_ROOT_INO (sbi) && - (offset || length !=folio_size (folio))) + (offset || length !=folio_size (folio))) { +size_t clear_start =round_up (offset,PAGE_SIZE ); +size_t clear_end =round_down (offset + length,PAGE_SIZE ); +size_t clear_length; +bool dirty; + +/* +* If the truncated range falls within a single subpage, no +* subpage state needs to be cleared. +*/ +if (clear_start >= clear_end || !f2fs_folio_has_ffs (folio)) +return ; + + clear_length = clear_end - clear_start; + dirty =f2fs_ffs_clear_subrange_dirty_and_test (folio, + clear_start, clear_length); +ffs_clear_subrange_uptodate (folio, clear_start, clear_length); +folio_clear_uptodate (folio); + +/* +* If the truncated subrange happens to clear the remaining +* dirty bitmap of the whole folio, cancel the folio-level +* dirty state. +*/ +if (!dirty &&folio_test_dirty (folio)) +folio_cancel_dirty (folio); +if (!dirty && !folio_test_writeback (folio)) +folio_clear_f2fs_gcing (folio);return ; + } -if (folio_test_dirty (folio)) { +if (f2fs_folio_has_ffs (folio)) { +f2fs_ffs_clear_subrange_dirty_and_test (folio,0 , +folio_size (folio)); + }else if (folio_test_dirty (folio)) {inode_dec_dirty_block (inode);f2fs_remove_dirty_inode (inode); }
Signature · 1 line
2.43.0
PATCH v6 12/15 f2fs: fix zeroing paths for large folios
In reply to Nanzhe ZhaoFrom: Nanzhe Zhao <[email protected]>
Several f2fs zeroing paths still use PAGE_SIZE based offsets after a file mapping can contain large folios. This is fine for order-0 folios, but it zeros the wrong range once the target block is not at offset 0 in a large folio.
Use offset_in_folio() to translate the file block index to the folio offset before zeroing data in truncate_partial_data_page(), fill_zero(), and f2fs_get_new_data_folio().
--- fs/f2fs/data.c | 18 +++++++++++++----- fs/f2fs/f2fs.h | 1 + fs/f2fs/file.c | 29 ++++++++++++++++++++++++----- 3 files changed, 38 insertions(+), 10 deletions(-)
fs/f2fs/data.c +13 -5
@@ -1839,6 +1839,12 @@ struct folio *f2fs_get_new_data_folio(struct inode *inode,return ERR_PTR (-ENOMEM ); } +if (folio_test_large (folio) && !f2fs_ffs_find_or_alloc (folio)) { +f2fs_folio_put (folio, true); +f2fs_put_cache (ientry, true); +return ERR_PTR (-ENOMEM ); + } +set_new_dnode (&dn, inode, ientry,NULL ,0 ); err =f2fs_reserve_block (&dn, index);if (err) {
@@ -1848,13 +1854,15 @@ struct folio *f2fs_get_new_data_folio(struct inode *inode,if (!ientry)f2fs_put_dnode (&dn); -if (folio_test_uptodate (folio)) +if (f2fs_ffs_test_blk_uptodate (folio, index)) goto got_it;if (dn.data_blkaddr ==NEW_ADDR ) { -folio_zero_segment (folio,0 ,folio_size (folio)); -if (!folio_test_uptodate (folio)) -folio_mark_uptodate (folio); +size_t off =offset_in_folio (folio, + (loff_t )index <<PAGE_SHIFT ); + +folio_zero_segment (folio, off, off +PAGE_SIZE ); +f2fs_ffs_mark_subrange_uptodate (folio, off,PAGE_SIZE ); }else {f2fs_folio_put (folio, true);
@@ -2931,7 +2939,7 @@ bool f2fs_ffs_test_blk_uptodate(const struct folio *folio, pgoff_t index)return test_bit (idx, ffs->state); } -static void f2fs_ffs_mark_subrange_uptodate (struct folio *folio,size_t offset, +void f2fs_ffs_mark_subrange_uptodate (struct folio *folio,size_t offset,size_t len) {struct f2fs_folio_state *ffs;
fs/f2fs/f2fs.h +1 -0
@@ -4480,6 +4480,7 @@ struct folio *f2fs_get_lock_data_folio(struct inode *inode, pgoff_t index, bool for_write);struct folio *f2fs_get_new_data_folio (struct inode *inode,struct f2fs_cached_block *ientry,pgoff_t index,bool new_i_size); +void f2fs_ffs_mark_subrange_uptodate (struct folio *folio,size_t offset,size_t len);int f2fs_do_write_data_page (struct f2fs_io_info *fio);int f2fs_map_blocks (struct inode *inode,struct f2fs_map_blocks *map,int flag); int f2fs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
fs/f2fs/file.c +24 -5
@@ -833,12 +833,13 @@ void f2fs_truncate_data_blocks_range(struct dnode_of_data *dn, int count)static int truncate_partial_data_page (struct inode *inode,u64 from,bool cache_only) { -loff_t offset = from & (PAGE_SIZE -1 );pgoff_t index = from >>PAGE_SHIFT ;struct address_space *mapping = inode->i_mapping;struct folio *folio; +size_t folio_off; +size_t blk_end; -if (!offset && !cache_only) +if (!(from & (PAGE_SIZE -1 )) && !cache_only)return 0 ;if (cache_only) {
@@ -856,12 +857,22 @@ static int truncate_partial_data_page(struct inode *inode, u64 from,return PTR_ERR (folio) == -ENOENT ?0 :PTR_ERR (folio); truncate_out:f2fs_folio_wait_writeback (folio, true, true); -folio_zero_segment (folio, offset,folio_size (folio)); + folio_off =offset_in_folio (folio, from); + blk_end =min_t (size_t,round_up (folio_off,PAGE_SIZE ), +folio_size (folio)); +folio_zero_segment (folio, folio_off, blk_end);/* An encrypted inode should have a key and truncate the last page. */ f2fs_bug_on (F2FS_I_SB (inode), cache_only &&IS_ENCRYPTED (inode)); -if (!cache_only) +if (!cache_only) { +/* +* The folio was read back above, so the subpage is +* already uptodate and dirty data stays valid. +*/ +f2fs_ffs_mark_subrange_dirty (folio, folio_off, + blk_end - folio_off);folio_mark_dirty (folio); + }f2fs_folio_put (folio, true);return 0 ; }
@@ -1325,6 +1336,7 @@ static int fill_zero(struct inode *inode, pgoff_t index,struct f2fs_sb_info *sbi =F2FS_I_SB (inode);struct folio *folio;struct f2fs_lock_context lc; +size_t folio_off;if (!len)return 0 ;
@@ -1339,7 +1351,14 @@ static int fill_zero(struct inode *inode, pgoff_t index,return PTR_ERR (folio);f2fs_folio_wait_writeback (folio, true, true); -folio_zero_range (folio, start, len); + folio_off =offset_in_folio (folio, + (loff_t )index <<PAGE_SHIFT ) + start; +folio_zero_range (folio, folio_off, len); +/* +* This subpage must be uptodate here, which is guaranteed by +* f2fs_get_new_data_folio() above. +*/ +f2fs_ffs_mark_subrange_dirty (folio, folio_off, len);folio_mark_dirty (folio);f2fs_folio_put (folio, true);return 0 ;
Signature · 1 line
2.43.0
PATCH v6 13/15 f2fs: handle block cloning within the same large folio
In reply to Nanzhe ZhaoFrom: Nanzhe Zhao <[email protected]>
With large folios, the source and destination block in __clone_blkaddrs() can belong to the same folio during same-inode operations such as collapse range and insert range.
In that case, locking the source folio and then looking up the destination folio can try to lock the same folio again. It also copies from and to offset 0, which is only correct for order-0 folios.
Detect the same-inode, same-folio case before looking up the destination folio. Then in this case,we reserve the destination block explicitly.
--- fs/f2fs/file.c | 61 +++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 53 insertions(+), 8 deletions(-)
fs/f2fs/file.c +53 -8
@@ -1598,25 +1598,70 @@ static int __clone_blkaddrs(struct inode *src_inode, struct inode *dst_inode,f2fs_put_dnode (&dn); }else {struct folio *fsrc, *fdst; +size_t src_off, dst_off; +bool same_folio; fsrc =f2fs_get_lock_data_folio (src_inode, src + i, true);if (IS_ERR (fsrc))return PTR_ERR (fsrc); - fdst =f2fs_get_new_data_folio (dst_inode,NULL , dst + i, - true); -if (IS_ERR (fdst)) { -f2fs_folio_put (fsrc, true); -return PTR_ERR (fdst); + + src_off =offset_in_folio (fsrc, + (loff_t)(src + i) <<PAGE_SHIFT ); + +/* +* For same-inode operations (collapse/insert), src and +* dst may fall within the same large folio. Detect this +* to avoid self-deadlock on folio lock. +*/ + same_folio = src_inode == dst_inode && +folio_contains (fsrc, dst + i); +if (same_folio) { +struct dnode_of_data dn; + +/* Reserve block for dst before copying */ +set_new_dnode (&dn, dst_inode,NULL ,NULL ,0 ); + ret =f2fs_reserve_block (&dn, dst + i); +if (ret) { +f2fs_folio_put (fsrc, true); +return ret; + } + fdst = fsrc; + }else { + fdst =f2fs_get_new_data_folio (dst_inode,NULL , + dst + i, true); +if (IS_ERR (fdst)) { +f2fs_folio_put (fsrc, true); +return PTR_ERR (fdst); + } } + dst_off =offset_in_folio (fdst, + (loff_t)(dst + i) <<PAGE_SHIFT );f2fs_folio_wait_writeback (fdst, true, true); - -memcpy_folio (fdst,0 , fsrc,0 ,PAGE_SIZE ); +memcpy_folio (fdst, dst_off, fsrc, src_off, +PAGE_SIZE ); +if (folio_test_large (fdst)) { +if (!f2fs_ffs_find_or_alloc (fdst)) { +f2fs_folio_put (fdst, true); +if (!same_folio) +f2fs_folio_put (fsrc, true); +return -ENOMEM ; + } +f2fs_ffs_mark_subrange_uptodate (fdst, + dst_off,PAGE_SIZE ); +f2fs_ffs_mark_subrange_dirty (fdst, dst_off, +PAGE_SIZE ); + }folio_mark_dirty (fdst); +if (same_folio &&i_size_read (dst_inode) < + ((loff_t)(dst + i +1 ) <<PAGE_SHIFT )) +f2fs_i_size_write (dst_inode, + ((loff_t)(dst + i +1 ) <<PAGE_SHIFT ));folio_set_f2fs_gcing (fdst);f2fs_folio_put (fdst, true); -f2fs_folio_put (fsrc, true); +if (!same_folio) +f2fs_folio_put (fsrc, true); ret =f2fs_truncate_hole (src_inode, src + i, src + i +1 );
Signature · 1 line
2.43.0
PATCH v6 14/15 f2fs: allow large folio support to writeable files
In reply to Nanzhe ZhaoFrom: Nanzhe Zhao <[email protected]>
Now we make all write path support large folios,
so we open permission to let writeable file set
large folio mapping.
--- fs/f2fs/data.c | 2 +- fs/f2fs/f2fs.h | 17 +++++++++++++++++ fs/f2fs/file.c | 16 +--------------- fs/f2fs/inline.c | 6 ++++++ fs/f2fs/inode.c | 4 +--- fs/f2fs/namei.c | 1 + 6 files changed, 27 insertions(+), 19 deletions(-)
fs/f2fs/data.c +1 -1
@@ -3266,7 +3266,7 @@ static int f2fs_read_data_large_folio(struct inode *inode,int ret =0 ;bool folio_in_bio = false; -if (!IS_IMMUTABLE (inode) ||f2fs_compressed_file (inode)) { +if (f2fs_compressed_file (inode)) {if (folio)folio_unlock (folio);return -EOPNOTSUPP ;
fs/f2fs/f2fs.h +17 -0
@@ -5348,6 +5348,23 @@ static inline bool f2fs_quota_file(struct f2fs_sb_info *sbi, nid_t ino)return false; } +static inline void f2fs_mapping_set_large_folio (struct inode *inode) +{ +if (!S_ISREG (inode->i_mode) || +f2fs_compressed_file (inode) || +f2fs_quota_file (F2FS_I_SB (inode), inode->i_ino)) +return ; + +/* +* Keep the folio order range at 0 as a transitional step; large +* folios will be enabled once the whole write path is audited. +*/ +if (IS_IMMUTABLE (inode)) +mapping_set_folio_min_order (inode->i_mapping,0 ); +else +mapping_set_folio_order_range (inode->i_mapping,0 ,0 ); +} +static inline bool f2fs_block_unit_discard (struct f2fs_sb_info *sbi) {return F2FS_OPTION (sbi).discard_unit ==DISCARD_UNIT_BLOCK ;
fs/f2fs/file.c +1 -15
@@ -163,17 +163,8 @@ static vm_fault_t f2fs_vm_page_mkwrite(struct vm_fault *vmf)int err =0 ;vm_fault_t ret; -/* -* We only support large folio on the read case. -* Don't make any dirty pages. -*/ -if (unlikely (IS_IMMUTABLE (inode)) || -mapping_large_folio_support (inode->i_mapping)) { -f2fs_err (sbi,"Not expected: immutable: %d large_folio: %d" , -IS_IMMUTABLE (inode), -mapping_large_folio_support (inode->i_mapping)); +if (unlikely (IS_IMMUTABLE (inode)))return VM_FAULT_SIGBUS ; - }if (is_inode_flag_set (inode,FI_COMPRESS_RELEASED )) { err = -EIO ;
@@ -720,9 +711,6 @@ static int f2fs_file_open(struct inode *inode, struct file *filp)if (!f2fs_is_compress_backend_ready (inode))return -EOPNOTSUPP ; -if (mapping_large_folio_support (inode->i_mapping) && - filp->f_mode &FMODE_WRITE ) -return -EOPNOTSUPP ; err =fsverity_file_open (inode, filp);if (err)
@@ -1194,8 +1182,6 @@ int f2fs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,return -EPERM ;if ((attr->ia_valid &ATTR_SIZE )) { -if (mapping_large_folio_support (inode->i_mapping)) -return -EOPNOTSUPP ;if (IS_DEVICE_ALIASING (inode))return -EPERM ;if (!f2fs_is_compress_backend_ready (inode))
fs/f2fs/inline.c +6 -0
@@ -239,6 +239,12 @@ int f2fs_convert_inline_inode(struct inode *inode)if (IS_ERR (folio))return PTR_ERR (folio); +/* +* Inline data is only supported in an order-0 index #0 folio; the +* inline write and mmap fault paths never request a larger order. +*/ +f2fs_bug_on (sbi,folio_test_large (folio)); +f2fs_lock_op (sbi, &lc); ientry =f2fs_get_inode_cache (sbi, inode->i_ino);
fs/f2fs/inode.c +1 -3
@@ -599,9 +599,7 @@ struct inode *f2fs_iget(struct super_block *sb, unsigned long ino) inode->i_op = &f2fs_file_inode_operations; inode->i_fop = &f2fs_file_operations; inode->i_mapping->a_ops = &f2fs_dblock_aops; -if (IS_IMMUTABLE (inode) && !f2fs_compressed_file (inode) && - !f2fs_quota_file (sbi, inode->i_ino)) -mapping_set_folio_min_order (inode->i_mapping,0 ); +f2fs_mapping_set_large_folio (inode); }else if (S_ISDIR (inode->i_mode)) { inode->i_op = &f2fs_dir_inode_operations; inode->i_fop = &f2fs_dir_operations;
fs/f2fs/namei.c +1 -0
@@ -341,6 +341,7 @@ static struct inode *f2fs_new_inode(struct mnt_idmap *idmap,f2fs_set_inode_flags (inode);f2fs_init_extent_tree (inode); +f2fs_mapping_set_large_folio (inode);trace_f2fs_new_inode (inode,0 );return inode;
Signature · 1 line
2.43.0
PATCH v6 15/15 f2fs: make compressed files compatible with large folio
In reply to Nanzhe ZhaoFrom: Nanzhe Zhao <[email protected]>
The compression flag is the hint indicates that the inode can be compressed, when the inode is using large folio, we expected it keeps using the large folio read/write paths and its data stays uncompressed on disk until the inode is evicted and re-read
Let f2fs_write_begin() skip the compression overwrite preparation for such inodes and remove the compressed-file gate in f2fs_read_data_large_folio() so the data is simply read/written as regular blocks.
For the same reason, reject F2FS_IOC_COMPRESS_FILE with -EOPNOTSUPP once the inode mapping is switched to large folios.
--- Documentation/filesystems/f2fs.rst | 10 ++++++++++ fs/f2fs/compress.c | 2 ++ fs/f2fs/data.c | 9 ++------- fs/f2fs/file.c | 7 +++++++ 4 files changed, 21 insertions(+), 7 deletions(-)
Documentation/filesystems/f2fs.rst +10 -0
@@ -942,6 +942,16 @@ Compression implementation reserved via ioctl(F2FS_IOC_RESERVE_COMPRESS_BLOCKS) or the file size is truncated to zero. +- Compression and large folios are not effective at the same time on a file: + a compressed inode does not use large folios, while an inode which is + using large folios keeps its data uncompressed on disk. If the compression + flag is set on an inode that is already using large folios, the flag works + as a hint until the inode is evicted: the inode keeps using the large folio + read/write paths, f2fs_write_begin() skips the compression overwrite + preparation, and ioctl(F2FS_IOC_COMPRESS_FILE) fails with -EOPNOTSUPP. + Once the inode is evicted and read back, it uses order-0 folios again and + compression is applied as usual. + Compress metadata layout:: [Dnode Structure]
fs/f2fs/compress.c +2 -0
@@ -78,6 +78,8 @@ bool f2fs_is_compressed_page(struct folio *folio)return false;if (folio_test_f2fs_nonpointer (folio))return false; +if (f2fs_folio_has_ffs (folio)) +return false;f2fs_bug_on (F2FS_F_SB (folio), *((u32 *)folio->private) !=F2FS_COMPRESSED_PAGE_MAGIC );
fs/f2fs/data.c +2 -7
@@ -3266,12 +3266,6 @@ static int f2fs_read_data_large_folio(struct inode *inode,int ret =0 ;bool folio_in_bio = false; -if (f2fs_compressed_file (inode)) { -if (folio) -folio_unlock (folio); -return -EOPNOTSUPP ; - } - map.m_seg_type =NO_CHECK_TYPE ;if (rac)
@@ -5286,7 +5280,8 @@ static int f2fs_write_begin(const struct kiocb *iocb, }#ifdef CONFIG_F2FS_FS_COMPRESSION -if (f2fs_compressed_file (inode)) { +if (f2fs_compressed_file (inode) && + !mapping_large_folio_support (inode->i_mapping)) {int ret;struct page *page;
fs/f2fs/file.c +7 -0
@@ -5021,6 +5021,13 @@ static int f2fs_ioc_compress_file(struct file *filp)if (!(filp->f_mode &FMODE_WRITE ))return -EBADF ; +/* +* The mapping is already using large folios, where the data is kept +* uncompressed, so refuse to start compressing the file. +*/ +if (mapping_large_folio_support (inode->i_mapping)) +return -EOPNOTSUPP ; +f2fs_balance_fs (sbi, true); ret =mnt_want_write_file (filp);
Signature · 1 line
2.43.0
Chao Yu
maintainerNanzhe,
FYI, this is from my local sashiko, please take a look to see if there is any valid review comment.
Patch 1: f2fs: extend folio state for large folio write path Result:
Critical: 1 · High: 0 · Medium: 0 · Low: 0
Reviewed
▼ Inline Review
Copy
commit 8845b499928f22b0f7dcf2d87614719b304cb8d8
Author: Nanzhe Zhao <[email protected]>
f2fs: extend folio state for large folio write path
Large folio write path needs a subpage status bitmap and write pages pending counter, while keeping compatible with f2fs private flags. This patch moves struct f2fs_folio_state to f2fs.h and updates PAGE_PRIVATE functions to be compatible with it.
Quoted 4 lines
fs/f2fs/f2fs.h +0
-0
[ ... ]
fs/f2fs/f2fs.h enum { · line 1650
Quoted 11 lines
fs/f2fs/f2fs.h +7
-0@@ -1629,6 +1641,13 @@ enum { PAGE_PRIVATE_MAX }; +static inline bool f2fs_folio_has_ffs (const struct folio *folio) +{ +unsigned long private = (unsigned long )folio->private; + +return folio_test_large (folio) && private; +} +
Should this check also exclude the PAGE_PRIVATE_NOT_POINTER bit? If a large folio has no ffs structure attached, but has an integer stored in folio->private with the PAGE_PRIVATE_NOT_POINTER bit set, this function will incorrectly return true.
[ ... ]
Quoted 1 line
fs/f2fs/f2fs.h +0
-0@@ -2769,13 +2788,35 @@ static inline int inc_valid_block_count(struct f2fs_sb_info *sbi,
[ ... ]
fs/f2fs/f2fs.h
Quoted 8 lines
fs/f2fs/f2fs.h +8
-0+static inline unsigned long *f2fs_folio_flags_addr (struct folio *folio) +{ +if (f2fs_folio_has_ffs (folio)) +return &((struct f2fs_folio_state *)folio->private)->private_flags; + +return (unsigned long *)&folio->private; +} +
If f2fs_folio_has_ffs() returns true because an integer with the PAGE_PRIVATE_NOT_POINTER bit is stored in folio->private, does this code cast that raw integer into a struct f2fs_folio_state pointer?
This would return an invalid out-of-bounds address for the private_flags field, leading to a crash when it gets dereferenced.
[ ... ]
Quoted 8 lines
fs/f2fs/f2fs.h +0
-3@@ -2787,14 +2828,10 @@ static inline bool page_private_##name(struct page *page) \#define PAGE_PRIVATE_SET_FUNC (name, flagname) \ static inline void folio_set_f2fs_##name(struct folio *folio) \ { \ - unsigned long v = (1UL << PAGE_PRIVATE_NOT_POINTER) | \ - (1UL << PAGE_PRIVATE_##flagname); \ if (!folio->private) \ - folio_attach_private(folio, (void *)v); \
fs/f2fs/f2fs.h static inline bool page_private_##name(struct page *page) \ · line 2837
Quoted 10 lines
fs/f2fs/f2fs.h +3
-4-else { \ - v |= (unsigned long )folio->private; \ - folio->private = (void *)v; \ - } \ +folio_attach_private (folio, \ + (void *)BIT (PAGE_PRIVATE_NOT_POINTER )); \ + set_bit(PAGE_PRIVATE_##flagname, f2fs_folio_flags_addr(folio)); \ } \ static inline void set_page_private_##name(struct page *page) \ { \
Can this sequence trigger an invalid pointer dereference and a kernel panic? If PAGE_PRIVATE_SET_FUNC (e.g., folio_set_f2fs_gcing) is called on a large folio without an ffs structure:
1. folio->private is set to BIT(PAGE_PRIVATE_NOT_POINTER) (which is 1).
2. f2fs_folio_flags_addr() is called.
3. f2fs_folio_has_ffs() sees folio_test_large() and private != 0, returning true.
4. f2fs_folio_flags_addr() casts the integer 1 to a struct f2fs_folio_state pointer, returning a memory address based off this invalid pointer.
5. set_bit() attempts to write to this invalid unmapped memory address.
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 1376k · Cached: 7798k · Out: 22k
View Review Map·View Raw Log
↑ Back to Summary
Patch 2: f2fs: carry subpage offset and count in write IO Result:
No regressions
Reviewed
▶ Inline Review
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 1891k · Cached: 28375k · Out: 43k View Review Map·View Raw Log
↑ Back to Summary
Patch 3: f2fs: support regular file buffered writes on large folios Result:
Critical: 0 · High: 2 · Medium: 0 · Low: 0
Reviewed
▼ Inline Review
Copy
commit 0f231c7061b3be0f1eb6bb222db57bfbcdc48ecb
Author: Nanzhe Zhao <[email protected]>
f2fs: support regular file buffered writes on large folios This commit introduces large folio support for f2fs regular buffered writes. It preallocates partial blocks for inodes that use large folios to avoid complex unlocking during write_begin. During write_begin, it only reads the partial head and tail 4K subpages that require read-before-write.
Quoted 3 lines
fs/f2fs/data.c +0
-0
[ ... ]
Quoted 1 line
fs/f2fs/data.c +0
-0@@ -4158,6 +4335,151 @@ static int prepare_atomic_write_begin(struct f2fs_sb_info *sbi,
[ ... ]
Quoted 33 lines
fs/f2fs/data.c +33
-0+static int prepare_large_folio_write_begin (struct inode *inode, +struct folio *folio,loff_t pos, +unsigned int len) +{ +struct f2fs_sb_info *sbi =F2FS_I_SB (inode); +struct f2fs_folio_state *ffs; +size_t ori_off =offset_in_folio (folio, pos); +size_t need_off = ori_off; +int err =0 ; + +/* +* when the write did not come through f2fs_write_iter, we preallocate all +* blocks in the write range here. +*/ +if (!is_inode_flag_set (inode,FI_PREALLOCATED_ALL ) && + !IS_DEVICE_ALIASING (inode)) { +pgoff_t first =F2FS_BYTES_TO_BLK (sbi, pos); +pgoff_t last =F2FS_BLK_ALIGN (sbi, pos + len); +pgoff_t idx; + +for (idx = first; idx < last; idx++) { +block_t blkaddr =NULL_ADDR ; +bool node_changed = false; + + err =__reserve_data_block (inode, idx, &blkaddr, + &node_changed); +if (err) +return err; +if (f2fs_balance_fs_folio_locked (folio, folio->mapping, + node_changed)) +return -EAGAIN ; + } + }
[ ... ]
fs/f2fs/data.c
Quoted 7 lines
fs/f2fs/data.c +7
-0+/* +* The read extent cache only validates the first and last +* block of i_ext, so check both the cached and dnode paths. +*/ +if (!f2fs_is_valid_blkaddr (sbi, blkaddr, +DATA_GENERIC_ENHANCE_READ )) +return -EFSCORRUPTED ;
Can this result in a spurious -EFSCORRUPTED error during a direct I/O fallback?
In f2fs_preallocate_blocks(), FI_PREALLOCATED_ALL is set unconditionally when f2fs_map_blocks() returns 0. However, for direct I/O, the allocation exits early on physically unmergeable extents, meaning map.m_len might be smaller than requested.
If a partial direct I/O write falls back to buffered I/O via f2fs_buffered_write_iter(), this new prepare_large_folio_write_begin() path will see FI_PREALLOCATED_ALL and skip block reservation for the unallocated tail.
Will reading the unallocated hole then yield a NULL_ADDR and trigger the -EFSCORRUPTED failure here?
[ ... ]
Quoted 15 lines
fs/f2fs/data.c +9
-2@@ -4395,8 +4744,22 @@ static bool f2fs_dirty_data_folio(struct address_space *mapping,trace_f2fs_set_page_dirty (folio,DATA ); -if (!folio_test_uptodate (folio)) -folio_mark_uptodate (folio); +if (!folio_test_uptodate (folio)) { +bool uptodate = true; + +if (f2fs_folio_has_ffs (folio)) { +struct f2fs_folio_state *ffs = + (struct f2fs_folio_state *)folio->private; +unsigned long flags; + +spin_lock_irqsave (&ffs->state_lock, flags);
fs/f2fs/data.c static bool f2fs_dirty_data_folio(struct address_space *mapping, · line 4765
Quoted 10 lines
fs/f2fs/data.c +7
-0+ uptodate =bitmap_full (ffs->state,folio_nr_pages (folio)) && + !ffs->read_pages_pending; +spin_unlock_irqrestore (&ffs->state_lock, flags); + } +if (uptodate) +folio_mark_uptodate (folio); + }BUG_ON (folio_test_swapcache (folio));if (filemap_dirty_folio (mapping, folio)) {
Does this miss updating the ffs dirty bitmap for large folios modified via external paths like get_user_pages?
Modifications made to an mmapped f2fs large folio via external subsystems (like direct I/O or device DMA using get_user_pages) call folio_mark_dirty() when unpinning. This triggers f2fs_dirty_data_folio() which sets the generic PG_dirty flag.
However, because the subpages are not marked dirty in the ffs bitmap, when writeback later runs f2fs_write_cache_folios(), it relies on ffs_find_dirty_range(). If the ffs dirty bitmap is empty, it appears the loop will skip the I/O entirely and discard the data.
Should we be updating the ffs dirty bitmap here after a successful filemap_dirty_folio() for large folios?
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 1542k · Cached: 14448k · Out: 36k
View Review Map·View Raw Log
↑ Back to Summary
Patch 4: f2fs: support atomic file large folios buffered write Result:
Critical: 0 · High: 0 · Medium: 1 · Low: 0
Reviewed
▼ Inline Review
Copy
commit 53688cad23a91b76f64efcd823a6c489381ac485
Author: Nanzhe Zhao <[email protected]>
f2fs: support atomic file large folios buffered write
This commit adds support for large folio buffered writes to f2fs atomic files. It introduces a helper to reserve COW mappings for the write range and handle partial head and tail subpages.
Quoted 3 lines
fs/f2fs/data.c +0
-0
[ ... ]
Quoted 5 lines
fs/f2fs/data.c +4
-0@@ -4480,6 +4478,61 @@ static int prepare_large_folio_write_begin(struct inode *inode, +static int prepare_large_folio_atomic_write_begin (struct inode *inode, +struct address_space *mapping,struct folio *folio,loff_t pos, +unsigned int len) +{
[ ... ]
Quoted 9 lines
fs/f2fs/data.c +9
-0+for (index = start; index <= end; index++) { +block_t blkaddr =NULL_ADDR ; +bool node_changed = false; +size_t off = (index - folio->index) <<PAGE_SHIFT ; + + err =prepare_atomic_write_begin (sbi, inode, index, + &blkaddr, &node_changed); +if (err) +return err;
[ ... ]
fs/f2fs/data.c
Quoted 3 lines
fs/f2fs/data.c +3
-0+balance: +if (f2fs_balance_fs_folio_locked (folio, mapping, node_changed)) +return -EAGAIN ;
Can returning -EAGAIN here cause atomic write counts to be double counted for prior subpages?
If f2fs_balance_fs_folio_locked() requires balance, it returns -EAGAIN. This causes the outer loop in f2fs_write_begin() to restart the folio preparation, which re-runs prepare_large_folio_atomic_write_begin() starting from the first subpage.
On this retry, prepare_atomic_write_begin() will be called again for subpages that have already been processed. For append writes, the COW lookup is skipped and it goes straight to block reservation:
fs/f2fs/data.c:prepare_atomic_write_begin() {
...
if (((loff_t)index << PAGE_SHIFT) >= i_size_read(inode))
goto reserve_block;
...
reserve_block:
if (!cow_has_reserved_block) {
err = __reserve_data_block(...);
...
inc_atomic_write_cnt(inode);
}
}Because cow_has_reserved_block defaults to false and the COW lookup was skipped, inc_atomic_write_cnt() will be incremented a second time for every subpage already processed before the abort. Could this corrupt the atomic write statistics?
fs/f2fs/data.c
Quoted 4 lines
fs/f2fs/data.c +4
-0+ } + +return 0 ; +}
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 1041k · Cached: 12285k · Out: 31k View Review Map·View Raw Log
↑ Back to Summary
Patch 5: f2fs: support large folio writeback
Result:
Critical: 0 · High: 3 · Medium: 0 · Low: 0
Reviewed
▼ Inline Review
Copy
commit 5beb2c47fdab941c94ce2dbf16d7119ff73077df
Author: Nanzhe Zhao <[email protected]>
f2fs: support large folio writeback
This commit adds a folio-based writeback path for large-folio mapping files to handle multiple dirty ranges within a large folio. It introduces f2fs_write_cache_folios() for large folios while keeping the legacy f2fs_write_cache_pages() path for non-large-folio files.
Quoted 4 lines
fs/f2fs/data.c +0
-0
[ ... ]
Quoted 5 lines
fs/f2fs/data.c +1
-0@@ -358,6 +358,49 @@ static void f2fs_cache_write_end_bio(struct bio *bio)bio_put (bio); } +static bool f2fs_ffs_has_dirty_subpage (struct folio *folio)
[ ... ]
Quoted 6 lines
fs/f2fs/data.c +6
-0+static void f2fs_ffs_put_write_pending (struct folio *folio,unsigned int nr) +{ +struct f2fs_folio_state *ffs; + +if (!f2fs_folio_has_ffs (folio)) + goto release;
fs/f2fs/data.c
Quoted 10 lines
fs/f2fs/data.c +10
-0+ + ffs = (struct f2fs_folio_state *)folio->private; +if (!atomic_sub_and_test (nr, &ffs->write_pages_pending)) +return ; +release: +if (!f2fs_ffs_has_dirty_subpage (folio)) +folio_clear_f2fs_gcing (folio); +if (folio_test_writeback (folio)) +folio_end_writeback (folio); +}
Does this prematurely end writeback for the entire large folio when it lacks FFS state?
If a large folio is dirtied without an attached f2fs_folio_state (FFS), it bypasses the write_pages_pending reference counter during background writeback. When the first I/O block completes, f2fs_ffs_put_write_pending() will immediately call folio_end_writeback(). This clears the page cache writeback state while other blocks from the same folio might still be undergoing active DMA, which could lead to data corruption or a use-after-free if the page cache frees the folio or userspace modifies it.
A Time-Of-Check to Time-Of-Use (TOCTOU) race exists when retrieving a folio using f2fs_get_lock_data_folio(). It calls f2fs_get_read_data_folio(), which allocates FFS but then unlocks the folio if it is already up-to-date. Before f2fs_get_lock_data_folio() re-acquires the lock, a concurrent memory reclaim can call f2fs_release_folio() on the clean folio, freeing its FFS state. Once successfully re-locked, callers like move_data_page() or truncate_partial_data_page() dirty the folio, silently falling back to folio_mark_dirty() and inserting a dirty large folio without FFS into the writeback path.
[ ... ]
Quoted 9 lines
fs/f2fs/data.c +5
-0@@ -3523,6 +3668,144 @@ int f2fs_do_write_data_page(struct f2fs_io_info *fio)return err; } +static int f2fs_write_folio_dirty_range (struct folio *folio,int *submitted, +struct writeback_control *wbc, +enum iostat_type io_type, +u64 *pos,u64 len) +{
[ ... ]
Quoted 4 lines
fs/f2fs/data.c +4
-0+ err =f2fs_get_dnode_of_data (&dn, data_idx,LOOKUP_NODE ); +if (err) + goto block_done; + dn_held = true;
fs/f2fs/data.c
Quoted 10 lines
fs/f2fs/data.c +10
-0+ + fio.old_blkaddr = dn.data_blkaddr; + +got_it: +if (__is_valid_data_blkaddr (fio.old_blkaddr) && + !f2fs_is_valid_blkaddr (sbi, fio.old_blkaddr, +DATA_GENERIC_ENHANCE )) { + err = -EFSCORRUPTED ; + goto block_done; + }
Can this crash the kernel via f2fs_bug_on() due to a missing NULL_ADDR check? When f2fs_get_dnode_of_data() returns the dnode for a punched hole block, its data_blkaddr is NULL_ADDR. This code assigns it to fio.old_blkaddr but fails to check if fio.old_blkaddr is NULL_ADDR before unconditionally calling f2fs_outplace_write_data().
The legacy f2fs_do_write_data_page() checks if the old block address is NULL_ADDR to cleanly skip subpages that were hole-punched after being dirtied. Without that check here, f2fs_outplace_write_data() will hit this assertion and panic the kernel:
f2fs_bug_on(sbi, dn->data_blkaddr == NULL_ADDR);
This could be triggered by overlapping mmap writes and fallocate hole punches. [ ... ]
Quoted 5 lines
fs/f2fs/data.c +1
-0@@ -3972,6 +4255,226 @@ static int f2fs_write_cache_pages(struct address_space *mapping,return ret; } +static int f2fs_write_cache_folios(struct address_space *mapping,
[ ... ]
fs/f2fs/data.c
Quoted 12 lines
fs/f2fs/data.c +12
-0+/* +* Large folios can be submitted as multiple bios, which may +* complete while we are still submitting the remaining dirty +* ranges. Hold a bias on write_pages_pending to prevent +* folio_end_writeback() from being called early. +*/ +if (!bias_added &&f2fs_folio_has_ffs (folio)) { + ffs = (struct f2fs_folio_state *)folio->private; +WARN_ON_ONCE (atomic_read (&ffs->write_pages_pending) !=0 ); +atomic_inc (&ffs->write_pages_pending); + bias_added = true; + }
If a large folio lacks FFS state (for instance, due to the reclaim race mentioned above), this path skips incrementing the write_pages_pending bias but will still loop over and submit I/O for all blocks in the folio. This directly contributes to the premature writeback completion issue. [ ... ]
fs/f2fs/data.c
Quoted 11 lines
fs/f2fs/data.c +11
-0+out: +/* +* Clear the dirty state of the subranges that were written back. +* If some subranges are still dirty (e.g. the folio was only +* partially written back), or if the writeback failed, the +* folio must stay dirty so that the remaining subranges are +* written back later. +*/ +if (f2fs_ffs_clear_subrange_dirty_and_test (folio,0 , + (err ? pos : end_pos) -folio_pos (folio)) || err) +folio_redirty_for_writepage (wbc, folio);
Does this logic trap the worker in an infinite writeback loop on truncated or hole-punched large folios?
If a hole is punched, f2fs_get_dnode_of_data() returns -ENOENT, which is propagated up to f2fs_write_cache_folios() as err. The || err condition evaluates to true and unconditionally redirties the folio, causing it to be retried endlessly.
Similarly, if the file is truncated such that the EOF splits the folio, end_pos is clamped to isize. f2fs_ffs_clear_subrange_dirty_and_test() will clear bits from 0 to end_pos, skipping the subpages beyond EOF. Because those dirty bits remain, it returns true, which also triggers folio_redirty_for_writepage() and leaves the folio dirty permanently.
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 1211k · Cached: 11018k · Out: 26k
View Review Map·View Raw Log
↑ Back to Summary
Patch 6: f2fs: account large folio dirty data at block granularity Result:
No regressions
Reviewed
▶ Inline Review
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 698k · Cached: 5473k · Out: 14k
View Review Map·View Raw Log
↑ Back to Summary
Patch 7: f2fs: prepare mmap write faults for large folios Result:
No regressions
Reviewed
▶ Inline Review
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 1435k · Cached: 6126k · Out: 20k View Review Map·View Raw Log
↑ Back to Summary
Patch 8: f2fs: make GC migration large-folio aware
Result:
Critical: 0 · High: 0 · Medium: 1 · Low: 0
Reviewed
▼ Inline Review
Copy
commit 69c900aae91680bd5f0dda56fae4dc1617abe3a5
Author: Nanzhe Zhao <[email protected]>
f2fs: make GC migration large-folio aware
This patch makes garbage collection migration large-folio aware by updating data lookup helpers to test and update uptodate state for the addressed subpage. It also modifies move_data_page() to track dirty state per subpage and delegates write_pages_pending tracking and cleanup to f2fs_do_write_data_page().
Quoted 4 lines
fs/f2fs/data.c +0
-0
[ ... ]
Quoted 18 lines
fs/f2fs/data.c +7
-0@@ -3684,6 +3706,13 @@ int f2fs_do_write_data_page(struct f2fs_io_info *fio) out:if (fio->need_lock ==LOCK_REQ )f2fs_unlock_op (fio->sbi, &lc); +if (!submitted) { +if (pending_added) { +f2fs_ffs_put_write_pending (folio,1 ); + }else if (!f2fs_ffs_has_dirty_subpage (folio)) { +folio_clear_f2fs_gcing (folio); + } + }return err; }fs/f2fs/gc.c +0
-0
[ ... ]
Quoted 1 line
fs/f2fs/gc.c +0
-0@@ -1552,33 +1561,43 @@ static int move_data_page(struct inode *inode, block_t bidx, int gc_type,
[ ... ]
fs/f2fs/gc.c
Quoted 9 lines
fs/f2fs/gc.c +0
-1folio_set_f2fs_gcing (folio); err =f2fs_do_write_data_page (&fio);if (err) { -folio_clear_f2fs_gcing (folio);if (err == -ENOMEM ) {memalloc_retry_wait (GFP_NOFS ); goto retry; }
Is there a regression here where f2fs_do_write_data_page() bypasses the newly added cleanup code on early errors, leaking the PG_f2fs_gcing flag on the folio?
The removed cleanup relies on f2fs_do_write_data_page() performing it at the out label added above, but f2fs_do_write_data_page() can return directly without reaching that label. For example, it might fail on lock acquisition:
/* Deadlock due to between page->lock and f2fs_lock_op */ if (fio->need_lock == LOCK_REQ && !f2fs_trylock_op(fio->sbi, &lc)) return -EAGAIN;
Could the folio permanently retain the PG_f2fs_gcing flag since the caller-side cleanup was removed?
fs/f2fs/gc.c
Quoted 8 lines
fs/f2fs/gc.c +4
-1-if (is_dirty) +if (is_dirty) { +if (large) +f2fs_ffs_mark_subrange_dirty (folio, foff,PAGE_SIZE );folio_mark_dirty (folio); + } } }
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 1183k · Cached: 20602k · Out: 37k View Review Map·View Raw Log
↑ Back to Summary
Patch 9: f2fs: optimize small block size large folio read Result:
No regressions
Reviewed
▶ Inline Review
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 886k · Cached: 7605k · Out: 20k View Review Map·View Raw Log
↑ Back to Summary
Patch 10: f2fs: support partial uptodate large folio read Result:
No regressions
Reviewed
▶ Inline Review
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 613k · Cached: 1023k · Out: 12k View Review Map·View Raw Log
↑ Back to Summary
Patch 11: f2fs: handle partial truncate of large folio dirty subpages Result:
No regressions
Reviewed
▶ Inline Review
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 1417k · Cached: 16831k · Out: 28k
View Review Map·View Raw Log
↑ Back to Summary
Patch 12: f2fs: fix zeroing paths for large folios
Result:
Critical: 0 · High: 1 · Medium: 0 · Low: 0
Reviewed
▼ Inline Review
Copy
commit 506953384e1ed7cc966a73a775ee46b38f01377e
Author: Nanzhe Zhao <[email protected]>
f2fs: fix zeroing paths for large folios
This commit updates several f2fs zeroing paths to use folio offsets instead of PAGE_SIZE based offsets to properly handle large folios.
Quoted 4 lines
fs/f2fs/file.c +0
-0
[ ... ]
fs/f2fs/file.c static int truncate_partial_data_page(struct inode *inode, u64 from, · line 860
Quoted 6 lines
fs/f2fs/file.c +1
-1@@ -856,12 +857,22 @@ static int truncate_partial_data_page(struct inode *inode, u64 from,return PTR_ERR (folio) == -ENOENT ?0 :PTR_ERR (folio); truncate_out:f2fs_folio_wait_writeback (folio, true, true); -folio_zero_segment (folio, offset,folio_size (folio)); + folio_off =offset_in_folio (folio, from);
Does this code skip zeroing valid subpages of partially up-to-date large folios?
Just above this hunk in truncate_partial_data_page(), the cache_only block checks the uptodate status of the folio:
if (cache_only) {
folio = filemap_lock_folio(mapping, index);
if (IS_ERR(folio))
return 0;
if (folio_test_uptodate(folio))
goto truncate_out;
f2fs_folio_put(folio, true);
return 0;
}For large folios, folio_test_uptodate() returns true only if the entire folio is up-to-date. If the folio is only partially up-to-date, but the specific subpage being truncated is valid, this check returns false. This causes the function to exit without jumping to truncate_out, skipping the zeroing and leaking stale pre-truncation data in the page cache.
Should this check be converted to f2fs_ffs_test_blk_uptodate(folio, index) to match the changes made in f2fs_get_new_data_folio()?
fs/f2fs/file.c static int truncate_partial_data_page(struct inode *inode, u64 from, · line 863
Quoted 3 lines
fs/f2fs/file.c +3
-0+ blk_end =min_t (size_t,round_up (folio_off,PAGE_SIZE ), +folio_size (folio)); +folio_zero_segment (folio, folio_off, blk_end);
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 1446k · Cached: 13715k · Out: 21k View Review Map·View Raw Log
↑ Back to Summary
Patch 13: f2fs: handle block cloning within the same large folio Result:
Critical: 0 · High: 1 · Medium: 0 · Low: 0
Reviewed
▼ Inline Review
Copy
commit e71bedd5f33b6f06c04e1ac6a7f0f828fabd0fc0
Author: Nanzhe Zhao <[email protected]>
f2fs: handle block cloning within the same large folio
This commit modifies __clone_blkaddrs() to correctly handle block cloning when source and destination blocks belong to the same large folio. It detects the same-folio case and explicitly reserves the destination block to avoid self-deadlocks.
Quoted 4 lines
fs/f2fs/file.c +0
-0
[ ... ]
Quoted 4 lines
fs/f2fs/file.c +0
-0@@ -1598,25 +1598,70 @@ static int __clone_blkaddrs(struct inode *src_inode, struct inode *dst_inode,f2fs_put_dnode (&dn); }else {struct folio *fsrc, *fdst;
[ ... ]
Quoted 16 lines
fs/f2fs/file.c +16
-0+ same_folio = src_inode == dst_inode && +folio_contains (fsrc, dst + i); +if (same_folio) { +struct dnode_of_data dn; + +/* Reserve block for dst before copying */ +set_new_dnode (&dn, dst_inode,NULL ,NULL ,0 ); + ret =f2fs_reserve_block (&dn, dst + i); +if (ret) { +f2fs_folio_put (fsrc, true); +return ret; + } + fdst = fsrc; + }else { + fdst =f2fs_get_new_data_folio (dst_inode,NULL , + dst + i, true);
[ ... ]
fs/f2fs/file.c
Quoted 12 lines
fs/f2fs/file.c +9
-2f2fs_folio_wait_writeback (fdst, true, true); - -memcpy_folio (fdst,0 , fsrc,0 ,PAGE_SIZE ); +memcpy_folio (fdst, dst_off, fsrc, src_off, +PAGE_SIZE ); +if (folio_test_large (fdst)) { +if (!f2fs_ffs_find_or_alloc (fdst)) { +f2fs_folio_put (fdst, true); +if (!same_folio) +f2fs_folio_put (fsrc, true); +return -ENOMEM ; + }
Does returning -ENOMEM here leave the page cache corrupted? Before this check, memcpy_folio() has already copied the data into the destination folio. If f2fs_ffs_find_or_alloc() fails and we return -ENOMEM, the page cache modification is not reverted.
If the cloning operation is aborted, would userspace read the incorrectly modified page cache? Could this corrupted data also be persisted to disk if the folio is later dirtied?
Additionally, when same_folio is true, the block reserved earlier with f2fs_reserve_block() does not appear to be reverted on this error path.
fs/f2fs/file.c
Quoted 6 lines
fs/f2fs/file.c +5
-0+f2fs_ffs_mark_subrange_uptodate (fdst, + dst_off,PAGE_SIZE ); +f2fs_ffs_mark_subrange_dirty (fdst, dst_off, +PAGE_SIZE ); + }folio_mark_dirty (fdst);
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 418k · Cached: 3283k · Out: 15k
View Review Map·View Raw Log
↑ Back to Summary
Patch 14: f2fs: allow large folio support to writeable files Result:
Critical: 0 · High: 1 · Medium: 1 · Low: 0
Reviewed
▼ Inline Review
Copy
commit 2533e48a3606c7c0d5518871039a69a5277636bd
Author: Nanzhe Zhao <[email protected]>
f2fs: allow large folio support to writeable files
This commit enables large folio mappings for writable files in f2fs by removing runtime restrictions. It attempts to restrict them using an IS_IMMUTABLE check at inode initialization as a transitional safety measure.
Quoted 4 lines
fs/f2fs/f2fs.h +0
-0
[ ... ]
Quoted 7 lines
fs/f2fs/f2fs.h +3
-0@@ -5358,6 +5358,23 @@ static inline bool f2fs_quota_file(struct f2fs_sb_info *sbi, nid_t ino)return false; } +static inline void f2fs_mapping_set_large_folio (struct inode *inode) +{ + if (!S_ISREG(inode->i_mode) ||
fs/f2fs/f2fs.h static inline bool f2fs_quota_file(struct f2fs_sb_info *sbi, nid_t ino) · line 5373
Quoted 10 lines
fs/f2fs/f2fs.h +10
-0+f2fs_compressed_file (inode) || + f2fs_quota_file(F2FS_I_SB(inode), inode->i_ino)) + return; + +/* +* Keep the folio order range at 0 as a transitional step; large +* folios will be enabled once the whole write path is audited. +*/ +if (IS_IMMUTABLE (inode)) +mapping_set_folio_min_order (inode->i_mapping,0 );
Can this check be bypassed using FS_IOC_SETFLAGS?
If a user creates a file, sets it immutable (chattr +i), and drops caches to force an inode reload, the mapping is configured with MAX_PAGECACHE_ORDER. The user can then clear the immutable flag (chattr -i).
Since f2fs_setflags_common() clears S_IMMUTABLE but does not downgrade the VFS mapping limits, this now-mutable file can be opened for writing and populate the page cache with large folios.
Quoted 13 lines
fs/f2fs/f2fs.h +3
-0+else +mapping_set_folio_order_range (inode->i_mapping,0 ,0 ); +}fs/f2fs/file.c +0
-2@@ -163,17 +163,8 @@ static vm_fault_t f2fs_vm_page_mkwrite(struct vm_fault *vmf)int err =0 ;vm_fault_t ret; -/* -* We only support large folio on the read case.
fs/f2fs/file.c static vm_fault_t f2fs_vm_page_mkwrite(struct vm_fault *vmf) · line 176
Quoted 10 lines
fs/f2fs/file.c +1
-8-* Don't make any dirty pages. -*/ -if (unlikely (IS_IMMUTABLE (inode)) || -mapping_large_folio_support (inode->i_mapping)) { -f2fs_err (sbi,"Not expected: immutable: %d large_folio: %d" , -IS_IMMUTABLE (inode), -mapping_large_folio_support (inode->i_mapping)); +if (unlikely (IS_IMMUTABLE (inode)))return VM_FAULT_SIGBUS ; - }
Because this patch removes the runtime mapping_large_folio_support() safety checks here (and in f2fs_file_open and f2fs_setattr), the folios from the bypass described above will enter the unaudited write paths.
Does this cause O(N^2) complexity and massive stat inflation for large folios? When a large folio is mapped into a writable VMA, the core MM generates page faults for each 4KB subpage independently. In f2fs_vm_page_mkwrite(), the code calculates dirty_len as the size of the entire valid portion of the folio up to EOF, rather than the size of the faulting subpage.
It then loops over all blocks in the folio:
for (i = 0; i < nr; i++) {
err = f2fs_get_block_mkwrite(inode, folio, folio->index + i,
need_alloc);
and increments the IO stats by the full folio size:
f2fs_update_iostat(sbi, inode, APP_MAPPED_IO, dirty_len);For a 2MB large folio, sequentially writing to all 512 subpages will trigger this page fault handler 512 times. Each invocation processes all 512 blocks and increments the IO stats by 2MB, resulting in 262,144 block iterations and a 1GB inflation to APP_MAPPED_IO.
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 1573k · Cached: 22463k · Out: 34k
View Review Map·View Raw Log
↑ Back to Summary
Patch 15: f2fs: make compressed files compatible with large folio Result:
No regressions
Reviewed
▶ Inline Review
To: None Cc: None Status: Disabled (SMTP not configured)
Tokens used: In: 743k · Cached: 15590k · Out: 28k
View Review Map·View Raw Log
↑ Back to Summary
Hi Chao,
Thanks for forwarding the local Sashiko review. I went through every comment. Below I quote the review text and reply item by item.
== Patch 1: f2fs: extend folio state for large folio write path ==
Quoted 11 lines
Should this check also exclude the
PAGE_PRIVATE_NOT_POINTERbit? If a large folio has no ffs structure attached, but has an integer stored infolio->privatewith thePAGE_PRIVATE_NOT_POINTERbit set, this function will incorrectly return true.If
f2fs_folio_has_ffs()returns true because an integer with thePAGE_PRIVATE_NOT_POINTERbit is stored infolio->private, does this code cast that raw integer into a structf2fs_folio_statepointer?
This would return an invalid out-of-bounds address for theprivate_flagsfield, leading to a crash when it gets dereferenced.
Quoted 10 lines
Can this sequence trigger an invalid pointer dereference and a kernel panic? If
PAGE_PRIVATE_SET_FUNC(e.g.,folio_set_f2fs_gcing) is called on a large folio without an ffs structure:
1.folio->privateis set toBIT(PAGE_PRIVATE_NOT_POINTER)(which is 1).
2.f2fs_folio_flags_addr()is called.
3.f2fs_folio_has_ffs()seesfolio_test_large()and private != 0, returning true.
4.f2fs_folio_flags_addr()casts the integer 1 to a structf2fs_folio_statepointer, returning a memory address based off this invalid pointer.
5.set_bit()attempts to write to this invalid unmapped memory address.
In the current implementation, every path that can carry a large folio also allocates and keeps f2fs_folio_state; the private-flag layout is only used for order-0 folios. However, I did find one race window:
f2fs_get_read_data_folio():
if (f2fs_ffs_test_blk_uptodate(folio, index)) {
folio_unlock(folio);
return folio;
}
f2fs_get_lock_data_folio():
folio = f2fs_get_read_data_folio(inode, index, 0, for_write, NULL);
...
folio_lock(folio);
if (unlikely(folio->mapping != mapping ||
!f2fs_ffs_test_blk_uptodate(folio, index))) {
f2fs_folio_put(folio, true);
return ERR_PTR(-EIO);
}
return folio;A concurrent shrink can call ->release_folio() in the unlock window. On a clean large folio, f2fs_release_folio() detaches and frees the ffs:
bool f2fs_release_folio(struct folio *folio, gfp_t wait)
{
if (folio_test_dirty(folio))
return false;
ffs_detach_free(folio);
return true;
}__remove_mapping() then fails the folio_ref_freeze() check because the caller still holds a reference, so the folio stays in the mapping but has no ffs. On relock, the fully uptodate folio hits the early check in f2fs_ffs_test_blk_uptodate():
if (folio_test_uptodate(folio))
return true;and is returned to GC. GC later calls folio_set_f2fs_gcing() on a large folio whose private is NULL. This is the same root cause as the Patch 5 "large folio without ffs" comment; fixing this also fixes that one.
Expected diff:
diff --git a/fs/f2fs/data.c b/fs/f2fs/data.c
@@ struct folio *f2fs_get_lock_data_folio(struct inode *inode,
/* wait for read completion */ folio_lock(folio);
- if (unlikely(folio->mapping != mapping ||
- !f2fs_ffs_test_blk_uptodate(folio, index))) {
+ if (unlikely(folio->mapping != mapping)) {
f2fs_folio_put(folio, true);
return ERR_PTR(-EIO);
}
+ if (folio_test_large(folio) && !f2fs_folio_has_ffs(folio)) {
+ if (!f2fs_ffs_find_or_alloc(folio)) {
+ f2fs_folio_put(folio, true);
+ return ERR_PTR(-ENOMEM);
+ }
+ }
+ if (unlikely(!f2fs_ffs_test_blk_uptodate(folio, index))) {
+ f2fs_folio_put(folio, true);
+ return ERR_PTR(-EIO);
+ }
return folio;
== Patch 3: f2fs: support regular file buffered writes on large folios ==
Quoted 9 lines
Can this result in a spurious
-EFSCORRUPTEDerror during a direct I/O fallback?
Inf2fs_preallocate_blocks(),FI_PREALLOCATED_ALLis set unconditionally whenf2fs_map_blocks()returns 0. However, for direct I/O, the allocation exits early on physically unmergeable extents, meaning map.m_len might be smaller than requested.
...
Will reading the unallocated hole then yield aNULL_ADDRand trigger the-EFSCORRUPTEDfailure here?
False Positive. Our code path here is the buffered IO path, not the DIO case described.
Quoted 5 lines
Does this miss updating the ffs dirty bitmap for large folios modified via external paths like
get_user_pages?
...
Should we be updating the ffs dirty bitmap here after a successfulfilemap_dirty_folio()for large folios?
A writable mapping goes through f2fs_vm_page_mkwrite(), which marks the whole valid folio dirty before folio_mark_dirty():
if (folio_test_large(folio))
f2fs_ffs_mark_subrange_dirty(folio, 0, dirty_len);
folio_mark_dirty(folio);A GUP/DMA write needs a writable PTE, so it is covered by that page_mkwrite. I am not aware of a FOLL_WRITE path that bypasses page_mkwrite.
== Patch 4: f2fs: support atomic file large folios buffered write ==
Quoted 7 lines
Can returning
-EAGAINhere cause atomic write counts to be double counted for prior subpages?
...
Becausecow_has_reserved_blockdefaults to false and the COW lookup was skipped,inc_atomic_write_cnt()will be incremented a second time for every subpage already processed before the abort. Could this corrupt the atomic write statistics?
This is valid. For a large folio, the assumption behind this check does not hold:
if (((loff_t)index << PAGE_SHIFT) >= i_size_read(inode))
goto reserve_block;The retry can be caused by f2fs_balance_fs_folio_locked() dropping the folio lock and a concurrent reclaim calling ->release_folio(), which frees the ffs. The retry is not necessarily caused by a truncate, so the block at that index can still be NEW_ADDR.
The append branch itself is not new: the original 4K code skipped the COW lookup in the same way, so a retry there can also double count. The large-folio path makes it much easier to hit because balance can retry on ffs release or folio order change and restarts the whole folio.
The fix is to check the COW block only on retry. The first attempt keeps the original fast path (no COW lookup); once f2fs_write_begin() retries, it passes check_reserved=true so an already reserved NEW_ADDR block is not reserved and accounted again. This does not depend on whether a truncate path clears the block address.
Expected diff:
diff --git a/fs/f2fs/data.c b/fs/f2fs/data.c
@@ static int prepare_atomic_write_begin(struct f2fs_sb_info *sbi,
- struct inode *inode, pgoff_t index,
- block_t *blk_addr, bool *node_changed)
+ struct inode *inode, pgoff_t index,
+ block_t *blk_addr, bool *node_changed,
+ bool check_reserved)
{
struct inode *cow_inode = F2FS_I(inode)->cow_inode;
int err = 0;
block_t ori_blk_addr = NULL_ADDR;
bool cow_has_reserved_block = false;
+ bool append = ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode);
- if (((loff_t)index << PAGE_SHIFT) >= i_size_read(inode))
+ if (append && !check_reserved)
goto reserve_block;
/* Look for the block in COW inode first */
err = __find_data_block(cow_inode, index, blk_addr);
...
if (*blk_addr == NEW_ADDR)
cow_has_reserved_block = true;
- if (is_inode_flag_set(inode, FI_ATOMIC_REPLACE))
+ if (append || is_inode_flag_set(inode, FI_ATOMIC_REPLACE))
goto reserve_block;
@@ static int prepare_large_folio_atomic_write_begin(struct inode *inode,
- unsigned int len)
+ unsigned int len, bool retried)
{
...
err = prepare_atomic_write_begin(sbi, inode, index,
- &blkaddr, &node_changed);
+ &blkaddr, &node_changed, retried);
@@ static int f2fs_write_begin(const struct kiocb *iocb,
bool need_balance = false;
+ bool retried = false;
block_t blkaddr = NULL_ADDR;
...
if (err) {
if (err == -EAGAIN) {
+ retried = true;
f2fs_folio_put(folio, true);
goto repeat;
}
goto put_folio;
}
if (f2fs_balance_fs_folio_locked(folio, mapping, need_balance)) {
+ retried = true;
f2fs_folio_put(folio, true);
goto repeat;
}== Patch 5: f2fs: support large folio writeback ==
Quoted 5 lines
Does this prematurely end writeback for the entire large folio when it lacks FFS state?
If a large folio is dirtied without an attachedf2fs_folio_state(FFS), it bypasses thewrite_pages_pendingreference counter during background writeback.
Quoted 8 lines
When the first I/O block completes,
f2fs_ffs_put_write_pending()will immediately callfolio_end_writeback().
...
A Time-Of-Check to Time-Of-Use (TOCTOU) race exists when retrieving a folio usingf2fs_get_lock_data_folio(). It callsf2fs_get_read_data_folio(), which allocates FFS but then unlocks the folio if it is already up-to-date. Beforef2fs_get_lock_data_folio()re-acquires the lock, a concurrent memory reclaim can callf2fs_release_folio()on the clean folio, freeing its FFS state.
This is the same race as the one described for Patch 1. Once f2fs_get_lock_data_folio() rebuilds the ffs after relock, a large folio cannot enter writeback without ffs, so this one is fixed by the Patch 1 change rather than by a separate put() workaround.
Quoted 5 lines
Can this crash the kernel via
f2fs_bug_on()due to a missingNULL_ADDRcheck?
...
Without that check here,f2fs_outplace_write_data()will hit this assertion and panic the kernel:f2fs_bug_on(sbi, dn->data_blkaddr == NULL_ADDR);
False Positive. This is covered by 11/15, which adds the subpage-aware truncated state:
if (err == -ENOENT || fio.old_blkaddr == NULL_ADDR) {
f2fs_clear_truncated_page_state(folio, i);
err = 0;
goto block_done;
}Quoted 3 lines
Does this logic trap the worker in an infinite writeback loop on truncated or hole-punched large folios?
...
Same, covered by 11/15.
== Patch 8: f2fs: make GC migration large-folio aware ==
Quoted 11 lines
Is there a regression here where
f2fs_do_write_data_page()bypasses the newly added cleanup code on early errors, leaking thePG_f2fs_gcingflag on the folio?
The removed cleanup relies onf2fs_do_write_data_page()performing it at the out label added above, butf2fs_do_write_data_page()can return directly without reaching that label. For example, it might fail on lock acquisition:
/* Deadlock due to betweenpage->lockandf2fs_lock_op*/
if (fio->need_lock==LOCK_REQ&& !f2fs_trylock_op(fio->sbi, &lc))return -EAGAIN;Could the folio permanently retain the
PG_f2fs_gcingflag since the caller-side cleanup was removed?
This one is also valid. The early trylock failure returns directly and bypasses the common out path. Expected diff:
diff --git a/fs/f2fs/data.c b/fs/f2fs/data.c
@@ int f2fs_do_write_data_page(struct f2fs_io_info *fio)
/* Deadlock due to between page->lock and f2fs_lock_op */
- if (fio->need_lock == LOCK_REQ && !f2fs_trylock_op(fio->sbi, &lc))
- return -EAGAIN;
+ if (fio->need_lock == LOCK_REQ && !f2fs_trylock_op(fio->sbi, &lc)) {
+ if (!f2fs_ffs_has_dirty_subpage(folio))
+ folio_clear_f2fs_gcing(folio);
+ return -EAGAIN;
+ }
The Patch 1 race and this early-return path are the two issues I can fix immediately; the Patch 4 atomic accounting and the Patch 14 mkwrite part are also valid, but need more design work.
== Patch 12: f2fs: fix zeroing paths for large folios ==
Quoted 5 lines
Does this code skip zeroing valid subpages of partially up-to-date large folios?
...
Should this check be converted tof2fs_ffs_test_blk_uptodate(folio, index)to match the changes made inf2fs_get_new_data_folio()?
False Positive. cache_only is only passed for inline data: truncate_page is set only in the f2fs_has_inline_data() branch of f2fs_do_truncate_blocks(). Inline data is order-0, and f2fs_read_inline_data() marks the whole folio uptodate, so the large-folio partially-uptodate case cannot reach the cache_only branch.
== Patch 13: f2fs: handle block cloning within the same large folio ==
Quoted 9 lines
Does returning
-ENOMEMhere leave the page cache corrupted? Before this check,memcpy_folio()has already copied the data into the destination folio. Iff2fs_ffs_find_or_alloc()fails and we return-ENOMEM, the page cache modification is not reverted.
If the cloning operation is aborted, would userspace read the incorrectly modified page cache? Could this corrupted data also be persisted to disk if the folio is later dirtied?
Additionally, whensame_foliois true, the block reserved earlier withf2fs_reserve_block()does not appear to be reverted on this error path.
f2fs_get_new_data_folio() already calls f2fs_ffs_find_or_alloc() before returning the locked folio:
if (folio_test_large(folio) && !f2fs_ffs_find_or_alloc(folio)) {
f2fs_folio_put(folio, true);
f2fs_put_cache(ientry, true);
return ERR_PTR(-ENOMEM);
}False Positive. For same_folio, fdst is fsrc from f2fs_get_lock_data_folio(), which also has the ffs. The later f2fs_ffs_find_or_alloc(fdst) is redundant, and the post-memcpy ENOMEM path is unreachable in the normal flow.
== Patch 14: f2fs: allow large folio support to writeable files ==
Quoted 7 lines
Can this check be bypassed using
FS_IOC_SETFLAGS?
If a user creates a file, sets it immutable (chattr +i), and drops caches to force an inode reload, the mapping is configured withMAX_PAGECACHE_ORDER. The user can then clear the immutable flag (chattr -i).
Sincef2fs_setflags_common()clearsS_IMMUTABLEbut does not downgrade the VFS mapping limits, this now-mutable file can be opened for writing and populate the page cache with large folios.
Not important. Our final
direction is to enable large folios for writable files as well.
Quoted 6 lines
Does this cause O(N^2) complexity and massive stat inflation for large folios?
...
For a 2MB large folio, sequentially writing to all 512 subpages will trigger this page fault handler 512 times. Each invocation processes all 512 blocks and increments the IO stats by 2MB, resulting in 262,144 block iterations and a 1GB inflation toAPP_MAPPED_IO.
As explained before, do_shared_fault()'s finish_fault() installs writable PTEs for the whole folio. So we should dirty the whole folio to avoid data loss.
I will send a v7 series with these fixes.
Thanks,
Nanzhe
_______________________________________________
Linux-f2fs-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/linux-f2fs-devel
Hi Nanzhe,
Thanks for the updates.
Quoted 110 lines · Nanzhe Zhao
Hi Chao,
Thanks for forwarding the local Sashiko review. I went through every comment. Below I quote the review text and reply item by item.
== Patch 1: f2fs: extend folio state for large folio write path ==
Quoted 11 lines
Should this check also exclude the
PAGE_PRIVATE_NOT_POINTERbit? If a large folio has no ffs structure attached, but has an integer stored infolio->privatewith thePAGE_PRIVATE_NOT_POINTERbit set, this function will incorrectly return true.If
f2fs_folio_has_ffs()returns true because an integer with thePAGE_PRIVATE_NOT_POINTERbit is stored infolio->private, does this code cast that raw integer into a structf2fs_folio_statepointer?
This would return an invalid out-of-bounds address for theprivate_flagsfield, leading to a crash when it gets dereferenced.Quoted 10 lines
Can this sequence trigger an invalid pointer dereference and a kernel panic? If
PAGE_PRIVATE_SET_FUNC(e.g.,folio_set_f2fs_gcing) is called on a large folio without an ffs structure:
1.folio->privateis set toBIT(PAGE_PRIVATE_NOT_POINTER)(which is 1).
2.f2fs_folio_flags_addr()is called.
3.f2fs_folio_has_ffs()seesfolio_test_large()and private != 0, returning true.
4.f2fs_folio_flags_addr()casts the integer 1 to a structf2fs_folio_statepointer, returning a memory address based off this invalid pointer.
5.set_bit()attempts to write to this invalid unmapped memory address.In the current implementation, every path that can carry a large folio also allocates and keeps
f2fs_folio_state; the private-flag layout is only used for order-0 folios. However, I did find one race window:f2fs_get_read_data_folio(): if (f2fs_ffs_test_blk_uptodate(folio, index)) { folio_unlock(folio); return folio; } f2fs_get_lock_data_folio(): folio = f2fs_get_read_data_folio(inode, index, 0, for_write, NULL); ... folio_lock(folio); if (unlikely(folio->mapping != mapping || !f2fs_ffs_test_blk_uptodate(folio, index))) { f2fs_folio_put(folio, true); return ERR_PTR(-EIO); } return folio;A concurrent shrink can call ->release_folio() in the unlock window. On a clean large folio,
f2fs_release_folio()detaches and frees the ffs:bool f2fs_release_folio(struct folio *folio, gfp_t wait) { if (folio_test_dirty(folio)) return false; ffs_detach_free(folio); return true; }
__remove_mapping()then fails thefolio_ref_freeze()check because the caller still holds a reference, so the folio stays in the mapping but has no ffs. On relock, the fully uptodate folio hits the early check inf2fs_ffs_test_blk_uptodate():if (folio_test_uptodate(folio)) return true;and is returned to GC. GC later calls
folio_set_f2fs_gcing()on a large folio whose private is NULL. This is the same root cause as the Patch 5 "large folio without ffs" comment; fixing this also fixes that one.Expected diff:
diff --git
a/fs/f2fs/data.cb/fs/f2fs/data.c
@@ struct folio *f2fs_get_lock_data_folio(struct inode *inode,
/* wait for read completion */folio_lock(folio);
- if (unlikely(folio->mapping != mapping ||
- !f2fs_ffs_test_blk_uptodate(folio, index))) {
+ if (unlikely(folio->mapping != mapping)) {
f2fs_folio_put(folio, true);
returnERR_PTR(-EIO);
}
+ if (folio_test_large(folio)&& !f2fs_folio_has_ffs(folio)) {
+ if (!f2fs_ffs_find_or_alloc(folio)) {
+f2fs_folio_put(folio, true);
+ returnERR_PTR(-ENOMEM);
+ }
+ }
+ if (unlikely(!f2fs_ffs_test_blk_uptodate(folio, index))) {
+f2fs_folio_put(folio, true);
+ returnERR_PTR(-EIO);
+ }
return folio;== Patch 3: f2fs: support regular file buffered writes on large folios ==
Quoted 9 lines
Can this result in a spurious
-EFSCORRUPTEDerror during a direct I/O fallback?
Inf2fs_preallocate_blocks(),FI_PREALLOCATED_ALLis set unconditionally whenf2fs_map_blocks()returns 0. However, for direct I/O, the allocation exits early on physically unmergeable extents, meaning map.m_len might be smaller than requested.
...
Will reading the unallocated hole then yield aNULL_ADDRand trigger the-EFSCORRUPTEDfailure here?
Quoted 1 line
False Positive. Our code path here is the buffered IO path, not the DIO case described.
Agreed,
Looks like a bug, maybe we can add f2fs_bug_on for such case?
Quoted 14 lines
Quoted 6 lines
Does this miss updating the ffs dirty bitmap for large folios modified via external paths like
get_user_pages?
...
Should we be updating the ffs dirty bitmap here after a successfulfilemap_dirty_folio()for large folios?A writable mapping goes through
f2fs_vm_page_mkwrite(), which marks the whole valid folio dirty beforefolio_mark_dirty():if (folio_test_large(folio)) f2fs_ffs_mark_subrange_dirty(folio, 0, dirty_len); folio_mark_dirty(folio);
Quoted 13 lines
A GUP/DMA write needs a writable PTE, so it is covered by that
page_mkwrite. I am not aware of aFOLL_WRITEpath that bypassespage_mkwrite.== Patch 4: f2fs: support atomic file large folios buffered write ==
Quoted 7 lines
Can returning
-EAGAINhere cause atomic write counts to be double counted for prior subpages?
...
Becausecow_has_reserved_blockdefaults to false and the COW lookup was skipped,inc_atomic_write_cnt()will be incremented a second time for every subpage already processed before the abort. Could this corrupt the atomic write statistics?
I'm a bit confuse about what detailed number inc_atomic_write_cnt() tries to record, previously we need to call inc_atomic_write_cnt() only if node_changed is true, if it tries to record the first time write on cow inode, IIUC, please correct me if I understand incorrectly.
To Daeho, could you please take a look and help to review the comments and below change?
Quoted 216 lines
This is valid. For a large folio, the assumption behind this check does not hold:
if (((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) goto reserve_block;The retry can be caused by
f2fs_balance_fs_folio_locked()dropping the folio lock and a concurrent reclaim calling ->release_folio(), which frees the ffs. The retry is not necessarily caused by a truncate, so the block at that index can still beNEW_ADDR.The append branch itself is not new: the original 4K code skipped the COW lookup in the same way, so a retry there can also double count. The large-folio path makes it much easier to hit because balance can retry on ffs release or folio order change and restarts the whole folio.
The fix is to check the COW block only on retry. The first attempt keeps the original fast path (no COW lookup); once
f2fs_write_begin()retries, it passes check_reserved=true so an already reservedNEW_ADDRblock is not reserved and accounted again. This does not depend on whether a truncate path clears the block address.Expected diff:
diff --git a/fs/f2fs/data.c b/fs/f2fs/data.c @@ static int prepare_atomic_write_begin(struct f2fs_sb_info *sbi, - struct inode *inode, pgoff_t index, - block_t *blk_addr, bool *node_changed) + struct inode *inode, pgoff_t index, + block_t *blk_addr, bool *node_changed, + bool check_reserved) { struct inode *cow_inode = F2FS_I(inode)->cow_inode; int err = 0; block_t ori_blk_addr = NULL_ADDR; bool cow_has_reserved_block = false; + bool append = ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode); - if (((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) + if (append && !check_reserved) goto reserve_block; /* Look for the block in COW inode first */ err = __find_data_block(cow_inode, index, blk_addr); ... if (*blk_addr == NEW_ADDR) cow_has_reserved_block = true; - if (is_inode_flag_set(inode, FI_ATOMIC_REPLACE)) + if (append || is_inode_flag_set(inode, FI_ATOMIC_REPLACE)) goto reserve_block; @@ static int prepare_large_folio_atomic_write_begin(struct inode *inode, - unsigned int len) + unsigned int len, bool retried) { ... err = prepare_atomic_write_begin(sbi, inode, index, - &blkaddr, &node_changed); + &blkaddr, &node_changed, retried); @@ static int f2fs_write_begin(const struct kiocb *iocb, bool need_balance = false; + bool retried = false; block_t blkaddr = NULL_ADDR; ... if (err) { if (err == -EAGAIN) { + retried = true; f2fs_folio_put(folio, true); goto repeat; } goto put_folio; } if (f2fs_balance_fs_folio_locked(folio, mapping, need_balance)) { + retried = true; f2fs_folio_put(folio, true); goto repeat; }== Patch 5: f2fs: support large folio writeback ==
Quoted 5 lines
Does this prematurely end writeback for the entire large folio when it lacks FFS state?
If a large folio is dirtied without an attachedf2fs_folio_state(FFS), it bypasses thewrite_pages_pendingreference counter during background writeback.Quoted 8 lines
When the first I/O block completes,
f2fs_ffs_put_write_pending()will immediately callfolio_end_writeback().
...
A Time-Of-Check to Time-Of-Use (TOCTOU) race exists when retrieving a folio usingf2fs_get_lock_data_folio(). It callsf2fs_get_read_data_folio(), which allocates FFS but then unlocks the folio if it is already up-to-date. Beforef2fs_get_lock_data_folio()re-acquires the lock, a concurrent memory reclaim can callf2fs_release_folio()on the clean folio, freeing its FFS state.This is the same race as the one described for Patch 1. Once
f2fs_get_lock_data_folio()rebuilds the ffs after relock, a large folio cannot enter writeback without ffs, so this one is fixed by the Patch 1 change rather than by a separateput()workaround.Quoted 5 lines
Can this crash the kernel via
f2fs_bug_on()due to a missingNULL_ADDRcheck?
...
Without that check here,f2fs_outplace_write_data()will hit this assertion and panic the kernel:f2fs_bug_on(sbi, dn->data_blkaddr == NULL_ADDR);False Positive. This is covered by 11/15, which adds the subpage-aware truncated state:
if (err == -ENOENT || fio.old_blkaddr == NULL_ADDR) { f2fs_clear_truncated_page_state(folio, i); err = 0; goto block_done; }Quoted 3 lines
Does this logic trap the worker in an infinite writeback loop on truncated or hole-punched large folios?
...Same, covered by 11/15.
== Patch 8: f2fs: make GC migration large-folio aware ==
Quoted 11 lines
Is there a regression here where
f2fs_do_write_data_page()bypasses the newly added cleanup code on early errors, leaking thePG_f2fs_gcingflag on the folio?
The removed cleanup relies onf2fs_do_write_data_page()performing it at the out label added above, butf2fs_do_write_data_page()can return directly without reaching that label. For example, it might fail on lock acquisition:
/* Deadlock due to betweenpage->lockandf2fs_lock_op*/
if (fio->need_lock==LOCK_REQ&& !f2fs_trylock_op(fio->sbi, &lc))return -EAGAIN;Could the folio permanently retain the
PG_f2fs_gcingflag since the caller-side cleanup was removed?This one is also valid. The early trylock failure returns directly and bypasses the common out path. Expected diff:
diff --git
a/fs/f2fs/data.cb/fs/f2fs/data.c
@@ intf2fs_do_write_data_page(struct f2fs_io_info *fio)
/* Deadlock due to betweenpage->lockandf2fs_lock_op*/
- if (fio->need_lock==LOCK_REQ&& !f2fs_trylock_op(fio->sbi, &lc))
- return-EAGAIN;
+ if (fio->need_lock==LOCK_REQ&& !f2fs_trylock_op(fio->sbi, &lc)) {
+ if (!f2fs_ffs_has_dirty_subpage(folio))
+folio_clear_f2fs_gcing(folio);
+ return-EAGAIN;
+ }The Patch 1 race and this early-return path are the two issues I can fix immediately; the Patch 4 atomic accounting and the Patch 14 mkwrite part are also valid, but need more design work.
== Patch 12: f2fs: fix zeroing paths for large folios ==
Quoted 5 lines
Does this code skip zeroing valid subpages of partially up-to-date large folios?
...
Should this check be converted tof2fs_ffs_test_blk_uptodate(folio, index)to match the changes made inf2fs_get_new_data_folio()?False Positive.
cache_onlyis only passed for inline data:truncate_pageis set only in thef2fs_has_inline_data()branch off2fs_do_truncate_blocks(). Inline data is order-0, andf2fs_read_inline_data()marks the whole folio uptodate, so the large-folio partially-uptodate case cannot reach thecache_onlybranch.== Patch 13: f2fs: handle block cloning within the same large folio ==
Quoted 9 lines
Does returning
-ENOMEMhere leave the page cache corrupted? Before this check,memcpy_folio()has already copied the data into the destination folio. Iff2fs_ffs_find_or_alloc()fails and we return-ENOMEM, the page cache modification is not reverted.
If the cloning operation is aborted, would userspace read the incorrectly modified page cache? Could this corrupted data also be persisted to disk if the folio is later dirtied?
Additionally, whensame_foliois true, the block reserved earlier withf2fs_reserve_block()does not appear to be reverted on this error path.
f2fs_get_new_data_folio()already callsf2fs_ffs_find_or_alloc()before returning the locked folio:if (folio_test_large(folio) && !f2fs_ffs_find_or_alloc(folio)) { f2fs_folio_put(folio, true); f2fs_put_cache(ientry, true); return ERR_PTR(-ENOMEM); }False Positive. For
same_folio, fdst is fsrc fromf2fs_get_lock_data_folio(), which also has the ffs. The laterf2fs_ffs_find_or_alloc(fdst)is redundant, and the post-memcpy ENOMEM path is unreachable in the normal flow.== Patch 14: f2fs: allow large folio support to writeable files ==
Quoted 7 lines
Can this check be bypassed using
FS_IOC_SETFLAGS?
If a user creates a file, sets it immutable (chattr +i), and drops caches to force an inode reload, the mapping is configured withMAX_PAGECACHE_ORDER. The user can then clear the immutable flag (chattr -i).
Sincef2fs_setflags_common()clearsS_IMMUTABLEbut does not downgrade the VFS mapping limits, this now-mutable file can be opened for writing and populate the page cache with large folios.Not important. Our final
direction is to enable large folios for writable files as well.Quoted 6 lines
Does this cause O(N^2) complexity and massive stat inflation for large folios?
...
For a 2MB large folio, sequentially writing to all 512 subpages will trigger this page fault handler 512 times. Each invocation processes all 512 blocks and increments the IO stats by 2MB, resulting in 262,144 block iterations and a 1GB inflation toAPP_MAPPED_IO.
Quoted 4 lines
As explained before, do_shared_fault()'s
finish_fault()installs writable PTEs for the whole folio. So we should dirty the whole folio to avoid data loss.I will send a v7 series with these fixes.
Thanks, will take a look soon.
Thanks,
Quoted 3 lines
Thanks,
Nanzhe
_______________________________________________
Linux-f2fs-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/linux-f2fs-devel
Can you access this? based on v7
Quoted 373 lines · Chao Yu
Hi Nanzhe,
Thanks for the updates.
Quoted 110 lines · Nanzhe Zhao
Hi Chao,
Thanks for forwarding the local Sashiko review. I went through every comment. Below I quote the review text and reply item by item.
== Patch 1: f2fs: extend folio state for large folio write path ==
Quoted 11 lines
Should this check also exclude the
PAGE_PRIVATE_NOT_POINTERbit? If a large folio has no ffs structure attached, but has an integer stored infolio->privatewith thePAGE_PRIVATE_NOT_POINTERbit set, this function will incorrectly return true.If
f2fs_folio_has_ffs()returns true because an integer with thePAGE_PRIVATE_NOT_POINTERbit is stored infolio->private, does this code cast that raw integer into a structf2fs_folio_statepointer?
This would return an invalid out-of-bounds address for theprivate_flagsfield, leading to a crash when it gets dereferenced.Quoted 10 lines
Can this sequence trigger an invalid pointer dereference and a kernel panic? If
PAGE_PRIVATE_SET_FUNC(e.g.,folio_set_f2fs_gcing) is called on a large folio without an ffs structure:
1.folio->privateis set toBIT(PAGE_PRIVATE_NOT_POINTER)(which is 1).
2.f2fs_folio_flags_addr()is called.
3.f2fs_folio_has_ffs()seesfolio_test_large()and private != 0, returning true.
4.f2fs_folio_flags_addr()casts the integer 1 to a structf2fs_folio_statepointer, returning a memory address based off this invalid pointer.
5.set_bit()attempts to write to this invalid unmapped memory address.In the current implementation, every path that can carry a large folio also allocates and keeps
f2fs_folio_state; the private-flag layout is only used for order-0 folios. However, I did find one race window:f2fs_get_read_data_folio(): if (f2fs_ffs_test_blk_uptodate(folio, index)) { folio_unlock(folio); return folio; } f2fs_get_lock_data_folio(): folio = f2fs_get_read_data_folio(inode, index, 0, for_write, NULL); ... folio_lock(folio); if (unlikely(folio->mapping != mapping || !f2fs_ffs_test_blk_uptodate(folio, index))) { f2fs_folio_put(folio, true); return ERR_PTR(-EIO); } return folio;A concurrent shrink can call ->release_folio() in the unlock window. On a clean large folio,
f2fs_release_folio()detaches and frees the ffs:bool f2fs_release_folio(struct folio *folio, gfp_t wait) { if (folio_test_dirty(folio)) return false; ffs_detach_free(folio); return true; }
__remove_mapping()then fails thefolio_ref_freeze()check because the caller still holds a reference, so the folio stays in the mapping but has no ffs. On relock, the fully uptodate folio hits the early check inf2fs_ffs_test_blk_uptodate():if (folio_test_uptodate(folio)) return true;and is returned to GC. GC later calls
folio_set_f2fs_gcing()on a large folio whose private is NULL. This is the same root cause as the Patch 5 "large folio without ffs" comment; fixing this also fixes that one.Expected diff:
diff --git
a/fs/f2fs/data.cb/fs/f2fs/data.c
@@ struct folio *f2fs_get_lock_data_folio(struct inode *inode,
/* wait for read completion */folio_lock(folio);
- if (unlikely(folio->mapping != mapping ||
- !f2fs_ffs_test_blk_uptodate(folio, index))) {
+ if (unlikely(folio->mapping != mapping)) {
f2fs_folio_put(folio, true);
returnERR_PTR(-EIO);
}
+ if (folio_test_large(folio)&& !f2fs_folio_has_ffs(folio)) {
+ if (!f2fs_ffs_find_or_alloc(folio)) {
+f2fs_folio_put(folio, true);
+ returnERR_PTR(-ENOMEM);
+ }
+ }
+ if (unlikely(!f2fs_ffs_test_blk_uptodate(folio, index))) {
+f2fs_folio_put(folio, true);
+ returnERR_PTR(-EIO);
+ }
return folio;== Patch 3: f2fs: support regular file buffered writes on large folios ==
Quoted 9 lines
Can this result in a spurious
-EFSCORRUPTEDerror during a direct I/O fallback?
Inf2fs_preallocate_blocks(),FI_PREALLOCATED_ALLis set unconditionally whenf2fs_map_blocks()returns 0. However, for direct I/O, the allocation exits early on physically unmergeable extents, meaning map.m_len might be smaller than requested.
...
Will reading the unallocated hole then yield aNULL_ADDRand trigger the-EFSCORRUPTEDfailure here?Quoted 1 line
False Positive. Our code path here is the buffered IO path, not the DIO case described.
Agreed,
Looks like a bug, maybe we can add
f2fs_bug_onfor such case?Quoted 14 lines
Quoted 6 lines
Does this miss updating the ffs dirty bitmap for large folios modified via external paths like
get_user_pages?
...
Should we be updating the ffs dirty bitmap here after a successfulfilemap_dirty_folio()for large folios?A writable mapping goes through
f2fs_vm_page_mkwrite(), which marks the whole valid folio dirty beforefolio_mark_dirty():if (folio_test_large(folio)) f2fs_ffs_mark_subrange_dirty(folio, 0, dirty_len); folio_mark_dirty(folio);Quoted 13 lines
A GUP/DMA write needs a writable PTE, so it is covered by that
page_mkwrite. I am not aware of aFOLL_WRITEpath that bypassespage_mkwrite.== Patch 4: f2fs: support atomic file large folios buffered write ==
Quoted 7 lines
Can returning
-EAGAINhere cause atomic write counts to be double counted for prior subpages?
...
Becausecow_has_reserved_blockdefaults to false and the COW lookup was skipped,inc_atomic_write_cnt()will be incremented a second time for every subpage already processed before the abort. Could this corrupt the atomic write statistics?I'm a bit confuse about what detailed number
inc_atomic_write_cnt()tries to record, previously we need to callinc_atomic_write_cnt()only ifnode_changedis true, if it tries to record the first time write on cow inode, IIUC, please correct me if I understand incorrectly.To Daeho, could you please take a look and help to review the comments and below change?
Quoted 216 lines
This is valid. For a large folio, the assumption behind this check does not hold:
if (((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) goto reserve_block;The retry can be caused by
f2fs_balance_fs_folio_locked()dropping the folio lock and a concurrent reclaim calling ->release_folio(), which frees the ffs. The retry is not necessarily caused by a truncate, so the block at that index can still beNEW_ADDR.The append branch itself is not new: the original 4K code skipped the COW lookup in the same way, so a retry there can also double count. The large-folio path makes it much easier to hit because balance can retry on ffs release or folio order change and restarts the whole folio.
The fix is to check the COW block only on retry. The first attempt keeps the original fast path (no COW lookup); once
f2fs_write_begin()retries, it passes check_reserved=true so an already reservedNEW_ADDRblock is not reserved and accounted again. This does not depend on whether a truncate path clears the block address.Expected diff:
diff --git a/fs/f2fs/data.c b/fs/f2fs/data.c @@ static int prepare_atomic_write_begin(struct f2fs_sb_info *sbi, - struct inode *inode, pgoff_t index, - block_t *blk_addr, bool *node_changed) + struct inode *inode, pgoff_t index, + block_t *blk_addr, bool *node_changed, + bool check_reserved) { struct inode *cow_inode = F2FS_I(inode)->cow_inode; int err = 0; block_t ori_blk_addr = NULL_ADDR; bool cow_has_reserved_block = false; + bool append = ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode); - if (((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) + if (append && !check_reserved) goto reserve_block; /* Look for the block in COW inode first */ err = __find_data_block(cow_inode, index, blk_addr); ... if (*blk_addr == NEW_ADDR) cow_has_reserved_block = true; - if (is_inode_flag_set(inode, FI_ATOMIC_REPLACE)) + if (append || is_inode_flag_set(inode, FI_ATOMIC_REPLACE)) goto reserve_block; @@ static int prepare_large_folio_atomic_write_begin(struct inode *inode, - unsigned int len) + unsigned int len, bool retried) { ... err = prepare_atomic_write_begin(sbi, inode, index, - &blkaddr, &node_changed); + &blkaddr, &node_changed, retried); @@ static int f2fs_write_begin(const struct kiocb *iocb, bool need_balance = false; + bool retried = false; block_t blkaddr = NULL_ADDR; ... if (err) { if (err == -EAGAIN) { + retried = true; f2fs_folio_put(folio, true); goto repeat; } goto put_folio; } if (f2fs_balance_fs_folio_locked(folio, mapping, need_balance)) { + retried = true; f2fs_folio_put(folio, true); goto repeat; }== Patch 5: f2fs: support large folio writeback ==
Quoted 5 lines
Does this prematurely end writeback for the entire large folio when it lacks FFS state?
If a large folio is dirtied without an attachedf2fs_folio_state(FFS), it bypasses thewrite_pages_pendingreference counter during background writeback.Quoted 8 lines
When the first I/O block completes,
f2fs_ffs_put_write_pending()will immediately callfolio_end_writeback().
...
A Time-Of-Check to Time-Of-Use (TOCTOU) race exists when retrieving a folio usingf2fs_get_lock_data_folio(). It callsf2fs_get_read_data_folio(), which allocates FFS but then unlocks the folio if it is already up-to-date. Beforef2fs_get_lock_data_folio()re-acquires the lock, a concurrent memory reclaim can callf2fs_release_folio()on the clean folio, freeing its FFS state.This is the same race as the one described for Patch 1. Once
f2fs_get_lock_data_folio()rebuilds the ffs after relock, a large folio cannot enter writeback without ffs, so this one is fixed by the Patch 1 change rather than by a separateput()workaround.Quoted 5 lines
Can this crash the kernel via
f2fs_bug_on()due to a missingNULL_ADDRcheck?
...
Without that check here,f2fs_outplace_write_data()will hit this assertion and panic the kernel:f2fs_bug_on(sbi, dn->data_blkaddr == NULL_ADDR);False Positive. This is covered by 11/15, which adds the subpage-aware truncated state:
if (err == -ENOENT || fio.old_blkaddr == NULL_ADDR) { f2fs_clear_truncated_page_state(folio, i); err = 0; goto block_done; }Quoted 3 lines
Does this logic trap the worker in an infinite writeback loop on truncated or hole-punched large folios?
...Same, covered by 11/15.
== Patch 8: f2fs: make GC migration large-folio aware ==
Quoted 11 lines
Is there a regression here where
f2fs_do_write_data_page()bypasses the newly added cleanup code on early errors, leaking thePG_f2fs_gcingflag on the folio?
The removed cleanup relies onf2fs_do_write_data_page()performing it at the out label added above, butf2fs_do_write_data_page()can return directly without reaching that label. For example, it might fail on lock acquisition:
/* Deadlock due to betweenpage->lockandf2fs_lock_op*/
if (fio->need_lock==LOCK_REQ&& !f2fs_trylock_op(fio->sbi, &lc))return -EAGAIN;Could the folio permanently retain the
PG_f2fs_gcingflag since the caller-side cleanup was removed?This one is also valid. The early trylock failure returns directly and bypasses the common out path. Expected diff:
diff --git
a/fs/f2fs/data.cb/fs/f2fs/data.c
@@ intf2fs_do_write_data_page(struct f2fs_io_info *fio)
/* Deadlock due to betweenpage->lockandf2fs_lock_op*/
- if (fio->need_lock==LOCK_REQ&& !f2fs_trylock_op(fio->sbi, &lc))
- return-EAGAIN;
+ if (fio->need_lock==LOCK_REQ&& !f2fs_trylock_op(fio->sbi, &lc)) {
+ if (!f2fs_ffs_has_dirty_subpage(folio))
+folio_clear_f2fs_gcing(folio);
+ return-EAGAIN;
+ }The Patch 1 race and this early-return path are the two issues I can fix immediately; the Patch 4 atomic accounting and the Patch 14 mkwrite part are also valid, but need more design work.
== Patch 12: f2fs: fix zeroing paths for large folios ==
Quoted 5 lines
Does this code skip zeroing valid subpages of partially up-to-date large folios?
...
Should this check be converted tof2fs_ffs_test_blk_uptodate(folio, index)to match the changes made inf2fs_get_new_data_folio()?False Positive.
cache_onlyis only passed for inline data:truncate_pageis set only in thef2fs_has_inline_data()branch off2fs_do_truncate_blocks(). Inline data is order-0, andf2fs_read_inline_data()marks the whole folio uptodate, so the large-folio partially-uptodate case cannot reach thecache_onlybranch.== Patch 13: f2fs: handle block cloning within the same large folio ==
Quoted 9 lines
Does returning
-ENOMEMhere leave the page cache corrupted? Before this check,memcpy_folio()has already copied the data into the destination folio. Iff2fs_ffs_find_or_alloc()fails and we return-ENOMEM, the page cache modification is not reverted.
If the cloning operation is aborted, would userspace read the incorrectly modified page cache? Could this corrupted data also be persisted to disk if the folio is later dirtied?
Additionally, whensame_foliois true, the block reserved earlier withf2fs_reserve_block()does not appear to be reverted on this error path.
f2fs_get_new_data_folio()already callsf2fs_ffs_find_or_alloc()before returning the locked folio:if (folio_test_large(folio) && !f2fs_ffs_find_or_alloc(folio)) { f2fs_folio_put(folio, true); f2fs_put_cache(ientry, true); return ERR_PTR(-ENOMEM); }False Positive. For
same_folio, fdst is fsrc fromf2fs_get_lock_data_folio(), which also has the ffs. The laterf2fs_ffs_find_or_alloc(fdst)is redundant, and the post-memcpy ENOMEM path is unreachable in the normal flow.== Patch 14: f2fs: allow large folio support to writeable files ==
Quoted 7 lines
Can this check be bypassed using
FS_IOC_SETFLAGS?
If a user creates a file, sets it immutable (chattr +i), and drops caches to force an inode reload, the mapping is configured withMAX_PAGECACHE_ORDER. The user can then clear the immutable flag (chattr -i).
Sincef2fs_setflags_common()clearsS_IMMUTABLEbut does not downgrade the VFS mapping limits, this now-mutable file can be opened for writing and populate the page cache with large folios.Not important. Our final
direction is to enable large folios for writable files as well.Quoted 6 lines
Does this cause O(N^2) complexity and massive stat inflation for large folios?
...
For a 2MB large folio, sequentially writing to all 512 subpages will trigger this page fault handler 512 times. Each invocation processes all 512 blocks and increments the IO stats by 2MB, resulting in 262,144 block iterations and a 1GB inflation toAPP_MAPPED_IO.
Quoted 13 lines
Quoted 4 lines
As explained before, do_shared_fault()'s
finish_fault()installs writable PTEs for the whole folio. So we should dirty the whole folio to avoid data loss.I will send a v7 series with these fixes.
Thanks, will take a look soon.
Thanks,
Quoted 3 lines
Thanks,
Nanzhe
_______________________________________________
Linux-f2fs-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/linux-f2fs-devel
Quoted 3 lines · Chao Yu
Can you access this? based on v7
Sorry, it's internal link.
I will reply to v7 w/ sashiko review comment.
Quoted 380 lines · Chao Yu
Quoted 378 lines
Hi Nanzhe,
Thanks for the updates.
Quoted 110 lines · Nanzhe Zhao
Hi Chao,
Thanks for forwarding the local Sashiko review. I went through every comment. Below I quote the review text and reply item by item.
== Patch 1: f2fs: extend folio state for large folio write path ==
Quoted 11 lines
Should this check also exclude the
PAGE_PRIVATE_NOT_POINTERbit? If a large folio has no ffs structure attached, but has an integer stored infolio->privatewith thePAGE_PRIVATE_NOT_POINTERbit set, this function will incorrectly return true.If
f2fs_folio_has_ffs()returns true because an integer with thePAGE_PRIVATE_NOT_POINTERbit is stored infolio->private, does this code cast that raw integer into a structf2fs_folio_statepointer?
This would return an invalid out-of-bounds address for theprivate_flagsfield, leading to a crash when it gets dereferenced.Quoted 10 lines
Can this sequence trigger an invalid pointer dereference and a kernel panic? If
PAGE_PRIVATE_SET_FUNC(e.g.,folio_set_f2fs_gcing) is called on a large folio without an ffs structure:
1.folio->privateis set toBIT(PAGE_PRIVATE_NOT_POINTER)(which is 1).
2.f2fs_folio_flags_addr()is called.
3.f2fs_folio_has_ffs()seesfolio_test_large()and private != 0, returning true.
4.f2fs_folio_flags_addr()casts the integer 1 to a structf2fs_folio_statepointer, returning a memory address based off this invalid pointer.
5.set_bit()attempts to write to this invalid unmapped memory address.In the current implementation, every path that can carry a large folio also allocates and keeps
f2fs_folio_state; the private-flag layout is only used for order-0 folios. However, I did find one race window:f2fs_get_read_data_folio(): if (f2fs_ffs_test_blk_uptodate(folio, index)) { folio_unlock(folio); return folio; } f2fs_get_lock_data_folio(): folio = f2fs_get_read_data_folio(inode, index, 0, for_write, NULL); ... folio_lock(folio); if (unlikely(folio->mapping != mapping || !f2fs_ffs_test_blk_uptodate(folio, index))) { f2fs_folio_put(folio, true); return ERR_PTR(-EIO); } return folio;A concurrent shrink can call ->release_folio() in the unlock window. On a clean large folio,
f2fs_release_folio()detaches and frees the ffs:bool f2fs_release_folio(struct folio *folio, gfp_t wait) { if (folio_test_dirty(folio)) return false; ffs_detach_free(folio); return true; }
__remove_mapping()then fails thefolio_ref_freeze()check because the caller still holds a reference, so the folio stays in the mapping but has no ffs. On relock, the fully uptodate folio hits the early check inf2fs_ffs_test_blk_uptodate():if (folio_test_uptodate(folio)) return true;and is returned to GC. GC later calls
folio_set_f2fs_gcing()on a large folio whose private is NULL. This is the same root cause as the Patch 5 "large folio without ffs" comment; fixing this also fixes that one.Expected diff:
diff --git
a/fs/f2fs/data.cb/fs/f2fs/data.c
@@ struct folio *f2fs_get_lock_data_folio(struct inode *inode,
/* wait for read completion */folio_lock(folio);
- if (unlikely(folio->mapping != mapping ||
- !f2fs_ffs_test_blk_uptodate(folio, index))) {
+ if (unlikely(folio->mapping != mapping)) {
f2fs_folio_put(folio, true);
returnERR_PTR(-EIO);
}
+ if (folio_test_large(folio)&& !f2fs_folio_has_ffs(folio)) {
+ if (!f2fs_ffs_find_or_alloc(folio)) {
+f2fs_folio_put(folio, true);
+ returnERR_PTR(-ENOMEM);
+ }
+ }
+ if (unlikely(!f2fs_ffs_test_blk_uptodate(folio, index))) {
+f2fs_folio_put(folio, true);
+ returnERR_PTR(-EIO);
+ }
return folio;== Patch 3: f2fs: support regular file buffered writes on large folios ==
Quoted 9 lines
Can this result in a spurious
-EFSCORRUPTEDerror during a direct I/O fallback?
Inf2fs_preallocate_blocks(),FI_PREALLOCATED_ALLis set unconditionally whenf2fs_map_blocks()returns 0. However, for direct I/O, the allocation exits early on physically unmergeable extents, meaning map.m_len might be smaller than requested.
...
Will reading the unallocated hole then yield aNULL_ADDRand trigger the-EFSCORRUPTEDfailure here?Quoted 1 line
False Positive. Our code path here is the buffered IO path, not the DIO case described.
Agreed,
Looks like a bug, maybe we can add
f2fs_bug_onfor such case?Quoted 14 lines
Quoted 6 lines
Does this miss updating the ffs dirty bitmap for large folios modified via external paths like
get_user_pages?
...
Should we be updating the ffs dirty bitmap here after a successfulfilemap_dirty_folio()for large folios?A writable mapping goes through
f2fs_vm_page_mkwrite(), which marks the whole valid folio dirty beforefolio_mark_dirty():if (folio_test_large(folio)) f2fs_ffs_mark_subrange_dirty(folio, 0, dirty_len); folio_mark_dirty(folio);Quoted 13 lines
A GUP/DMA write needs a writable PTE, so it is covered by that
page_mkwrite. I am not aware of aFOLL_WRITEpath that bypassespage_mkwrite.== Patch 4: f2fs: support atomic file large folios buffered write ==
Quoted 7 lines
Can returning
-EAGAINhere cause atomic write counts to be double counted for prior subpages?
...
Becausecow_has_reserved_blockdefaults to false and the COW lookup was skipped,inc_atomic_write_cnt()will be incremented a second time for every subpage already processed before the abort. Could this corrupt the atomic write statistics?I'm a bit confuse about what detailed number
inc_atomic_write_cnt()tries to record, previously we need to callinc_atomic_write_cnt()only ifnode_changedis true, if it tries to record the first time write on cow inode, IIUC, please correct me if I understand incorrectly.To Daeho, could you please take a look and help to review the comments and below change?
Quoted 220 lines
This is valid. For a large folio, the assumption behind this check does not hold:
if (((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) goto reserve_block;The retry can be caused by
f2fs_balance_fs_folio_locked()dropping the folio lock and a concurrent reclaim calling ->release_folio(), which frees the ffs. The retry is not necessarily caused by a truncate, so the block at that index can still beNEW_ADDR.The append branch itself is not new: the original 4K code skipped the COW lookup in the same way, so a retry there can also double count. The large-folio path makes it much easier to hit because balance can retry on ffs release or folio order change and restarts the whole folio.
The fix is to check the COW block only on retry. The first attempt keeps the original fast path (no COW lookup); once
f2fs_write_begin()retries, it passes check_reserved=true so an already reservedNEW_ADDRblock is not reserved and accounted again. This does not depend on whether a truncate path clears the block address.Expected diff:
diff --git a/fs/f2fs/data.c b/fs/f2fs/data.c @@ static int prepare_atomic_write_begin(struct f2fs_sb_info *sbi, - struct inode *inode, pgoff_t index, - block_t *blk_addr, bool *node_changed) + struct inode *inode, pgoff_t index, + block_t *blk_addr, bool *node_changed, + bool check_reserved) { struct inode *cow_inode = F2FS_I(inode)->cow_inode; int err = 0; block_t ori_blk_addr = NULL_ADDR; bool cow_has_reserved_block = false; + bool append = ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode); - if (((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) + if (append && !check_reserved) goto reserve_block; /* Look for the block in COW inode first */ err = __find_data_block(cow_inode, index, blk_addr); ... if (*blk_addr == NEW_ADDR) cow_has_reserved_block = true; - if (is_inode_flag_set(inode, FI_ATOMIC_REPLACE)) + if (append || is_inode_flag_set(inode, FI_ATOMIC_REPLACE)) goto reserve_block; @@ static int prepare_large_folio_atomic_write_begin(struct inode *inode, - unsigned int len) + unsigned int len, bool retried) { ... err = prepare_atomic_write_begin(sbi, inode, index, - &blkaddr, &node_changed); + &blkaddr, &node_changed, retried); @@ static int f2fs_write_begin(const struct kiocb *iocb, bool need_balance = false; + bool retried = false; block_t blkaddr = NULL_ADDR; ... if (err) { if (err == -EAGAIN) { + retried = true; f2fs_folio_put(folio, true); goto repeat; } goto put_folio; } if (f2fs_balance_fs_folio_locked(folio, mapping, need_balance)) { + retried = true; f2fs_folio_put(folio, true); goto repeat; }== Patch 5: f2fs: support large folio writeback ==
Quoted 5 lines
Does this prematurely end writeback for the entire large folio when it lacks FFS state?
If a large folio is dirtied without an attachedf2fs_folio_state(FFS), it bypasses thewrite_pages_pendingreference counter during background writeback.Quoted 8 lines
When the first I/O block completes,
f2fs_ffs_put_write_pending()will immediately callfolio_end_writeback().
...
A Time-Of-Check to Time-Of-Use (TOCTOU) race exists when retrieving a folio usingf2fs_get_lock_data_folio(). It callsf2fs_get_read_data_folio(), which allocates FFS but then unlocks the folio if it is already up-to-date. Beforef2fs_get_lock_data_folio()re-acquires the lock, a concurrent memory reclaim can callf2fs_release_folio()on the clean folio, freeing its FFS state.This is the same race as the one described for Patch 1. Once
f2fs_get_lock_data_folio()rebuilds the ffs after relock, a large folio cannot enter writeback without ffs, so this one is fixed by the Patch 1 change rather than by a separateput()workaround.Quoted 5 lines
Can this crash the kernel via
f2fs_bug_on()due to a missingNULL_ADDRcheck?
...
Without that check here,f2fs_outplace_write_data()will hit this assertion and panic the kernel:f2fs_bug_on(sbi, dn->data_blkaddr == NULL_ADDR);False Positive. This is covered by 11/15, which adds the subpage-aware truncated state:
if (err == -ENOENT || fio.old_blkaddr == NULL_ADDR) { f2fs_clear_truncated_page_state(folio, i); err = 0; goto block_done; }Quoted 3 lines
Does this logic trap the worker in an infinite writeback loop on truncated or hole-punched large folios?
...Same, covered by 11/15.
== Patch 8: f2fs: make GC migration large-folio aware ==
Quoted 11 lines
Is there a regression here where
f2fs_do_write_data_page()bypasses the newly added cleanup code on early errors, leaking thePG_f2fs_gcingflag on the folio?
The removed cleanup relies onf2fs_do_write_data_page()performing it at the out label added above, butf2fs_do_write_data_page()can return directly without reaching that label. For example, it might fail on lock acquisition:
/* Deadlock due to betweenpage->lockandf2fs_lock_op*/
if (fio->need_lock==LOCK_REQ&& !f2fs_trylock_op(fio->sbi, &lc))return -EAGAIN;Could the folio permanently retain the
PG_f2fs_gcingflag since the caller-side cleanup was removed?This one is also valid. The early trylock failure returns directly and bypasses the common out path. Expected diff:
diff --git
a/fs/f2fs/data.cb/fs/f2fs/data.c
@@ intf2fs_do_write_data_page(struct f2fs_io_info *fio)
/* Deadlock due to betweenpage->lockandf2fs_lock_op*/
- if (fio->need_lock==LOCK_REQ&& !f2fs_trylock_op(fio->sbi, &lc))
- return-EAGAIN;
+ if (fio->need_lock==LOCK_REQ&& !f2fs_trylock_op(fio->sbi, &lc)) {
+ if (!f2fs_ffs_has_dirty_subpage(folio))
+folio_clear_f2fs_gcing(folio);
+ return-EAGAIN;
+ }The Patch 1 race and this early-return path are the two issues I can fix immediately; the Patch 4 atomic accounting and the Patch 14 mkwrite part are also valid, but need more design work.
== Patch 12: f2fs: fix zeroing paths for large folios ==
Quoted 5 lines
Does this code skip zeroing valid subpages of partially up-to-date large folios?
...
Should this check be converted tof2fs_ffs_test_blk_uptodate(folio, index)to match the changes made inf2fs_get_new_data_folio()?False Positive.
cache_onlyis only passed for inline data:truncate_pageis set only in thef2fs_has_inline_data()branch off2fs_do_truncate_blocks(). Inline data is order-0, andf2fs_read_inline_data()marks the whole folio uptodate, so the large-folio partially-uptodate case cannot reach thecache_onlybranch.== Patch 13: f2fs: handle block cloning within the same large folio ==
Quoted 9 lines
Does returning
-ENOMEMhere leave the page cache corrupted? Before this check,memcpy_folio()has already copied the data into the destination folio. Iff2fs_ffs_find_or_alloc()fails and we return-ENOMEM, the page cache modification is not reverted.
If the cloning operation is aborted, would userspace read the incorrectly modified page cache? Could this corrupted data also be persisted to disk if the folio is later dirtied?
Additionally, whensame_foliois true, the block reserved earlier withf2fs_reserve_block()does not appear to be reverted on this error path.
f2fs_get_new_data_folio()already callsf2fs_ffs_find_or_alloc()before returning the locked folio:if (folio_test_large(folio) && !f2fs_ffs_find_or_alloc(folio)) { f2fs_folio_put(folio, true); f2fs_put_cache(ientry, true); return ERR_PTR(-ENOMEM); }False Positive. For
same_folio, fdst is fsrc fromf2fs_get_lock_data_folio(), which also has the ffs. The laterf2fs_ffs_find_or_alloc(fdst)is redundant, and the post-memcpy ENOMEM path is unreachable in the normal flow.== Patch 14: f2fs: allow large folio support to writeable files ==
Quoted 7 lines
Can this check be bypassed using
FS_IOC_SETFLAGS?
If a user creates a file, sets it immutable (chattr +i), and drops caches to force an inode reload, the mapping is configured withMAX_PAGECACHE_ORDER. The user can then clear the immutable flag (chattr -i).
Sincef2fs_setflags_common()clearsS_IMMUTABLEbut does not downgrade the VFS mapping limits, this now-mutable file can be opened for writing and populate the page cache with large folios.Not important. Our final
direction is to enable large folios for writable files as well.Quoted 6 lines
Does this cause O(N^2) complexity and massive stat inflation for large folios?
...
For a 2MB large folio, sequentially writing to all 512 subpages will trigger this page fault handler 512 times. Each invocation processes all 512 blocks and increments the IO stats by 2MB, resulting in 262,144 block iterations and a 1GB inflation toAPP_MAPPED_IO.As explained before, do_shared_fault()'s
finish_fault()installs writable PTEs for the whole folio. So we should dirty the whole folio to avoid data loss.I will send a v7 series with these fixes.
Quoted 9 lines
Quoted 8 lines
Thanks, will take a look soon.
Thanks,
Quoted 3 lines
Thanks,
Nanzhe
_______________________________________________
Linux-f2fs-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/linux-f2fs-devel