strat9_kernel/arch/x86_64/ioapic.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//! I/O APIC driver
24//!
25//! The I/O APIC handles routing of external hardware interrupts to
26//! Local APICs. It uses indirect MMIO: write register index to IOREGSEL,
27//! then read/write IOWIN.
28
29use crate::{acpi::madt::InterruptSourceOverride, memory};
30use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
31
32/// Whether the I/O APIC has been initialized
33static IOAPIC_INITIALIZED: AtomicBool = AtomicBool::new(false);
34
35/// Virtual base address of the I/O APIC MMIO registers
36static IOAPIC_BASE_VIRT: AtomicU64 = AtomicU64::new(0);
37
38/// GSI base for this I/O APIC
39static IOAPIC_GSI_BASE: AtomicU32 = AtomicU32::new(0);
40
41/// MADT interrupt-source overrides, stored so PCI NIC drivers can route
42/// their IRQ correctly after the APIC init phase.
43static MADT_OVERRIDES: spin::Mutex<[Option<InterruptSourceOverride>; 16]> =
44 spin::Mutex::new([None; 16]);
45
46// I/O APIC register offsets (indirect access)
47const IOREGSEL: u64 = 0x00;
48const IOWIN: u64 = 0x10;
49
50// I/O APIC registers (selected via IOREGSEL)
51const IOAPICID: u32 = 0x00;
52const IOAPICVER: u32 = 0x01;
53// Redirection table entries start at register 0x10
54// Each entry is 64 bits (two 32-bit registers): low at 0x10+2*n, high at 0x10+2*n+1
55const IOREDTBL_BASE: u32 = 0x10;
56
57// Redirection entry bit fields
58const REDIR_MASK: u64 = 1 << 16;
59const REDIR_LEVEL_TRIGGER: u64 = 1 << 15;
60const REDIR_ACTIVE_LOW: u64 = 1 << 13;
61
62/// Read an I/O APIC register (indirect access)
63///
64/// # Safety
65/// I/O APIC must be initialized.
66unsafe fn ioapic_read(reg: u32) -> u32 {
67 let base = IOAPIC_BASE_VIRT.load(Ordering::Relaxed);
68 // SAFETY: I/O APIC MMIO is mapped via HHDM
69 unsafe {
70 core::ptr::write_volatile((base + IOREGSEL) as *mut u32, reg);
71 core::ptr::read_volatile((base + IOWIN) as *const u32)
72 }
73}
74
75/// Write an I/O APIC register (indirect access)
76///
77/// # Safety
78/// I/O APIC must be initialized.
79unsafe fn ioapic_write(reg: u32, value: u32) {
80 let base = IOAPIC_BASE_VIRT.load(Ordering::Relaxed);
81 // SAFETY: I/O APIC MMIO is mapped via HHDM
82 unsafe {
83 core::ptr::write_volatile((base + IOREGSEL) as *mut u32, reg);
84 core::ptr::write_volatile((base + IOWIN) as *mut u32, value);
85 }
86}
87
88/// Read a 64-bit redirection entry
89///
90/// # Safety
91/// I/O APIC must be initialized, index must be valid.
92unsafe fn read_redir(index: u32) -> u64 {
93 let reg_low = IOREDTBL_BASE + index * 2;
94 let reg_high = IOREDTBL_BASE + index * 2 + 1;
95 // SAFETY: caller ensures valid index
96 let low = unsafe { ioapic_read(reg_low) } as u64;
97 let high = unsafe { ioapic_read(reg_high) } as u64;
98 low | (high << 32)
99}
100
101/// Write a 64-bit redirection entry
102///
103/// # Safety
104/// I/O APIC must be initialized, index must be valid.
105unsafe fn write_redir(index: u32, value: u64) {
106 let reg_low = IOREDTBL_BASE + index * 2;
107 let reg_high = IOREDTBL_BASE + index * 2 + 1;
108 // SAFETY: caller ensures valid index
109 unsafe {
110 ioapic_write(reg_low, value as u32);
111 ioapic_write(reg_high, (value >> 32) as u32);
112 }
113}
114
115/// Store the MADT interrupt-source overrides for later use by PCI NIC drivers.
116///
117/// Must be called once after MADT parsing, before any NIC init runs.
118pub fn store_madt_overrides(overrides: &[Option<InterruptSourceOverride>]) {
119 let mut dest = MADT_OVERRIDES.lock();
120 for (i, ovr) in overrides.iter().enumerate().take(16) {
121 dest[i] = ovr.clone();
122 }
123}
124
125/// Initialize the I/O APIC.
126///
127/// `phys_addr` is the I/O APIC base physical address from MADT.
128/// `gsi_base` is the first GSI handled by this I/O APIC.
129pub fn init(phys_addr: u32, gsi_base: u32) {
130 let virt_addr = memory::phys_to_virt(phys_addr as u64);
131 IOAPIC_BASE_VIRT.store(virt_addr, Ordering::Relaxed);
132 IOAPIC_GSI_BASE.store(gsi_base, Ordering::Relaxed);
133
134 // SAFETY: I/O APIC MMIO is mapped via HHDM
135 let id = unsafe { ioapic_read(IOAPICID) >> 24 };
136 let ver_reg = unsafe { ioapic_read(IOAPICVER) };
137 let version = ver_reg & 0xFF;
138 let max_redir = ((ver_reg >> 16) & 0xFF) + 1;
139
140 // Mask all interrupts initially
141 for i in 0..max_redir {
142 // SAFETY: index within max_redir
143 unsafe {
144 let entry = read_redir(i);
145 write_redir(i, entry | REDIR_MASK);
146 }
147 }
148
149 IOAPIC_INITIALIZED.store(true, Ordering::Relaxed);
150
151 log::info!(
152 "I/O APIC: id={}, version={}, {} entries, GSI base={}, virt=0x{:X}",
153 id,
154 version,
155 max_redir,
156 gsi_base,
157 virt_addr
158 );
159}
160
161/// Route a GSI to a specific LAPIC and vector.
162///
163/// `gsi` is the Global System Interrupt number.
164/// `lapic_id` is the destination LAPIC ID.
165/// `vector` is the interrupt vector (0x20+).
166/// `trigger` is the trigger mode (0=edge, 1=level).
167/// `polarity` is the polarity (0=active high, 1=active low).
168pub fn route_irq(gsi: u32, lapic_id: u32, vector: u8, trigger: u8, polarity: u8) {
169 let gsi_base = IOAPIC_GSI_BASE.load(Ordering::Relaxed);
170 if gsi < gsi_base {
171 log::warn!("I/O APIC: GSI {} below base {}", gsi, gsi_base);
172 return;
173 }
174 let index = gsi - gsi_base;
175
176 // Build redirection entry:
177 // [7:0] vector
178 // [10:8] delivery mode (000 = fixed)
179 // [11] destination mode (0 = physical)
180 // [13] polarity (0 = active high, 1 = active low)
181 // [15] trigger mode (0 = edge, 1 = level)
182 // [16] mask (0 = enabled)
183 // [63:56] destination LAPIC ID
184 let mut entry: u64 = vector as u64;
185
186 if polarity == 0x03 || polarity == 1 {
187 entry |= REDIR_ACTIVE_LOW;
188 }
189 if trigger == 0x03 || trigger == 1 {
190 entry |= REDIR_LEVEL_TRIGGER;
191 }
192
193 // Destination in bits [63:56]
194 entry |= (lapic_id as u64) << 56;
195
196 // SAFETY: I/O APIC is initialized, index is valid
197 unsafe {
198 write_redir(index, entry);
199 }
200
201 log::debug!(
202 "I/O APIC: GSI{} -> vec 0x{:02X}, LAPIC {}, pol={}, trig={}",
203 gsi,
204 vector,
205 lapic_id,
206 polarity,
207 trigger
208 );
209}
210
211/// Route a legacy ISA IRQ, applying MADT interrupt source overrides.
212///
213/// This handles the common case of IRQ0=>GSI2 remapping on QEMU q35.
214pub fn route_legacy_irq(
215 irq: u8,
216 lapic_id: u32,
217 vector: u8,
218 overrides: &[Option<InterruptSourceOverride>],
219) {
220 // Check if there's a source override for this IRQ
221 let (gsi, polarity, trigger) = find_override(irq, overrides);
222
223 route_irq(gsi, lapic_id, vector, trigger, polarity);
224
225 if gsi != irq as u32 {
226 log::info!("I/O APIC: IRQ{} remapped to GSI{} (override)", irq, gsi);
227 }
228}
229
230/// Find the override for a legacy IRQ, returning (gsi, polarity, trigger).
231fn find_override(irq: u8, overrides: &[Option<InterruptSourceOverride>]) -> (u32, u8, u8) {
232 for ovr in overrides {
233 if let Some(ref o) = ovr {
234 if o.irq_source == irq {
235 return (o.gsi, o.polarity(), o.trigger_mode());
236 }
237 }
238 }
239 // No override: GSI == IRQ, ISA defaults (edge, active high)
240 (irq as u32, 0, 0)
241}
242
243/// Mask a legacy IRQ, resolving MADT overrides to the correct GSI.
244pub fn mask_legacy_irq(irq: u8, overrides: &[Option<InterruptSourceOverride>]) {
245 let (gsi, _, _) = find_override(irq, overrides);
246 mask_irq(gsi);
247 log::debug!("I/O APIC: masked legacy IRQ{} (GSI{})", irq, gsi);
248}
249
250/// Mask a GSI (disable the interrupt)
251pub fn mask_irq(gsi: u32) {
252 let gsi_base = IOAPIC_GSI_BASE.load(Ordering::Relaxed);
253 if gsi < gsi_base {
254 return;
255 }
256 let index = gsi - gsi_base;
257 // SAFETY: I/O APIC is initialized
258 unsafe {
259 let entry = read_redir(index);
260 write_redir(index, entry | REDIR_MASK);
261 }
262}
263
264/// Unmask a GSI (enable the interrupt)
265#[allow(dead_code)]
266pub fn unmask_irq(gsi: u32) {
267 let gsi_base = IOAPIC_GSI_BASE.load(Ordering::Relaxed);
268 if gsi < gsi_base {
269 return;
270 }
271 let index = gsi - gsi_base;
272 // SAFETY: I/O APIC is initialized
273 unsafe {
274 let entry = read_redir(index);
275 write_redir(index, entry & !REDIR_MASK);
276 }
277}
278
279/// Route a PCI NIC interrupt through the I/O APIC using stored MADT overrides.
280///
281/// `irq` is the PCI interrupt line (from `pci_dev.interrupt_line`).
282/// `vector` is the IDT vector to route to (typically `PIC1_OFFSET + irq` for
283/// legacy IRQs, or `irq` itself for MSI / GSIs ≥ 16).
284///
285/// This should be called from the NIC driver's `init()` after the device is
286/// registered, with interrupts on the device-side already masked via IMC so
287/// no stray IRQ arrives before the handler is live.
288pub fn route_nic_irq(irq: u8, vector: u8) {
289 let lapic_id = super::apic::lapic_id();
290 let overrides = MADT_OVERRIDES.lock();
291 route_legacy_irq(irq, lapic_id, vector, &overrides[..]);
292}
293// MADT_OVERRIDES guard dropped here : overrides no longer needed.