diff --git a/alioth/src/virtio/dev/blk.rs b/alioth/src/virtio/dev/blk.rs index ee8d16c8..2977ccb8 100644 --- a/alioth/src/virtio/dev/blk.rs +++ b/alioth/src/virtio/dev/blk.rs @@ -13,7 +13,7 @@ // limitations under the License. use std::fs::{File, OpenOptions}; -use std::io::{IoSlice, IoSliceMut, Read}; +use std::io::{self, ErrorKind, IoSlice, IoSliceMut, Read}; #[cfg(target_os = "linux")] use std::os::fd::AsRawFd; use std::os::unix::fs::FileExt; @@ -66,7 +66,7 @@ consts! { } #[repr(C)] -#[derive(Debug, FromBytes)] +#[derive(Debug, FromBytes, Immutable, IntoBytes)] pub struct Request { type_: RequestType, reserved: u32, @@ -151,6 +151,41 @@ impl DevSpec for BlkFileSpec { } } +/// Completes reading `buf.len()` bytes at `offset`, assuming `filled` bytes +/// have already been read into `buf[..filled]`, and zero-pads an unaligned +/// trailing sector past EOF. +/// +/// The device capacity is the file size rounded up to whole 512-byte +/// sectors, so an in-bounds sector-aligned read covering an unaligned tail +/// legitimately extends up to `SECTOR_SIZE - 1` bytes past EOF. EOF with a +/// full sector or more unread, which includes EOF at the start of the +/// request, remains an [`ErrorKind::UnexpectedEof`] error. +fn read_exact_zero_tail( + file: &File, + buf: &mut [u8], + offset: u64, + mut filled: usize, +) -> io::Result<()> { + while filled < buf.len() { + let Some(cur_offset) = offset.checked_add(filled as u64) else { + return Err(ErrorKind::InvalidInput.into()); + }; + match file.read_at(&mut buf[filled..], cur_offset) { + Ok(0) => { + if buf.len() - filled >= SECTOR_SIZE { + return Err(ErrorKind::UnexpectedEof.into()); + } + buf[filled..].fill(0); + return Ok(()); + } + Ok(n) => filled += n, + Err(e) if e.kind() == ErrorKind::Interrupted => continue, + Err(e) => return Err(e), + } + } + Ok(()) +} + enum BlkRequest<'d, 'm> { Done { written: u32, @@ -201,7 +236,12 @@ impl Block { let len = disk.metadata().context(access_disk)?.len(); let config = BlockConfig { - capacity: len / SECTOR_SIZE as u64, + // The device capacity is the file size rounded up to whole + // 512-byte sectors, so an unaligned tail (e.g. a 461-byte file) + // still appears as a full, NUL-padded sector instead of silently + // truncating the last bytes. `read_exact_zero_tail` serves the + // bytes beyond EOF as zeroes. + capacity: len.div_ceil(SECTOR_SIZE as u64), num_queues: 1, ..Default::default() }; @@ -219,6 +259,29 @@ impl Block { }) } + /// Returns the offset of the data of `request` in the disk image, or + /// logs and returns `None` if `len` bytes from its sector are not whole + /// sectors within the capacity of the device. + fn check_range(&self, request: &Request, len: usize) -> Option { + let capacity = self.config.capacity; + let sector = request.sector; + let nb_sectors = (len / SECTOR_SIZE) as u64; + if len.is_multiple_of(SECTOR_SIZE) + && sector <= capacity + && nb_sectors <= capacity - sector + && let Some(offset) = sector.checked_mul(SECTOR_SIZE as u64) + { + Some(offset) + } else { + log::error!( + "{}: {:?} out of range: sector={sector:#x}, len={len:#x}, capacity={capacity:#x}", + self.name, + request.type_, + ); + None + } + } + fn handle_desc<'d, 'm>(&self, desc: &'d mut DescChain<'m>) -> Result> { let [hdr, data_out @ ..] = &desc.readable[..] else { return error::InvalidBuffer.fail(); @@ -232,12 +295,15 @@ impl Block { let [status] = &mut status_buf[..] else { return error::InvalidBuffer.fail(); }; - let offset = request.sector * SECTOR_SIZE as u64; match request.type_ { RequestType::IN => { let [data] = data_in else { return error::InvalidBuffer.fail(); }; + let Some(offset) = self.check_range(&request, data.len()) else { + *status = Status::IOERR.into(); + return Ok(BlkRequest::Done { written: 1 }); + }; Ok(BlkRequest::In { data, offset, @@ -253,6 +319,10 @@ impl Block { let [data] = data_out else { return error::InvalidBuffer.fail(); }; + let Some(offset) = self.check_range(&request, data.len()) else { + *status = Status::IOERR.into(); + return Ok(BlkRequest::Done { written: 1 }); + }; Ok(BlkRequest::Out { data, offset, @@ -358,7 +428,7 @@ impl VirtioMio for Block { data, offset, status, - }) => match self.disk.read_exact_at(data, offset) { + }) => match read_exact_zero_tail(&self.disk, data, offset, 0) { Ok(_) => { *status = Status::OK.into(); data.len() as u32 + 1 @@ -438,18 +508,36 @@ impl VirtioIoUring for Block { let status_code = if result >= 0 { Status::OK } else { - let err = std::io::Error::from_raw_os_error(-result); - log::error!("{}: queue-{q_index} io error: {err}", self.name,); + let err = io::Error::from_raw_os_error(-result); + log::error!("{}: queue-{q_index} io error: {err}", self.name); Status::IOERR }; match Block::handle_desc(self, chain)? { - BlkRequest::Done { .. } => unreachable!(), + // The header is read from guest memory again, so a driver that + // changed it while the request was in flight can end up here. + // The status is already set. + BlkRequest::Done { written } => Ok(written), BlkRequest::Flush { status } => { *status = status_code.into(); Ok(1) } - BlkRequest::In { data, status, .. } => { - *status = status_code.into(); + BlkRequest::In { + data, + offset, + status, + } => { + let Ok(filled) = usize::try_from(result) else { + *status = Status::IOERR.into(); + return Ok(1); + }; + if filled < data.len() + && let Err(e) = read_exact_zero_tail(&self.disk, data, offset, filled) + { + log::error!("{}: queue-{q_index} read: {e}", self.name); + *status = Status::IOERR.into(); + return Ok(1); + } + *status = Status::OK.into(); Ok(data.len() as u32 + 1) } BlkRequest::Out { status, .. } => { @@ -459,3 +547,7 @@ impl VirtioIoUring for Block { } } } + +#[cfg(test)] +#[path = "blk_test.rs"] +mod tests; diff --git a/alioth/src/virtio/dev/blk_test.rs b/alioth/src/virtio/dev/blk_test.rs new file mode 100644 index 00000000..11bd4e2c --- /dev/null +++ b/alioth/src/virtio/dev/blk_test.rs @@ -0,0 +1,475 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::fs::{self, File}; +use std::io::{ErrorKind, Write}; +use std::path::Path; +use std::sync::Arc; +use std::thread::JoinHandle; +use std::time::Duration; + +use flume::Receiver; +use rstest::rstest; +use tempfile::TempDir; +use zerocopy::IntoBytes; + +use crate::mem::mapped::{Ram, RamBus}; +use crate::virtio::VirtioFeature; +use crate::virtio::dev::blk::{ + BlkFileSpec, Block, Request, RequestType, SECTOR_SIZE, Status, read_exact_zero_tail, +}; +use crate::virtio::dev::{DevSpec, StartParam, Virtio, WakeEvent, WorkerCtl, WorkerParam}; +use crate::virtio::queue::QueueReg; +use crate::virtio::queue::split::SplitQueue; +use crate::virtio::queue::tests::GuestQueue; +#[cfg(target_os = "linux")] +use crate::virtio::queue::{Queue, Status as QStatus}; +use crate::virtio::tests::{self, DATA_ADDR, FakeIrqSender}; +use crate::virtio::worker::WorkerApi; +#[cfg(target_os = "linux")] +use crate::virtio::worker::io_uring::{BufferAction, VirtioIoUring}; + +const TIMEOUT: Duration = Duration::from_secs(5); +const REQ_ADDR: u64 = DATA_ADDR; +const STATUS_ADDR: u64 = DATA_ADDR + 0x100; +const BUF_ADDR: u64 = DATA_ADDR + 0x1000; + +struct BlkWorker { + ram_bus: Arc, + regs: Arc<[QueueReg]>, + ctl: WorkerCtl, + irq_rx: Receiver, + handle: JoinHandle<()>, +} + +impl BlkWorker { + fn spawn(path: &Path, readonly: bool, api: WorkerApi) -> Self { + let dev = BlkFileSpec { + path: Box::from(path), + readonly, + api, + } + .build("blk") + .unwrap(); + let ram_bus = Arc::new(tests::fixture_ram_bus()); + let regs: Arc<[QueueReg]> = Arc::from(tests::fixture_queues(1)); + let (event_tx, event_rx) = flume::unbounded(); + let (report_tx, report_rx) = flume::unbounded(); + let (handle, notifier) = dev + .spawn_worker(WorkerParam { + event_rx, + report_tx, + memory: ram_bus.clone(), + queue_regs: regs.clone(), + }) + .unwrap(); + let (irq_tx, irq_rx) = flume::unbounded(); + let ctl = WorkerCtl::new("blk".into(), event_tx, notifier, report_rx); + let param = StartParam { + feature: VirtioFeature::VERSION_1.bits(), + irq_sender: Arc::new(FakeIrqSender { q_tx: irq_tx }), + notifiers: None, + }; + assert!(ctl.wake(WakeEvent::Start { param })); + Self { + ram_bus, + regs, + ctl, + irq_rx, + handle, + } + } + + fn run(&self, f: F) + where + F: FnOnce(&mut BlkSession<'_>), + { + let ram = self.ram_bus.load(); + let reg = &self.regs[0]; + let guest_q = GuestQueue::new(SplitQueue::new(reg, &ram, false).unwrap().unwrap(), reg); + let mut session = BlkSession { + worker: self, + ram: &ram, + guest_q, + }; + f(&mut session); + } + + fn shutdown(self) { + assert!(self.ctl.wake(WakeEvent::Shutdown)); + self.handle.join().unwrap(); + } +} + +struct BlkSession<'a> { + worker: &'a BlkWorker, + ram: &'a Ram, + guest_q: GuestQueue, +} + +impl BlkSession<'_> { + fn read(&mut self, sector: u64, len: usize) -> (Status, u32, Vec) { + let req = Request { + type_: RequestType::IN, + reserved: 0, + sector, + }; + self.ram.write(REQ_ADDR, req.as_bytes()).unwrap(); + self.ram.write(BUF_ADDR, &vec![0x5a; len]).unwrap(); + self.ram.write(STATUS_ADDR, &[0xff]).unwrap(); + + let id = self.guest_q.add_desc( + &[(REQ_ADDR, size_of::() as u32)], + &[(BUF_ADDR, len as u32), (STATUS_ADDR, 1)], + ); + assert!(self.worker.ctl.wake(WakeEvent::Notify { q_index: 0 })); + assert_eq!(self.worker.irq_rx.recv_timeout(TIMEOUT), Ok(0)); + let used = self.guest_q.get_used().unwrap(); + assert_eq!(used.id, id); + + let mut status = [0u8; 1]; + self.ram.read(STATUS_ADDR, &mut status).unwrap(); + let mut buf = vec![0u8; len]; + self.ram.read(BUF_ADDR, &mut buf).unwrap(); + (Status::from(status[0]), used.len, buf) + } + + fn write(&mut self, sector: u64, data: &[u8]) -> (Status, u32) { + let req = Request { + type_: RequestType::OUT, + reserved: 0, + sector, + }; + self.ram.write(REQ_ADDR, req.as_bytes()).unwrap(); + self.ram.write(BUF_ADDR, data).unwrap(); + self.ram.write(STATUS_ADDR, &[0xff]).unwrap(); + + let id = self.guest_q.add_desc( + &[ + (REQ_ADDR, size_of::() as u32), + (BUF_ADDR, data.len() as u32), + ], + &[(STATUS_ADDR, 1)], + ); + assert!(self.worker.ctl.wake(WakeEvent::Notify { q_index: 0 })); + assert_eq!(self.worker.irq_rx.recv_timeout(TIMEOUT), Ok(0)); + let used = self.guest_q.get_used().unwrap(); + assert_eq!(used.id, id); + + let mut status = [0u8; 1]; + self.ram.read(STATUS_ADDR, &mut status).unwrap(); + (Status::from(status[0]), used.len) + } +} + +#[rstest] +#[case::mio(WorkerApi::Mio)] +#[cfg_attr(target_os = "linux", case::io_uring(WorkerApi::IoUring))] +fn worker_aligned_and_empty_bounds(#[case] api: WorkerApi) { + let dir = TempDir::new().unwrap(); + let aligned_path = dir.path().join("aligned.img"); + File::create(&aligned_path) + .unwrap() + .write_all(&[0x11; SECTOR_SIZE]) + .unwrap(); + + let empty_path = dir.path().join("empty.img"); + File::create(&empty_path).unwrap(); + + let worker = BlkWorker::spawn(&aligned_path, false, api); + worker.run(|s| { + let (status, written, buf) = s.read(0, SECTOR_SIZE); + assert_eq!(status, Status::OK); + assert_eq!(written, SECTOR_SIZE as u32 + 1); + assert!(buf.iter().all(|&b| b == 0x11)); + + // Out-of-bounds read starting before EOF on an aligned image must fail. + let (status, written, _) = s.read(0, SECTOR_SIZE * 2); + assert_eq!(status, Status::IOERR); + assert_eq!(written, 1); + + // Overflowing sector fails cleanly. + let (status, written, _) = s.read(u64::MAX, SECTOR_SIZE); + assert_eq!(status, Status::IOERR); + assert_eq!(written, 1); + + // Unaligned data buffer length fails. + let (status, written, _) = s.read(0, 461); + assert_eq!(status, Status::IOERR); + assert_eq!(written, 1); + + // Out-of-bounds write must fail and not extend the file. + let (status, written) = s.write(1, &[0x22; SECTOR_SIZE]); + assert_eq!(status, Status::IOERR); + assert_eq!(written, 1); + }); + worker.shutdown(); + assert_eq!( + fs::metadata(&aligned_path).unwrap().len(), + SECTOR_SIZE as u64 + ); + + let worker = BlkWorker::spawn(&empty_path, true, api); + worker.run(|s| { + let (status, written, _) = s.read(0, SECTOR_SIZE); + assert_eq!(status, Status::IOERR); + assert_eq!(written, 1); + }); + worker.shutdown(); +} + +#[rstest] +#[case(0, 0)] +#[case(1, 1)] +#[case(461, 1)] +#[case(512, 1)] +#[case(513, 2)] +#[case(1000, 2)] +#[case(1024, 2)] +fn capacity_is_rounded_up_to_whole_sectors(#[case] file_len: usize, #[case] expected: u64) { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("disk.img"); + File::create(&path) + .unwrap() + .write_all(&vec![0xa5; file_len]) + .unwrap(); + let block = Block::new( + BlkFileSpec { + path: Box::from(path.as_path()), + readonly: true, + api: WorkerApi::default(), + }, + "test", + ) + .unwrap(); + assert_eq!(block.config.capacity, expected); +} + +#[test] +fn read_exact_zero_tail_cases() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("unaligned.img"); + File::create(&path) + .unwrap() + .write_all(&[0xa5; 461]) + .unwrap(); + let file = File::open(&path).unwrap(); + + // Full-sector read covers the 461 real bytes and zero-pads the rest. + let mut buf = [0x5a; SECTOR_SIZE]; + read_exact_zero_tail(&file, &mut buf, 0, 0).unwrap(); + assert!(buf[..461].iter().all(|&b| b == 0xa5)); + assert!(buf[461..].iter().all(|&b| b == 0)); + + // Completing after an initial partial read (e.g. io_uring short read before EOF). + let mut buf = [0x5a; SECTOR_SIZE]; + buf[..200].fill(0xa5); + read_exact_zero_tail(&file, &mut buf, 0, 200).unwrap(); + assert!(buf[..461].iter().all(|&b| b == 0xa5)); + assert!(buf[461..].iter().all(|&b| b == 0)); + + // Completing when the initial read already reached EOF. + let mut buf = [0x5a; SECTOR_SIZE]; + buf[..461].fill(0xa5); + read_exact_zero_tail(&file, &mut buf, 0, 461).unwrap(); + assert!(buf[..461].iter().all(|&b| b == 0xa5)); + assert!(buf[461..].iter().all(|&b| b == 0)); + + // Read starting beyond EOF is an error. + let mut buf = [0u8; SECTOR_SIZE]; + let err = read_exact_zero_tail(&file, &mut buf, SECTOR_SIZE as u64, 0).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::UnexpectedEof); + + // Read starting before EOF but extending a full sector or more past EOF is an error. + let mut buf = [0u8; SECTOR_SIZE * 2]; + let err = read_exact_zero_tail(&file, &mut buf, 0, 0).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::UnexpectedEof); + + // Overflowing offset is rejected. + let mut buf = [0u8; SECTOR_SIZE]; + let err = read_exact_zero_tail(&file, &mut buf, u64::MAX, 1).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::InvalidInput); +} + +#[rstest] +#[case::mio(WorkerApi::Mio)] +#[cfg_attr(target_os = "linux", case::io_uring(WorkerApi::IoUring))] +fn worker_unaligned_tail_reads(#[case] api: WorkerApi) { + let dir = TempDir::new().unwrap(); + let short_path = dir.path().join("short.img"); + File::create(&short_path) + .unwrap() + .write_all(&[0xa5; 461]) + .unwrap(); + + let multi_path = dir.path().join("multi.img"); + let mut multi_data = vec![0xa5; SECTOR_SIZE]; + multi_data.extend_from_slice(&[0x3c; 488]); + File::create(&multi_path) + .unwrap() + .write_all(&multi_data) + .unwrap(); + + let worker = BlkWorker::spawn(&short_path, true, api); + worker.run(|s| { + // Single-sector read zero-pads the unaligned tail. + let (status, written, buf) = s.read(0, SECTOR_SIZE); + assert_eq!(status, Status::OK); + assert_eq!(written, SECTOR_SIZE as u32 + 1); + assert!(buf[..461].iter().all(|&b| b == 0xa5)); + assert!(buf[461..].iter().all(|&b| b == 0)); + + // Read starting before EOF and crossing beyond capacity fails. + let (status, written, _) = s.read(0, SECTOR_SIZE * 2); + assert_eq!(status, Status::IOERR); + assert_eq!(written, 1); + + // Read starting at/beyond capacity fails. + let (status, written, _) = s.read(1, SECTOR_SIZE); + assert_eq!(status, Status::IOERR); + assert_eq!(written, 1); + }); + worker.shutdown(); + + let worker = BlkWorker::spawn(&multi_path, true, api); + worker.run(|s| { + // Multi-sector read covering an unaligned tail. + let (status, written, buf) = s.read(0, SECTOR_SIZE * 2); + assert_eq!(status, Status::OK); + assert_eq!(written, (SECTOR_SIZE * 2) as u32 + 1); + assert!(buf[..SECTOR_SIZE].iter().all(|&b| b == 0xa5)); + assert!(buf[SECTOR_SIZE..1000].iter().all(|&b| b == 0x3c)); + assert!(buf[1000..].iter().all(|&b| b == 0)); + + // Last-sector read. + let (status, written, buf) = s.read(1, SECTOR_SIZE); + assert_eq!(status, Status::OK); + assert_eq!(written, SECTOR_SIZE as u32 + 1); + assert!(buf[..488].iter().all(|&b| b == 0x3c)); + assert!(buf[488..].iter().all(|&b| b == 0)); + + // Out-of-bounds multi-sector read starting in the last valid sector. + let (status, written, _) = s.read(1, SECTOR_SIZE * 2); + assert_eq!(status, Status::IOERR); + assert_eq!(written, 1); + }); + worker.shutdown(); +} + +#[rstest] +#[case::mio(WorkerApi::Mio)] +#[cfg_attr(target_os = "linux", case::io_uring(WorkerApi::IoUring))] +fn worker_unaligned_write_extends_last_sector(#[case] api: WorkerApi) { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("rw_unaligned.img"); + File::create(&path) + .unwrap() + .write_all(&[0xa5; 461]) + .unwrap(); + + let worker = BlkWorker::spawn(&path, false, api); + worker.run(|s| { + let (status, written) = s.write(0, &[0x77; SECTOR_SIZE]); + assert_eq!(status, Status::OK); + assert_eq!(written, 1); + + let (status, written, buf) = s.read(0, SECTOR_SIZE); + assert_eq!(status, Status::OK); + assert_eq!(written, SECTOR_SIZE as u32 + 1); + assert!(buf.iter().all(|&b| b == 0x77)); + + let (status, written) = s.write(1, &[0x88; SECTOR_SIZE]); + assert_eq!(status, Status::IOERR); + assert_eq!(written, 1); + }); + worker.shutdown(); + assert_eq!(fs::metadata(&path).unwrap().len(), SECTOR_SIZE as u64); +} + +#[cfg(target_os = "linux")] +#[rstest] +#[case::unknown_type(RequestType(0xff), 0, Status::UNSUPP)] +#[case::sector_out_of_range(RequestType::IN, 1, Status::IOERR)] +fn io_uring_request_changed_in_flight( + #[case] type_: RequestType, + #[case] sector: u64, + #[case] expected: Status, +) { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("disk.img"); + File::create(&path) + .unwrap() + .write_all(&[0x11; SECTOR_SIZE]) + .unwrap(); + let spec = BlkFileSpec { + path: Box::from(path.as_path()), + readonly: true, + api: WorkerApi::IoUring, + }; + let mut block = Block::new(spec, "blk").unwrap(); + + let ram_bus = Arc::new(tests::fixture_ram_bus()); + let ram = ram_bus.load(); + let regs = tests::fixture_queues(1); + let reg = ®s[0]; + let mut guest_q = GuestQueue::new(SplitQueue::new(reg, &ram, false).unwrap().unwrap(), reg); + let mut queue = Queue::::new(reg, ram_bus.clone(), false) + .unwrap() + .unwrap(); + + let req = Request { + type_: RequestType::IN, + reserved: 0, + sector: 0, + }; + ram.write(REQ_ADDR, req.as_bytes()).unwrap(); + ram.write(STATUS_ADDR, &[0xff]).unwrap(); + let id = guest_q.add_desc( + &[(REQ_ADDR, size_of::() as u32)], + &[(BUF_ADDR, SECTOR_SIZE as u32), (STATUS_ADDR, 1)], + ); + + let mut ring = io_uring::IoUring::new(1).unwrap(); + let (irq_tx, irq_rx) = flume::unbounded(); + let irq_sender = FakeIrqSender { q_tx: irq_tx }; + queue + .handle_desc(0, &irq_sender, |chain| { + let action = VirtioIoUring::handle_desc(&mut block, 0, chain).unwrap(); + let BufferAction::Sqe(sqe) = action else { + panic!("the read is not submitted: {action:?}"); + }; + unsafe { ring.submission().push(&sqe) }.unwrap(); + ring.submit_and_wait(1).unwrap(); + let cqe = ring.completion().next().unwrap(); + + // The driver changes the header while the read is in flight. + let req = Request { + type_, + reserved: 0, + sector, + }; + ram.write(REQ_ADDR, req.as_bytes()).unwrap(); + + let len = block.complete_desc(0, chain, &cqe).unwrap(); + Ok(QStatus::Done { len }) + }) + .unwrap(); + + assert_eq!(irq_rx.try_recv(), Ok(0)); + let used = guest_q.get_used().unwrap(); + assert_eq!((used.id, used.len), (id, 1)); + let mut status = [0u8; 1]; + ram.read(STATUS_ADDR, &mut status).unwrap(); + assert_eq!(Status::from(status[0]), expected); +}