12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511 |
- #![allow(dead_code)]
- use super::device::pci_device_manager;
- use super::pci_irq::{IrqType, PciIrqError};
- use super::raw_device::PciGeneralDevice;
- use super::root::{pci_root_0, PciRoot};
- use crate::arch::{PciArch, TraitPciArch};
- use crate::driver::pci::subsys::pci_bus_subsys_init;
- use crate::exception::IrqNumber;
- use crate::libs::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
- use crate::mm::mmio_buddy::{mmio_pool, MMIOSpaceGuard};
- use crate::mm::VirtAddr;
- use alloc::string::String;
- use alloc::sync::Arc;
- use alloc::vec::Vec;
- use alloc::{boxed::Box, collections::LinkedList};
- use bitflags::bitflags;
- use log::{debug, error, info, warn};
- use core::{
- convert::TryFrom,
- fmt::{self, Debug, Display, Formatter},
- };
- lazy_static! {
- pub static ref PCI_DEVICE_LINKEDLIST: PciDeviceLinkedList = PciDeviceLinkedList::new();
- }
- #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
- #[repr(transparent)]
- pub struct PciAddr(usize);
- impl PciAddr {
- #[inline(always)]
- pub const fn new(address: usize) -> Self {
- Self(address)
- }
-
- #[inline(always)]
- pub fn data(&self) -> usize {
- self.0
- }
-
- #[inline(always)]
- pub fn add(self, offset: usize) -> Self {
- Self(self.0 + offset)
- }
-
- #[inline(always)]
- pub fn check_aligned(&self, align: usize) -> bool {
- return self.0 & (align - 1) == 0;
- }
- }
- impl Debug for PciAddr {
- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
- write!(f, "PciAddr({:#x})", self.0)
- }
- }
- pub struct PciDeviceLinkedList {
- list: RwLock<LinkedList<Box<dyn PciDeviceStructure>>>,
- }
- impl PciDeviceLinkedList {
-
- fn new() -> Self {
- PciDeviceLinkedList {
- list: RwLock::new(LinkedList::new()),
- }
- }
-
-
- pub fn read(&self) -> RwLockReadGuard<LinkedList<Box<dyn PciDeviceStructure>>> {
- self.list.read()
- }
-
-
- pub fn write(&self) -> RwLockWriteGuard<LinkedList<Box<dyn PciDeviceStructure>>> {
- self.list.write()
- }
-
-
- pub fn num(&self) -> usize {
- let list = self.list.read();
- list.len()
- }
-
- pub fn add(&self, device: Box<dyn PciDeviceStructure>) {
- let mut list = self.list.write();
- list.push_back(device);
- }
- }
- pub fn get_pci_device_structures_mut_by_vendor_id<'a>(
- list: &'a mut RwLockWriteGuard<'_, LinkedList<Box<dyn PciDeviceStructure>>>,
- vendor_id: u16,
- ) -> Vec<&'a mut Box<(dyn PciDeviceStructure)>> {
- let mut result = Vec::new();
- for box_pci_device_structure in list.iter_mut() {
- let common_header = (*box_pci_device_structure).common_header();
- if common_header.vendor_id == vendor_id {
- result.push(box_pci_device_structure);
- }
- }
- result
- }
- pub fn get_pci_device_structure_mut<'a>(
- list: &'a mut RwLockWriteGuard<'_, LinkedList<Box<dyn PciDeviceStructure>>>,
- class_code: u8,
- subclass: u8,
- ) -> Vec<&'a mut Box<(dyn PciDeviceStructure)>> {
- let mut result = Vec::new();
- for box_pci_device_structure in list.iter_mut() {
- let common_header = (*box_pci_device_structure).common_header();
- if (common_header.class_code == class_code) && (common_header.subclass == subclass) {
- result.push(box_pci_device_structure);
- }
- }
- result
- }
- #[allow(clippy::borrowed_box)]
- pub fn get_pci_device_structure<'a>(
- list: &'a mut RwLockReadGuard<'_, LinkedList<Box<dyn PciDeviceStructure>>>,
- class_code: u8,
- subclass: u8,
- ) -> Vec<&'a Box<(dyn PciDeviceStructure)>> {
- let mut result = Vec::new();
- for box_pci_device_structure in list.iter() {
- let common_header = (*box_pci_device_structure).common_header();
- if (common_header.class_code == class_code) && (common_header.subclass == subclass) {
- result.push(box_pci_device_structure);
- }
- }
- result
- }
- const BAR0_OFFSET: u8 = 0x10;
- const STATUS_COMMAND_OFFSET: u8 = 0x04;
- pub const PCI_CAP_ID_VNDR: u8 = 0x09;
- pub const PCI_CAP_ID_MSI: u8 = 0x05;
- pub const PCI_CAP_ID_MSIX: u8 = 0x11;
- pub const PORT_PCI_CONFIG_ADDRESS: u16 = 0xcf8;
- pub const PORT_PCI_CONFIG_DATA: u16 = 0xcfc;
- pub type SegmentGroupNumber = u16;
- bitflags! {
-
- pub struct Status: u16 {
-
-
- const INTERRUPT_STATUS = 1 << 3;
-
- const CAPABILITIES_LIST = 1 << 4;
-
- const MHZ_66_CAPABLE = 1 << 5;
-
-
- const FAST_BACK_TO_BACK_CAPABLE = 1 << 7;
-
- const MASTER_DATA_PARITY_ERROR = 1 << 8;
-
-
- const SIGNALED_TARGET_ABORT = 1 << 11;
-
- const RECEIVED_TARGET_ABORT = 1 << 12;
-
- const RECEIVED_MASTER_ABORT = 1 << 13;
-
- const SIGNALED_SYSTEM_ERROR = 1 << 14;
-
- const DETECTED_PARITY_ERROR = 1 << 15;
- }
- }
- bitflags! {
-
- pub struct Command: u16 {
-
- const IO_SPACE = 1 << 0;
-
- const MEMORY_SPACE = 1 << 1;
-
- const BUS_MASTER = 1 << 2;
-
- const SPECIAL_CYCLES = 1 << 3;
-
- const MEMORY_WRITE_AND_INVALIDATE_ENABLE = 1 << 4;
-
- const VGA_PALETTE_SNOOP = 1 << 5;
-
- const PARITY_ERROR_RESPONSE = 1 << 6;
-
-
- const SERR_ENABLE = 1 << 8;
-
- const FAST_BACK_TO_BACK_ENABLE = 1 << 9;
-
- const INTERRUPT_DISABLE = 1 << 10;
- }
- }
- #[derive(Copy, Clone, Debug, Eq, PartialEq)]
- pub enum HeaderType {
-
- Standard,
-
- PciPciBridge,
-
- PciCardbusBridge,
-
- Unrecognised(u8),
- }
- impl From<u8> for HeaderType {
- fn from(value: u8) -> Self {
- match value {
- 0x00 => Self::Standard,
- 0x01 => Self::PciPciBridge,
- 0x02 => Self::PciCardbusBridge,
- _ => Self::Unrecognised(value),
- }
- }
- }
- #[derive(Copy, Clone, Debug, Eq, PartialEq)]
- pub enum PciError {
-
- InvalidBarType,
- CreateMmioError,
- InvalidBusDeviceFunction,
- SegmentNotFound,
- McfgTableNotFound,
- GetWrongHeader,
- UnrecognisedHeaderType,
- PciDeviceStructureTransformError,
- PciIrqError(PciIrqError),
- }
- impl Display for PciError {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- match self {
- Self::InvalidBarType => write!(f, "Invalid PCI BAR type."),
- Self::CreateMmioError => write!(f, "Error occurred while creating mmio."),
- Self::InvalidBusDeviceFunction => write!(f, "Found invalid BusDeviceFunction."),
- Self::SegmentNotFound => write!(f, "Target segment not found"),
- Self::McfgTableNotFound => write!(f, "ACPI MCFG Table not found"),
- Self::GetWrongHeader => write!(f, "GetWrongHeader with vendor id 0xffff"),
- Self::UnrecognisedHeaderType => write!(f, "Found device with unrecognised header type"),
- Self::PciDeviceStructureTransformError => {
- write!(f, "Found None When transform Pci device structure")
- }
- Self::PciIrqError(err) => write!(f, "Error occurred while setting irq :{:?}.", err),
- }
- }
- }
- pub trait PciDeviceStructure: Send + Sync {
-
-
- fn header_type(&self) -> HeaderType;
-
- #[inline(always)]
- fn as_standard_device(&self) -> Option<&PciDeviceStructureGeneralDevice> {
- None
- }
-
- #[inline(always)]
- fn as_pci_to_pci_bridge_device(&self) -> Option<&PciDeviceStructurePciToPciBridge> {
- None
- }
-
- #[inline(always)]
- fn as_pci_to_carbus_bridge_device(&self) -> Option<&PciDeviceStructurePciToCardbusBridge> {
- None
- }
-
-
- fn common_header(&self) -> &PciDeviceStructureHeader;
-
- #[inline(always)]
- fn as_standard_device_mut(&mut self) -> Option<&mut PciDeviceStructureGeneralDevice> {
- None
- }
-
- #[inline(always)]
- fn as_pci_to_pci_bridge_device_mut(&mut self) -> Option<&mut PciDeviceStructurePciToPciBridge> {
- None
- }
-
- #[inline(always)]
- fn as_pci_to_carbus_bridge_device_mut(
- &mut self,
- ) -> Option<&mut PciDeviceStructurePciToCardbusBridge> {
- None
- }
-
- fn capabilities(&self) -> Option<CapabilityIterator> {
- None
- }
-
- fn status_command(&self) -> (Status, Command) {
- let common_header = self.common_header();
- let status = Status::from_bits_truncate(common_header.status);
- let command = Command::from_bits_truncate(common_header.command);
- (status, command)
- }
-
- fn set_command(&mut self, command: Command) {
- let common_header = self.common_header_mut();
- let command = command.bits();
- common_header.command = command;
- pci_root_0().write_config(
- common_header.bus_device_function,
- STATUS_COMMAND_OFFSET.into(),
- command as u32,
- );
- }
-
-
- fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader;
-
-
- #[inline(always)]
- fn bar_ioremap(&mut self) -> Option<Result<u8, PciError>> {
- None
- }
-
-
- #[inline(always)]
- fn bar(&mut self) -> Option<&PciStandardDeviceBar> {
- None
- }
-
- fn enable_master(&mut self) {
- self.set_command(Command::IO_SPACE | Command::MEMORY_SPACE | Command::BUS_MASTER);
- }
-
- fn msix_capability_offset(&self) -> Option<u8> {
- for capability in self.capabilities()? {
- if capability.id == PCI_CAP_ID_MSIX {
- return Some(capability.offset);
- }
- }
- None
- }
-
- fn msi_capability_offset(&self) -> Option<u8> {
- for capability in self.capabilities()? {
- if capability.id == PCI_CAP_ID_MSI {
- return Some(capability.offset);
- }
- }
- None
- }
-
- fn irq_type_mut(&mut self) -> Option<&mut IrqType>;
-
- fn irq_vector_mut(&mut self) -> Option<&mut Vec<IrqNumber>>;
- }
- #[derive(Clone, Debug)]
- pub struct PciDeviceStructureHeader {
-
- pub bus_device_function: BusDeviceFunction,
- pub vendor_id: u16,
- pub device_id: u16,
- pub command: u16,
- pub status: u16,
- pub revision_id: u8,
- pub prog_if: u8,
- pub subclass: u8,
- pub class_code: u8,
- pub cache_line_size: u8,
- pub latency_timer: u8,
- pub header_type: u8,
- pub bist: u8,
-
-
-
-
- }
- #[derive(Clone, Debug)]
- pub struct PciDeviceStructureGeneralDevice {
- pub common_header: PciDeviceStructureHeader,
-
- pub irq_type: IrqType,
-
- pub irq_vector: Vec<IrqNumber>,
- pub standard_device_bar: PciStandardDeviceBar,
- pub cardbus_cis_pointer: u32,
- pub subsystem_vendor_id: u16,
- pub subsystem_id: u16,
- pub expansion_rom_base_address: u32,
- pub capabilities_pointer: u8,
- pub reserved0: u8,
- pub reserved1: u16,
- pub reserved2: u32,
- pub interrupt_line: u8,
- pub interrupt_pin: u8,
- pub min_grant: u8,
- pub max_latency: u8,
- }
- impl PciDeviceStructure for PciDeviceStructureGeneralDevice {
- #[inline(always)]
- fn header_type(&self) -> HeaderType {
- HeaderType::Standard
- }
- #[inline(always)]
- fn as_standard_device(&self) -> Option<&PciDeviceStructureGeneralDevice> {
- Some(self)
- }
- #[inline(always)]
- fn as_standard_device_mut(&mut self) -> Option<&mut PciDeviceStructureGeneralDevice> {
- Some(self)
- }
- #[inline(always)]
- fn common_header(&self) -> &PciDeviceStructureHeader {
- &self.common_header
- }
- #[inline(always)]
- fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader {
- &mut self.common_header
- }
- fn capabilities(&self) -> Option<CapabilityIterator> {
- Some(CapabilityIterator {
- bus_device_function: self.common_header.bus_device_function,
- next_capability_offset: Some(self.capabilities_pointer),
- })
- }
- fn bar_ioremap(&mut self) -> Option<Result<u8, PciError>> {
- let common_header = &self.common_header;
- match pci_bar_init(common_header.bus_device_function) {
- Ok(bar) => {
- self.standard_device_bar = bar;
- Some(Ok(0))
- }
- Err(e) => Some(Err(e)),
- }
- }
- fn bar(&mut self) -> Option<&PciStandardDeviceBar> {
- Some(&self.standard_device_bar)
- }
- #[inline(always)]
- fn irq_type_mut(&mut self) -> Option<&mut IrqType> {
- Some(&mut self.irq_type)
- }
- #[inline(always)]
- fn irq_vector_mut(&mut self) -> Option<&mut Vec<IrqNumber>> {
- Some(&mut self.irq_vector)
- }
- }
- #[derive(Clone, Debug)]
- pub struct PciDeviceStructurePciToPciBridge {
- pub common_header: PciDeviceStructureHeader,
-
- pub irq_type: IrqType,
-
- pub irq_vector: Vec<IrqNumber>,
- pub bar0: u32,
- pub bar1: u32,
- pub primary_bus_number: u8,
- pub secondary_bus_number: u8,
- pub subordinate_bus_number: u8,
- pub secondary_latency_timer: u8,
- pub io_base: u8,
- pub io_limit: u8,
- pub secondary_status: u16,
- pub memory_base: u16,
- pub memory_limit: u16,
- pub prefetchable_memory_base: u16,
- pub prefetchable_memory_limit: u16,
- pub prefetchable_base_upper_32_bits: u32,
- pub prefetchable_limit_upper_32_bits: u32,
- pub io_base_upper_16_bits: u16,
- pub io_limit_upper_16_bits: u16,
- pub capability_pointer: u8,
- pub reserved0: u8,
- pub reserved1: u16,
- pub expansion_rom_base_address: u32,
- pub interrupt_line: u8,
- pub interrupt_pin: u8,
- pub bridge_control: u16,
- }
- impl PciDeviceStructure for PciDeviceStructurePciToPciBridge {
- #[inline(always)]
- fn header_type(&self) -> HeaderType {
- HeaderType::PciPciBridge
- }
- #[inline(always)]
- fn as_pci_to_pci_bridge_device(&self) -> Option<&PciDeviceStructurePciToPciBridge> {
- Some(self)
- }
- #[inline(always)]
- fn as_pci_to_pci_bridge_device_mut(&mut self) -> Option<&mut PciDeviceStructurePciToPciBridge> {
- Some(self)
- }
- #[inline(always)]
- fn common_header(&self) -> &PciDeviceStructureHeader {
- &self.common_header
- }
- #[inline(always)]
- fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader {
- &mut self.common_header
- }
- #[inline(always)]
- fn irq_type_mut(&mut self) -> Option<&mut IrqType> {
- Some(&mut self.irq_type)
- }
- #[inline(always)]
- fn irq_vector_mut(&mut self) -> Option<&mut Vec<IrqNumber>> {
- Some(&mut self.irq_vector)
- }
- }
- #[derive(Clone, Debug)]
- pub struct PciDeviceStructurePciToCardbusBridge {
- pub common_header: PciDeviceStructureHeader,
- pub cardbus_socket_ex_ca_base_address: u32,
- pub offset_of_capabilities_list: u8,
- pub reserved: u8,
- pub secondary_status: u16,
- pub pci_bus_number: u8,
- pub card_bus_bus_number: u8,
- pub subordinate_bus_number: u8,
- pub card_bus_latency_timer: u8,
- pub memory_base_address0: u32,
- pub memory_limit0: u32,
- pub memory_base_address1: u32,
- pub memory_limit1: u32,
- pub io_base_address0: u32,
- pub io_limit0: u32,
- pub io_base_address1: u32,
- pub io_limit1: u32,
- pub interrupt_line: u8,
- pub interrupt_pin: u8,
- pub bridge_control: u16,
- pub subsystem_device_id: u16,
- pub subsystem_vendor_id: u16,
- pub pc_card_legacy_mode_base_address_16_bit: u32,
- }
- impl PciDeviceStructure for PciDeviceStructurePciToCardbusBridge {
- #[inline(always)]
- fn header_type(&self) -> HeaderType {
- HeaderType::PciCardbusBridge
- }
- #[inline(always)]
- fn as_pci_to_carbus_bridge_device(&self) -> Option<&PciDeviceStructurePciToCardbusBridge> {
- Some(self)
- }
- #[inline(always)]
- fn as_pci_to_carbus_bridge_device_mut(
- &mut self,
- ) -> Option<&mut PciDeviceStructurePciToCardbusBridge> {
- Some(self)
- }
- #[inline(always)]
- fn common_header(&self) -> &PciDeviceStructureHeader {
- &self.common_header
- }
- #[inline(always)]
- fn common_header_mut(&mut self) -> &mut PciDeviceStructureHeader {
- &mut self.common_header
- }
- #[inline(always)]
- fn irq_type_mut(&mut self) -> Option<&mut IrqType> {
- None
- }
- #[inline(always)]
- fn irq_vector_mut(&mut self) -> Option<&mut Vec<IrqNumber>> {
- None
- }
- }
- #[derive(Copy, Clone, Debug, Eq, PartialEq)]
- pub enum PciCam {
-
-
-
- MmioCam,
-
-
-
- Ecam,
- }
- impl PciCam {
-
- pub const fn size(self) -> u32 {
- match self {
- Self::MmioCam => 0x1000000,
- Self::Ecam => 0x10000000,
- }
- }
- }
- pub fn capabilities_offset(bus_device_function: BusDeviceFunction) -> Option<u8> {
- let result = pci_root_0().read_config(bus_device_function, STATUS_COMMAND_OFFSET.into());
- let status: Status = Status::from_bits_truncate((result >> 16) as u16);
- if status.contains(Status::CAPABILITIES_LIST) {
- let cap_pointer = pci_root_0().read_config(bus_device_function, 0x34) as u8 & 0xFC;
- Some(cap_pointer)
- } else {
- None
- }
- }
- fn pci_read_header(
- bus_device_function: BusDeviceFunction,
- add_to_list: bool,
- ) -> Result<Box<dyn PciDeviceStructure>, PciError> {
-
- let result = pci_root_0().read_config(bus_device_function, 0x00);
- let vendor_id = result as u16;
- let device_id = (result >> 16) as u16;
- let result = pci_root_0().read_config(bus_device_function, 0x04);
- let command = result as u16;
- let status = (result >> 16) as u16;
- let result = pci_root_0().read_config(bus_device_function, 0x08);
- let revision_id = result as u8;
- let prog_if = (result >> 8) as u8;
- let subclass = (result >> 16) as u8;
- let class_code = (result >> 24) as u8;
- let result = pci_root_0().read_config(bus_device_function, 0x0c);
- let cache_line_size = result as u8;
- let latency_timer = (result >> 8) as u8;
- let header_type = (result >> 16) as u8;
- let bist = (result >> 24) as u8;
- if vendor_id == 0xffff {
- return Err(PciError::GetWrongHeader);
- }
- let header = PciDeviceStructureHeader {
- bus_device_function,
- vendor_id,
- device_id,
- command,
- status,
- revision_id,
- prog_if,
- subclass,
- class_code,
- cache_line_size,
- latency_timer,
- header_type,
- bist,
- };
- match HeaderType::from(header_type & 0x7f) {
- HeaderType::Standard => {
- let general_device: PciDeviceStructureGeneralDevice =
- pci_read_general_device_header(header, &bus_device_function);
- let box_general_device = Box::new(general_device.clone());
- let box_general_device_clone = box_general_device.clone();
- if add_to_list {
- PCI_DEVICE_LINKEDLIST.add(box_general_device);
-
-
-
-
- let raw = PciGeneralDevice::from(&general_device);
- let _ = pci_device_manager().device_add(Arc::new(raw));
- }
- Ok(box_general_device_clone)
- }
- HeaderType::PciPciBridge => {
- let pci_to_pci_bridge = pci_read_pci_to_pci_bridge_header(header, &bus_device_function);
- let box_pci_to_pci_bridge = Box::new(pci_to_pci_bridge);
- let box_pci_to_pci_bridge_clone = box_pci_to_pci_bridge.clone();
- if add_to_list {
- PCI_DEVICE_LINKEDLIST.add(box_pci_to_pci_bridge);
- }
- Ok(box_pci_to_pci_bridge_clone)
- }
- HeaderType::PciCardbusBridge => {
- let pci_cardbus_bridge =
- pci_read_pci_to_cardbus_bridge_header(header, &bus_device_function);
- let box_pci_cardbus_bridge = Box::new(pci_cardbus_bridge);
- let box_pci_cardbus_bridge_clone = box_pci_cardbus_bridge.clone();
- if add_to_list {
- PCI_DEVICE_LINKEDLIST.add(box_pci_cardbus_bridge);
- }
- Ok(box_pci_cardbus_bridge_clone)
- }
- HeaderType::Unrecognised(_) => Err(PciError::UnrecognisedHeaderType),
- }
- }
- fn pci_read_general_device_header(
- common_header: PciDeviceStructureHeader,
- bus_device_function: &BusDeviceFunction,
- ) -> PciDeviceStructureGeneralDevice {
- let standard_device_bar = PciStandardDeviceBar::default();
- let cardbus_cis_pointer = pci_root_0().read_config(*bus_device_function, 0x28);
- let result = pci_root_0().read_config(*bus_device_function, 0x2c);
- let subsystem_vendor_id = result as u16;
- let subsystem_id = (result >> 16) as u16;
- let expansion_rom_base_address = pci_root_0().read_config(*bus_device_function, 0x30);
- let result = pci_root_0().read_config(*bus_device_function, 0x34);
- let capabilities_pointer = result as u8;
- let reserved0 = (result >> 8) as u8;
- let reserved1 = (result >> 16) as u16;
- let reserved2 = pci_root_0().read_config(*bus_device_function, 0x38);
- let result = pci_root_0().read_config(*bus_device_function, 0x3c);
- let interrupt_line = result as u8;
- let interrupt_pin = (result >> 8) as u8;
- let min_grant = (result >> 16) as u8;
- let max_latency = (result >> 24) as u8;
- PciDeviceStructureGeneralDevice {
- common_header,
- irq_type: IrqType::Unused,
- irq_vector: Vec::new(),
- standard_device_bar,
- cardbus_cis_pointer,
- subsystem_vendor_id,
- subsystem_id,
- expansion_rom_base_address,
- capabilities_pointer,
- reserved0,
- reserved1,
- reserved2,
- interrupt_line,
- interrupt_pin,
- min_grant,
- max_latency,
- }
- }
- fn pci_read_pci_to_pci_bridge_header(
- common_header: PciDeviceStructureHeader,
- bus_device_function: &BusDeviceFunction,
- ) -> PciDeviceStructurePciToPciBridge {
- let bar0 = pci_root_0().read_config(*bus_device_function, 0x10);
- let bar1 = pci_root_0().read_config(*bus_device_function, 0x14);
- let result = pci_root_0().read_config(*bus_device_function, 0x18);
- let primary_bus_number = result as u8;
- let secondary_bus_number = (result >> 8) as u8;
- let subordinate_bus_number = (result >> 16) as u8;
- let secondary_latency_timer = (result >> 24) as u8;
- let result = pci_root_0().read_config(*bus_device_function, 0x1c);
- let io_base = result as u8;
- let io_limit = (result >> 8) as u8;
- let secondary_status = (result >> 16) as u16;
- let result = pci_root_0().read_config(*bus_device_function, 0x20);
- let memory_base = result as u16;
- let memory_limit = (result >> 16) as u16;
- let result = pci_root_0().read_config(*bus_device_function, 0x24);
- let prefetchable_memory_base = result as u16;
- let prefetchable_memory_limit = (result >> 16) as u16;
- let prefetchable_base_upper_32_bits = pci_root_0().read_config(*bus_device_function, 0x28);
- let prefetchable_limit_upper_32_bits = pci_root_0().read_config(*bus_device_function, 0x2c);
- let result = pci_root_0().read_config(*bus_device_function, 0x30);
- let io_base_upper_16_bits = result as u16;
- let io_limit_upper_16_bits = (result >> 16) as u16;
- let result = pci_root_0().read_config(*bus_device_function, 0x34);
- let capability_pointer = result as u8;
- let reserved0 = (result >> 8) as u8;
- let reserved1 = (result >> 16) as u16;
- let expansion_rom_base_address = pci_root_0().read_config(*bus_device_function, 0x38);
- let result = pci_root_0().read_config(*bus_device_function, 0x3c);
- let interrupt_line = result as u8;
- let interrupt_pin = (result >> 8) as u8;
- let bridge_control = (result >> 16) as u16;
- PciDeviceStructurePciToPciBridge {
- common_header,
- irq_type: IrqType::Unused,
- irq_vector: Vec::new(),
- bar0,
- bar1,
- primary_bus_number,
- secondary_bus_number,
- subordinate_bus_number,
- secondary_latency_timer,
- io_base,
- io_limit,
- secondary_status,
- memory_base,
- memory_limit,
- prefetchable_memory_base,
- prefetchable_memory_limit,
- prefetchable_base_upper_32_bits,
- prefetchable_limit_upper_32_bits,
- io_base_upper_16_bits,
- io_limit_upper_16_bits,
- capability_pointer,
- reserved0,
- reserved1,
- expansion_rom_base_address,
- interrupt_line,
- interrupt_pin,
- bridge_control,
- }
- }
- fn pci_read_pci_to_cardbus_bridge_header(
- common_header: PciDeviceStructureHeader,
- busdevicefunction: &BusDeviceFunction,
- ) -> PciDeviceStructurePciToCardbusBridge {
- let cardbus_socket_ex_ca_base_address = pci_root_0().read_config(*busdevicefunction, 0x10);
- let result = pci_root_0().read_config(*busdevicefunction, 0x14);
- let offset_of_capabilities_list = result as u8;
- let reserved = (result >> 8) as u8;
- let secondary_status = (result >> 16) as u16;
- let result = pci_root_0().read_config(*busdevicefunction, 0x18);
- let pci_bus_number = result as u8;
- let card_bus_bus_number = (result >> 8) as u8;
- let subordinate_bus_number = (result >> 16) as u8;
- let card_bus_latency_timer = (result >> 24) as u8;
- let memory_base_address0 = pci_root_0().read_config(*busdevicefunction, 0x1c);
- let memory_limit0 = pci_root_0().read_config(*busdevicefunction, 0x20);
- let memory_base_address1 = pci_root_0().read_config(*busdevicefunction, 0x24);
- let memory_limit1 = pci_root_0().read_config(*busdevicefunction, 0x28);
- let io_base_address0 = pci_root_0().read_config(*busdevicefunction, 0x2c);
- let io_limit0 = pci_root_0().read_config(*busdevicefunction, 0x30);
- let io_base_address1 = pci_root_0().read_config(*busdevicefunction, 0x34);
- let io_limit1 = pci_root_0().read_config(*busdevicefunction, 0x38);
- let result = pci_root_0().read_config(*busdevicefunction, 0x3c);
- let interrupt_line = result as u8;
- let interrupt_pin = (result >> 8) as u8;
- let bridge_control = (result >> 16) as u16;
- let result = pci_root_0().read_config(*busdevicefunction, 0x40);
- let subsystem_device_id = result as u16;
- let subsystem_vendor_id = (result >> 16) as u16;
- let pc_card_legacy_mode_base_address_16_bit =
- pci_root_0().read_config(*busdevicefunction, 0x44);
- PciDeviceStructurePciToCardbusBridge {
- common_header,
- cardbus_socket_ex_ca_base_address,
- offset_of_capabilities_list,
- reserved,
- secondary_status,
- pci_bus_number,
- card_bus_bus_number,
- subordinate_bus_number,
- card_bus_latency_timer,
- memory_base_address0,
- memory_limit0,
- memory_base_address1,
- memory_limit1,
- io_base_address0,
- io_limit0,
- io_base_address1,
- io_limit1,
- interrupt_line,
- interrupt_pin,
- bridge_control,
- subsystem_device_id,
- subsystem_vendor_id,
- pc_card_legacy_mode_base_address_16_bit,
- }
- }
- fn pci_check_all_buses() -> Result<u8, PciError> {
- info!("Checking all devices in PCI bus...");
- let busdevicefunction = BusDeviceFunction {
- bus: 0,
- device: 0,
- function: 0,
- };
- let header = pci_read_header(busdevicefunction, false)?;
- let common_header = header.common_header();
- pci_check_bus(0)?;
- if common_header.header_type & 0x80 != 0 {
- for function in 1..8 {
- pci_check_bus(function)?;
- }
- }
- Ok(0)
- }
- fn pci_check_function(busdevicefunction: BusDeviceFunction) -> Result<u8, PciError> {
-
- let header = match pci_read_header(busdevicefunction, true) {
- Ok(header) => header,
- Err(PciError::GetWrongHeader) => {
- return Ok(255);
- }
- Err(e) => {
- return Err(e);
- }
- };
- let common_header = header.common_header();
- if (common_header.class_code == 0x06)
- && (common_header.subclass == 0x04 || common_header.subclass == 0x09)
- {
- let pci_to_pci_bridge = header
- .as_pci_to_pci_bridge_device()
- .ok_or(PciError::PciDeviceStructureTransformError)?;
- let secondary_bus = pci_to_pci_bridge.secondary_bus_number;
- pci_check_bus(secondary_bus)?;
- }
- Ok(0)
- }
- fn pci_check_device(bus: u8, device: u8) -> Result<u8, PciError> {
-
- let busdevicefunction = BusDeviceFunction {
- bus,
- device,
- function: 0,
- };
- let header = match pci_read_header(busdevicefunction, false) {
- Ok(header) => header,
- Err(PciError::GetWrongHeader) => {
-
- return Ok(255);
- }
- Err(e) => {
- return Err(e);
- }
- };
- pci_check_function(busdevicefunction)?;
- let common_header = header.common_header();
- if common_header.header_type & 0x80 != 0 {
- debug!(
- "Detected multi func device in bus{},device{}",
- busdevicefunction.bus, busdevicefunction.device
- );
-
- for function in 1..8 {
- let busdevicefunction = BusDeviceFunction {
- bus,
- device,
- function,
- };
- pci_check_function(busdevicefunction)?;
- }
- }
- Ok(0)
- }
- fn pci_check_bus(bus: u8) -> Result<u8, PciError> {
-
- for device in 0..32 {
- pci_check_device(bus, device)?;
- }
- Ok(0)
- }
- #[inline(never)]
- pub fn pci_init() {
- info!("Initializing PCI bus...");
- pci_bus_subsys_init().expect("Failed to init pci bus subsystem");
- if let Err(e) = pci_check_all_buses() {
- error!("pci init failed when checking bus because of error: {}", e);
- return;
- }
- info!(
- "Total pci device and function num = {}",
- PCI_DEVICE_LINKEDLIST.num()
- );
- let list = PCI_DEVICE_LINKEDLIST.read();
- for box_pci_device in list.iter() {
- let common_header = box_pci_device.common_header();
- match box_pci_device.header_type() {
- HeaderType::Standard if common_header.status & 0x10 != 0 => {
- info!("Found pci standard device with class code ={} subclass={} status={:#x} cap_pointer={:#x} vendor={:#x}, device id={:#x},bdf={}", common_header.class_code, common_header.subclass, common_header.status, box_pci_device.as_standard_device().unwrap().capabilities_pointer,common_header.vendor_id, common_header.device_id,common_header.bus_device_function);
- }
- HeaderType::Standard => {
- info!(
- "Found pci standard device with class code ={} subclass={} status={:#x} ",
- common_header.class_code, common_header.subclass, common_header.status
- );
- }
- HeaderType::PciPciBridge if common_header.status & 0x10 != 0 => {
- info!("Found pci-to-pci bridge device with class code ={} subclass={} status={:#x} cap_pointer={:#x}", common_header.class_code, common_header.subclass, common_header.status, box_pci_device.as_pci_to_pci_bridge_device().unwrap().capability_pointer);
- }
- HeaderType::PciPciBridge => {
- info!(
- "Found pci-to-pci bridge device with class code ={} subclass={} status={:#x} ",
- common_header.class_code, common_header.subclass, common_header.status
- );
- }
- HeaderType::PciCardbusBridge => {
- info!(
- "Found pcicardbus bridge device with class code ={} subclass={} status={:#x} ",
- common_header.class_code, common_header.subclass, common_header.status
- );
- }
- HeaderType::Unrecognised(_) => {}
- }
- }
- info!("PCI bus initialized.");
- }
- #[derive(Copy, Clone, Debug, Eq, PartialEq)]
- pub struct BusDeviceFunction {
-
- pub bus: u8,
-
- pub device: u8,
-
- pub function: u8,
- }
- impl BusDeviceFunction {
-
-
-
-
- #[allow(dead_code)]
- pub fn valid(&self) -> bool {
- self.device < 32 && self.function < 8
- }
- }
- impl From<BusDeviceFunction> for String {
-
-
- fn from(value: BusDeviceFunction) -> Self {
-
-
- format!(
- "0000:{:02x}:{:02x}.{}",
- value.bus, value.device, value.function
- )
- }
- }
- impl Display for BusDeviceFunction {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- write!(
- f,
- "bus {} device {} function{}",
- self.bus, self.device, self.function
- )
- }
- }
- #[derive(Copy, Clone, Debug, Eq, PartialEq)]
- pub enum MemoryBarType {
-
- Width32,
-
- Below1MiB,
-
- Width64,
- }
- impl From<MemoryBarType> for u8 {
- fn from(bar_type: MemoryBarType) -> Self {
- match bar_type {
- MemoryBarType::Width32 => 0,
- MemoryBarType::Below1MiB => 1,
- MemoryBarType::Width64 => 2,
- }
- }
- }
- impl TryFrom<u8> for MemoryBarType {
- type Error = PciError;
- fn try_from(value: u8) -> Result<Self, Self::Error> {
- match value {
- 0 => Ok(Self::Width32),
- 1 => Ok(Self::Below1MiB),
- 2 => Ok(Self::Width64),
- _ => Err(PciError::InvalidBarType),
- }
- }
- }
- #[derive(Clone, Debug)]
- pub enum BarInfo {
-
- Memory {
-
- address_type: MemoryBarType,
-
-
- prefetchable: bool,
-
- address: u64,
-
- size: u32,
-
- mmio_guard: Arc<MMIOSpaceGuard>,
- },
-
- IO {
-
- address: u32,
-
- size: u32,
- },
- Unused,
- }
- impl BarInfo {
-
-
-
-
-
- pub fn memory_address_size(&self) -> Option<(u64, u32)> {
- if let Self::Memory { address, size, .. } = self {
- Some((*address, *size))
- } else {
- None
- }
- }
-
-
-
- pub fn virtual_address(&self) -> Option<VirtAddr> {
- if let Self::Memory { mmio_guard, .. } = self {
- Some(mmio_guard.vaddr())
- } else {
- None
- }
- }
- }
- impl Display for BarInfo {
- fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
- match self {
- Self::Memory {
- address_type,
- prefetchable,
- address,
- size,
- mmio_guard,
- } => write!(
- f,
- "Memory space at {:#010x}, size {}, type {:?}, prefetchable {}, mmio_guard: {:?}",
- address, size, address_type, prefetchable, mmio_guard
- ),
- Self::IO { address, size } => {
- write!(f, "I/O space at {:#010x}, size {}", address, size)
- }
- Self::Unused => {
- write!(f, "Unused bar")
- }
- }
- }
- }
- pub trait PciDeviceBar {}
- #[derive(Clone, Debug)]
- pub struct PciStandardDeviceBar {
- bar0: BarInfo,
- bar1: BarInfo,
- bar2: BarInfo,
- bar3: BarInfo,
- bar4: BarInfo,
- bar5: BarInfo,
- }
- impl PciStandardDeviceBar {
-
-
-
- pub fn get_bar(&self, bar_index: u8) -> Result<&BarInfo, PciError> {
- match bar_index {
- 0 => Ok(&self.bar0),
- 1 => Ok(&self.bar1),
- 2 => Ok(&self.bar2),
- 3 => Ok(&self.bar3),
- 4 => Ok(&self.bar4),
- 5 => Ok(&self.bar5),
- _ => Err(PciError::InvalidBarType),
- }
- }
- }
- impl Display for PciStandardDeviceBar {
- fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
- write!(
- f,
- "\r\nBar0:{}\r\nBar1:{}\r\nBar2:{}\r\nBar3:{}\r\nBar4:{}\r\nBar5:{}",
- self.bar0, self.bar1, self.bar2, self.bar3, self.bar4, self.bar5
- )
- }
- }
- impl Default for PciStandardDeviceBar {
- fn default() -> Self {
- PciStandardDeviceBar {
- bar0: BarInfo::Unused,
- bar1: BarInfo::Unused,
- bar2: BarInfo::Unused,
- bar3: BarInfo::Unused,
- bar4: BarInfo::Unused,
- bar5: BarInfo::Unused,
- }
- }
- }
- pub fn pci_bar_init(
- bus_device_function: BusDeviceFunction,
- ) -> Result<PciStandardDeviceBar, PciError> {
- let mut device_bar: PciStandardDeviceBar = PciStandardDeviceBar::default();
- let mut bar_index_ignore: u8 = 255;
- for bar_index in 0..6 {
- if bar_index == bar_index_ignore {
- continue;
- }
- let bar_info;
- let bar_orig =
- pci_root_0().read_config(bus_device_function, (BAR0_OFFSET + 4 * bar_index).into());
- pci_root_0().write_config(
- bus_device_function,
- (BAR0_OFFSET + 4 * bar_index).into(),
- 0xffffffff,
- );
- let size_mask =
- pci_root_0().read_config(bus_device_function, (BAR0_OFFSET + 4 * bar_index).into());
-
-
- let size = (!(size_mask & 0xfffffff0)).wrapping_add(1);
-
-
- pci_root_0().write_config(
- bus_device_function,
- (BAR0_OFFSET + 4 * bar_index).into(),
- bar_orig,
- );
- if size == 0 {
- continue;
- }
- if bar_orig & 0x00000001 == 0x00000001 {
-
- let address = bar_orig & 0xfffffffc;
- bar_info = BarInfo::IO { address, size };
- } else {
-
- let mut address = u64::from(bar_orig & 0xfffffff0);
- let prefetchable = bar_orig & 0x00000008 != 0;
- let address_type = MemoryBarType::try_from(((bar_orig & 0x00000006) >> 1) as u8)?;
- if address_type == MemoryBarType::Width64 {
- if bar_index >= 5 {
- return Err(PciError::InvalidBarType);
- }
- let address_top = pci_root_0().read_config(
- bus_device_function,
- (BAR0_OFFSET + 4 * (bar_index + 1)).into(),
- );
- address |= u64::from(address_top) << 32;
- bar_index_ignore = bar_index + 1;
- }
- let pci_address = PciAddr::new(address as usize);
- let paddr = PciArch::address_pci_to_physical(pci_address);
- let space_guard: Arc<MMIOSpaceGuard>;
- unsafe {
- let size_want = size as usize;
- let tmp = mmio_pool()
- .create_mmio(size_want)
- .map_err(|_| PciError::CreateMmioError)?;
- space_guard = Arc::new(tmp);
-
- assert!(
- space_guard.map_phys(paddr, size_want).is_ok(),
- "pci_bar_init: map_phys failed"
- );
- }
- bar_info = BarInfo::Memory {
- address_type,
- prefetchable,
- address,
- size,
- mmio_guard: space_guard,
- };
- }
- match bar_index {
- 0 => {
- device_bar.bar0 = bar_info;
- }
- 1 => {
- device_bar.bar1 = bar_info;
- }
- 2 => {
- device_bar.bar2 = bar_info;
- }
- 3 => {
- device_bar.bar3 = bar_info;
- }
- 4 => {
- device_bar.bar4 = bar_info;
- }
- 5 => {
- device_bar.bar5 = bar_info;
- }
- _ => {}
- }
- }
-
- return Ok(device_bar);
- }
- #[derive(Debug, Copy, Clone, Eq, PartialEq)]
- pub struct CapabilityInfo {
-
- pub offset: u8,
-
- pub id: u8,
-
- pub private_header: u16,
- }
- #[derive(Debug)]
- pub struct CapabilityIterator {
- pub bus_device_function: BusDeviceFunction,
- pub next_capability_offset: Option<u8>,
- }
- impl Iterator for CapabilityIterator {
- type Item = CapabilityInfo;
- fn next(&mut self) -> Option<Self::Item> {
- let offset = self.next_capability_offset?;
-
- let capability_header = pci_root_0().read_config(self.bus_device_function, offset.into());
- let id = capability_header as u8;
- let next_offset = (capability_header >> 8) as u8;
- let private_header = (capability_header >> 16) as u16;
- self.next_capability_offset = if next_offset == 0 {
- None
- } else if next_offset < 64 || next_offset & 0x3 != 0 {
- warn!("Invalid next capability offset {:#04x}", next_offset);
- None
- } else {
- Some(next_offset)
- };
- Some(CapabilityInfo {
- offset,
- id,
- private_header,
- })
- }
- }
- #[derive(Debug, Copy, Clone, Eq, PartialEq)]
- pub struct ExternalCapabilityInfo {
-
- pub offset: u16,
-
- pub id: u16,
-
- pub capability_version: u8,
- }
- #[derive(Debug)]
- pub struct ExternalCapabilityIterator<'a> {
- pub root: &'a PciRoot,
- pub bus_device_function: BusDeviceFunction,
- pub next_capability_offset: Option<u16>,
- }
- impl<'a> Iterator for ExternalCapabilityIterator<'a> {
- type Item = ExternalCapabilityInfo;
- fn next(&mut self) -> Option<Self::Item> {
- let offset = self.next_capability_offset?;
-
- let capability_header = self.root.read_config(self.bus_device_function, offset);
- let id = capability_header as u16;
- let next_offset = (capability_header >> 20) as u16;
- let capability_version = ((capability_header >> 16) & 0xf) as u8;
- self.next_capability_offset = if next_offset == 0 {
- None
- } else if next_offset < 0x100 || next_offset & 0x3 != 0 {
- warn!("Invalid next capability offset {:#04x}", next_offset);
- None
- } else {
- Some(next_offset)
- };
- Some(ExternalCapabilityInfo {
- offset,
- id,
- capability_version,
- })
- }
- }
|