garage44.eu/jeroen/pinnacle

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

.. /kernel/src/x86_64/ioapic.rs

raw

//! The I/O APICs: where a PC's wired interrupts arrive (the keyboard
//! controller's, ACPI's SCI, a PCI device's INTx), each pin ("global
//! system interrupt", GSI) sent on to a core as a vector. Every PCI device
//! Pinnacle drives signals by message instead (MSI-X, MSI), past them; the
//! pins are for what has no other way. ACPI's MADT lists the I/O APICs,
//! and where an ISA interrupt is not on the pin of its number, says so
//! (an "interrupt source override": the timer's IRQ 0 on pin 2, the SCI's
//! level and polarity). Every pin starts masked; [`route`] opens one.

use crate::sync::SpinLock;
use alloc::vec::Vec;

const SELECT: usize = 0x00;
const WINDOW: usize = 0x10;
const VERSION: u32 = 0x01;
const REDIRECTION: u32 = 0x10;

const MASKED: u64 = 1 << 16;
const LEVEL: u64 = 1 << 15;
const ACTIVE_LOW: u64 = 1 << 13;

struct IoApic {
    /// Its registers, in the direct map.
    base: usize,
    /// Its first pin's GSI, and how many pins it has.
    first: u32,
    pins: u32,
}

impl IoApic {
    fn read(&self, register: u32) -> u32 {
        // SAFETY: the I/O APIC's two registers, mapped uncached (the
        // fourth GiB); the lock of `APICS` keeps select and window paired.
        unsafe {
            ((self.base + SELECT) as *mut u32).write_volatile(register);
            ((self.base + WINDOW) as *const u32).read_volatile()
        }
    }

    fn write(&self, register: u32, value: u32) {
        // SAFETY: as in `read`.
        unsafe {
            ((self.base + SELECT) as *mut u32).write_volatile(register);
            ((self.base + WINDOW) as *mut u32).write_volatile(value);
        }
    }

    fn set_entry(&self, pin: u32, entry: u64) {
        // The high half (the destination) first, so the entry is never
        // unmasked with half of it old.
        self.write(REDIRECTION + 2 * pin, MASKED as u32);
        self.write(REDIRECTION + 2 * pin + 1, (entry >> 32) as u32);
        self.write(REDIRECTION + 2 * pin, entry as u32);
    }
}

struct State {
    apics: Vec<IoApic>,
    /// The MADT's overrides: ISA IRQ, its GSI, its MPS flags.
    overrides: Vec<(u8, u32, u16)>,
}

static APICS: SpinLock<State> = SpinLock::new(State {
    apics: Vec::new(),
    overrides: Vec::new(),
});

/// Takes the I/O APICs the MADT lists (registers, first GSI) and its ISA
/// overrides, every pin masked. Returns how many pins there are.
pub fn init(apics: &[(u64, u32)], overrides: &[(u8, u32, u16)]) -> u32 {
    let mut state = APICS.lock();
    for &(physical, first) in apics {
        let mut apic = IoApic {
            base: crate::mmu::virt(physical as usize),
            first,
            pins: 0,
        };
        apic.pins = (apic.read(VERSION) >> 16 & 0xff) + 1;
        for pin in 0..apic.pins {
            apic.set_entry(pin, MASKED);
        }
        state.apics.push(apic);
    }
    state.overrides = overrides.to_vec();
    state.apics.iter().map(|a| a.pins).sum()
}

/// How a pin is triggered.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Trigger {
    pub level: bool,
    pub active_low: bool,
}

/// ISA's own: edge, active high.
pub const ISA: Trigger = Trigger {
    level: false,
    active_low: false,
};

/// ACPI's SCI unless an override says otherwise: level, active low.
pub const SCI: Trigger = Trigger {
    level: true,
    active_low: true,
};

/// The GSI and trigger of ISA interrupt `irq`, `default` its trigger where
/// the MADT does not say: its override, else its own pin.
pub fn isa(irq: u8, default: Trigger) -> (u32, Trigger) {
    let state = APICS.lock();
    let Some(&(_, gsi, flags)) = state.overrides.iter().find(|o| o.0 == irq) else {
        return (u32::from(irq), default);
    };
    // MPS flags: polarity in bits 0–1 (1 high, 3 low), trigger in 2–3
    // (1 edge, 3 level); 0 is the bus's own.
    let active_low = match flags & 3 {
        1 => false,
        3 => true,
        _ => default.active_low,
    };
    let level = match flags >> 2 & 3 {
        1 => false,
        3 => true,
        _ => default.level,
    };
    (gsi, Trigger { level, active_low })
}

/// Sends GSI `gsi` to core 0's APIC as `vector`, triggered as `trigger`.
/// False when no I/O APIC has the pin.
pub fn route(gsi: u32, vector: u32, trigger: Trigger) -> bool {
    let state = APICS.lock();
    let Some(apic) = state
        .apics
        .iter()
        .find(|a| (a.first..a.first + a.pins).contains(&gsi))
    else {
        return false;
    };
    // Fixed delivery, physical destination: core 0's APIC ID in the top
    // byte (an x2APIC ID above 255 needs interrupt remapping, which a
    // laptop's boot core never has).
    let destination = u64::from(crate::smp::apic_id(0) & 0xff) << 56;
    let mut entry = destination | u64::from(vector & 0xff);
    if trigger.level {
        entry |= LEVEL;
    }
    if trigger.active_low {
        entry |= ACTIVE_LOW;
    }
    apic.set_entry(gsi - apic.first, entry);
    true
}