Skip to main content

strat9_kernel/arch/x86_64/
pci.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! PCI Configuration Space Access
24//!
25//! Provides functions to scan the PCI bus and read/write configuration registers.
26//! Used to discover VirtIO and other PCI devices.
27//!
28//! Reference: PCI Local Bus Specification 3.0
29
30use super::io::{inl, outl};
31use crate::sync::SpinLock;
32use alloc::vec::Vec;
33use core::{
34    fmt,
35    sync::atomic::{AtomicBool, Ordering},
36};
37
38/// PCI Configuration Address Port
39const CONFIG_ADDRESS: u16 = 0xCF8;
40/// PCI Configuration Data Port
41const CONFIG_DATA: u16 = 0xCFC;
42
43/// Global lock for PCI configuration space I/O.
44///
45/// CONFIG_ADDRESS and CONFIG_DATA form a two-step transaction that must be
46/// atomic w.r.t. other CPUs. Every config read/write must hold this lock.
47static PCI_IO_LOCK: SpinLock<()> = SpinLock::new(());
48
49/// A mapped ECAM region covering a range of buses.
50struct EcamRegion {
51    start_bus: u8,
52    end_bus: u8,
53    base_virt: usize,
54}
55
56/// Cached ECAM MMIO regions for extended config space access (offsets >= 0x100).
57/// Populated during `scan_ecam_devices()` when an MCFG table is present.
58static ECAM_REGIONS: SpinLock<Vec<EcamRegion>> = SpinLock::new(Vec::new());
59
60// ---------------------------------------------------------------------------
61// ECAM (PCIe Enhanced Configuration Access Mechanism) helpers
62// ---------------------------------------------------------------------------
63
64/// Read a 32-bit register from an ECAM-mapped PCI config space.
65///
66/// `ecam_base` is the MMIO base address of the ECAM region.
67/// `bus`, `device`, `function` identify the device; `offset` is the register.
68#[inline]
69unsafe fn ecam_read32(ecam_base: usize, bus: u8, device: u8, function: u8, offset: u16) -> u32 {
70    let addr = ecam_base
71        + ((bus as usize) << 20)
72        + ((device as usize) << 15)
73        + ((function as usize) << 12)
74        + ((offset as usize) & !0x03);
75    core::ptr::read_volatile(addr as *const u32)
76}
77
78/// Write a 32-bit register to an ECAM-mapped PCI config space.
79#[inline]
80#[allow(dead_code)] // Retained ECAM register accessor.
81unsafe fn ecam_write32(ecam_base: usize, bus: u8, device: u8, function: u8, offset: u16, val: u32) {
82    let addr = ecam_base
83        + ((bus as usize) << 20)
84        + ((device as usize) << 15)
85        + ((function as usize) << 12)
86        + ((offset as usize) & !0x03);
87    core::ptr::write_volatile(addr as *mut u32, val);
88}
89
90/// Read a single byte from ECAM config space.
91#[inline]
92#[allow(dead_code)] // Retained ECAM byte accessor.
93unsafe fn ecam_read8(ecam_base: usize, bus: u8, device: u8, function: u8, offset: u16) -> u8 {
94    let dword = ecam_read32(ecam_base, bus, device, function, offset & !0x03);
95    ((dword >> ((offset & 0x3) * 8)) & 0xFF) as u8
96}
97
98// ---------------------------------------------------------------------------
99// Known device name lookup (for improved logging)
100// ---------------------------------------------------------------------------
101
102/// Known PCI device names for human-readable logging.
103fn device_name(vendor: u16, device: u16) -> Option<&'static str> {
104    match (vendor, device) {
105        // Intel Ethernet
106        (0x8086, 0x100E) => Some("Intel E1000 (QEMU)"),
107        (0x8086, 0x100F) => Some("Intel E1000 (QEMU)"),
108        (0x8086, 0x10D3) => Some("Intel E1000e (QEMU)"),
109        (0x8086, 0x153A) => Some("Intel I217-LM"),
110        (0x8086, 0x15F9) => Some("Intel I219-LM"),
111        (0x8086, 0x15FA) => Some("Intel I219-V"),
112        (0x8086, 0x15F2) => Some("Intel I225-LM"),
113        (0x8086, 0x15F3) => Some("Intel I225-V"),
114        (0x8086, 0x125B) => Some("Intel I226-LM"),
115        (0x8086, 0x125C) => Some("Intel I226-V"),
116        // VirtIO
117        (0x1AF4, 0x1000) => Some("VirtIO Net"),
118        (0x1AF4, 0x1001) => Some("VirtIO Block"),
119        (0x1AF4, 0x1003) => Some("VirtIO Console"),
120        (0x1AF4, 0x1005) => Some("VirtIO RNG"),
121        (0x1AF4, 0x1050) => Some("VirtIO GPU"),
122        (0x1AF4, 0x1052) => Some("VirtIO Input"),
123        // QEMU
124        (0x1234, 0x11E9) => Some("QEMU VGA"),
125        _ => None,
126    }
127}
128
129/// Human-readable PCI class name.
130///
131/// Public so the `lspci` shell command reports the same names the kernel
132/// decodes: it used to carry its own 20-arm table of the same class codes, in a
133/// different order and with different spellings.
134pub fn class_name(class: u8, subclass: u8) -> Option<&'static str> {
135    match (class, subclass) {
136        (0x00, 0x00) => Some("Legacy Device"),
137        (0x00, 0x01) => Some("VGA-Compatible Device"),
138        (0x01, 0x00) => Some("SCSI Controller"),
139        (0x01, 0x01) => Some("IDE Controller"),
140        (0x01, 0x06) => Some("SATA Controller"),
141        (0x01, 0x08) => Some("NVMe Controller"),
142        (0x02, 0x00) => Some("Ethernet Controller"),
143        (0x02, 0x80) => Some("Network Controller"),
144        (0x03, 0x00) => Some("VGA Controller"),
145        (0x03, 0x02) => Some("3D Controller"),
146        (0x04, 0x00) => Some("Multimedia Video"),
147        (0x04, 0x03) => Some("Audio Device"),
148        (0x06, 0x00) => Some("Host Bridge"),
149        (0x06, 0x01) => Some("ISA Bridge"),
150        (0x06, 0x04) => Some("PCI-to-PCI Bridge"),
151        (0x0C, 0x03) => Some("USB Controller"),
152        (0x08, 0x00) => Some("I20"),
153        _ => None,
154    }
155}
156
157#[derive(Clone, Copy)]
158struct PciLineQuirk {
159    vendor_id: u16,
160    device_id: u16,
161}
162
163const PCI_IRQ_LINE_ZERO_IF_FF: &[PciLineQuirk] = &[
164    PciLineQuirk {
165        vendor_id: vendor::INTEL,
166        device_id: intel_eth::E1000_82540EM,
167    },
168    PciLineQuirk {
169        vendor_id: vendor::INTEL,
170        device_id: intel_eth::E1000_82545EM,
171    },
172    PciLineQuirk {
173        vendor_id: vendor::INTEL,
174        device_id: intel_eth::E1000E_82574L,
175    },
176    PciLineQuirk {
177        vendor_id: vendor::VIRTIO,
178        device_id: device::VIRTIO_NET,
179    },
180    PciLineQuirk {
181        vendor_id: vendor::VIRTIO,
182        device_id: device::VIRTIO_BLOCK,
183    },
184];
185
186/// PCI Vendor IDs
187pub mod vendor {
188    pub const VIRTIO: u16 = 0x1AF4;
189    pub const QEMU: u16 = 0x1234;
190    pub const INTEL: u16 = 0x8086;
191    pub const AMD: u16 = 0x1022;
192    /// ATI/AMD display controller vendor ID (GPUs, APUs display)
193    pub const AMD_DISPLAY: u16 = 0x1002;
194}
195
196/// PCI Device IDs (VirtIO legacy)
197pub mod device {
198    pub const VIRTIO_NET: u16 = 0x1000;
199    pub const VIRTIO_BLOCK: u16 = 0x1001;
200    pub const VIRTIO_CONSOLE: u16 = 0x1003;
201    pub const VIRTIO_RNG: u16 = 0x1005;
202    pub const VIRTIO_GPU: u16 = 0x1050;
203    pub const VIRTIO_INPUT: u16 = 0x1052;
204}
205
206/// PCI base class codes
207pub mod class {
208    pub const MASS_STORAGE: u8 = 0x01;
209    pub const NETWORK: u8 = 0x02;
210}
211
212/// PCI subclasses for mass storage controllers
213pub mod storage_subclass {
214    pub const SCSI: u8 = 0x00;
215    pub const IDE: u8 = 0x01;
216    pub const FLOPPY: u8 = 0x02;
217    pub const IPI: u8 = 0x03;
218    pub const RAID: u8 = 0x04;
219    pub const ATA: u8 = 0x05;
220    pub const SATA: u8 = 0x06;
221    pub const SAS: u8 = 0x07;
222    pub const NVM: u8 = 0x08;
223    pub const OTHER: u8 = 0x80;
224}
225
226/// Programming interface codes for mass-storage SATA controllers
227pub mod sata_progif {
228    /// AHCI 1.0 (Advanced Host Controller Interface) : the standard modern mode
229    pub const AHCI: u8 = 0x01;
230    /// Vendor-specific / legacy IDE emulation
231    pub const VENDOR: u8 = 0x00;
232}
233
234/// PCI subclasses for network controllers
235pub mod net_subclass {
236    pub const ETHERNET: u8 = 0x00;
237    pub const OTHER: u8 = 0x80;
238}
239
240/// Intel Ethernet device IDs
241pub mod intel_eth {
242    pub const E1000_82540EM: u16 = 0x100E; // QEMU default e1000
243    pub const E1000_82545EM: u16 = 0x100F;
244    pub const E1000E_82574L: u16 = 0x10D3; // QEMU e1000e
245    pub const I210_AT: u16 = 0x1533;
246    pub const I350_AM2: u16 = 0x1521;
247    pub const I350_AM4: u16 = 0x1523;
248    pub const I217_LM: u16 = 0x153A;
249    pub const I211_AT: u16 = 0x1539;
250    pub const I219_LM: u16 = 0x15F9;
251    pub const I219_V: u16 = 0x15FA;
252    pub const I225_LM: u16 = 0x15F2;
253    pub const I225_V: u16 = 0x15F3;
254    pub const I226_LM: u16 = 0x125B;
255    pub const I226_V: u16 = 0x125C;
256}
257
258/// PCI configuration register offsets
259pub mod config {
260    pub const VENDOR_ID: u8 = 0x00;
261    pub const DEVICE_ID: u8 = 0x02;
262    pub const COMMAND: u8 = 0x04;
263    pub const STATUS: u8 = 0x06;
264    pub const REVISION_ID: u8 = 0x08;
265    pub const PROG_IF: u8 = 0x09;
266    pub const SUBCLASS: u8 = 0x0A;
267    pub const CLASS_CODE: u8 = 0x0B;
268    pub const CACHE_LINE_SIZE: u8 = 0x0C;
269    pub const LATENCY_TIMER: u8 = 0x0D;
270    pub const HEADER_TYPE: u8 = 0x0E;
271    pub const BIST: u8 = 0x0F;
272    pub const BAR0: u8 = 0x10;
273    pub const BAR1: u8 = 0x14;
274    pub const BAR2: u8 = 0x18;
275    pub const BAR3: u8 = 0x1C;
276    pub const BAR4: u8 = 0x20;
277    pub const BAR5: u8 = 0x24;
278    pub const CARDBUS_CIS: u8 = 0x28;
279    pub const SUBSYSTEM_VENDOR_ID: u8 = 0x2C;
280    pub const SUBSYSTEM_ID: u8 = 0x2E;
281    pub const ROM_BAR: u8 = 0x30;
282    pub const CAPABILITIES: u8 = 0x34;
283    pub const INTERRUPT_LINE: u8 = 0x3C;
284    pub const INTERRUPT_PIN: u8 = 0x3D;
285    pub const MIN_GNT: u8 = 0x3E;
286    pub const MAX_LAT: u8 = 0x3F;
287    pub const CAPABILITIES_PTR: u8 = 0x34;
288}
289
290/// PCI capability IDs
291pub mod cap_id {
292    /// MSI capability (PCI 2.2+)
293    pub const MSI: u8 = 0x05;
294    /// MSI-X capability (PCI 3.0+)
295    pub const MSIX: u8 = 0x11;
296}
297
298/// PCIe Extended Capability IDs (offset >= 0x100)
299pub mod ext_cap_id {
300    /// Advanced Error Reporting (AER)
301    pub const AER: u16 = 0x0001;
302    /// Virtual Channel
303    pub const VC: u16 = 0x0002;
304    /// Device Serial Number
305    pub const DSN: u16 = 0x0003;
306    /// Power Budgeting
307    pub const PB: u16 = 0x0004;
308    /// Root Link Declaration
309    pub const RLD: u16 = 0x0005;
310    /// Root Complex Link Declaration
311    pub const RCLD: u16 = 0x0006;
312    /// Multi-Root I/O Virtualization
313    pub const MRIOV: u16 = 0x0008;
314    /// Single-Root I/O Virtualization (SR-IOV)
315    pub const SRIOV: u16 = 0x0010;
316    /// Resizable BAR
317    pub const RBAR: u16 = 0x0015;
318    /// Dynamic Power Allocation
319    pub const DPA: u16 = 0x0016;
320    /// TPH Requester
321    pub const TPH: u16 = 0x0017;
322    /// Latency Tolerance Reporting
323    pub const LTR: u16 = 0x0018;
324    /// Secondary PCIe Capability
325    pub const SEC_PCIE: u16 = 0x0019;
326    /// PMUX
327    pub const PMUX: u16 = 0x001A;
328    /// Process Address Space ID (PASID)
329    pub const PASID: u16 = 0x001B;
330    /// LNR (Layer 3 Routing)
331    pub const LNR: u16 = 0x001C;
332    /// Address Translation Services (ATS)
333    pub const ATS: u16 = 0x001D;
334    /// Page Request Interface (PRI)
335    pub const PRI: u16 = 0x001E;
336    /// Process Address Space ID (PASID) Extended Capability
337    pub const PASID_EXT: u16 = 0x0020;
338    /// Shared Virtual Memory (SVM)
339    pub const SVM: u16 = 0x0021;
340    /// L1 PM Substates
341    pub const L1_PM: u16 = 0x0022;
342    /// Precision Time Measurement (PTM)
343    pub const PTM: u16 = 0x0023;
344    /// PCIe Tunneling
345    pub const TUNNEL: u16 = 0x0024;
346    /// Access Control Services (ACS)
347    pub const ACS: u16 = 0x0025;
348    /// Alternative Routing ID Interpretation (ARI)
349    pub const ARI: u16 = 0x0026;
350    /// Address Translation Services (ATS) Extended Capability
351    pub const ATS_EXT: u16 = 0x0027;
352    /// Single Root I/O Virtualization (SR-IOV) Extended Capability
353    pub const SRIOV_EXT: u16 = 0x0028;
354    /// Physical Function (PF) SR-IOV Extended Capability
355    pub const PF_SRIOV: u16 = 0x0029;
356}
357
358/// SR-IOV capability register offsets (relative to capability base).
359pub mod sriov_cap {
360    /// Capability register (16-bit)
361    pub const CAP: u8 = 0x00;
362    /// SR-IOV Control register (16-bit)
363    pub const CONTROL: u8 = 0x02;
364    /// SR-IOV Status register (16-bit)
365    pub const STATUS: u8 = 0x04;
366    /// SR-IOV PCIe Capability register (32-bit)
367    pub const PCIE_CAP: u8 = 0x08;
368    /// SR-IOV ARI Capability register (32-bit)
369    pub const ARI_CAP: u8 = 0x0C;
370    /// SR-IOV Initial VFs (16-bit)
371    pub const INITIAL_VF: u8 = 0x10;
372    /// SR-IOV Total VFs (16-bit)
373    pub const TOTAL_VF: u8 = 0x12;
374    /// SR-IOV Number of VFs (16-bit)
375    pub const NUM_VF: u8 = 0x14;
376    /// SR-IOV Function Dependency Link (8-bit)
377    pub const FDL: u8 = 0x16;
378    /// SR-IOV System Page Size (32-bit)
379    pub const SYS_PAGE_SIZE: u8 = 0x18;
380    /// SR-IOV BAR0 offset (32-bit)
381    pub const BAR0_OFFSET: u8 = 0x1C;
382    /// SR-IOV BAR1 offset (32-bit)
383    pub const BAR1_OFFSET: u8 = 0x20;
384    /// SR-IOV BAR2 offset (32-bit)
385    pub const BAR2_OFFSET: u8 = 0x24;
386    /// SR-IOV BAR3 offset (32-bit)
387    pub const BAR3_OFFSET: u8 = 0x28;
388    /// SR-IOV BAR4 offset (32-bit)
389    pub const BAR4_OFFSET: u8 = 0x2C;
390    /// SR-IOV BAR5 offset (32-bit)
391    pub const BAR5_OFFSET: u8 = 0x30;
392    /// SR-IOV VF Migration State Array Offset (32-bit)
393    pub const VF_MIGRATION_STATE: u8 = 0x3C;
394}
395
396/// SR-IOV Control register bits
397pub mod sriov_ctrl {
398    /// Enable SR-IOV
399    pub const ENABLE: u16 = 1 << 0;
400    /// Enable MSE (Memory Space Enable) for VFs
401    pub const MSE: u16 = 1 << 1;
402    /// Enable ARI (Alternate Routing ID)
403    pub const ARI_CAP: u16 = 1 << 2;
404    /// Enable IMS (Interrupt Mask Set) for VFs
405    pub const IMS_ENABLE: u16 = 1 << 4;
406    /// Enable PFARI (PF ARI Capability)
407    pub const PFARI_CAP: u16 = 1 << 5;
408    /// Enable VFARI (VF ARI Capability)
409    pub const VFARI_CAP: u16 = 1 << 6;
410    /// Enable VF Migration
411    pub const VF_MIGRATION: u16 = 1 << 7;
412}
413
414/// SR-IOV Status register bits
415pub mod sriov_status {
416    /// VF Memory Space Status
417    pub const VF_MEMORY_SPACE: u16 = 1 << 0;
418    /// VF ARI Capability Status
419    pub const VF_ARI_CAP: u16 = 1 << 1;
420    /// PF ARI Capability Status
421    pub const PF_ARI_CAP: u16 = 1 << 2;
422    /// VF Migration Status
423    pub const VF_MIGRATION_STATUS: u16 = 1 << 3;
424}
425
426/// AER (Advanced Error Reporting) capability register offsets.
427pub mod aer_cap {
428    /// AER Capability register (32-bit)
429    pub const CAP: u8 = 0x00;
430    /// AER UnCorrectable Error Status (32-bit)
431    pub const UNCERR_STATUS: u8 = 0x04;
432    /// AER UnCorrectable Error Mask (32-bit)
433    pub const UNCERR_MASK: u8 = 0x08;
434    /// AER UnCorrectable Error Severity (32-bit)
435    pub const UNCERR_SEVERITY: u8 = 0x0C;
436    /// AER Correctable Error Status (32-bit)
437    pub const CORERR_STATUS: u8 = 0x10;
438    /// AER Correctable Error Mask (32-bit)
439    pub const CORERR_MASK: u8 = 0x14;
440    /// AER Advanced Error Capabilities and Control (32-bit)
441    pub const ERR_CAP: u8 = 0x18;
442    /// AER Header Log (128-bit)
443    pub const HEADER_LOG: u8 = 0x1C;
444}
445
446/// Walk PCIe extended capabilities starting from `cap_ptr` (>= 0x100).
447///
448/// Returns a list of (capability_id, offset) pairs.
449pub fn walk_ext_capabilities(dev: &PciDevice, cap_ptr: u16) -> Vec<(u16, u16)> {
450    let mut caps = Vec::new();
451    let mut offset = cap_ptr;
452
453    while offset >= 0x100 && offset < 0xFFF {
454        let dword = match dev.read_config_u32_ext(offset) {
455            Some(v) => v,
456            None => break,
457        };
458        let cap_id = (dword & 0xFFFF) as u16;
459        let next_ptr = ((dword >> 20) & 0xFFC) as u16; // bits 31:20, aligned to 4
460
461        if cap_id == 0 {
462            break; // Invalid capability
463        }
464
465        caps.push((cap_id, offset));
466
467        if next_ptr == 0 || next_ptr == offset {
468            break; // End of list or self-loop
469        }
470        offset = next_ptr;
471    }
472
473    caps
474}
475
476/// Find the PCIe extended capability offset for a given capability ID.
477///
478/// Extended capabilities are always at offsets >= 0x100 in PCIe config space.
479/// Requires ECAM support (MCFG ACPI table) to read.
480pub fn find_ext_capability(dev: &PciDevice, cap_id: u16) -> Option<u16> {
481    if ECAM_REGIONS.lock().is_empty() {
482        return None; // No ECAM available, cannot read extended config space
483    }
484
485    for (found_id, offset) in walk_ext_capabilities(dev, 0x100) {
486        if found_id == cap_id {
487            return Some(offset);
488        }
489    }
490    None
491}
492
493/// Read SR-IOV capability information from a PCI device.
494///
495/// Returns `None` if the device doesn't have SR-IOV capability.
496pub fn read_sriov_info(dev: &PciDevice) -> Option<SriovInfo> {
497    let cap_offset = find_ext_capability(dev, ext_cap_id::SRIOV)?;
498    let control = dev.read_config_u32_ext(cap_offset + sriov_cap::CONTROL as u16)? as u16;
499    let status = dev.read_config_u32_ext(cap_offset + sriov_cap::STATUS as u16)? as u16;
500    let initial_vf = dev.read_config_u32_ext(cap_offset + sriov_cap::INITIAL_VF as u16)? as u16;
501    let total_vf = dev.read_config_u32_ext(cap_offset + sriov_cap::TOTAL_VF as u16)? as u16;
502    let num_vf = dev.read_config_u32_ext(cap_offset + sriov_cap::NUM_VF as u16)? as u16;
503
504    Some(SriovInfo {
505        cap_offset,
506        control,
507        status,
508        initial_vf,
509        total_vf,
510        num_vf,
511        enabled: (control & sriov_ctrl::ENABLE) != 0,
512    })
513}
514
515/// SR-IOV capability information.
516#[derive(Debug, Clone, Copy)]
517pub struct SriovInfo {
518    /// Offset of the SR-IOV capability in config space.
519    pub cap_offset: u16,
520    /// SR-IOV Control register value.
521    pub control: u16,
522    /// SR-IOV Status register value.
523    pub status: u16,
524    /// Number of initial VFs at power-on.
525    pub initial_vf: u16,
526    /// Total number of VFs supported.
527    pub total_vf: u16,
528    /// Number of VFs currently enabled.
529    pub num_vf: u16,
530    /// Whether SR-IOV is currently enabled.
531    pub enabled: bool,
532}
533
534/// Read AER (Advanced Error Reporting) capability information.
535pub fn read_aer_info(dev: &PciDevice) -> Option<AerInfo> {
536    let cap_offset = find_ext_capability(dev, ext_cap_id::AER)?;
537    let uncerr_status = dev.read_config_u32_ext(cap_offset + aer_cap::UNCERR_STATUS as u16)?;
538    let uncerr_mask = dev.read_config_u32_ext(cap_offset + aer_cap::UNCERR_MASK as u16)?;
539    let corerr_status = dev.read_config_u32_ext(cap_offset + aer_cap::CORERR_STATUS as u16)?;
540    let corerr_mask = dev.read_config_u32_ext(cap_offset + aer_cap::CORERR_MASK as u16)?;
541    let err_cap = dev.read_config_u32_ext(cap_offset + aer_cap::ERR_CAP as u16)?;
542
543    Some(AerInfo {
544        cap_offset,
545        uncerr_status,
546        uncerr_mask,
547        corerr_status,
548        corerr_mask,
549        first_error_pointer: ((err_cap >> 24) & 0x1F) as u8,
550        ecrc_error_capable: (err_cap & 0x01) != 0,
551        ecrc_generate_capable: (err_cap & 0x02) != 0,
552    })
553}
554
555/// AER (Advanced Error Reporting) capability information.
556#[derive(Debug, Clone, Copy)]
557pub struct AerInfo {
558    /// Offset of the AER capability in config space.
559    pub cap_offset: u16,
560    /// Uncorrectable error status bits.
561    pub uncerr_status: u32,
562    /// Uncorrectable error mask bits.
563    pub uncerr_mask: u32,
564    /// Correctable error status bits.
565    pub corerr_status: u32,
566    /// Correctable error mask bits.
567    pub corerr_mask: u32,
568    /// First error pointer (for error logging).
569    pub first_error_pointer: u8,
570    /// Whether ECRC error detection is supported.
571    pub ecrc_error_capable: bool,
572    /// Whether ECRC error generation is supported.
573    pub ecrc_generate_capable: bool,
574}
575
576/// Offsets within an MSI capability block (relative to capability base).
577pub mod msi_cap {
578    /// Capability ID (1 byte) + next ptr (1 byte) = 2 bytes header
579    /// Control register at +2 (16-bit)
580    pub const CONTROL: u8 = 0x02;
581    /// Message Address Register (32-bit) at +4
582    pub const ADDR_LOW: u8 = 0x04;
583    /// Message Upper Address Register (32-bit, 64-bit capable only) at +8
584    pub const ADDR_HIGH: u8 = 0x08;
585    /// Message Data Register (16-bit):
586    ///   - 32-bit capable: at +8
587    ///   - 64-bit capable: at +12
588    pub const DATA: u8 = 0x08;
589}
590
591/// MSI control register bit definitions (16-bit at cap_base + 2).
592pub mod msi_ctrl {
593    /// MSI Enable
594    pub const ENABLE: u16 = 1 << 0;
595    /// Multiple Message Enable (bits 4:6) : number of vectors allocated
596    pub const MME_MASK: u16 = 0b111 << 4;
597    /// Multiple Message Capable (bits 1:3) : number of vectors the device wants
598    pub const MMC_MASK: u16 = 0b111 << 1;
599    /// 64-bit addressing supported
600    pub const ADDR64: u16 = 1 << 7;
601    /// Per-vector masking supported
602    pub const PV_MASK: u16 = 1 << 8;
603}
604
605/// Offsets within an MSI-X capability block (relative to capability base).
606pub mod msix_cap {
607    /// Capability ID (1 byte) + next ptr (1 byte) = 2 bytes header
608    /// Control register at +2 (16-bit)
609    pub const CONTROL: u8 = 0x02;
610    /// Table offset / BAR indicator (32-bit) at +4
611    pub const TABLE: u8 = 0x04;
612    /// Pending Bit Array offset / BAR indicator (32-bit) at +8
613    pub const PBA: u8 = 0x08;
614}
615
616/// MSI-X control register bit definitions (16-bit at cap_base + 2).
617pub mod msix_ctrl {
618    /// MSI-X Enable
619    pub const ENABLE: u16 = 1 << 15;
620    /// Function Mask
621    pub const FUNC_MASK: u16 = 1 << 14;
622    /// Table size (bits 0:10) : number of entries minus 1
623    pub const TABLE_SIZE_MASK: u16 = (1 << 11) - 1;
624}
625
626/// x86 MSI message address (delivers to LAPIC via system bus).
627///
628/// Format:
629///   [31:20] = 0xFEE (fixed)
630///   [19:12] = Destination LAPIC ID
631///   [11:4]  = reserved
632///   [3]     = Redirection Hint (0 = physical destination)
633///   [2]     = Destination Mode (0 = physical)
634///   [1:0]   = 0b00
635pub const MSI_ADDR_BASE: u32 = 0xFEE0_0000;
636pub const MSI_ADDR_DEST_SHIFT: u32 = 12;
637
638/// PCI command register bits
639pub mod command {
640    pub const IO_SPACE: u16 = 1 << 0;
641    pub const MEMORY_SPACE: u16 = 1 << 1;
642    pub const BUS_MASTER: u16 = 1 << 2;
643    pub const SPECIAL_CYCLES: u16 = 1 << 3;
644    pub const MWI_ENABLE: u16 = 1 << 4;
645    pub const VGA_PALETTE_SNOOP: u16 = 1 << 5;
646    pub const PARITY_ERROR_RESPONSE: u16 = 1 << 6;
647    pub const STEPPING_CONTROL: u16 = 1 << 7;
648    pub const SERR_ENABLE: u16 = 1 << 8;
649    pub const FAST_BACK_TO_BACK: u16 = 1 << 9;
650    pub const INTERRUPT_DISABLE: u16 = 1 << 10;
651}
652
653/// Base Address Register (BAR) types
654#[derive(Debug, Clone, Copy, PartialEq, Eq)]
655pub enum Bar {
656    Io { port: u16 },
657    Memory32 { addr: u32, prefetchable: bool },
658    Memory64 { addr: u64, prefetchable: bool },
659}
660
661/// A PCI device location
662#[derive(Clone, Copy, PartialEq, Eq)]
663pub struct PciAddress {
664    pub bus: u8,
665    pub device: u8,
666    pub function: u8,
667}
668
669impl fmt::Debug for PciAddress {
670    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
671        write!(f, "{:02x}:{:02x}.{}", self.bus, self.device, self.function)
672    }
673}
674
675impl PciAddress {
676    /// Create a new PCI address
677    pub const fn new(bus: u8, device: u8, function: u8) -> Self {
678        Self {
679            bus,
680            device,
681            function,
682        }
683    }
684
685    /// Convert to configuration address format
686    fn config_address(&self, offset: u8) -> u32 {
687        let bus = self.bus as u32;
688        let device = (self.device as u32) & 0x1F;
689        let function = (self.function as u32) & 0x07;
690        let offset = (offset as u32) & 0xFC;
691
692        0x8000_0000 | (bus << 16) | (device << 11) | (function << 8) | offset
693    }
694}
695
696/// PCI device information
697#[derive(Clone, Copy)]
698pub struct PciDevice {
699    pub address: PciAddress,
700    pub vendor_id: u16,
701    pub device_id: u16,
702    pub class_code: u8,
703    pub subclass: u8,
704    pub prog_if: u8,
705    pub revision: u8,
706    pub header_type: u8,
707    pub interrupt_line: u8,
708    pub interrupt_pin: u8,
709}
710
711impl fmt::Debug for PciDevice {
712    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
713        write!(
714            f,
715            "PciDevice({:?} ID {:04x}:{:04x} Class {:02x}:{:02x})",
716            self.address, self.vendor_id, self.device_id, self.class_code, self.subclass
717        )
718    }
719}
720
721impl PciDevice {
722    /// Read a configuration register (8-bit)
723    pub fn read_config_u8(&self, offset: u8) -> u8 {
724        let addr = self.address.config_address(offset & !0x03);
725        let shift = (offset & 0x03) * 8;
726
727        let _lock = PCI_IO_LOCK.lock();
728        unsafe {
729            outl(CONFIG_ADDRESS, addr);
730            ((inl(CONFIG_DATA) >> shift) & 0xFF) as u8
731        }
732    }
733
734    /// Read a configuration register (16-bit)
735    pub fn read_config_u16(&self, offset: u8) -> u16 {
736        let addr = self.address.config_address(offset & !0x03);
737        let shift = (offset & 0x02) * 8;
738
739        let _lock = PCI_IO_LOCK.lock();
740        unsafe {
741            outl(CONFIG_ADDRESS, addr);
742            ((inl(CONFIG_DATA) >> shift) & 0xFFFF) as u16
743        }
744    }
745
746    /// Read a configuration register (32-bit)
747    pub fn read_config_u32(&self, offset: u8) -> u32 {
748        let addr = self.address.config_address(offset);
749
750        let _lock = PCI_IO_LOCK.lock();
751        unsafe {
752            outl(CONFIG_ADDRESS, addr);
753            inl(CONFIG_DATA)
754        }
755    }
756
757    /// Read a 32-bit register from extended config space (offset >= 0x100).
758    ///
759    /// Uses ECAM MMIO when available. Returns `None` if ECAM is not mapped.
760    pub fn read_config_u32_ext(&self, offset: u16) -> Option<u32> {
761        let regions = ECAM_REGIONS.lock();
762        let ecam = regions.iter().find_map(|r| {
763            if self.address.bus >= r.start_bus && self.address.bus <= r.end_bus {
764                Some(r.base_virt)
765            } else {
766                None
767            }
768        })?;
769        Some(unsafe {
770            ecam_read32(
771                ecam,
772                self.address.bus,
773                self.address.device,
774                self.address.function,
775                offset,
776            )
777        })
778    }
779
780    /// Write to a configuration register (8-bit)
781    pub fn write_config_u8(&self, offset: u8, value: u8) {
782        let addr = self.address.config_address(offset & !0x03);
783        let shift = (offset & 0x03) * 8;
784
785        let _lock = PCI_IO_LOCK.lock();
786        unsafe {
787            outl(CONFIG_ADDRESS, addr);
788            let old = inl(CONFIG_DATA);
789            let mask = !(0xFF << shift);
790            let new = (old & mask) | ((value as u32) << shift);
791            outl(CONFIG_ADDRESS, addr);
792            outl(CONFIG_DATA, new);
793        }
794    }
795
796    /// Write to a configuration register (16-bit)
797    pub fn write_config_u16(&self, offset: u8, value: u16) {
798        let addr = self.address.config_address(offset & !0x03);
799        let shift = (offset & 0x02) * 8;
800
801        let _lock = PCI_IO_LOCK.lock();
802        unsafe {
803            outl(CONFIG_ADDRESS, addr);
804            let old = inl(CONFIG_DATA);
805            let mask = !(0xFFFF << shift);
806            let new = (old & mask) | ((value as u32) << shift);
807            outl(CONFIG_ADDRESS, addr);
808            outl(CONFIG_DATA, new);
809        }
810    }
811
812    /// Write to a configuration register (32-bit)
813    pub fn write_config_u32(&self, offset: u8, value: u32) {
814        let addr = self.address.config_address(offset);
815
816        let _lock = PCI_IO_LOCK.lock();
817        unsafe {
818            outl(CONFIG_ADDRESS, addr);
819            outl(CONFIG_DATA, value);
820        }
821    }
822
823    /// Read a Base Address Register (BAR)
824    pub fn read_bar(&self, bar_index: u8) -> Option<Bar> {
825        if bar_index > 5 {
826            return None;
827        }
828
829        let offset = config::BAR0 + (bar_index * 4);
830        let bar_low = self.read_config_u32(offset);
831
832        if bar_low == 0 {
833            return None;
834        }
835
836        // Check if it's an I/O BAR (bit 0 set)
837        if bar_low & 0x1 != 0 {
838            let port = (bar_low & 0xFFFF_FFFC) as u16;
839            Some(Bar::Io { port })
840        } else {
841            let bar_type = (bar_low >> 1) & 0x3;
842            let prefetchable = (bar_low >> 3) & 0x1 != 0;
843
844            match bar_type {
845                0 => {
846                    let addr = bar_low & 0xFFFF_FFF0;
847                    Some(Bar::Memory32 { addr, prefetchable })
848                }
849                2 => {
850                    if bar_index >= 5 {
851                        return None;
852                    }
853                    let bar_high = self.read_config_u32(offset + 4);
854                    let addr = ((bar_high as u64) << 32) | ((bar_low & 0xFFFF_FFF0) as u64);
855                    Some(Bar::Memory64 { addr, prefetchable })
856                }
857                _ => None,
858            }
859        }
860    }
861
862    /// Get the raw BAR value (for legacy compatibility)
863    pub fn read_bar_raw(&self, bar_index: u8) -> Option<u64> {
864        match self.read_bar(bar_index) {
865            Some(Bar::Io { port }) => Some(port as u64),
866            Some(Bar::Memory32 { addr, .. }) => Some(addr as u64),
867            Some(Bar::Memory64 { addr, .. }) => Some(addr),
868            None => None,
869        }
870    }
871
872    /// Enable bus mastering for this device
873    pub fn enable_bus_master(&self) {
874        let mut cmd = self.read_config_u16(config::COMMAND);
875        cmd |= command::BUS_MASTER;
876        self.write_config_u16(config::COMMAND, cmd);
877    }
878
879    /// Enable memory space access for this device
880    pub fn enable_memory_space(&self) {
881        let mut cmd = self.read_config_u16(config::COMMAND);
882        cmd |= command::MEMORY_SPACE;
883        self.write_config_u16(config::COMMAND, cmd);
884    }
885
886    /// Enable I/O space access for this device
887    pub fn enable_io_space(&self) {
888        let mut cmd = self.read_config_u16(config::COMMAND);
889        cmd |= command::IO_SPACE;
890        self.write_config_u16(config::COMMAND, cmd);
891    }
892}
893
894// ---------------------------------------------------------------------------
895// Fast PCI bus scanner (BFS with early-exit)
896// ---------------------------------------------------------------------------
897//
898// Insipired by asterinas OS's PCI scanner:
899//
900//  1. For each (bus, device), probe function 0 first.
901//     If vendor == 0xFFFF => skip all 8 functions (early exit).
902//
903//  2. Read the Header Type from the function-0 dword at offset 0x0C.
904//     Bit 7 (multi-function flag) tells whether functions 1..7 can exist.
905//     If bit 7 is clear => skip functions 1..7 entirely.
906//
907//  3. If header_type & 0x7F == 0x01 (PCI-to-PCI bridge), read the
908//     secondary bus number and enqueue it.  The `seen_buses` bitmap
909//     prevents re-scanning a bus already visited.
910//
911// This reduces the worst-case probes from 256 × 32 × 8 = 65 536 down to
912// 256 × 32 × 1 = 8 192 for a topology with no multi-function devices
913// (the common case on QEMU / VMware).
914//
915// I/O cost per probe:
916//   Old: 4 dword reads under 4 separate lock acquisitions.
917//   New: 1 dword read (vendor check, early exit) + 3 dword reads only
918//        for devices that actually exist, all under a single lock hold
919//        via `probe_device_full`.
920
921/// Iterator for scanning PCI bus
922pub struct PciScanner {
923    bus_queue: [u8; 256],
924    queue_head: usize,
925    queue_tail: usize,
926    seen_buses: [bool; 256],
927    device: u8,
928    function: u8,
929    /// Cached multi-function flag for the current device (from function 0).
930    /// When `function > 0`, this tells us whether to keep scanning.
931    is_multi_function: bool,
932}
933
934impl PciScanner {
935    pub fn new() -> Self {
936        let mut s = Self {
937            bus_queue: [0u8; 256],
938            queue_head: 0,
939            queue_tail: 1,
940            seen_buses: [false; 256],
941            device: 0,
942            function: 0,
943            is_multi_function: false,
944        };
945        s.seen_buses[0] = true;
946        s
947    }
948
949    fn enqueue_bus(&mut self, bus: u8) {
950        if !self.seen_buses[bus as usize] && self.queue_tail < 256 {
951            self.seen_buses[bus as usize] = true;
952            self.bus_queue[self.queue_tail] = bus;
953            self.queue_tail += 1;
954        }
955    }
956
957    #[inline]
958    fn advance_to_next_device(&mut self) {
959        self.function = 0;
960        self.device += 1;
961        self.is_multi_function = false;
962    }
963}
964
965impl Iterator for PciScanner {
966    type Item = PciDevice;
967
968    fn next(&mut self) -> Option<Self::Item> {
969        loop {
970            // Advance to next bus if we exhausted all 32 devices.
971            if self.queue_head >= self.queue_tail {
972                return None;
973            }
974            let bus = self.bus_queue[self.queue_head];
975
976            if self.device >= 32 {
977                self.queue_head += 1;
978                self.device = 0;
979                self.function = 0;
980                self.is_multi_function = false;
981                continue;
982            }
983
984            let current_function = self.function;
985
986            // --- Function 0: fast vendor check + early exit ---
987            if current_function == 0 {
988                // Single dword read: vendor+device at offset 0x00.
989                // If 0xFFFF => no device at this slot, skip all 8 functions.
990                let word00 = raw_config_read(bus, self.device, 0, 0x00);
991                let vendor_id = (word00 & 0xFFFF) as u16;
992                if is_absent_vendor(vendor_id) {
993                    self.advance_to_next_device();
994                    continue;
995                }
996
997                // Device exists at function 0 : do the full probe.
998                let Some(dev) = probe_from_word00(PciAddress::new(bus, self.device, 0), word00)
999                else {
1000                    self.advance_to_next_device();
1001                    continue;
1002                };
1003
1004                // Cache multi-function status from header_type bit 7.
1005                self.is_multi_function = dev.header_type & 0x80 != 0;
1006
1007                // If it's a PCI-to-PCI bridge, enqueue the secondary bus.
1008                if dev.header_type & 0x7F == 0x01 {
1009                    let secondary = raw_config_read_u8(bus, self.device, 0, 0x19);
1010                    self.enqueue_bus(secondary);
1011                }
1012
1013                // Advance: if multi-function, move to function 1;
1014                // otherwise skip straight to the next device.
1015                if self.is_multi_function {
1016                    self.function = 1;
1017                } else {
1018                    self.advance_to_next_device();
1019                }
1020
1021                return Some(dev);
1022            }
1023
1024            // --- Functions 1..7 (only reached if multi-function) ---
1025            debug_assert!(self.is_multi_function);
1026
1027            self.function += 1;
1028            if self.function >= 8 {
1029                self.advance_to_next_device();
1030            }
1031
1032            let address = PciAddress::new(bus, self.device, current_function);
1033            let Some(dev) = probe_device_full(address) else {
1034                continue;
1035            };
1036
1037            if dev.header_type & 0x7F == 0x01 {
1038                let secondary = raw_config_read_u8(bus, self.device, current_function, 0x19);
1039                self.enqueue_bus(secondary);
1040            }
1041
1042            return Some(dev);
1043        }
1044    }
1045}
1046
1047// ---------------------------------------------------------------------------
1048// Low-level config-space helpers
1049// ---------------------------------------------------------------------------
1050
1051fn is_absent_vendor(vendor_id: u16) -> bool {
1052    vendor_id == 0xFFFF || vendor_id == 0x0000
1053}
1054
1055fn quirk_zero_irq_line(vendor_id: u16, device_id: u16, irq_line: u8) -> u8 {
1056    if irq_line != 0xFF {
1057        return irq_line;
1058    }
1059    if PCI_IRQ_LINE_ZERO_IF_FF
1060        .iter()
1061        .any(|q| q.vendor_id == vendor_id && q.device_id == device_id)
1062    {
1063        return 0;
1064    }
1065    0
1066}
1067
1068fn valid_header_type(header_type: u8) -> bool {
1069    matches!(header_type & 0x7F, 0x00..=0x02)
1070}
1071
1072fn is_ghost_device(class_code: u8, subclass: u8, prog_if: u8) -> bool {
1073    class_code == 0xFF && subclass == 0xFF && prog_if == 0xFF
1074}
1075
1076/// Single dword config read without building a PciDevice/PciAddress.
1077/// Acquires PCI_IO_LOCK once.
1078#[inline]
1079fn raw_config_read(bus: u8, device: u8, function: u8, offset: u8) -> u32 {
1080    let addr = 0x8000_0000u32
1081        | ((bus as u32) << 16)
1082        | (((device as u32) & 0x1F) << 11)
1083        | (((function as u32) & 0x07) << 8)
1084        | ((offset as u32) & 0xFC);
1085    let _lock = PCI_IO_LOCK.lock();
1086    unsafe {
1087        outl(CONFIG_ADDRESS, addr);
1088        inl(CONFIG_DATA)
1089    }
1090}
1091
1092/// Read a single byte from config space (derived from a dword read).
1093#[inline]
1094fn raw_config_read_u8(bus: u8, device: u8, function: u8, offset: u8) -> u8 {
1095    let dword = raw_config_read(bus, device, function, offset & !0x03);
1096    let shift = (offset & 0x03) * 8;
1097    ((dword >> shift) & 0xFF) as u8
1098}
1099
1100/// Probe a PCI address using 4 batched dword reads under a single lock hold.
1101///
1102/// Reads: 0x00 (vendor+device), 0x08 (rev+progif+subclass+class),
1103///        0x0C (cacheline+latency+headertype+bist), 0x3C (intline+intpin).
1104fn probe_device_full(address: PciAddress) -> Option<PciDevice> {
1105    let _lock = PCI_IO_LOCK.lock();
1106
1107    let word00 = unsafe {
1108        outl(CONFIG_ADDRESS, address.config_address(0x00));
1109        inl(CONFIG_DATA)
1110    };
1111    let vendor_id = (word00 & 0xFFFF) as u16;
1112    if is_absent_vendor(vendor_id) {
1113        return None;
1114    }
1115    let device_id = (word00 >> 16) as u16;
1116    if device_id == 0xFFFF || device_id == 0x0000 {
1117        return None;
1118    }
1119
1120    let word08 = unsafe {
1121        outl(CONFIG_ADDRESS, address.config_address(0x08));
1122        inl(CONFIG_DATA)
1123    };
1124    let word0c = unsafe {
1125        outl(CONFIG_ADDRESS, address.config_address(0x0C));
1126        inl(CONFIG_DATA)
1127    };
1128
1129    let header_type = ((word0c >> 16) & 0xFF) as u8;
1130    if !valid_header_type(header_type) {
1131        return None;
1132    }
1133
1134    let class_code = ((word08 >> 24) & 0xFF) as u8;
1135    let subclass = ((word08 >> 16) & 0xFF) as u8;
1136    let prog_if = ((word08 >> 8) & 0xFF) as u8;
1137    if is_ghost_device(class_code, subclass, prog_if) {
1138        return None;
1139    }
1140
1141    let word3c = unsafe {
1142        outl(CONFIG_ADDRESS, address.config_address(0x3C));
1143        inl(CONFIG_DATA)
1144    };
1145    let interrupt_line = quirk_zero_irq_line(vendor_id, device_id, (word3c & 0xFF) as u8);
1146
1147    Some(PciDevice {
1148        address,
1149        vendor_id,
1150        device_id,
1151        class_code,
1152        subclass,
1153        prog_if,
1154        revision: (word08 & 0xFF) as u8,
1155        header_type,
1156        interrupt_line,
1157        interrupt_pin: ((word3c >> 8) & 0xFF) as u8,
1158    })
1159}
1160
1161/// Build a PciDevice when `word00` (vendor+device dword) was already read
1162/// by the caller's fast-path vendor check, avoiding a redundant I/O cycle.
1163fn probe_from_word00(address: PciAddress, word00: u32) -> Option<PciDevice> {
1164    let vendor_id = (word00 & 0xFFFF) as u16;
1165    let device_id = (word00 >> 16) as u16;
1166    if device_id == 0xFFFF || device_id == 0x0000 {
1167        return None;
1168    }
1169
1170    let _lock = PCI_IO_LOCK.lock();
1171
1172    let word08 = unsafe {
1173        outl(CONFIG_ADDRESS, address.config_address(0x08));
1174        inl(CONFIG_DATA)
1175    };
1176    let word0c = unsafe {
1177        outl(CONFIG_ADDRESS, address.config_address(0x0C));
1178        inl(CONFIG_DATA)
1179    };
1180
1181    let header_type = ((word0c >> 16) & 0xFF) as u8;
1182    if !valid_header_type(header_type) {
1183        return None;
1184    }
1185
1186    let class_code = ((word08 >> 24) & 0xFF) as u8;
1187    let subclass = ((word08 >> 16) & 0xFF) as u8;
1188    let prog_if = ((word08 >> 8) & 0xFF) as u8;
1189    if is_ghost_device(class_code, subclass, prog_if) {
1190        return None;
1191    }
1192
1193    let word3c = unsafe {
1194        outl(CONFIG_ADDRESS, address.config_address(0x3C));
1195        inl(CONFIG_DATA)
1196    };
1197    let interrupt_line = quirk_zero_irq_line(vendor_id, device_id, (word3c & 0xFF) as u8);
1198
1199    Some(PciDevice {
1200        address,
1201        vendor_id,
1202        device_id,
1203        class_code,
1204        subclass,
1205        prog_if,
1206        revision: (word08 & 0xFF) as u8,
1207        header_type,
1208        interrupt_line,
1209        interrupt_pin: ((word3c >> 8) & 0xFF) as u8,
1210    })
1211}
1212
1213// ---------------------------------------------------------------------------
1214// Cached device inventory
1215// ---------------------------------------------------------------------------
1216
1217/// Cached PCI device inventory.
1218///
1219/// The first lookup performs a full bus scan, then all subsequent lookups reuse
1220/// this snapshot. Every query function borrows the cache through the lock and
1221/// operates on the `&[PciDevice]` directly : no `clone()` of the Vec.
1222///
1223/// # Invariant
1224///
1225/// `PCI_DEVICE_CACHE` is populated once at boot and never invalidated during
1226/// normal operation. The `SpinLock<Option<Vec<PciDevice>>>` is held only for
1227/// the initial scan (which allocates the Vec) and for subsequent reads. No
1228/// code path re-scans the bus or reallocates under the lock. If PCI hotplug
1229/// or re-enumeration is added in the future, this must be changed to either :
1230///   - a `Mutex` (sleepable) to allow re-scanning, or
1231///   - a lock-free double-buffered snapshot model.
1232static PCI_DEVICE_CACHE: SpinLock<Option<Vec<PciDevice>>> = SpinLock::new(None);
1233
1234/// When set, `with_cache`/ECAM scanning suppress serial diagnostics.  Used by
1235/// the periodic hotplug poll: a 500 ms rescan must not flood the boot console.
1236static PCI_SCAN_QUIET: AtomicBool = AtomicBool::new(false);
1237
1238/// Invalidate the boot-time snapshot and re-enumerate the bus.
1239///
1240/// Hotplug support: the old snapshot is dropped, then `all_devices()`
1241/// performs a fresh I/O + ECAM scan.  Drivers must re-probe after this call.
1242pub fn rescan() -> usize {
1243    {
1244        let mut cache = PCI_DEVICE_CACHE.lock();
1245        *cache = None;
1246    }
1247    all_devices().len()
1248}
1249
1250/// Same as [`rescan`], but suppresses the scan diagnostics.  The hotplug
1251/// watchdog uses it so a quiet system does not emit the full PCI inventory
1252/// every 500 ms.
1253pub fn rescan_quiet() -> usize {
1254    let previous = PCI_SCAN_QUIET.swap(true, Ordering::AcqRel);
1255    let count = rescan();
1256    PCI_SCAN_QUIET.store(previous, Ordering::Release);
1257    count
1258}
1259
1260// ---------------------------------------------------------------------------
1261// ECAM (PCIe Enhanced Configuration Access Mechanism) scanner
1262// ---------------------------------------------------------------------------
1263
1264/// Scan PCI devices via ECAM (Memory-Mapped Configuration).
1265///
1266/// Uses MCFG ACPI table entries to discover MMIO-mapped PCI config spaces.
1267/// For each ECAM region, scans all bus/device/function combinations.
1268/// Returns only devices not already found by the I/O port scanner.
1269fn scan_ecam_devices() -> Vec<PciDevice> {
1270    use crate::{acpi::mcfg, memory};
1271
1272    let log_scan = !PCI_SCAN_QUIET.load(Ordering::Relaxed);
1273    let mcfg_info = match mcfg::parse_mcfg() {
1274        Some(info) => info,
1275        None => {
1276            if log_scan {
1277                log::info!("[PCI-ECAM] No MCFG table found, skipping ECAM scan");
1278            }
1279            return Vec::new();
1280        }
1281    };
1282
1283    if log_scan {
1284        log::info!(
1285            "[PCI-ECAM] Found {} ECAM region(s)",
1286            mcfg_info.entries.len()
1287        );
1288    }
1289
1290    let mut devices = Vec::new();
1291
1292    for entry in &mcfg_info.entries {
1293        let ecam_phys = entry.base_address;
1294        let start_bus = entry.start_bus;
1295        let end_bus = entry.end_bus;
1296
1297        // Ensure the ECAM region is identity-mapped
1298        let region_size = ((end_bus as usize - start_bus as usize + 1) as u64) * (32 * 8 * 4096);
1299        memory::paging::ensure_identity_map_range(ecam_phys, region_size);
1300        let ecam_virt = crate::memory::phys_to_virt(ecam_phys) as usize;
1301
1302        // Cache ECAM region for extended config space reads
1303        ECAM_REGIONS.lock().push(EcamRegion {
1304            start_bus,
1305            end_bus,
1306            base_virt: ecam_virt,
1307        });
1308
1309        if log_scan {
1310            log::info!(
1311                "[PCI-ECAM] Region seg={} ecam={:#x} buses={}..{} virt={:#x}",
1312                entry.segment_group,
1313                ecam_phys,
1314                start_bus,
1315                end_bus,
1316                ecam_virt
1317            );
1318        }
1319
1320        // Scan each bus in the range
1321        for bus in start_bus..=end_bus {
1322            for dev in 0..32u8 {
1323                // Fast vendor check on function 0
1324                let word00 = unsafe { ecam_read32(ecam_virt, bus, dev, 0, 0x00) };
1325                let vendor_id = (word00 & 0xFFFF) as u16;
1326                if is_absent_vendor(vendor_id) {
1327                    continue;
1328                }
1329
1330                // Probe function 0
1331                if let Some(device) = probe_ecam_device(ecam_virt, bus, dev, 0, word00) {
1332                    let is_multi = device.header_type & 0x80 != 0;
1333                    devices.push(device);
1334
1335                    // Scan additional functions if multi-function
1336                    if is_multi {
1337                        for func in 1..8u8 {
1338                            if let Some(device) = probe_ecam_device(ecam_virt, bus, dev, func, 0) {
1339                                devices.push(device);
1340                            }
1341                        }
1342                    }
1343                }
1344            }
1345        }
1346    }
1347
1348    if log_scan {
1349        log::info!("[PCI-ECAM] ECAM scan found {} device(s)", devices.len());
1350    }
1351    devices
1352}
1353
1354/// Probe a single PCI device via ECAM MMIO.
1355fn probe_ecam_device(
1356    ecam_base: usize,
1357    bus: u8,
1358    device: u8,
1359    function: u8,
1360    word00: u32,
1361) -> Option<PciDevice> {
1362    let vendor_id = (word00 & 0xFFFF) as u16;
1363    let device_id = (word00 >> 16) as u16;
1364    if is_absent_vendor(vendor_id) || device_id == 0xFFFF || device_id == 0x0000 {
1365        return None;
1366    }
1367
1368    let address = PciAddress::new(bus, device, function);
1369
1370    let word08 = unsafe { ecam_read32(ecam_base, bus, device, function, 0x08) };
1371    let word0c = unsafe { ecam_read32(ecam_base, bus, device, function, 0x0C) };
1372
1373    let header_type = ((word0c >> 16) & 0xFF) as u8;
1374    if !valid_header_type(header_type) {
1375        return None;
1376    }
1377
1378    let class_code = ((word08 >> 24) & 0xFF) as u8;
1379    let subclass = ((word08 >> 16) & 0xFF) as u8;
1380    let prog_if = ((word08 >> 8) & 0xFF) as u8;
1381    if is_ghost_device(class_code, subclass, prog_if) {
1382        return None;
1383    }
1384
1385    let word3c = unsafe { ecam_read32(ecam_base, bus, device, function, 0x3C) };
1386    let interrupt_line = quirk_zero_irq_line(vendor_id, device_id, (word3c & 0xFF) as u8);
1387
1388    Some(PciDevice {
1389        address,
1390        vendor_id,
1391        device_id,
1392        class_code,
1393        subclass,
1394        prog_if,
1395        revision: (word08 & 0xFF) as u8,
1396        header_type,
1397        interrupt_line,
1398        interrupt_pin: ((word3c >> 8) & 0xFF) as u8,
1399    })
1400}
1401
1402/// Populate the cache if empty, then run `f` on the device slice.
1403///
1404/// All query functions route through here so that only a single scan ever
1405/// happens, and the lock is held for the duration of the filter : not for
1406/// the entire boot.
1407fn with_cache<R>(f: impl FnOnce(&[PciDevice]) -> R) -> R {
1408    let mut cache = PCI_DEVICE_CACHE.lock();
1409    if cache.is_none() {
1410        let log_scan = !PCI_SCAN_QUIET.load(Ordering::Relaxed);
1411        let dummy = 0u64;
1412        let rsp = &dummy as *const u64 as u64;
1413        if log_scan {
1414            crate::serial_println!("[PCI] Scanning PCI bus (rsp={:#x})...", rsp);
1415        }
1416
1417        // Phase 1: I/O port scan (0xCF8/0xCFC)
1418        let io_devices: Vec<PciDevice> = PciScanner::new().collect();
1419        if log_scan {
1420            crate::serial_println!("[PCI] I/O scan: {} device(s)", io_devices.len());
1421        }
1422
1423        // Phase 2: ECAM MMIO scan (via MCFG ACPI table)
1424        let ecam_devices: Vec<PciDevice> = scan_ecam_devices();
1425        if log_scan {
1426            crate::serial_println!("[PCI] ECAM scan: {} device(s)", ecam_devices.len());
1427        }
1428
1429        // Merge: ECAM devices that are NOT already in the I/O scan
1430        let mut devices = io_devices;
1431        for ecam_dev in &ecam_devices {
1432            let duplicate = devices.iter().any(|d| {
1433                d.address.bus == ecam_dev.address.bus
1434                    && d.address.device == ecam_dev.address.device
1435                    && d.address.function == ecam_dev.address.function
1436            });
1437            if !duplicate {
1438                devices.push(*ecam_dev);
1439            }
1440        }
1441        if log_scan {
1442            crate::serial_println!("[PCI] Total: {} device(s) after merge", devices.len());
1443
1444            // Improved logging: human-readable names, IRQ, class
1445            for dev in &devices {
1446                let name = device_name(dev.vendor_id, dev.device_id).unwrap_or("Unknown");
1447                let class = class_name(dev.class_code, dev.subclass).unwrap_or("???");
1448                crate::serial_println!(
1449                    "[PCI]   {:02x}:{:02x}.{:x} {:<24} {} (IRQ={})",
1450                    dev.address.bus,
1451                    dev.address.device,
1452                    dev.address.function,
1453                    name,
1454                    class,
1455                    dev.interrupt_line,
1456                );
1457            }
1458        }
1459        *cache = Some(devices);
1460    }
1461    f(cache.as_deref().unwrap_or(&[]))
1462}
1463
1464/// Helper to find a device by vendor and device ID
1465pub fn find_device(vendor_id: u16, device_id: u16) -> Option<PciDevice> {
1466    with_cache(|devs| {
1467        devs.iter()
1468            .copied()
1469            .find(|dev| dev.vendor_id == vendor_id && dev.device_id == device_id)
1470    })
1471}
1472
1473/// Find all VirtIO devices on the PCI bus
1474pub fn find_virtio_devices() -> Vec<PciDevice> {
1475    find_devices_by_vendor(vendor::VIRTIO)
1476}
1477
1478/// Find a specific VirtIO device by device ID
1479pub fn find_virtio_device(device_id: u16) -> Option<PciDevice> {
1480    find_device(vendor::VIRTIO, device_id)
1481}
1482
1483/// Return a snapshot of all discovered PCI devices.
1484pub fn all_devices() -> Vec<PciDevice> {
1485    with_cache(|devs| devs.to_vec())
1486}
1487
1488/// Return all devices for a given vendor from the cached PCI inventory.
1489pub fn find_devices_by_vendor(vendor_id: u16) -> Vec<PciDevice> {
1490    with_cache(|devs| {
1491        devs.iter()
1492            .copied()
1493            .filter(|dev| dev.vendor_id == vendor_id)
1494            .collect()
1495    })
1496}
1497
1498/// Return all devices matching a PCI class/subclass pair.
1499pub fn find_devices_by_class(class_code: u8, subclass: u8) -> Vec<PciDevice> {
1500    with_cache(|devs| {
1501        devs.iter()
1502            .copied()
1503            .filter(|dev| dev.class_code == class_code && dev.subclass == subclass)
1504            .collect()
1505    })
1506}
1507
1508/// Full PCI probe criteria.
1509///
1510/// Any field left as `None` is treated as a wildcard.
1511#[derive(Debug, Clone, Copy, Default)]
1512pub struct ProbeCriteria {
1513    pub vendor_id: Option<u16>,
1514    pub device_id: Option<u16>,
1515    pub class_code: Option<u8>,
1516    pub subclass: Option<u8>,
1517    pub prog_if: Option<u8>,
1518}
1519
1520impl ProbeCriteria {
1521    pub const fn any() -> Self {
1522        Self {
1523            vendor_id: None,
1524            device_id: None,
1525            class_code: None,
1526            subclass: None,
1527            prog_if: None,
1528        }
1529    }
1530
1531    fn matches(&self, dev: &PciDevice) -> bool {
1532        if self.vendor_id.is_some_and(|v| dev.vendor_id != v) {
1533            return false;
1534        }
1535        if self.device_id.is_some_and(|d| dev.device_id != d) {
1536            return false;
1537        }
1538        if self.class_code.is_some_and(|c| dev.class_code != c) {
1539            return false;
1540        }
1541        if self.subclass.is_some_and(|s| dev.subclass != s) {
1542            return false;
1543        }
1544        if self.prog_if.is_some_and(|p| dev.prog_if != p) {
1545            return false;
1546        }
1547        true
1548    }
1549}
1550
1551/// Return all devices matching `criteria`.
1552pub fn probe_all(criteria: ProbeCriteria) -> Vec<PciDevice> {
1553    with_cache(|devs| {
1554        devs.iter()
1555            .copied()
1556            .filter(|dev| criteria.matches(dev))
1557            .collect()
1558    })
1559}
1560
1561/// Return the first device matching `criteria`.
1562pub fn probe_first(criteria: ProbeCriteria) -> Option<PciDevice> {
1563    with_cache(|devs| devs.iter().copied().find(|dev| criteria.matches(dev)))
1564}
1565
1566/// Invalidate PCI cache.
1567///
1568/// Useful when hotplug/re-enumeration support is added in the future.
1569pub fn invalidate_cache() {
1570    *PCI_DEVICE_CACHE.lock() = None;
1571}