use std::io;
use bitvec::prelude::*;
use log::warn;
use zerocopy::byteorder::native_endian::{U32, U64};
use zerocopy::*;
pub const VIRTIO_F_NOTIFY_ON_EMPTY: u64 = 1 << 24;
pub const VIRTIO_F_INDIRECT_DESC: u64 = 1 << 28;
pub const VIRTIO_F_EVENT_IDX: u64 = 1 << 29;
pub const VHOST_USER_F_PROTOCOL_FEATURES: u64 = 1 << 30;
pub const VIRTIO_F_VERSION_1: u64 = 1 << 32;
#[derive(Debug, PartialEq, Eq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
#[repr(C)]
pub struct VringState {
pub vring_idx: U32,
pub num: U32,
}
#[derive(Debug, PartialEq, Eq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
#[repr(C)]
pub struct VringAddr {
pub vring_idx: U32,
pub flags: U32,
pub descriptor: U64,
pub used: U64,
pub available: U64,
pub log: U64,
}
#[derive(Debug, PartialEq, Eq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
#[repr(C)]
pub struct VringDescriptorIndex {
pub vring_idx: U32,
pub descriptor_idx: U32,
}
#[derive(Debug, PartialEq, Eq, Clone, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
#[repr(C)]
pub struct MemoryRegionDescription {
pub guest_address: U64,
pub size: U64,
pub user_address: U64,
pub mmap_offset: U64,
}
#[derive(Debug, PartialEq, Eq, Clone, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
#[repr(C)]
pub struct SingleMemoryRegionDescription {
_padding: U64,
region: MemoryRegionDescription,
}
#[derive(Debug, PartialEq, Eq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
#[repr(C)]
pub struct MultipleMemoryRegionDescription {
num: U32,
_padding: U32,
regions: [MemoryRegionDescription],
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct VecMemoryRegionDescription {
pub regions: Vec<MemoryRegionDescription>,
}
impl TryFrom<&MultipleMemoryRegionDescription> for VecMemoryRegionDescription {
type Error = io::Error;
fn try_from(
descriptions: &MultipleMemoryRegionDescription,
) -> io::Result<VecMemoryRegionDescription> {
let num = u32::from(descriptions.num) as usize;
if descriptions.regions.len() != num {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Bad data in MultipleMemoryRegionDescription regions",
));
}
let mut regions = Vec::with_capacity(num);
for region in &descriptions.regions {
regions.push(region.clone());
}
Ok(VecMemoryRegionDescription { regions })
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct VringFdMeta {
pub vring_idx: u8,
pub is_invalid: bool,
}
impl From<&U64> for VringFdMeta {
fn from(bits: &U64) -> VringFdMeta {
let bytes = bits.as_bytes();
let bits = bytes[0].view_bits::<Lsb0>();
let vring_idx = bits[0..7].load();
let is_invalid = bits[7];
VringFdMeta {
vring_idx,
is_invalid,
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum VhostUser01Request<'a> {
GetFeatures,
SetFeatures(&'a U64),
SetOwner,
ResetOwner,
SetMemTable(&'a MultipleMemoryRegionDescription),
SetVringNum(&'a VringState),
SetVringAddr(&'a VringAddr),
SetVringBase(&'a VringDescriptorIndex),
GetVringBase(&'a VringState),
SetVringKick(&'a U64), SetVringCall(&'a U64), SetVringErr(&'a U64), GetProtocolFeatures,
SetProtocolFeatures(&'a U64),
SetVringEnable(&'a VringState),
Unknown { msg_type: u32, payload: &'a [u8] },
}
#[derive(Debug, PartialEq, Eq)]
pub enum VhostUser01Reply {
GetFeatures(u64),
GetVringBase(VringDescriptorIndex),
GetProtocolFeatures(u64),
}
#[derive(Debug, PartialEq, Eq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
#[repr(C)]
pub struct VhostUserHdr {
msg_type: U32,
flags_and_version: U32,
pub payload_len: U32,
}
impl VhostUserHdr {
fn new_01(is_reply: bool) -> VhostUserHdr {
let mut flags_and_version = 0;
flags_and_version |= 0b01;
if is_reply {
flags_and_version |= 0b100;
}
VhostUserHdr {
flags_and_version: flags_and_version.into(),
msg_type: 0.into(),
payload_len: 0.into(),
}
}
pub fn is_valid_01(&self) -> bool {
const VERSION_MASK: u32 = 0b011;
self.flags_and_version & VERSION_MASK == 1
}
pub fn is_reply(&self) -> bool {
const IS_REPLY_MASK: u32 = 0b100;
self.flags_and_version & IS_REPLY_MASK != 0
}
}
impl VhostUser01Reply {
pub fn write_to<W: std::io::Write>(&self, buf: &mut W) -> io::Result<()> {
let (msg_type, payload) = match self {
VhostUser01Reply::GetFeatures(bits) => (1, bits.as_bytes()),
VhostUser01Reply::GetVringBase(idx) => (11, idx.as_bytes()),
VhostUser01Reply::GetProtocolFeatures(bits) => (15, bits.as_bytes()),
};
let mut hdr = VhostUserHdr::new_01(true);
hdr.msg_type = msg_type.into();
hdr.payload_len = (payload.len() as u32).into();
(&hdr).write_to_io(&mut *buf)?;
buf.write_all(payload)
}
}
impl<'a> TryFrom<(VhostUserHdr, &'a [u8])> for VhostUser01Request<'a> {
type Error = io::Error;
fn try_from((hdr, payload): (VhostUserHdr, &'a [u8])) -> io::Result<Self> {
let msg_type = u32::from(hdr.msg_type);
Ok(match msg_type {
1 => {
if !payload.is_empty() {
return Err(io::Error::other("Extra data in GetFeatures"));
}
VhostUser01Request::GetFeatures
}
2 => {
let bits = U64::ref_from_bytes(&payload)
.map_err(|_| io::Error::other("Feature bits from bytes"))?;
VhostUser01Request::SetFeatures(bits)
}
3 => {
if !payload.is_empty() {
warn!("Extra data in SetOwner ignoring");
}
VhostUser01Request::SetOwner
}
4 => {
if !payload.is_empty() {
return Err(io::Error::other("Extra data in ResetOwner"));
}
VhostUser01Request::ResetOwner
}
5 => {
let mem_table = MultipleMemoryRegionDescription::ref_from_bytes(&payload)
.map_err(|_| io::Error::other("MultipleMemoryRegionDescription from bytes"))?;
VhostUser01Request::SetMemTable(mem_table)
}
8 => {
let vring_state = VringState::ref_from_bytes(&payload)
.map_err(|_| io::Error::other("VringState from bytes"))?;
VhostUser01Request::SetVringNum(vring_state)
}
9 => {
let vring_addr = VringAddr::ref_from_bytes(&payload)
.map_err(|_| io::Error::other("VringAddr from bytes"))?;
VhostUser01Request::SetVringAddr(vring_addr)
}
10 => {
let idx = VringDescriptorIndex::ref_from_bytes(&payload)
.map_err(|_| io::Error::other("VringDescriptorIndex from bytes"))?;
VhostUser01Request::SetVringBase(idx)
}
11 => {
let vring_state = VringState::ref_from_bytes(&payload)
.map_err(|_| io::Error::other("VringState from bytes"))?;
VhostUser01Request::GetVringBase(vring_state)
}
12 => {
let bits = U64::ref_from_bytes(&payload)
.map_err(|_| io::Error::other("Fd meta from bytes"))?;
VhostUser01Request::SetVringKick(bits)
}
13 => {
let bits = U64::ref_from_bytes(&payload)
.map_err(|_| io::Error::other("Fd meta from bytes"))?;
VhostUser01Request::SetVringCall(bits)
}
14 => {
let bits = U64::ref_from_bytes(&payload)
.map_err(|_| io::Error::other("Fd meta from bytes"))?;
VhostUser01Request::SetVringErr(bits)
}
15 => {
if !payload.is_empty() {
return Err(io::Error::other("Extra data in GetProtocolFeatures"));
}
VhostUser01Request::GetProtocolFeatures
}
16 => {
let bits = U64::ref_from_bytes(&payload)
.map_err(|_| io::Error::other("Feature bits from bytes"))?;
VhostUser01Request::SetProtocolFeatures(bits)
}
18 => {
let vring_state = VringState::ref_from_bytes(&payload)
.map_err(|_| io::Error::other("VringState from bytes"))?;
VhostUser01Request::SetVringEnable(vring_state)
}
_ => VhostUser01Request::Unknown { msg_type, payload },
})
}
}