[PATCH] nilfs2: fix data corruption in dsync block recovery for small block sizes

From: Ryusuke Konishi
Date: Wed Jan 24 2024 - 07:19:59 EST


The helper function nilfs_recovery_copy_block() of
nilfs_recovery_dsync_blocks(), which recovers data from logs created by
data sync writes during a mount after an unclean shutdown, incorrectly
calculates the on-page offset when copying repair data to the file's page
cache. In environments where the block size is smaller than the page size,
this flaw can cause data corruption and leak uninitialized memory bytes
during the recovery process.

Fix these issues by correcting this byte offset calculation on the page.

Signed-off-by: Ryusuke Konishi <konishi.ryusuke@xxxxxxxxx>
Tested-by: Ryusuke Konishi <konishi.ryusuke@xxxxxxxxx>
Cc: <stable@xxxxxxxxxxxxxxx>
---
Andrew, please apply this patch as a bug fix.

This patch may conflict with the first patch of the kmap conversion series
that I posted earlier.

Since this fix should be a priority, I made it against the mainline
so that it can be applied before the kmap conversion patches.

If the conflict ia a problem for your patch handling, please drop the
first patch of the kmap conversion series (it can be dropped independently).
In that case, I will repost the patch that resolves the conflict.


Thanks,
Ryusuke Konishi

fs/nilfs2/recovery.c | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/fs/nilfs2/recovery.c b/fs/nilfs2/recovery.c
index 0955b657938f..a9b8d77c8c1d 100644
--- a/fs/nilfs2/recovery.c
+++ b/fs/nilfs2/recovery.c
@@ -472,9 +472,10 @@ static int nilfs_prepare_segment_for_recovery(struct the_nilfs *nilfs,

static int nilfs_recovery_copy_block(struct the_nilfs *nilfs,
struct nilfs_recovery_block *rb,
- struct page *page)
+ loff_t pos, struct page *page)
{
struct buffer_head *bh_org;
+ size_t from = pos & ~PAGE_MASK;
void *kaddr;

bh_org = __bread(nilfs->ns_bdev, rb->blocknr, nilfs->ns_blocksize);
@@ -482,7 +483,7 @@ static int nilfs_recovery_copy_block(struct the_nilfs *nilfs,
return -EIO;

kaddr = kmap_atomic(page);
- memcpy(kaddr + bh_offset(bh_org), bh_org->b_data, bh_org->b_size);
+ memcpy(kaddr + from, bh_org->b_data, bh_org->b_size);
kunmap_atomic(kaddr);
brelse(bh_org);
return 0;
@@ -521,7 +522,7 @@ static int nilfs_recover_dsync_blocks(struct the_nilfs *nilfs,
goto failed_inode;
}

- err = nilfs_recovery_copy_block(nilfs, rb, page);
+ err = nilfs_recovery_copy_block(nilfs, rb, pos, page);
if (unlikely(err))
goto failed_page;

--
2.34.1