Skip to content

Commit

Permalink
kernel: Add in-svsm tests for VirtioBlkDriver
Browse files Browse the repository at this point in the history
Add simple write+readback tests for the VirtioBlkDriver.

Signed-off-by: Oliver Steffen <osteffen@redhat.com>
  • Loading branch information
osteffenrh committed Mar 4, 2025
1 parent ccefeb8 commit fb2f700
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions kernel/src/block/virtio_blk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,63 @@ impl BlockDriver for VirtIOBlkDriver {
self.0.device.lock().capacity() as usize * SECTOR_SIZE
}
}

#[cfg(test)]
mod tests {
use crate::{address::PhysAddr, fw_cfg::FwCfg, platform::SVSM_PLATFORM};
extern crate alloc;
use alloc::vec::Vec;
use zerocopy::IntoBytes;

use super::*;

/// Find the first virtio-blk device in the hardware-info list
fn get_blk_device() -> VirtIOBlkDriver {
let cfg = FwCfg::new(SVSM_PLATFORM.get_io_port());

let dev = cfg
.get_virtio_mmio()
.unwrap_or_default()
.iter()
.find_map(|a| VirtIOBlkDriver::new(PhysAddr::from(*a)).ok())
.expect("No virtio-blk device found");

dev
}

#[test]
#[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")]
pub fn test_virtio_blk_512() {
let drv = get_blk_device();
readback_test(&drv, 512);
}

#[test]
#[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")]
pub fn test_virtio_blk_4096() {
let drv = get_blk_device();
readback_test(&drv, 4096);
}

fn readback_test(blk: &VirtIOBlkDriver, block_size: usize) {
for l in [[0xaa, 0x55], [0x55, 0xaa]] {
let mut buf: Vec<u8> = core::iter::repeat(l).flatten().take(block_size).collect();
let blocks = blk.size() / block_size;

for i in 0..blocks {
buf[0..size_of::<usize>()].copy_from_slice(usize::as_bytes(&i));
blk.write_blocks(i * (block_size / SECTOR_SIZE), &buf)
.unwrap();
}

let mut rbuf: Vec<u8> = alloc::vec![0; block_size];

for i in 0..blocks {
buf[0..size_of::<usize>()].copy_from_slice(usize::as_bytes(&i));
blk.read_blocks(i * (block_size / SECTOR_SIZE), &mut rbuf)
.unwrap();
assert!(rbuf == buf, "Error in block {i}: {rbuf:x?} != {buf:x?}");
}
}
}
}

0 comments on commit fb2f700

Please sign in to comment.