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
80 changes: 66 additions & 14 deletions alioth/src/vfio/cdev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,26 @@
// limitations under the License.

use std::fmt::Debug;
use std::fs::{File, OpenOptions};
use std::fs::OpenOptions;
use std::mem::size_of;
use std::os::fd::AsRawFd;
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
use std::path::Path;
use std::sync::Arc;

use snafu::ResultExt;

use crate::sys::vfio::{
VfioDeviceAttachIommufdPt, VfioDeviceBindIommufd, VfioDeviceDetachIommufdPt,
vfio_device_attach_iommufd_pt, vfio_device_bind_iommufd, vfio_device_detach_iommufd_pt,
VfioDeviceAttachIommufdPt, VfioDeviceBindIommufd, VfioDeviceDetachIommufdPt, VfioDeviceInfo,
VfioIrqInfo, VfioRegionInfo, vfio_device_attach_iommufd_pt, vfio_device_bind_iommufd,
vfio_device_detach_iommufd_pt,
};
use crate::vfio::device::Device;
use crate::vfio::device::{Device, Kdev};
use crate::vfio::iommu::Ioas;
use crate::vfio::{Result, error};

#[derive(Debug)]
pub struct Cdev {
fd: File,
kdev: Kdev,
ioas: Option<Arc<Ioas>>,
}

Expand All @@ -44,7 +45,10 @@ impl Cdev {
.context(error::AccessDevice {
path: path.as_ref(),
})?;
Ok(Cdev { fd, ioas: None })
Ok(Cdev {
kdev: Kdev::new(fd),
ioas: None,
})
}
}

Expand All @@ -55,41 +59,89 @@ impl Cdev {
iommufd: ioas.iommu.fd.as_raw_fd(),
..Default::default()
};
unsafe { vfio_device_bind_iommufd(&self.fd, &bind) }?;
unsafe { vfio_device_bind_iommufd(&self.kdev, &bind) }?;
let attach = VfioDeviceAttachIommufdPt {
argsz: size_of::<VfioDeviceAttachIommufdPt>() as u32,
pt_id: ioas.id,
..Default::default()
};
unsafe { vfio_device_attach_iommufd_pt(&self.fd, &attach) }?;
unsafe { vfio_device_attach_iommufd_pt(&self.kdev, &attach) }?;
self.ioas.replace(ioas);
Ok(())
}

pub fn detach_iommu_ioas(&mut self) -> Result<()> {
if self.ioas.is_none() {
return Ok(());
};
}
let detach = VfioDeviceDetachIommufdPt {
argsz: size_of::<VfioDeviceDetachIommufdPt>() as u32,
flags: 0,
};
unsafe { vfio_device_detach_iommufd_pt(&self.fd, &detach) }?;
unsafe { vfio_device_detach_iommufd_pt(&self.kdev, &detach) }?;
self.ioas = None;
Ok(())
}
}

impl Device for Cdev {
fn fd(&self) -> &File {
&self.fd
fn get_info(&self) -> Result<VfioDeviceInfo> {
self.kdev.get_info()
}

fn get_region_info(&self, index: u32) -> Result<VfioRegionInfo> {
self.kdev.get_region_info(index)
}

fn get_irq_info(&self, index: u32) -> Result<VfioIrqInfo> {
self.kdev.get_irq_info(index)
}

fn reset(&self) -> Result<()> {
self.kdev.reset()
}

fn set_irq_eventfd(
&self,
index: u32,
start: u32,
eventfds: &[Option<BorrowedFd<'_>>],
) -> Result<()> {
self.kdev.set_irq_eventfd(index, start, eventfds)
}

fn disable_irq(&self, index: u32) -> Result<()> {
self.kdev.disable_irq(index)
}

fn read_region(&self, region: &VfioRegionInfo, offset: u64, buf: &mut [u8]) -> Result<()> {
self.kdev.read_region(region, offset, buf)
}

fn write_region(&self, region: &VfioRegionInfo, offset: u64, buf: &[u8]) -> Result<()> {
self.kdev.write_region(region, offset, buf)
}

fn get_region_mmap_fd(&self, index: u32) -> Result<Option<OwnedFd>> {
self.kdev.get_region_mmap_fd(index)
}

fn get_dma_buf_fd(&self, index: u32, offset: u64, size: usize) -> Result<OwnedFd> {
self.kdev.get_dma_buf_fd(index, offset, size)
}
}

impl Drop for Cdev {
fn drop(&mut self) {
if let Err(e) = self.detach_iommu_ioas() {
log::error!("Cdev-{}: detaching ioas: {e:?}", self.fd.as_raw_fd())
log::error!(
"Cdev-{}: detaching ioas: {e:?}",
self.kdev.as_fd().as_raw_fd()
)
}
}
}

#[cfg(test)]
#[path = "cdev_test.rs"]
mod tests;
53 changes: 53 additions & 0 deletions alioth/src/vfio/cdev_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// 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::io::Write;

use assert_matches::assert_matches;

use crate::sys::vfio::{VfioRegionInfo, VfioRegionInfoFlag};
use crate::vfio::cdev::Cdev;
use crate::vfio::device::Device;

#[test]
fn test_cdev_detach_when_not_attached() {
// Cdev detach when not attached returns Ok(())
let tmp_cdev = tempfile::NamedTempFile::new().unwrap();
let mut cdev = Cdev::new(tmp_cdev.path()).unwrap();
assert_matches!(cdev.detach_iommu_ioas(), Ok(()));
}

#[test]
fn test_cdev_device_impl() {
let mut fake = tempfile::NamedTempFile::new().unwrap();
fake.write_all(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa])
.unwrap();

let cdev = Cdev::new(fake.path()).unwrap();
let region = VfioRegionInfo {
index: 0,
size: 8,
offset: 2,
flags: VfioRegionInfoFlag::READ | VfioRegionInfoFlag::WRITE,
..Default::default()
};

let mut buf = [0u8; 4];
cdev.read_region(&region, 2, &mut buf).unwrap();
assert_eq!(buf, [0x55, 0x66, 0x77, 0x88]);

cdev.write_region(&region, 0, &[0xaa, 0xbb]).unwrap();
cdev.read_region(&region, 0, &mut buf).unwrap();
assert_eq!(buf, [0xaa, 0xbb, 0x55, 0x66]);
}
4 changes: 4 additions & 0 deletions alioth/src/vfio/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,7 @@ impl LayoutChanged for UpdateContainerMapping {
self.ram_removed(gpa, pages)
}
}

#[cfg(test)]
#[path = "container_test.rs"]
mod tests;
40 changes: 40 additions & 0 deletions alioth/src/vfio/container_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// 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 assert_matches::assert_matches;

use crate::sys::vfio::VfioIommu;
use crate::vfio::Error;
use crate::vfio::container::Container;

#[test]
fn test_container_set_iommu_mismatch() {
let tmp_file = tempfile::NamedTempFile::new().unwrap();
let container = Container::new(tmp_file.path()).unwrap();
// Simulate container already having TYPE1
*container.iommu.lock() = Some(VfioIommu::TYPE1);

// Setting same IOMMU returns Ok(())
assert_matches!(container.set_iommu(VfioIommu::TYPE1), Ok(()));

// Setting different IOMMU returns SetContainerIommu error
assert_matches!(
container.set_iommu(VfioIommu::TYPE1_V2),
Err(Error::SetContainerIommu {
current: VfioIommu::TYPE1,
new: VfioIommu::TYPE1_V2,
..
})
);
}
Loading