virtio_drivers/
lib.rs

1//! VirtIO guest drivers.
2//!
3//! These drivers can be used by bare-metal code (such as a bootloader or OS kernel) running in a VM
4//! to interact with VirtIO devices provided by the VMM (such as QEMU or crosvm).
5//!
6//! # Usage
7//!
8//! You must first implement the [`Hal`] trait, to allocate DMA regions and translate between
9//! physical addresses (as seen by devices) and virtual addresses (as seen by your program). You can
10//! then construct the appropriate transport for the VirtIO device, e.g. for an MMIO device (perhaps
11//! discovered from the device tree):
12//!
13//! ```
14//! use core::ptr::NonNull;
15//! use virtio_drivers::transport::mmio::{MmioTransport, VirtIOHeader};
16//!
17//! # fn example(mmio_device_address: usize, mmio_size: usize) {
18//! let header = NonNull::new(mmio_device_address as *mut VirtIOHeader).unwrap();
19//! let transport = unsafe { MmioTransport::new(header, mmio_size) }.unwrap();
20//! # }
21//! ```
22//!
23//! You can then check what kind of VirtIO device it is and construct the appropriate driver:
24//!
25//! ```
26//! # use virtio_drivers::Hal;
27//! # #[cfg(feature = "alloc")]
28//! use virtio_drivers::{
29//!     device::console::VirtIOConsole,
30//!     transport::{mmio::MmioTransport, DeviceType, Transport},
31//! };
32
33//!
34//! # #[cfg(feature = "alloc")]
35//! # fn example<HalImpl: Hal>(transport: MmioTransport) {
36//! if transport.device_type() == DeviceType::Console {
37//!     let mut console = VirtIOConsole::<HalImpl, _>::new(transport).unwrap();
38//!     // Send a byte to the console.
39//!     console.send(b'H').unwrap();
40//! }
41//! # }
42//! ```
43
44#![cfg_attr(not(test), no_std)]
45#![deny(unused_must_use, missing_docs, clippy::undocumented_unsafe_blocks)]
46#![allow(clippy::identity_op)]
47#![allow(dead_code)]
48
49#[cfg(any(feature = "alloc", test))]
50extern crate alloc;
51
52mod config;
53pub mod device;
54#[cfg(feature = "embedded-io")]
55mod embedded_io;
56mod hal;
57mod queue;
58pub mod transport;
59
60use device::socket::SocketError;
61use thiserror::Error;
62
63pub use self::hal::{BufferDirection, Hal, PhysAddr};
64pub use safe_mmio::UniqueMmioPointer;
65
66/// The page size in bytes supported by the library (4 KiB).
67pub const PAGE_SIZE: usize = 0x1000;
68
69const PAGE_SIZE_PHYS: PhysAddr = PAGE_SIZE as PhysAddr;
70
71/// The type returned by driver methods.
72pub type Result<T = ()> = core::result::Result<T, Error>;
73
74/// The error type of VirtIO drivers.
75#[derive(Copy, Clone, Debug, Eq, Error, PartialEq)]
76pub enum Error {
77    /// There are not enough descriptors available in the virtqueue, try again later.
78    #[error("Virtqueue is full")]
79    QueueFull,
80    /// The device is not ready.
81    #[error("Device not ready")]
82    NotReady,
83    /// The device used a different descriptor chain to the one we were expecting.
84    #[error("Device used a different descriptor chain to the one we were expecting")]
85    WrongToken,
86    /// The queue is already in use.
87    #[error("Virtqueue is already in use")]
88    AlreadyUsed,
89    /// Invalid parameter.
90    #[error("Invalid parameter")]
91    InvalidParam,
92    /// Failed to allocate DMA memory.
93    #[error("Failed to allocate DMA memory")]
94    DmaError,
95    /// I/O error
96    #[error("I/O error")]
97    IoError,
98    /// The request was not supported by the device.
99    #[error("Request not supported by device")]
100    Unsupported,
101    /// The config space advertised by the device is smaller than the driver expected.
102    #[error("Config space advertised by the device is smaller than expected")]
103    ConfigSpaceTooSmall,
104    /// The device doesn't have any config space, but the driver expects some.
105    #[error("The device doesn't have any config space, but the driver expects some")]
106    ConfigSpaceMissing,
107    /// Error from the socket device.
108    #[error("Error from the socket device: {0}")]
109    SocketDeviceError(#[from] SocketError),
110}
111
112#[cfg(feature = "alloc")]
113impl From<alloc::string::FromUtf8Error> for Error {
114    fn from(_value: alloc::string::FromUtf8Error) -> Self {
115        Self::IoError
116    }
117}
118
119/// Align `size` up to a page.
120fn align_up(size: usize) -> usize {
121    (size + PAGE_SIZE) & !(PAGE_SIZE - 1)
122}
123
124/// Align `size` up to a page.
125fn align_up_phys(size: PhysAddr) -> PhysAddr {
126    (size + PAGE_SIZE_PHYS) & !(PAGE_SIZE_PHYS - 1)
127}
128
129/// The number of pages required to store `size` bytes, rounded up to a whole number of pages.
130fn pages(size: usize) -> usize {
131    size.div_ceil(PAGE_SIZE)
132}