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