pci.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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, VirtAddr},
  7. volatile::{
  8. volread, volwrite, ReadOnly, Volatile, VolatileReadable, VolatileWritable, WriteOnly,
  9. },
  10. Error,
  11. };
  12. use core::{
  13. fmt::{self, Display, Formatter},
  14. mem::{align_of, size_of},
  15. ptr::{self, addr_of_mut, NonNull},
  16. };
  17. /// The PCI vendor ID for VirtIO devices.
  18. const VIRTIO_VENDOR_ID: u16 = 0x1af4;
  19. /// The offset to add to a VirtIO device ID to get the corresponding PCI device ID.
  20. const PCI_DEVICE_ID_OFFSET: u16 = 0x1040;
  21. const TRANSITIONAL_NETWORK: u16 = 0x1000;
  22. const TRANSITIONAL_BLOCK: u16 = 0x1001;
  23. const TRANSITIONAL_MEMORY_BALLOONING: u16 = 0x1002;
  24. const TRANSITIONAL_CONSOLE: u16 = 0x1003;
  25. const TRANSITIONAL_SCSI_HOST: u16 = 0x1004;
  26. const TRANSITIONAL_ENTROPY_SOURCE: u16 = 0x1005;
  27. const TRANSITIONAL_9P_TRANSPORT: u16 = 0x1009;
  28. /// The offset of the bar field within `virtio_pci_cap`.
  29. const CAP_BAR_OFFSET: u8 = 4;
  30. /// The offset of the offset field with `virtio_pci_cap`.
  31. const CAP_BAR_OFFSET_OFFSET: u8 = 8;
  32. /// The offset of the `length` field within `virtio_pci_cap`.
  33. const CAP_LENGTH_OFFSET: u8 = 12;
  34. /// The offset of the`notify_off_multiplier` field within `virtio_pci_notify_cap`.
  35. const CAP_NOTIFY_OFF_MULTIPLIER_OFFSET: u8 = 16;
  36. /// Common configuration.
  37. const VIRTIO_PCI_CAP_COMMON_CFG: u8 = 1;
  38. /// Notifications.
  39. const VIRTIO_PCI_CAP_NOTIFY_CFG: u8 = 2;
  40. /// ISR Status.
  41. const VIRTIO_PCI_CAP_ISR_CFG: u8 = 3;
  42. /// Device specific configuration.
  43. const VIRTIO_PCI_CAP_DEVICE_CFG: u8 = 4;
  44. fn device_type(pci_device_id: u16) -> DeviceType {
  45. match pci_device_id {
  46. TRANSITIONAL_NETWORK => DeviceType::Network,
  47. TRANSITIONAL_BLOCK => DeviceType::Block,
  48. TRANSITIONAL_MEMORY_BALLOONING => DeviceType::MemoryBalloon,
  49. TRANSITIONAL_CONSOLE => DeviceType::Console,
  50. TRANSITIONAL_SCSI_HOST => DeviceType::ScsiHost,
  51. TRANSITIONAL_ENTROPY_SOURCE => DeviceType::EntropySource,
  52. TRANSITIONAL_9P_TRANSPORT => DeviceType::_9P,
  53. id if id >= PCI_DEVICE_ID_OFFSET => DeviceType::from(id - PCI_DEVICE_ID_OFFSET),
  54. _ => DeviceType::Invalid,
  55. }
  56. }
  57. /// Returns the type of VirtIO device to which the given PCI vendor and device ID corresponds, or
  58. /// `None` if it is not a recognised VirtIO device.
  59. pub fn virtio_device_type(device_function_info: &DeviceFunctionInfo) -> Option<DeviceType> {
  60. if device_function_info.vendor_id == VIRTIO_VENDOR_ID {
  61. let device_type = device_type(device_function_info.device_id);
  62. if device_type != DeviceType::Invalid {
  63. return Some(device_type);
  64. }
  65. }
  66. None
  67. }
  68. /// PCI transport for VirtIO.
  69. ///
  70. /// Ref: 4.1 Virtio Over PCI Bus
  71. #[derive(Debug)]
  72. pub struct PciTransport {
  73. device_type: DeviceType,
  74. /// The bus, device and function identifier for the VirtIO device.
  75. device_function: DeviceFunction,
  76. /// The common configuration structure within some BAR.
  77. common_cfg: NonNull<CommonCfg>,
  78. /// The start of the queue notification region within some BAR.
  79. notify_region: NonNull<[WriteOnly<u16>]>,
  80. notify_off_multiplier: u32,
  81. /// The ISR status register within some BAR.
  82. isr_status: NonNull<Volatile<u8>>,
  83. /// The VirtIO device-specific configuration within some BAR.
  84. config_space: Option<NonNull<[u32]>>,
  85. }
  86. impl PciTransport {
  87. /// Construct a new PCI VirtIO device driver for the given device function on the given PCI
  88. /// root controller.
  89. ///
  90. /// The PCI device must already have had its BARs allocated.
  91. pub fn new<H: Hal>(
  92. root: &mut PciRoot,
  93. device_function: DeviceFunction,
  94. ) -> Result<Self, VirtioPciError> {
  95. let device_vendor = root.config_read_word(device_function, 0);
  96. let device_id = (device_vendor >> 16) as u16;
  97. let vendor_id = device_vendor as u16;
  98. if vendor_id != VIRTIO_VENDOR_ID {
  99. return Err(VirtioPciError::InvalidVendorId(vendor_id));
  100. }
  101. let device_type = device_type(device_id);
  102. // Find the PCI capabilities we need.
  103. let mut common_cfg = None;
  104. let mut notify_cfg = None;
  105. let mut notify_off_multiplier = 0;
  106. let mut isr_cfg = None;
  107. let mut device_cfg = None;
  108. for capability in root.capabilities(device_function) {
  109. if capability.id != PCI_CAP_ID_VNDR {
  110. continue;
  111. }
  112. let cap_len = capability.private_header as u8;
  113. let cfg_type = (capability.private_header >> 8) as u8;
  114. if cap_len < 16 {
  115. continue;
  116. }
  117. let struct_info = VirtioCapabilityInfo {
  118. bar: root.config_read_word(device_function, capability.offset + CAP_BAR_OFFSET)
  119. as u8,
  120. offset: root
  121. .config_read_word(device_function, capability.offset + CAP_BAR_OFFSET_OFFSET),
  122. length: root
  123. .config_read_word(device_function, capability.offset + CAP_LENGTH_OFFSET),
  124. };
  125. match cfg_type {
  126. VIRTIO_PCI_CAP_COMMON_CFG if common_cfg.is_none() => {
  127. common_cfg = Some(struct_info);
  128. }
  129. VIRTIO_PCI_CAP_NOTIFY_CFG if cap_len >= 20 && notify_cfg.is_none() => {
  130. notify_cfg = Some(struct_info);
  131. notify_off_multiplier = root.config_read_word(
  132. device_function,
  133. capability.offset + CAP_NOTIFY_OFF_MULTIPLIER_OFFSET,
  134. );
  135. }
  136. VIRTIO_PCI_CAP_ISR_CFG if isr_cfg.is_none() => {
  137. isr_cfg = Some(struct_info);
  138. }
  139. VIRTIO_PCI_CAP_DEVICE_CFG if device_cfg.is_none() => {
  140. device_cfg = Some(struct_info);
  141. }
  142. _ => {}
  143. }
  144. }
  145. let common_cfg = get_bar_region::<H, _>(
  146. root,
  147. device_function,
  148. &common_cfg.ok_or(VirtioPciError::MissingCommonConfig)?,
  149. )?;
  150. let notify_cfg = notify_cfg.ok_or(VirtioPciError::MissingNotifyConfig)?;
  151. if notify_off_multiplier % 2 != 0 {
  152. return Err(VirtioPciError::InvalidNotifyOffMultiplier(
  153. notify_off_multiplier,
  154. ));
  155. }
  156. let notify_region = get_bar_region_slice::<H, _>(root, device_function, &notify_cfg)?;
  157. let isr_status = get_bar_region::<H, _>(
  158. root,
  159. device_function,
  160. &isr_cfg.ok_or(VirtioPciError::MissingIsrConfig)?,
  161. )?;
  162. let config_space = if let Some(device_cfg) = device_cfg {
  163. Some(get_bar_region_slice::<H, _>(
  164. root,
  165. device_function,
  166. &device_cfg,
  167. )?)
  168. } else {
  169. None
  170. };
  171. Ok(Self {
  172. device_type,
  173. device_function,
  174. common_cfg,
  175. notify_region,
  176. notify_off_multiplier,
  177. isr_status,
  178. config_space,
  179. })
  180. }
  181. }
  182. impl Transport for PciTransport {
  183. fn device_type(&self) -> DeviceType {
  184. self.device_type
  185. }
  186. fn read_device_features(&mut self) -> u64 {
  187. // Safe because the common config pointer is valid and we checked in get_bar_region that it
  188. // was aligned.
  189. unsafe {
  190. volwrite!(self.common_cfg, device_feature_select, 0);
  191. let mut device_features_bits = volread!(self.common_cfg, device_feature) as u64;
  192. volwrite!(self.common_cfg, device_feature_select, 1);
  193. device_features_bits |= (volread!(self.common_cfg, device_feature) as u64) << 32;
  194. device_features_bits
  195. }
  196. }
  197. fn write_driver_features(&mut self, driver_features: u64) {
  198. // Safe because the common config pointer is valid and we checked in get_bar_region that it
  199. // was aligned.
  200. unsafe {
  201. volwrite!(self.common_cfg, driver_feature_select, 0);
  202. volwrite!(self.common_cfg, driver_feature, driver_features as u32);
  203. volwrite!(self.common_cfg, driver_feature_select, 1);
  204. volwrite!(
  205. self.common_cfg,
  206. driver_feature,
  207. (driver_features >> 32) as u32
  208. );
  209. }
  210. }
  211. fn max_queue_size(&self) -> u32 {
  212. // Safe because the common config pointer is valid and we checked in get_bar_region that it
  213. // was aligned.
  214. unsafe { volread!(self.common_cfg, queue_size) }.into()
  215. }
  216. fn notify(&mut self, queue: u16) {
  217. // Safe because the common config and notify region pointers are valid and we checked in
  218. // get_bar_region that they were aligned.
  219. unsafe {
  220. volwrite!(self.common_cfg, queue_select, queue);
  221. // TODO: Consider caching this somewhere (per queue).
  222. let queue_notify_off = volread!(self.common_cfg, queue_notify_off);
  223. let offset_bytes = usize::from(queue_notify_off) * self.notify_off_multiplier as usize;
  224. let index = offset_bytes / size_of::<u16>();
  225. addr_of_mut!((*self.notify_region.as_ptr())[index]).vwrite(queue);
  226. }
  227. }
  228. fn set_status(&mut self, status: DeviceStatus) {
  229. // Safe because the common config pointer is valid and we checked in get_bar_region that it
  230. // was aligned.
  231. unsafe {
  232. volwrite!(self.common_cfg, device_status, status.bits() as u8);
  233. }
  234. }
  235. fn set_guest_page_size(&mut self, _guest_page_size: u32) {
  236. // No-op, the PCI transport doesn't care.
  237. }
  238. fn requires_legacy_layout(&self) -> bool {
  239. false
  240. }
  241. fn queue_set(
  242. &mut self,
  243. queue: u16,
  244. size: u32,
  245. descriptors: PhysAddr,
  246. driver_area: PhysAddr,
  247. device_area: PhysAddr,
  248. ) {
  249. // Safe because the common config pointer is valid and we checked in get_bar_region that it
  250. // was aligned.
  251. unsafe {
  252. volwrite!(self.common_cfg, queue_select, queue);
  253. volwrite!(self.common_cfg, queue_size, size as u16);
  254. volwrite!(self.common_cfg, queue_desc, descriptors as u64);
  255. volwrite!(self.common_cfg, queue_driver, driver_area as u64);
  256. volwrite!(self.common_cfg, queue_device, device_area as u64);
  257. volwrite!(self.common_cfg, queue_enable, 1);
  258. }
  259. }
  260. fn queue_unset(&mut self, queue: u16) {
  261. // Safe because the common config pointer is valid and we checked in get_bar_region that it
  262. // was aligned.
  263. unsafe {
  264. volwrite!(self.common_cfg, queue_enable, 0);
  265. volwrite!(self.common_cfg, queue_select, queue);
  266. volwrite!(self.common_cfg, queue_size, 0);
  267. volwrite!(self.common_cfg, queue_desc, 0);
  268. volwrite!(self.common_cfg, queue_driver, 0);
  269. volwrite!(self.common_cfg, queue_device, 0);
  270. }
  271. }
  272. fn queue_used(&mut self, queue: u16) -> bool {
  273. // Safe because the common config pointer is valid and we checked in get_bar_region that it
  274. // was aligned.
  275. unsafe {
  276. volwrite!(self.common_cfg, queue_select, queue);
  277. volread!(self.common_cfg, queue_enable) == 1
  278. }
  279. }
  280. fn ack_interrupt(&mut self) -> bool {
  281. // Safe because the common config pointer is valid and we checked in get_bar_region that it
  282. // was aligned.
  283. // Reading the ISR status resets it to 0 and causes the device to de-assert the interrupt.
  284. let isr_status = unsafe { self.isr_status.as_ptr().vread() };
  285. // TODO: Distinguish between queue interrupt and device configuration interrupt.
  286. isr_status & 0x3 != 0
  287. }
  288. fn config_space<T>(&self) -> Result<NonNull<T>, Error> {
  289. if let Some(config_space) = self.config_space {
  290. if size_of::<T>() > config_space.len() * size_of::<u32>() {
  291. Err(Error::ConfigSpaceTooSmall)
  292. } else if align_of::<T>() > 4 {
  293. // Panic as this should only happen if the driver is written incorrectly.
  294. panic!(
  295. "Driver expected config space alignment of {} bytes, but VirtIO only guarantees 4 byte alignment.",
  296. align_of::<T>()
  297. );
  298. } else {
  299. // TODO: Use NonNull::as_non_null_ptr once it is stable.
  300. let config_space_ptr = NonNull::new(config_space.as_ptr() as *mut u32).unwrap();
  301. Ok(config_space_ptr.cast())
  302. }
  303. } else {
  304. Err(Error::ConfigSpaceMissing)
  305. }
  306. }
  307. }
  308. /// `virtio_pci_common_cfg`, see 4.1.4.3 "Common configuration structure layout".
  309. #[repr(C)]
  310. struct CommonCfg {
  311. device_feature_select: Volatile<u32>,
  312. device_feature: ReadOnly<u32>,
  313. driver_feature_select: Volatile<u32>,
  314. driver_feature: Volatile<u32>,
  315. msix_config: Volatile<u16>,
  316. num_queues: ReadOnly<u16>,
  317. device_status: Volatile<u8>,
  318. config_generation: ReadOnly<u8>,
  319. queue_select: Volatile<u16>,
  320. queue_size: Volatile<u16>,
  321. queue_msix_vector: Volatile<u16>,
  322. queue_enable: Volatile<u16>,
  323. queue_notify_off: Volatile<u16>,
  324. queue_desc: Volatile<u64>,
  325. queue_driver: Volatile<u64>,
  326. queue_device: Volatile<u64>,
  327. }
  328. /// Information about a VirtIO structure within some BAR, as provided by a `virtio_pci_cap`.
  329. #[derive(Clone, Debug, Eq, PartialEq)]
  330. struct VirtioCapabilityInfo {
  331. /// The bar in which the structure can be found.
  332. bar: u8,
  333. /// The offset within the bar.
  334. offset: u32,
  335. /// The length in bytes of the structure within the bar.
  336. length: u32,
  337. }
  338. fn get_bar_region<H: Hal, T>(
  339. root: &mut PciRoot,
  340. device_function: DeviceFunction,
  341. struct_info: &VirtioCapabilityInfo,
  342. ) -> Result<NonNull<T>, VirtioPciError> {
  343. let bar_info = root.bar_info(device_function, struct_info.bar)?;
  344. let (bar_address, bar_size) = bar_info
  345. .memory_address_size()
  346. .ok_or(VirtioPciError::UnexpectedIoBar)?;
  347. if bar_address == 0 {
  348. return Err(VirtioPciError::BarNotAllocated(struct_info.bar));
  349. }
  350. if struct_info.offset + struct_info.length > bar_size
  351. || size_of::<T>() > struct_info.length as usize
  352. {
  353. return Err(VirtioPciError::BarOffsetOutOfRange);
  354. }
  355. let paddr = bar_address as PhysAddr + struct_info.offset as PhysAddr;
  356. let vaddr = H::phys_to_virt(paddr);
  357. if vaddr % align_of::<T>() != 0 {
  358. return Err(VirtioPciError::Misaligned {
  359. vaddr,
  360. alignment: align_of::<T>(),
  361. });
  362. }
  363. Ok(NonNull::new(vaddr as _).unwrap())
  364. }
  365. fn get_bar_region_slice<H: Hal, T>(
  366. root: &mut PciRoot,
  367. device_function: DeviceFunction,
  368. struct_info: &VirtioCapabilityInfo,
  369. ) -> Result<NonNull<[T]>, VirtioPciError> {
  370. let ptr = get_bar_region::<H, T>(root, device_function, struct_info)?;
  371. let raw_slice =
  372. ptr::slice_from_raw_parts_mut(ptr.as_ptr(), struct_info.length as usize / size_of::<T>());
  373. Ok(NonNull::new(raw_slice).unwrap())
  374. }
  375. /// An error encountered initialising a VirtIO PCI transport.
  376. #[derive(Clone, Debug, Eq, PartialEq)]
  377. pub enum VirtioPciError {
  378. /// PCI device vender ID was not the VirtIO vendor ID.
  379. InvalidVendorId(u16),
  380. /// No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found.
  381. MissingCommonConfig,
  382. /// No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found.
  383. MissingNotifyConfig,
  384. /// `VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple
  385. /// of 2.
  386. InvalidNotifyOffMultiplier(u32),
  387. /// No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.
  388. MissingIsrConfig,
  389. /// An IO BAR was provided rather than a memory BAR.
  390. UnexpectedIoBar,
  391. /// A BAR which we need was not allocated an address.
  392. BarNotAllocated(u8),
  393. /// The offset for some capability was greater than the length of the BAR.
  394. BarOffsetOutOfRange,
  395. /// The virtual address was not aligned as expected.
  396. Misaligned {
  397. /// The virtual address in question.
  398. vaddr: VirtAddr,
  399. /// The expected alignment in bytes.
  400. alignment: usize,
  401. },
  402. /// A generic PCI error,
  403. Pci(PciError),
  404. }
  405. impl Display for VirtioPciError {
  406. fn fmt(&self, f: &mut Formatter) -> fmt::Result {
  407. match self {
  408. Self::InvalidVendorId(vendor_id) => write!(
  409. f,
  410. "PCI device vender ID {:#06x} was not the VirtIO vendor ID {:#06x}.",
  411. vendor_id, VIRTIO_VENDOR_ID
  412. ),
  413. Self::MissingCommonConfig => write!(
  414. f,
  415. "No valid `VIRTIO_PCI_CAP_COMMON_CFG` capability was found."
  416. ),
  417. Self::MissingNotifyConfig => write!(
  418. f,
  419. "No valid `VIRTIO_PCI_CAP_NOTIFY_CFG` capability was found."
  420. ),
  421. Self::InvalidNotifyOffMultiplier(notify_off_multiplier) => {
  422. write!(
  423. f,
  424. "`VIRTIO_PCI_CAP_NOTIFY_CFG` capability has a `notify_off_multiplier` that is not a multiple of 2: {}",
  425. notify_off_multiplier
  426. )
  427. }
  428. Self::MissingIsrConfig => {
  429. write!(f, "No valid `VIRTIO_PCI_CAP_ISR_CFG` capability was found.")
  430. }
  431. Self::UnexpectedIoBar => write!(f, "Unexpected IO BAR (expected memory BAR)."),
  432. Self::BarNotAllocated(bar_index) => write!(f, "Bar {} not allocated.", bar_index),
  433. Self::BarOffsetOutOfRange => write!(f, "Capability offset greater than BAR length."),
  434. Self::Misaligned { vaddr, alignment } => write!(
  435. f,
  436. "Virtual address {:#018x} was not aligned to a {} byte boundary as expected.",
  437. vaddr, alignment
  438. ),
  439. Self::Pci(pci_error) => pci_error.fmt(f),
  440. }
  441. }
  442. }
  443. impl From<PciError> for VirtioPciError {
  444. fn from(error: PciError) -> Self {
  445. Self::Pci(error)
  446. }
  447. }
  448. #[cfg(test)]
  449. mod tests {
  450. use super::*;
  451. #[test]
  452. fn transitional_device_ids() {
  453. assert_eq!(device_type(0x1000), DeviceType::Network);
  454. assert_eq!(device_type(0x1002), DeviceType::MemoryBalloon);
  455. assert_eq!(device_type(0x1009), DeviceType::_9P);
  456. }
  457. #[test]
  458. fn offset_device_ids() {
  459. assert_eq!(device_type(0x1045), DeviceType::MemoryBalloon);
  460. assert_eq!(device_type(0x1049), DeviceType::_9P);
  461. assert_eq!(device_type(0x1058), DeviceType::Memory);
  462. assert_eq!(device_type(0x1040), DeviceType::Invalid);
  463. assert_eq!(device_type(0x1059), DeviceType::Invalid);
  464. }
  465. #[test]
  466. fn virtio_device_type_valid() {
  467. assert_eq!(
  468. virtio_device_type(&DeviceFunctionInfo {
  469. vendor_id: VIRTIO_VENDOR_ID,
  470. device_id: TRANSITIONAL_BLOCK,
  471. class: 0,
  472. subclass: 0,
  473. prog_if: 0,
  474. revision: 0,
  475. header_type: bus::HeaderType::Standard,
  476. }),
  477. Some(DeviceType::Block)
  478. );
  479. }
  480. #[test]
  481. fn virtio_device_type_invalid() {
  482. // Non-VirtIO vendor ID.
  483. assert_eq!(
  484. virtio_device_type(&DeviceFunctionInfo {
  485. vendor_id: 0x1234,
  486. device_id: TRANSITIONAL_BLOCK,
  487. class: 0,
  488. subclass: 0,
  489. prog_if: 0,
  490. revision: 0,
  491. header_type: bus::HeaderType::Standard,
  492. }),
  493. None
  494. );
  495. // Invalid device ID.
  496. assert_eq!(
  497. virtio_device_type(&DeviceFunctionInfo {
  498. vendor_id: VIRTIO_VENDOR_ID,
  499. device_id: 0x1040,
  500. class: 0,
  501. subclass: 0,
  502. prog_if: 0,
  503. revision: 0,
  504. header_type: bus::HeaderType::Standard,
  505. }),
  506. None
  507. );
  508. }
  509. }