garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /kernel/src/pci.rs

raw

//! PCI Express, on either architecture: its configuration space through
//! ECAM (each function's 4 KiB at bus << 20 | device << 15 | function << 12),
//! found in the device tree's `pci-host-ecam-generic` node on ARM and in
//! ACPI's MCFG on a PC. Every function is scanned, its memory windows
//! (BARs) sized and, where no firmware assigned them (ARM's QEMU has none),
//! placed in the host's 32-bit window from the device tree's `ranges`; each
//! is listed with the other devices (`device`), as `pciVVVV,DDDD`.
//!
//! A function's interrupt is its INTx pin, routed by the device tree's
//! `interrupt-map` to a GIC interrupt on ARM; on a PC, where that routing is
//! ACPI's bytecode, a driver asks for a message interrupt (MSI-X) instead
//! (`gic::message_interrupt`).

use crate::device::{self, Class, Device};
use crate::sync::SpinLock;
use alloc::string::String;
use alloc::vec::Vec;

/// One function on the bus.
#[derive(Clone)]
pub struct Function {
    pub bus: u8,
    pub device: u8,
    pub function: u8,
    /// Its configuration space, as the kernel maps it.
    config: usize,
    pub vendor: u16,
    pub id: u16,
    /// Class, subclass and programming interface.
    pub class: u32,
    /// Its memory windows: physical address and size (0: none).
    pub bars: [(u64, u64); 6],
    /// Its INTx interrupt, routed (ARM), if it has a pin.
    pub intx: Option<u32>,
}

impl Function {
    pub fn read32(&self, offset: usize) -> u32 {
        // SAFETY: this function's configuration space, mapped uncached.
        unsafe { ((self.config + offset) as *const u32).read_volatile() }
    }

    pub fn write32(&self, offset: usize, value: u32) {
        // SAFETY: as in `read32`.
        unsafe { ((self.config + offset) as *mut u32).write_volatile(value) }
    }

    pub fn read8(&self, offset: usize) -> u8 {
        (self.read32(offset & !3) >> (8 * (offset & 3))) as u8
    }

    pub fn read16(&self, offset: usize) -> u16 {
        (self.read32(offset & !3) >> (8 * (offset & 2))) as u16
    }

    pub fn write16(&self, offset: usize, value: u16) {
        let word = self.read32(offset & !3);
        let shift = 8 * (offset & 2);
        self.write32(
            offset & !3,
            (word & !(0xffff << shift)) | (u32::from(value) << shift),
        );
    }

    /// Its capabilities: (ID, offset in configuration space).
    pub fn capabilities(&self) -> impl Iterator<Item = (u8, usize)> + '_ {
        const STATUS_CAPABILITIES: u16 = 1 << 4;
        let mut at = if self.read16(0x06) & STATUS_CAPABILITIES != 0 {
            usize::from(self.read8(0x34) & 0xfc)
        } else {
            0
        };
        let mut seen = 0;
        core::iter::from_fn(move || {
            // At most 48 fit in the 192 bytes; a loop is a broken list.
            if at < 0x40 || seen == 48 {
                return None;
            }
            seen += 1;
            let here = at;
            at = usize::from(self.read8(here + 1) & 0xfc);
            Some((self.read8(here), here))
        })
    }

    /// The kernel's address of `offset` into BAR `bar`, if it has one.
    pub fn bar_address(&self, bar: usize, offset: u64) -> Option<usize> {
        let (address, size) = *self.bars.get(bar)?;
        (size != 0 && offset < size).then(|| crate::mmu::virt((address + offset) as usize))
    }

    /// Turns on its memory decoding and its bus mastering (DMA), and turns
    /// INTx off when it will signal by message.
    pub fn enable(&self, intx: bool) {
        const MEMORY: u16 = 1 << 1;
        const BUS_MASTER: u16 = 1 << 2;
        const INTX_DISABLE: u16 = 1 << 10;
        let mut command = self.read16(0x04) | MEMORY | BUS_MASTER;
        if intx {
            command &= !INTX_DISABLE;
        } else {
            command |= INTX_DISABLE;
        }
        self.write16(0x04, command);
    }

    /// Points MSI-X table entry `entry` at `address` with `data`, unmasked,
    /// and turns MSI-X on. False if the function has no MSI-X.
    pub fn msix(&self, entry: usize, address: u64, data: u32) -> bool {
        const MSIX: u8 = 0x11;
        let Some((_, cap)) = self.capabilities().find(|&(id, _)| id == MSIX) else {
            return false;
        };
        let table = self.read32(cap + 4);
        let Some(at) = self.bar_address((table & 7) as usize, u64::from(table & !7) + 16 * entry as u64)
        else {
            return false;
        };
        // SAFETY: the function's MSI-X table entry, in its BAR.
        unsafe {
            let e = at as *mut u32;
            e.write_volatile(address as u32);
            e.add(1).write_volatile((address >> 32) as u32);
            e.add(2).write_volatile(data);
            e.add(3).write_volatile(0);
        }
        const ENABLE: u16 = 1 << 15;
        const MASK_ALL: u16 = 1 << 14;
        self.write16(cap + 2, (self.read16(cap + 2) | ENABLE) & !MASK_ALL);
        true
    }

    /// Points its MSI (one message) at `address` with `data` and turns it
    /// on: for a function with MSI and no MSI-X (an AHCI controller). False
    /// if it has none.
    pub fn msi(&self, address: u64, data: u32) -> bool {
        const MSI: u8 = 0x05;
        let Some((_, cap)) = self.capabilities().find(|&(id, _)| id == MSI) else {
            return false;
        };
        const WIDE: u16 = 1 << 7;
        let control = self.read16(cap + 2);
        self.write32(cap + 4, address as u32);
        let data_at = if control & WIDE != 0 {
            self.write32(cap + 8, (address >> 32) as u32);
            cap + 12
        } else {
            cap + 8
        };
        self.write16(data_at, data as u16);
        // One message (Multiple Message Enable 0), enabled.
        self.write16(cap + 2, (control & !(7 << 4)) | 1);
        true
    }

    /// Its interrupt, as its driver should take it: a message (MSI-X, else
    /// MSI) where the architecture takes them, else its INTx; bus mastering
    /// and memory decoding turned on. The INTID (or vector) that arrives,
    /// or None when it has no way to interrupt.
    pub fn take_interrupt(&self) -> Option<u32> {
        let message = crate::gic::message_interrupt().and_then(|(address, data, vector)| {
            (self.msix(0, address, data) || self.msi(address, data)).then_some(vector)
        });
        self.enable(message.is_none());
        message.or(self.intx)
    }
}

