Skip to content
Merged
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
112 changes: 102 additions & 10 deletions alioth/src/virtio/dev/blk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -66,7 +66,7 @@ consts! {
}

#[repr(C)]
#[derive(Debug, FromBytes)]
#[derive(Debug, FromBytes, Immutable, IntoBytes)]
pub struct Request {
type_: RequestType,
reserved: u32,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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()
};
Expand All @@ -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<u64> {
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<BlkRequest<'d, 'm>> {
let [hdr, data_out @ ..] = &desc.readable[..] else {
return error::InvalidBuffer.fail();
Expand All @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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, .. } => {
Expand All @@ -459,3 +547,7 @@ impl VirtioIoUring for Block {
}
}
}

#[cfg(test)]
#[path = "blk_test.rs"]
mod tests;
Loading
Loading