transport_pci.rs 19 KB

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