Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 163 additions & 2 deletions vm/devices/virtio/virtio_blk/src/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::VirtioBlkDevice;
use chipset_device::mmio::ExternallyManagedMmioIntercepts;
use disk_backend::UnmapBehavior;
use disk_hook::Disk;
use disk_hook::DiskError;
use disk_hook::DiskOperation;
use disk_hook::HookDisk;
use futures::future::Either;
Expand Down Expand Up @@ -130,9 +131,13 @@ impl TestHarness {

/// Enable the device with one queue.
async fn enable(&mut self) {
self.enable_with_features(VirtioDeviceFeatures::new()).await;
}

async fn enable_with_features(&mut self, features: VirtioDeviceFeatures) {
let resources = self.resources();
self.device
.start_queue(0, resources, &VirtioDeviceFeatures::new(), None)
.start_queue(0, resources, &features, None)
.await
.unwrap();
}
Expand Down Expand Up @@ -468,7 +473,7 @@ impl TestHarness {
status_gpa
}

/// Build a request with an arbitrary type code (for testing unsupported types).
/// Build a request with an arbitrary type code and no data descriptors.
fn post_raw_request(&mut self, head_desc: u16, request_type: u32, sector: u64) -> u64 {
let header_gpa = self.alloc_data(REQ_HEADER_SIZE);
let status_gpa = self.alloc_data(1);
Expand Down Expand Up @@ -1054,6 +1059,162 @@ async fn write_to_read_only_disk_fails(driver: DefaultDriver) {
assert_eq!(status, VIRTIO_BLK_S_IOERR);
}

#[async_test]
async fn write_cache_policy_matches_flush_negotiation(driver: DefaultDriver) {
for flush_negotiated in [false, true] {
for fua_respected in [false, true] {
let (operations, recorded_operations) = std::sync::mpsc::channel();
let disk = HookDisk::new(64 * 1024, 512)
.with_fua_respected(fua_respected)
.with_sync_hook(move |operation| {
operations.send(operation).unwrap();
Ok(())
})
.into_disk();
let mut harness = TestHarness::new(&driver, disk, false);
harness
.enable_with_features(VirtioDeviceFeatures::new().with_device_specific_low(
if flush_negotiated {
VIRTIO_BLK_F_FLUSH
} else {
0
},
))
.await;

let status_gpa = harness.post_write_request(0, 7, &[0xa5; 512]);
assert_eq!(harness.wait_for_used().await, (0, 1));
assert_eq!(harness.read_status(status_gpa), VIRTIO_BLK_S_OK);

let mut expected = vec![DiskOperation::Write {
sector: 7,
len: 512,
fua: !flush_negotiated && fua_respected,
}];
if !flush_negotiated && !fua_respected {
expected.push(DiskOperation::SyncCache);
}
assert_eq!(
recorded_operations.try_iter().collect::<Vec<_>>(),
expected,
"flush_negotiated={flush_negotiated}, fua_respected={fua_respected}"
);

if flush_negotiated {
let status_gpa = harness.post_raw_request(3, VIRTIO_BLK_T_FLUSH, 0);
assert_eq!(harness.wait_for_used().await, (3, 1));
assert_eq!(harness.read_status(status_gpa), VIRTIO_BLK_S_OK);
assert_eq!(
recorded_operations.try_iter().collect::<Vec<_>>(),
[DiskOperation::SyncCache]
);
}
}
}
}

#[async_test]
async fn write_without_flush_waits_for_sync_cache(driver: DefaultDriver) {
for fail_flush in [false, true] {
let (write_started, write_started_recv) = async_channel::bounded(1);
let (release_write, release_write_recv) = async_channel::bounded(1);
let (sync_started, sync_started_recv) = async_channel::bounded(1);
let (release_sync, release_sync_recv) = async_channel::bounded(1);
let disk = HookDisk::new(64 * 1024, 512)
.with_fua_respected(false)
.with_async_hook(move |operation| {
let write_started = write_started.clone();
let release_write = release_write_recv.clone();
let sync_started = sync_started.clone();
let release_sync = release_sync_recv.clone();
async move {
match operation {
DiskOperation::Write { fua: false, .. } => {
write_started.send(()).await.unwrap();
release_write.recv().await.unwrap();
Ok(())
}
DiskOperation::SyncCache => {
sync_started.send(()).await.unwrap();
release_sync.recv().await.unwrap()
}
_ => Ok(()),
}
}
})
.into_disk();
let mut harness = TestHarness::new(&driver, disk, false);
harness.enable().await;
let status_gpa = harness.post_write_request(0, 0, &[0xa5; 512]);
harness.mem.write_at(status_gpa, &[0xff]).unwrap();

match select(
pin!(write_started_recv.recv()),
pin!(harness.wait_for_used()),
)
.await
{
Either::Left((started, _)) => started.unwrap(),
Either::Right(_) => panic!("request completed before its backend write"),
}
assert_eq!(
sync_started_recv.try_recv(),
Err(async_channel::TryRecvError::Empty),
"cache flush started while the backend write was pending"
);
release_write.send(()).await.unwrap();

match select(
pin!(sync_started_recv.recv()),
pin!(harness.wait_for_used()),
)
.await
{
Either::Left((started, _)) => started.unwrap(),
Either::Right(_) => panic!("write completed before its cache flush"),
}
assert_eq!(read_used_idx(&harness.mem, USED_ADDR), 0);
assert_eq!(harness.read_status(status_gpa), 0xff);

release_sync
.send(if fail_flush {
Err(DiskError::Io(std::io::Error::other("cache flush failed")))
} else {
Ok(())
})
.await
.unwrap();
assert_eq!(harness.wait_for_used().await, (0, 1));
assert_eq!(
harness.read_status(status_gpa),
if fail_flush {
VIRTIO_BLK_S_IOERR
} else {
VIRTIO_BLK_S_OK
}
);
}
}

#[async_test]
async fn write_without_flush_reports_fua_error(driver: DefaultDriver) {
let disk = HookDisk::new(64 * 1024, 512)
.with_fua_respected(true)
.with_sync_hook(|operation| match operation {
DiskOperation::Write { fua: true, .. } => {
Err(DiskError::Io(std::io::Error::other("FUA write failed")))
}
_ => Ok(()),
})
.into_disk();
let mut harness = TestHarness::new(&driver, disk, false);
harness.enable().await;

let status_gpa = harness.post_write_request(0, 0, &[0xa5; 512]);
assert_eq!(harness.wait_for_used().await, (0, 1));
assert_eq!(harness.read_status(status_gpa), VIRTIO_BLK_S_IOERR);
}

/// Flush command should succeed.
#[async_test]
async fn flush_succeeds(driver: DefaultDriver) {
Expand Down
95 changes: 83 additions & 12 deletions vm/devices/virtio/virtio_blk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,13 @@ struct BlkWorker {
struct BlkQueueState {
queue: VirtioQueue,
memory: GuestMemory,
write_cache_policy: WriteCachePolicy,
}

#[derive(Clone, Copy, Inspect)]
enum WriteCachePolicy {
WriteBack,
WriteThrough,
}

#[derive(Inspect, Default)]
Expand Down Expand Up @@ -219,9 +226,18 @@ impl AsyncRun<BlkQueueState> for BlkWorker {
let disk = self.disk.clone();
let mem = state.memory.clone();
let read_only = self.read_only;
let write_cache_policy = state.write_cache_policy;
let serial = self.serial;
self.ios.push(Box::pin(async move {
process_request(&disk, &mem, read_only, serial, work).await
process_request(
&disk,
&mem,
read_only,
write_cache_policy,
serial,
work,
)
.await
}));
}
Event::NewWork(Err(err)) => {
Expand Down Expand Up @@ -319,8 +335,7 @@ impl VirtioBlkDevice {
// Optimal (max) I/O size in logical blocks. 0 = no hint.
opt_io_size: 0,
},
// We don't advertise CONFIG_WCE; set writeback=1 to indicate
// writeback cache semantics (driver should use FLUSH).
// CONFIG_WCE is not advertised, so FLUSH negotiation sets the cache mode.
writeback: 1,
unused0: 0,
num_queues: options.queue_count,
Expand Down Expand Up @@ -478,6 +493,11 @@ impl VirtioDevice for VirtioBlkDevice {
BlkQueueState {
queue,
memory: resources.guest_memory,
write_cache_policy: if features.device_specific_low() & VIRTIO_BLK_F_FLUSH == 0 {
WriteCachePolicy::WriteThrough
} else {
WriteCachePolicy::WriteBack
},
},
);
worker.worker.start();
Expand Down Expand Up @@ -516,10 +536,11 @@ async fn process_request(
disk: &Disk,
mem: &GuestMemory,
read_only: bool,
write_cache_policy: WriteCachePolicy,
serial: Option<[u8; VIRTIO_BLK_ID_BYTES]>,
work: VirtioQueueCallbackWork,
) -> IoCompletion {
match process_request_inner(disk, mem, read_only, serial, &work).await {
match process_request_inner(disk, mem, read_only, write_cache_policy, serial, &work).await {
Ok((bytes_written, stat, bounced)) => {
if let Err(err) = write_status_byte(mem, &work, VIRTIO_BLK_S_OK) {
tracelimit::error_ratelimited!(
Expand Down Expand Up @@ -557,6 +578,7 @@ async fn process_request_inner(
disk: &Disk,
mem: &GuestMemory,
read_only: bool,
write_cache_policy: WriteCachePolicy,
serial: Option<[u8; VIRTIO_BLK_ID_BYTES]>,
work: &VirtioQueueCallbackWork,
) -> Result<(u32, IoStat, bool), u8> {
Expand Down Expand Up @@ -587,7 +609,12 @@ async fn process_request_inner(
return Err(VIRTIO_BLK_S_IOERR);
}
let disk_sector = virtio_to_disk_sector(header.sector, sector_shift, sector_mask)?;
let (bytes, bounced) = do_io(disk, mem, work, disk_sector, false).await?;
let (bytes, bounced) = match write_cache_policy {
WriteCachePolicy::WriteBack => do_io(disk, mem, work, disk_sector, false).await?,
WriteCachePolicy::WriteThrough => {
do_write_through(disk, mem, work, disk_sector).await?
}
};
Ok((bytes, IoStat::Write, bounced))
}
VIRTIO_BLK_T_FLUSH => {
Expand Down Expand Up @@ -730,6 +757,43 @@ async fn do_io(
start_disk_sector: u64,
is_read: bool,
) -> Result<(u32, bool), u8> {
let operation = if is_read {
IoOperation::Read
} else {
IoOperation::Write(WriteCachePolicy::WriteBack)
};
do_io_with(disk, mem, work, start_disk_sector, operation).await
}

async fn do_write_through(
disk: &Disk,
mem: &GuestMemory,
work: &VirtioQueueCallbackWork,
start_disk_sector: u64,
) -> Result<(u32, bool), u8> {
do_io_with(
disk,
mem,
work,
start_disk_sector,
IoOperation::Write(WriteCachePolicy::WriteThrough),
)
.await
}

enum IoOperation {
Read,
Write(WriteCachePolicy),
}

async fn do_io_with(
disk: &Disk,
mem: &GuestMemory,
work: &VirtioQueueCallbackWork,
start_disk_sector: u64,
operation: IoOperation,
) -> Result<(u32, bool), u8> {
let is_read = matches!(operation, IoOperation::Read);
let writable = is_read;
let total_payload = work.get_payload_length(writable);
let skip_bytes: u64 = if !is_read {
Expand Down Expand Up @@ -797,14 +861,21 @@ async fn do_io(
PagedRange::new(io_range.offset, io_range.len, &io_range.gpns).ok_or(VIRTIO_BLK_S_IOERR)?;
let buffers = RequestBuffers::new(effective_mem, range, is_read);

if is_read {
disk.read_vectored(&buffers, start_disk_sector)
.await
.map_err(|_| VIRTIO_BLK_S_IOERR)?;
} else {
disk.write_vectored(&buffers, start_disk_sector, false)
match operation {
IoOperation::Read => disk
.read_vectored(&buffers, start_disk_sector)
.await
.map_err(|_| VIRTIO_BLK_S_IOERR)?;
.map_err(|_| VIRTIO_BLK_S_IOERR)?,
IoOperation::Write(write_cache_policy) => {
let write_through = matches!(write_cache_policy, WriteCachePolicy::WriteThrough);
let fua = write_through && disk.is_fua_respected();
disk.write_vectored(&buffers, start_disk_sector, fua)
.await
.map_err(|_| VIRTIO_BLK_S_IOERR)?;
if write_through && !fua {
disk.sync_cache().await.map_err(|_| VIRTIO_BLK_S_IOERR)?;
}
}
}

if bounced && is_read {
Expand Down
Loading