From 8f95f754b7f8b4c9f1f4ed71a98d08dfed587f1b Mon Sep 17 00:00:00 2001 From: Changyuan Lyu Date: Mon, 5 Jan 2026 10:20:02 -0800 Subject: [PATCH] fix(blk): add file lock to disk image Introduce file locking for the virtio block device's disk image to prevent multiple processes or VMs from accessing the same disk image concurrently, which could lead to data corruption. A shared lock is used for read-only access, and an exclusive lock for read-write access. Signed-off-by: Changyuan Lyu --- alioth/src/virtio/dev/blk.rs | 10 ++++++++++ alioth/src/virtio/virtio.rs | 5 +++++ 2 files changed, 15 insertions(+) diff --git a/alioth/src/virtio/dev/blk.rs b/alioth/src/virtio/dev/blk.rs index e42f1bdf..87e2e80a 100644 --- a/alioth/src/virtio/dev/blk.rs +++ b/alioth/src/virtio/dev/blk.rs @@ -198,6 +198,16 @@ impl Block { .write(!param.readonly) .open(¶m.path) .context(access_disk)?; + + let ctx_lock = error::LockFile { + path: param.path.as_ref(), + }; + if param.readonly { + disk.try_lock_shared().context(ctx_lock) + } else { + disk.try_lock().context(ctx_lock) + }?; + let len = disk.metadata().context(access_disk)?.len(); let config = BlockConfig { capacity: len / SECTOR_SIZE as u64, diff --git a/alioth/src/virtio/virtio.rs b/alioth/src/virtio/virtio.rs index 77420026..cd142115 100644 --- a/alioth/src/virtio/virtio.rs +++ b/alioth/src/virtio/virtio.rs @@ -49,6 +49,11 @@ pub enum Error { path: Box, error: std::io::Error, }, + #[snafu(display("Failed to lock file {path:?}"))] + LockFile { + path: Box, + error: std::fs::TryLockError, + }, #[snafu(display("Error from OS"), context(false))] System { error: std::io::Error }, #[snafu(display("Failed to create a poll"))]