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