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

Darrick J. Wong
2025-05-22T00:10:04Z

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 | 13 ++++++++++---
1 file changed, 10 insertions(+), 3 deletions(-)

diff --git a/lib/ext2fs/unix_io.c b/lib/ext2fs/unix_io.c
index 8a8afe47ee4503..4c924ec9ee0760 100644
--- a/lib/ext2fs/unix_io.c
+++ b/lib/ext2fs/unix_io.c
@@ -1523,6 +1523,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);
@@ -1538,12 +1539,18 @@ 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.
*/
- retval = flush_cached_blocks(channel, data, IO_CHANNEL_TAG_NULL,
- FLUSH_INVALIDATE);
+ retval = flush_cached_blocks(channel, data, IO_CHANNEL_TAG_NULL, 0);
if (retval)
return retval;
+
+ bno = offset / channel->block_size;
+ nbno = (offset + size + channel->block_size - 1) / channel->block_size;
+
+ for (; bno < nbno; bno++)
+ invalidate_cached_block(channel, data, bno);
#endif

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