static FUNCTIONS: SpinLock<Vec<Function>> = SpinLock::new(Vec::new());

/// Where the host's configuration space is, its buses, the 32-bit memory
/// window BARs may be placed in (ARM), and its INTx routing.
pub struct Host {
    pub ecam: u64,
    pub buses: (u8, u8),
    pub window: Option<(u64, u64)>,
    pub interrupt_map: Option<&'static [u8]>,
    pub interrupt_mask: Option<&'static [u8]>,
}

fn be32(b: &[u8], at: usize) -> u32 {
    u32::from_be_bytes(b[at..at + 4].try_into().unwrap())
}

fn be64(b: &[u8], at: usize) -> u64 {
    u64::from(be32(b, at)) << 32 | u64::from(be32(b, at + 4))
}

/// The host as the device tree describes it.
pub fn host_from_device_tree() -> Option<Host> {
    let node = device::find("pci-host-ecam-generic")?;
    device::mark(&node.name, "pci", Class::Other);
    let &(ecam, size) = node.regs.first()?;
    if ecam + size > crate::mmu::MAPPED_GIB << 30 {
        crate::println!("pci: the configuration window at {ecam:#x} lies above what the kernel maps");
        return None;
    }
    let buses = node
        .property("bus-range")
        .filter(|b| b.len() == 8)
        .map_or((0, ((size >> 20).max(1) - 1).min(255) as u8), |b| {
            (be32(b, 0) as u8, be32(b, 4) as u8)
        });
    // `ranges`: the PCI address (3 cells, the first saying the space), the
    // CPU's (2) and the size (2). The 32-bit memory space is 0b10.
    let window = node.property("ranges").and_then(|r| {
        r.as_chunks::<28>()
            .0
            .iter()
            .map(|e| &e[..])
            .find(|e| (be32(e, 0) >> 24) & 3 == 0b10)
            .map(|e| (be64(e, 12), be64(e, 20)))
    });
    Some(Host {
        ecam: ecam as u64,
        buses,
        window,
        interrupt_map: node.property("interrupt-map"),
        interrupt_mask: node.property("interrupt-map-mask"),
    })
}

/// The GIC interrupt `interrupt-map` routes pin `pin` (1–4) of the
/// function at `bdf` to. Its entries are the child's unit address (3
/// cells) and pin (1), the parent's phandle (1), unit address (2, as the
/// GIC has #address-cells = 2 on the machines run so far) and interrupt
/// (3, the GIC's).
fn route(host: &Host, bdf: u32, pin: u8) -> Option<u32> {
    let map = host.interrupt_map?;
    let mask = host.interrupt_mask.filter(|m| m.len() == 16)?;
    let (mask_hi, mask_pin) = (be32(mask, 0), be32(mask, 12));
    let child = (bdf << 8) & mask_hi;
    map.as_chunks::<40>()
        .0
        .iter()
        .map(|e| &e[..])
        .find(|e| be32(e, 0) == child && be32(e, 12) == u32::from(pin) & mask_pin)
        .and_then(|e| match be32(e, 28) {
            0 => Some(be32(e, 32) + 32),
            1 => Some(be32(e, 32) + 16),
            _ => None,
        })
}

