pci.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. //! PCI transport for VirtIO.
  2. pub mod bus;
  3. use self::bus::{DeviceFunction, DeviceFunctionInfo, PciError, PciRoot, PCI_CAP_ID_VNDR};
  4. use super::{DeviceStatus, DeviceType, Transport};
  5. use crate::{
  6. hal::{Hal, PhysAddr},
  7. volatile::{volread, volwrite, ReadOnly, Volatile},
  8. };
  9. use core::{
  10. fmt::{self, Display, Formatter},
  11. mem::size_of,
  12. ptr::NonNull,
  13. };
  14. /// The PCI vendor ID for VirtIO devices.
  15. const VIRTIO_VENDOR_ID: u16 = 0x1af4;
  16. /// The offset to add to a VirtIO device ID to get the corresponding PCI device ID.
  17. const PCI_DEVICE_ID_OFFSET: u16 = 0x1040;
  18. const TRANSITIONAL_NETWORK: u16 = 0x1000;
  19. const TRANSITIONAL_BLOCK: u16 = 0x1001;
  20. const TRANSITIONAL_MEMORY_BALLOONING: u16 = 0x1002;
  21. const TRANSITIONAL_CONSOLE: u16 = 0x1003;
  22. const TRANSITIONAL_SCSI_HOST: u16 = 0x1004;
  23. const TRANSITIONAL_ENTROPY_SOURCE: u16 = 0x1005;
  24. const TRANSITIONAL_9P_TRANSPORT: u16 = 0x1009;
  25. /// The offset of the bar field within `virtio_pci_cap`.
  26. const CAP_BAR_OFFSET: u8 = 4;
  27. /// The offset of the offset field with `virtio_pci_cap`.
  28. const CAP_BAR_OFFSET_OFFSET: u8 = 8;
  29. /// The offset of the `length` field within `virtio_pci_cap`.
  30. const CAP_LENGTH_OFFSET: u8 = 12;
  31. /// Common configuration.
  32. const VIRTIO_PCI_CAP_COMMON_CFG: u8 = 1;
  33. /// Notifications.
  34. const VIRTIO_PCI_CAP_NOTIFY_CFG: u8 = 2;
  35. /// ISR Status.
  36. const VIRTIO_PCI_CAP_ISR_CFG: u8 = 3;
  37. /// Device specific configuration.
  38. const VIRTIO_PCI_CAP_DEVICE_CFG: u8 = 4;
  39. fn device_type(pci_device_id: u16) -> DeviceType {
  40. match pci_device_id {
  41. TRANSITIONAL_NETWORK => DeviceType::Network,
  42. TRANSITIONAL_BLOCK => DeviceType::Block,
  43. TRANSITIONAL_MEMORY_BALLOONING => DeviceType::MemoryBalloon,
  44. TRANSITIONAL_CONSOLE => DeviceType::Console,
  45. TRANSITIONAL_SCSI_HOST => DeviceType::ScsiHost,
  46. TRANSITIONAL_ENTROPY_SOURCE => DeviceType::EntropySource,
  47. TRANSITIONAL_9P_TRANSPORT => DeviceType::_9P,
  48. id if id >= PCI_DEVICE_ID_OFFSET => DeviceType::from(id - PCI_DEVICE_ID_OFFSET),
  49. _ => DeviceType::Invalid,
  50. }
  51. }
  52. /// Returns the type of VirtIO device to which the given PCI vendor and device ID corresponds, or
  53. /// `None` if it is not a recognised VirtIO device.
  54. pub fn virtio_device_type(device_function_info: &DeviceFunctionInfo) -> Option<DeviceType> {
  55. if device_function_info.vendor_id == VIRTIO_VENDOR_ID {
  56. let device_type = device_type(device_function_info.device_id);
  57. if device_type != DeviceType::Invalid {
  58. return Some(device_type);
  59. }
  60. }
  61. None
  62. }
  63. /// PCI transport for VirtIO.
  64. ///
  65. /// Ref: 4.1 Virtio Over PCI Bus
  66. #[derive(Debug)]
  67. pub struct PciTransport {
  68. root: PciRoot,
  69. /// The bus, device and function identifier for the VirtIO device.
  70. device_function: DeviceFunction,
  71. /// The common configuration structure within some BAR.
  72. common_cfg: NonNull<CommonCfg>,
  73. }
  74. impl PciTransport {
  75. /// Construct a new PCI VirtIO device driver for the given device function on the given PCI
  76. /// root controller.
  77. ///
  78. /// The PCI device must already have had its BARs allocated.
  79. pub fn new<H: Hal>(
  80. mut root: PciRoot,
  81. device_function: DeviceFunction,
  82. ) -> Result<Self, VirtioPciError> {
  83. // Find the PCI capabilities we need.
  84. let mut common_cfg = None;
  85. for capability in root.capabilities(device_function) {
  86. if capability.id != PCI_CAP_ID_VNDR {
  87. continue;
  88. }
  89. let cap_len = capability.private_header as u8;
  90. let cfg_type = (capability.private_header >> 8) as u8;
  91. if cap_len < 16 {
  92. continue;
  93. }
  94. let struct_info = VirtioCapabilityInfo {
  95. bar: root.config_read_word(device_function, capability.offset + CAP_BAR_OFFSET)
  96. as u8,
  97. offset: root
  98. .config_read_word(device_function, capability.offset + CAP_BAR_OFFSET_OFFSET),
  99. length: root
  100. .config_read_word(device_function, capability.offset + CAP_LENGTH_OFFSET),
  101. };
  102. match cfg_type {
  103. VIRTIO_PCI_CAP_COMMON_CFG if common_cfg.is_none() => {
  104. common_cfg = Some(struct_info);
  105. }
  106. _ => {}
  107. }
  108. }
  109. let common_cfg = get_bar_region::<H, _>(
  110. &mut root,
  111. device_function,
  112. &common_cfg.ok_or(VirtioPciError::MissingCommonConfig)?,
  113. )?;
  114. Ok(Self {
  115. root,
  116. device_function,
  117. common_cfg,
  118. })
  119. }
  120. }
  121. impl Transport for PciTransport {
  122. fn device_type(&self) -> DeviceType {
  123. let header = self.root.config_read_word(self.device_function, 0);
  124. let device_id = (header >> 16) as u16;
  125. device_type(device_id)
  126. }
  127. fn read_device_features(&mut self) -> u64 {
  128. // Safe because TODO
  129. unsafe {
  130. volwrite!(self.common_cfg, device_feature_select, 0);
  131. let mut device_features_bits = volread!(self.common_cfg, device_feature) as u64;
  132. volwrite!(self.common_cfg, device_feature_select, 1);
  133. device_features_bits |= (volread!(self.common_cfg, device_feature) as u64) << 32;
  134. device_features_bits
  135. }
  136. }
  137. fn write_driver_features(&mut self, driver_features: u64) {
  138. // Safe because TODO
  139. unsafe {
  140. volwrite!(self.common_cfg, driver_feature_select, 0);
  141. volwrite!(self.common_cfg, driver_feature, driver_features as u32);
  142. volwrite!(self.common_cfg, driver_feature_select, 1);
  143. volwrite!(
  144. self.common_cfg,
  145. driver_feature,
  146. (driver_features >> 32) as u32
  147. );
  148. }
  149. }
  150. fn max_queue_size(&self) -> u32 {
  151. unsafe { volread!(self.common_cfg, queue_size) }.into()
  152. }
  153. fn notify(&mut self, queue: u16) {
  154. todo!()
  155. }
  156. fn set_status(&mut self, status: DeviceStatus) {
  157. // Safe because TODO
  158. unsafe {
  159. volwrite!(self.common_cfg, device_status, status.bits() as u8);
  160. }
  161. }
  162. fn set_guest_page_size(&mut self, _guest_page_size: u32) {
  163. // No-op, the PCI transport doesn't care.
  164. }
  165. fn queue_set(
  166. &mut self,
  167. queue: u16,
  168. size: u32,
  169. descriptors: PhysAddr,
  170. driver_area: PhysAddr,
  171. device_area: PhysAddr,
  172. ) {
  173. // Safe because TODO
  174. unsafe {
  175. volwrite!(self.common_cfg, queue_select, queue);
  176. volwrite!(self.common_cfg, queue_size, size as u16);
  177. volwrite!(self.common_cfg, queue_desc, descriptors as u64);
  178. volwrite!(self.common_cfg, queue_driver, driver_area as u64);
  179. volwrite!(self.common_cfg, queue_device, device_area as u64);
  180. volwrite!(self.common_cfg, queue_enable, 1);
  181. }
  182. }
  183. fn queue_used(&mut self, queue: u16) -> bool {
  184. // Safe because TODO
  185. unsafe {
  186. volwrite!(self.common_cfg, queue_select, queue);
  187. volread!(self.common_cfg, queue_enable) == 1
  188. }
  189. }
  190. fn ack_interrupt(&mut self) -> bool {
  191. todo!()
  192. }
  193. fn config_space(&self) -> NonNull<u64> {
  194. todo!()
  195. }
  196. }
  197. /// `virtio_pci_common_cfg`, see 4.1.4.3 "Common configuration structure layout".
  198. #[repr(C)]
  199. struct CommonCfg {
  200. device_feature_select: Volatile<u32>,
  201. device_feature: ReadOnly<u32>,
  202. driver_feature_select: Volatile<u32>,
  203. driver_feature: Volatile<u32>,
  204. msix_config: Volatile<u16>,
  205. num_queues: ReadOnly<u16>,
  206. device_status: Volatile<u8>,
  207. config_generation: ReadOnly<u8>,
  208. queue_select: Volatile<u16>,
  209. queue_size: Volatile<u16>,
  210. queue_msix_vector: Volatile<u16>,
  211. queue_enable: Volatile<u16>,
  212. queue_notify_off: Volatile<u16>,
  213. queue_desc: Volatile<u64>,
  214. queue_driver: Volatile<u64>,
  215. queue_device: Volatile<u64>,
  216. }
  217. /// Information about a VirtIO structure within some BAR, as provided by a `virtio_pci_cap`.
  218. #[derive(Clone, Debug, Eq, PartialEq)]
  219. struct VirtioCapabilityInfo {
  220. /// The bar in which the structure can be found.
  221. bar: u8,
  222. /// The offset within the bar.
  223. offset: u32,
  224. /// The length in bytes of the structure within the bar.
  225. length: u32,
  226. }
  227. fn get_bar_region<H: Hal, T>(
  228. root: &mut PciRoot,
  229. device_function: DeviceFunction,
  230. struct_info: &VirtioCapabilityInfo,
  231. ) -> Result<NonNull<T>, VirtioPciError> {
  232. let bar_info = root.bar_info(device_function, struct_info.bar)?;
  233. let (bar_address, bar_size) = bar_info
  234. .memory_address_size()
  235. .ok_or(VirtioPciError::UnexpectedIoBar)?;
  236. if bar_address == 0 {
  237. return Err(VirtioPciError::BarNotAllocated(struct_info.bar));
  238. }
  239. if struct_info.offset + struct_info.length > bar_size
  240. || size_of::<T>() > struct_info.length as usize
  241. {
  242. return Err(VirtioPciError::BarOffsetOutOfRange);
  243. }
  244. let paddr = bar_address as PhysAddr + struct_info.offset as PhysAddr;
  245. Ok(NonNull::new(H::phys_to_virt(paddr) as _).unwrap())
  246. }
  247. /// An error encountered initialising a VirtIO PCI transport.
  248. #[derive(Clone, Debug, Eq, PartialEq)]
  249. pub enum VirtioPciError {
  250. /// No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found.
  251. MissingCommonConfig,
  252. /// An IO BAR was provided rather than a memory BAR.
  253. UnexpectedIoBar,
  254. /// A BAR which we need was not allocated an address.
  255. BarNotAllocated(u8),
  256. /// The offset for some capability was greater than the length of the BAR.
  257. BarOffsetOutOfRange,
  258. /// A generic PCI error,
  259. Pci(PciError),
  260. }
  261. impl Display for VirtioPciError {
  262. fn fmt(&self, f: &mut Formatter) -> fmt::Result {
  263. match self {
  264. Self::MissingCommonConfig => write!(
  265. f,
  266. "No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found."
  267. ),
  268. Self::UnexpectedIoBar => write!(f, "Unexpected IO BAR (expected memory BAR)."),
  269. Self::BarNotAllocated(bar_index) => write!(f, "Bar {} not allocated.", bar_index),
  270. Self::BarOffsetOutOfRange => write!(f, "Capability offset greater than BAR length."),
  271. Self::Pci(pci_error) => pci_error.fmt(f),
  272. }
  273. }
  274. }
  275. impl From<PciError> for VirtioPciError {
  276. fn from(error: PciError) -> Self {
  277. Self::Pci(error)
  278. }
  279. }
  280. #[cfg(test)]
  281. mod tests {
  282. use super::*;
  283. #[test]
  284. fn transitional_device_ids() {
  285. assert_eq!(device_type(0x1000), DeviceType::Network);
  286. assert_eq!(device_type(0x1002), DeviceType::MemoryBalloon);
  287. assert_eq!(device_type(0x1009), DeviceType::_9P);
  288. }
  289. #[test]
  290. fn offset_device_ids() {
  291. assert_eq!(device_type(0x1045), DeviceType::MemoryBalloon);
  292. assert_eq!(device_type(0x1049), DeviceType::_9P);
  293. assert_eq!(device_type(0x1058), DeviceType::Memory);
  294. assert_eq!(device_type(0x1040), DeviceType::Invalid);
  295. assert_eq!(device_type(0x1059), DeviceType::Invalid);
  296. }
  297. #[test]
  298. fn virtio_device_type_valid() {
  299. assert_eq!(
  300. virtio_device_type(&DeviceFunctionInfo {
  301. vendor_id: VIRTIO_VENDOR_ID,
  302. device_id: TRANSITIONAL_BLOCK,
  303. class: 0,
  304. subclass: 0,
  305. prog_if: 0,
  306. revision: 0,
  307. header_type: bus::HeaderType::Standard,
  308. }),
  309. Some(DeviceType::Block)
  310. );
  311. }
  312. #[test]
  313. fn virtio_device_type_invalid() {
  314. // Non-VirtIO vendor ID.
  315. assert_eq!(
  316. virtio_device_type(&DeviceFunctionInfo {
  317. vendor_id: 0x1234,
  318. device_id: TRANSITIONAL_BLOCK,
  319. class: 0,
  320. subclass: 0,
  321. prog_if: 0,
  322. revision: 0,
  323. header_type: bus::HeaderType::Standard,
  324. }),
  325. None
  326. );
  327. // Invalid device ID.
  328. assert_eq!(
  329. virtio_device_type(&DeviceFunctionInfo {
  330. vendor_id: VIRTIO_VENDOR_ID,
  331. device_id: 0x1040,
  332. class: 0,
  333. subclass: 0,
  334. prog_if: 0,
  335. revision: 0,
  336. header_type: bus::HeaderType::Standard,
  337. }),
  338. None
  339. );
  340. }
  341. }