[PATCH 06/10] libext2fs: only flush affected blocks in unix_write_byte

Darrick J. Wong
2025-09-16T00:57:41Z

There's no need to invalidate the entire cache when writing a range of
bytes to the device. The only ones we need to invalidate are the ones
that we're writing separately.

Signed-off-by: "Darrick J. Wong" <djwong@kernel.org>
---
lib/ext2fs/unix_io.c | 12 ++++++++++--
1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/lib/ext2fs/unix_io.c b/lib/ext2fs/unix_io.c
index be253b5fddf281..d4973d1a878057 100644
--- a/lib/ext2fs/unix_io.c
+++ b/lib/ext2fs/unix_io.c
@@ -1468,6 +1468,7 @@ static errcode_t unix_write_byte(io_channel channel, unsigned long offset,
{
struct unix_private_data *data;
errcode_t retval = 0;
+ unsigned long long bno, nbno;
ssize_t actual;

EXT2_CHECK_MAGIC(channel, EXT2_ET_MAGIC_IO_CHANNEL);
@@ -1483,10 +1484,17 @@ static errcode_t unix_write_byte(io_channel channel, unsigned long offset,

#ifndef NO_IO_CACHE
/*
- * Flush out the cache completely
+ * Flush all the dirty blocks, then invalidate the blocks we're about
+ * to write.
*/
- if ((retval = flush_cached_blocks(channel, data, FLUSH_INVALIDATE)))
+ retval = flush_cached_blocks(channel, data, 0);
+ if (retval)
return retval;
+
+ bno = offset / channel->block_size;
+ nbno = (offset + size + channel->block_size - 1) / channel->block_size;
+
+ invalidate_cached_blocks(channel, data, bno, nbno - bno);
#endif

if (lseek(data->dev, offset + data->offset, SEEK_SET) < 0)