/// Sizes BAR `i` of `f` (writing all ones and reading back), placing it at
/// `next` in the window when it has no address yet. Returns how many BAR
/// slots it took (2 for a 64-bit one).
fn size_bar(f: &mut Function, i: usize, next: &mut Option<(u64, u64)>) -> usize {
    let offset = 0x10 + 4 * i;
    let original = f.read32(offset);
    if original & 1 != 0 {
        return 1; // I/O space: not used.
    }
    let wide = (original >> 1) & 3 == 0b10;
    f.write32(offset, u32::MAX);
    let mut mask = u64::from(f.read32(offset) & !0xf);
    f.write32(offset, original);
    let mut address = u64::from(original & !0xf);
    if wide {
        let high = f.read32(offset + 4);
        f.write32(offset + 4, u32::MAX);
        mask |= u64::from(f.read32(offset + 4)) << 32;
        f.write32(offset + 4, high);
        address |= u64::from(high) << 32;
    } else {
        mask |= 0xffff_ffff_0000_0000;
    }
    let size = (!mask).wrapping_add(1);
    if mask == 0 || size == 0 {
        return if wide { 2 } else { 1 };
    }
    if address == 0
        && let Some((at, end)) = next
    {
        let placed = at.next_multiple_of(size);
        if placed + size <= *end {
            address = placed;
            *at = placed + size;
            f.write32(offset, address as u32 | (original & 0xf));
            if wide {
                f.write32(offset + 4, (address >> 32) as u32);
            }
        }
    }
    if address != 0 {
        f.bars[i] = (address, size);
    }
    if wide { 2 } else { 1 }
}

/// Scans the host's buses: every function found, sized, placed, listed.
/// Returns how many.
pub fn scan(host: &Host) -> usize {
    let mut window = host.window.map(|(at, size)| (at, at + size));
    let mut found = Vec::new();
    for bus in host.buses.0..=host.buses.1 {
        for dev in 0..32u8 {
            for function in 0..8u8 {
                let bdf = u32::from(bus) << 8 | u32::from(dev) << 3 | u32::from(function);
                let config = crate::mmu::virt((host.ecam + (u64::from(bdf) << 12)) as usize);
                // SAFETY: the function's first word in the ECAM window.
                let ids = unsafe { (config as *const u32).read_volatile() };
                if ids & 0xffff == 0xffff {
                    if function == 0 {
                        break;
                    }
                    continue;
                }
                let mut f = Function {
                    bus,
                    device: dev,
                    function,
                    config,
                    vendor: ids as u16,
                    id: (ids >> 16) as u16,
                    class: 0,
                    bars: [(0, 0); 6],
                    intx: None,
                };
                f.class = f.read32(0x08) >> 8;
                let header = f.read8(0x0e);
                if header & 0x7f == 0 {
                    let mut i = 0;
                    while i < 6 {
                        i += size_bar(&mut f, i, &mut window);
                    }
                    let pin = f.read8(0x3d);
                    if pin != 0 {
                        f.intx = route(host, bdf, pin);
                    }
                }
                device::add(Device {
                    name: alloc::format!("pci@{bus:02x}:{dev:02x}.{function}"),
                    compatible: alloc::vec![
                        alloc::format!("pci{:04x},{:04x}", f.vendor, f.id),
                        String::from(class_name(f.class)),
                    ],
                    regs: f
                        .bars
                        .iter()
                        .filter(|b| b.1 != 0)
                        .map(|&(a, s)| (a as usize, s as usize))
                        .collect(),
                    interrupts: f.intx.into_iter().collect(),
                    driver: None,
                    properties: Vec::new(),
                });
                found.push(f);
                // A single-function device answers for every function.
                if function == 0 && header & 0x80 == 0 {
                    break;
                }
            }
        }
    }
    let count = found.len();
    FUNCTIONS.lock().extend(found);
    count
}

/// What a class code says a function is, roughly, for the device list.
fn class_name(class: u32) -> &'static str {
    match class >> 16 {
        0x01 => "pci-storage",
        0x02 => "pci-network",
        0x03 => "pci-display",
        0x04 => "pci-multimedia",
        0x06 => "pci-bridge",
        0x07 => "pci-communication",
        0x09 => "pci-input",
        0x0c => "pci-serial-bus",
        _ => "pci-other",
    }
}

/// The functions from `vendor` with an ID in `ids`, as found.
pub fn find(vendor: u16, ids: core::ops::RangeInclusive<u16>) -> Vec<Function> {
    FUNCTIONS
        .lock()
        .iter()
        .filter(|f| f.vendor == vendor && ids.contains(&f.id))
        .cloned()
        .collect()
}

/// The functions of class `class` (class, subclass and programming
/// interface: 0x010802 an NVMe controller), as found.
pub fn find_class(class: u32) -> Vec<Function> {
    FUNCTIONS
        .lock()
        .iter()
        .filter(|f| f.class == class)
        .cloned()
        .collect()
}

/// Marks the function as `driver`'s in the device list.
pub fn claim(f: &Function, driver: &'static str, class: Class) {
    device::mark(
        &alloc::format!("pci@{:02x}:{:02x}.{}", f.bus, f.device, f.function),
        driver,
        class,
    );
}