Skip to main content

strat9_kernel/arch/x86_64/
apic.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//! Local APIC (Advanced Programmable Interrupt Controller) driver
24//!
25//! Provides MMIO-based access to the Local APIC registers.
26//! The Local APIC base address is discovered via ACPI MADT and
27//! accessed through the HHDM (Higher Half Direct Map).
28
29use crate::memory;
30use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
31
32/// Whether the Local APIC has been initialized
33static APIC_INITIALIZED: AtomicBool = AtomicBool::new(false);
34/// Whether x2APIC mode is active.
35static APIC_X2_MODE: AtomicBool = AtomicBool::new(false);
36
37/// Virtual base address of the Local APIC MMIO registers
38static APIC_BASE_VIRT: AtomicU64 = AtomicU64::new(0);
39
40/// Physical base address of the Local APIC MMIO registers (used by address-space init)
41static APIC_BASE_PHYS: AtomicU64 = AtomicU64::new(0);
42/// Per-CPU shadow of xAPIC-compatible ICR high writes (destination field).
43static ICR_HIGH_SHADOW: [AtomicU32; crate::arch::x86_64::percpu::MAX_CPUS] =
44    [const { AtomicU32::new(0) }; crate::arch::x86_64::percpu::MAX_CPUS];
45
46/// Return the physical base address of the LAPIC MMIO region, or 0 if not yet initialized.
47pub fn lapic_phys() -> u64 {
48    APIC_BASE_PHYS.load(Ordering::Relaxed)
49}
50
51// ===== Local APIC Register Offsets =====
52
53/// Local APIC ID Register
54const REG_ID: u32 = 0x020;
55/// Local APIC Version Register
56#[allow(dead_code)]
57const REG_VERSION: u32 = 0x030;
58/// Task Priority Register
59const REG_TPR: u32 = 0x080;
60/// End of Interrupt Register
61const REG_EOI: u32 = 0x0B0;
62/// Spurious Interrupt Vector Register
63const REG_SPURIOUS: u32 = 0x0F0;
64/// Error Status Register
65pub const REG_ESR: u32 = 0x280;
66/// Interrupt Command Register (low)
67pub const REG_ICR_LOW: u32 = 0x300;
68/// Interrupt Command Register (high)
69pub const REG_ICR_HIGH: u32 = 0x310;
70/// LVT Timer Register
71pub const REG_LVT_TIMER: u32 = 0x320;
72/// Timer Initial Count Register
73pub const REG_TIMER_INIT: u32 = 0x380;
74/// Timer Current Count Register
75pub const REG_TIMER_CURRENT: u32 = 0x390;
76/// Timer Divide Configuration Register
77pub const REG_TIMER_DIVIDE: u32 = 0x3E0;
78
79// ===== LVT Timer Modes =====
80
81/// LVT Timer: periodic mode (bit 17)
82pub const LVT_TIMER_PERIODIC: u32 = 1 << 17;
83/// LVT Timer: masked (bit 16)
84#[allow(dead_code)]
85pub const LVT_TIMER_MASKED: u32 = 1 << 16;
86/// Dedicated Local APIC timer interrupt vector (aligned with Theseus-style setup).
87pub const LVT_TIMER_VECTOR: u8 = 0xD2;
88
89/// MSR address for APIC base
90const IA32_APIC_BASE_MSR: u32 = 0x1B;
91/// IA32_APIC_BASE physical base address mask (up to MAXPHYADDR 52 bits).
92const APIC_BASE_ADDR_MASK: u64 = 0x000F_FFFF_FFFF_F000;
93/// APIC global enable bit in IA32_APIC_BASE MSR
94const APIC_BASE_ENABLE: u64 = 1 << 11;
95/// x2APIC enable bit in IA32_APIC_BASE MSR
96const APIC_BASE_EXTD: u64 = 1 << 10;
97
98/// Spurious interrupt vector number
99const SPURIOUS_VECTOR: u8 = 0xFF;
100
101/// Vector used for cross-CPU reschedule IPIs.
102pub const IPI_RESCHED_VECTOR: u8 = 0xE0;
103
104/// Vector used for TLB shootdown IPIs.
105pub const IPI_TLB_SHOOTDOWN_VECTOR: u8 = 0xF0;
106
107/// Vector used for N3 MMU migration synchronization IPIs.
108pub const IPI_N3_MIGRATE_VECTOR: u8 = 0xF1;
109
110/// Check if APIC is present via CPUID
111pub fn is_present() -> bool {
112    let (_eax, _ebx, _ecx, edx) = super::cpuid(1, 0);
113    // CPUID.01H:EDX bit 9 = APIC
114    edx & (1 << 9) != 0
115}
116
117/// Check if x2APIC is supported via CPUID
118pub fn is_x2apic_supported() -> bool {
119    let (_eax, _ebx, ecx, _edx) = super::cpuid(1, 0);
120    // CPUID.01H:ECX bit 21 = x2APIC
121    ecx & (1 << 21) != 0
122}
123
124/// Get the current Local APIC ID.
125///
126/// When APIC is initialized, read the LAPIC ID register (authoritative at runtime).
127/// Before APIC init, fall back to CPUID initial APIC ID.
128pub fn lapic_id() -> u32 {
129    if APIC_INITIALIZED.load(Ordering::Relaxed) {
130        // SAFETY: guarded by APIC_INITIALIZED.
131        let raw = unsafe { read_reg(REG_ID) };
132        if APIC_X2_MODE.load(Ordering::Relaxed) {
133            return raw;
134        }
135        return raw >> 24;
136    }
137
138    let (_eax, ebx, _ecx, _edx) = super::cpuid(1, 0);
139    (ebx >> 24) & 0xFF
140}
141
142/// Check if the Local APIC has been initialized
143pub fn is_initialized() -> bool {
144    APIC_INITIALIZED.load(Ordering::Relaxed)
145}
146
147/// Returns true when Local APIC is running in x2APIC mode.
148pub fn is_x2apic_enabled() -> bool {
149    APIC_X2_MODE.load(Ordering::Relaxed)
150}
151
152#[inline]
153fn x2apic_msr_for_reg(offset: u32) -> Option<u32> {
154    match offset {
155        REG_ID => Some(0x802),
156        REG_VERSION => Some(0x803),
157        REG_TPR => Some(0x808),
158        REG_EOI => Some(0x80B),
159        REG_SPURIOUS => Some(0x80F),
160        REG_ESR => Some(0x828),
161        REG_LVT_TIMER => Some(0x832),
162        REG_TIMER_INIT => Some(0x838),
163        REG_TIMER_CURRENT => Some(0x839),
164        REG_TIMER_DIVIDE => Some(0x83E),
165        _ => None,
166    }
167}
168
169#[inline]
170fn current_cpu_slot() -> usize {
171    let idx = crate::arch::x86_64::percpu::current_cpu_index();
172    if idx < crate::arch::x86_64::percpu::MAX_CPUS {
173        idx
174    } else {
175        0
176    }
177}
178
179/// Read a Local APIC register
180///
181/// # Safety
182/// APIC must be initialized (base address valid and mapped).
183pub unsafe fn read_reg(offset: u32) -> u32 {
184    if APIC_X2_MODE.load(Ordering::Relaxed) {
185        return match offset {
186            REG_ICR_LOW => super::rdmsr(0x830) as u32,
187            REG_ICR_HIGH => ((super::rdmsr(0x830) >> 32) as u32) << 24,
188            _ => {
189                let Some(msr) = x2apic_msr_for_reg(offset) else {
190                    return 0;
191                };
192                super::rdmsr(msr) as u32
193            }
194        };
195    }
196
197    let addr = APIC_BASE_VIRT.load(Ordering::Relaxed) + offset as u64;
198    // SAFETY: APIC MMIO is mapped via HHDM, volatile read required for MMIO
199    unsafe { core::ptr::read_volatile(addr as *const u32) }
200}
201
202/// Write a Local APIC register
203///
204/// # Safety
205/// APIC must be initialized (base address valid and mapped).
206pub unsafe fn write_reg(offset: u32, value: u32) {
207    if APIC_X2_MODE.load(Ordering::Relaxed) {
208        match offset {
209            REG_ICR_HIGH => {
210                let cpu = current_cpu_slot();
211                // xAPIC callers write destination as apic_id << 24 in ICR high.
212                // Keep this compatibility and decode to a raw x2APIC destination id.
213                let dest = if value & 0x00FF_FFFF == 0 {
214                    value >> 24
215                } else {
216                    value
217                };
218                ICR_HIGH_SHADOW[cpu].store(dest, Ordering::Relaxed);
219            }
220            REG_ICR_LOW => {
221                let cpu = current_cpu_slot();
222                let dest = ICR_HIGH_SHADOW[cpu].load(Ordering::Relaxed) as u64;
223                super::wrmsr(0x830, (dest << 32) | value as u64);
224            }
225            _ => {
226                if let Some(msr) = x2apic_msr_for_reg(offset) {
227                    super::wrmsr(msr, value as u64);
228                }
229            }
230        }
231        return;
232    }
233
234    let addr = APIC_BASE_VIRT.load(Ordering::Relaxed) + offset as u64;
235    // SAFETY: APIC MMIO is mapped via HHDM, volatile write required for MMIO
236    unsafe { core::ptr::write_volatile(addr as *mut u32, value) }
237}
238
239/// Initialize the Local APIC.
240///
241/// `madt_lapic_addr` is the LAPIC base physical address from the MADT.
242/// We use the MSR value as authoritative but log if it differs from MADT.
243pub fn init(madt_lapic_addr: u64) {
244    // Read the APIC base MSR to get the actual physical address
245    let apic_base_msr = super::rdmsr(IA32_APIC_BASE_MSR);
246    let apic_phys = apic_base_msr & APIC_BASE_ADDR_MASK;
247
248    if apic_phys != madt_lapic_addr as u64 {
249        log::warn!(
250            "LAPIC: MSR base 0x{:X} differs from MADT 0x{:X}, using MSR",
251            apic_phys,
252            madt_lapic_addr
253        );
254    }
255
256    let use_x2apic = if is_x2apic_supported() {
257        if apic_base_msr & APIC_BASE_ENABLE == 0 {
258            super::wrmsr(IA32_APIC_BASE_MSR, apic_base_msr | APIC_BASE_ENABLE);
259        }
260        super::wrmsr(
261            IA32_APIC_BASE_MSR,
262            apic_base_msr | APIC_BASE_ENABLE | APIC_BASE_EXTD,
263        );
264        let verify = super::rdmsr(IA32_APIC_BASE_MSR);
265        verify & (APIC_BASE_ENABLE | APIC_BASE_EXTD) == (APIC_BASE_ENABLE | APIC_BASE_EXTD)
266    } else {
267        if apic_base_msr & APIC_BASE_ENABLE == 0 {
268            super::wrmsr(IA32_APIC_BASE_MSR, apic_base_msr | APIC_BASE_ENABLE);
269        }
270        false
271    };
272    APIC_X2_MODE.store(use_x2apic, Ordering::Release);
273
274    // Convert physical base to virtual via HHDM
275    let apic_virt = memory::phys_to_virt(apic_phys);
276    APIC_BASE_VIRT.store(apic_virt, Ordering::Relaxed);
277    APIC_BASE_PHYS.store(apic_phys, Ordering::Relaxed);
278
279    // Diagnostic: log HHDM and computed addresses so we can detect HHDM=0 issues.
280    crate::serial_println!(
281        "[apic] init: hhdm={:#x} lapic_phys={:#x} lapic_virt={:#x}",
282        memory::hhdm_offset(),
283        apic_phys,
284        apic_virt
285    );
286    if apic_virt == apic_phys {
287        crate::serial_println!(
288            "[apic] WARN: lapic_virt == lapic_phys (HHDM offset is 0!) \
289             The LAPIC MMIO is identity-mapped at a low address. \
290             Kernel MMIO entries will be propagated to user page tables."
291        );
292    }
293
294    // SAFETY: APIC base is now set and mapped via HHDM
295    unsafe {
296        // Clear the Error Status Register (write twice per Intel SDM)
297        write_reg(REG_ESR, 0);
298        write_reg(REG_ESR, 0);
299
300        // Set Task Priority Register to 0 (accept all interrupts)
301        write_reg(REG_TPR, 0);
302
303        // Enable the APIC: set bit 8 (APIC Software Enable) + spurious vector
304        write_reg(REG_SPURIOUS, 0x100 | SPURIOUS_VECTOR as u32);
305    }
306
307    APIC_INITIALIZED.store(true, Ordering::Relaxed);
308
309    let id = lapic_id();
310    log::info!(
311        "LAPIC: initialized at phys=0x{:X} virt=0x{:X} (ID={}, mode={})",
312        apic_phys,
313        apic_virt,
314        id,
315        if use_x2apic { "x2APIC" } else { "xAPIC" }
316    );
317}
318
319/// Initialize per-core Local APIC state on Application Processors.
320///
321/// This assumes the APIC base is already mapped and `APIC_BASE_VIRT`
322/// has been set by the BSP during `init()`.
323pub fn init_ap() {
324    if !APIC_INITIALIZED.load(Ordering::Relaxed) {
325        log::warn!("LAPIC: init_ap called before init");
326        return;
327    }
328
329    if APIC_X2_MODE.load(Ordering::Acquire) {
330        let base = super::rdmsr(IA32_APIC_BASE_MSR);
331        if base & (APIC_BASE_ENABLE | APIC_BASE_EXTD) != (APIC_BASE_ENABLE | APIC_BASE_EXTD) {
332            if base & APIC_BASE_ENABLE == 0 {
333                super::wrmsr(IA32_APIC_BASE_MSR, base | APIC_BASE_ENABLE);
334            }
335            super::wrmsr(IA32_APIC_BASE_MSR, base | APIC_BASE_ENABLE | APIC_BASE_EXTD);
336        }
337    }
338
339    // SAFETY: APIC base is mapped via HHDM and APIC is enabled.
340    unsafe {
341        write_reg(REG_ESR, 0);
342        write_reg(REG_ESR, 0);
343        write_reg(REG_TPR, 0);
344        write_reg(REG_SPURIOUS, 0x100 | SPURIOUS_VECTOR as u32);
345    }
346}
347
348/// Send End-of-Interrupt to the Local APIC
349#[inline]
350pub fn eoi() {
351    // SAFETY: APIC is initialized when this is called from interrupt handlers
352    unsafe {
353        write_reg(REG_EOI, 0);
354    }
355}
356
357/// ICR low bit 12: delivery status (1 = send pending, 0 = idle).
358const ICR_DELIVERY_PENDING: u32 = 1 << 12;
359/// Bounded poll budget for the ICR delivery-pending bit.
360const ICR_POLL_LIMIT: u32 = 1_000_000;
361
362/// Wait until the ICR delivery-pending bit clears.
363///
364/// Returns `false` if the bit stayed set for `ICR_POLL_LIMIT` iterations.
365///
366/// # Safety
367/// APIC must be initialized (base address valid and mapped).
368unsafe fn wait_icr_idle() -> bool {
369    for _ in 0..ICR_POLL_LIMIT {
370        // SAFETY: caller guarantees APIC is initialized.
371        if read_reg(REG_ICR_LOW) & ICR_DELIVERY_PENDING == 0 {
372            return true;
373        }
374        core::hint::spin_loop();
375    }
376    false
377}
378
379/// Send an IPI with a pre-built ICR low value to a specific APIC destination.
380///
381/// `icr_low` must contain delivery mode/vector/flags in xAPIC layout.
382///
383/// In xAPIC mode the whole destination+command sequence runs with IRQs
384/// disabled on the current CPU, so an IPI issued from an interrupt handler
385/// cannot interleave between the `REG_ICR_HIGH` and `REG_ICR_LOW` writes and
386/// corrupt the destination. The delivery-pending bit (ICR low bit 12) is
387/// polled before the writes (never start a send while the previous one is
388/// still pending) and after them (do not return before the send is accepted),
389/// with a bounded iteration budget. If the ICR is still pending before the
390/// send, the new command is dropped (not written over the pending one) and
391/// `false` is returned; a post-write timeout also returns `false`.
392///
393/// Returns `true` when the command was accepted by the LAPIC.
394///
395/// In x2APIC mode a single MSR write is issued, which is synchronous and
396/// already serialized by the CPU, so no polling is required.
397pub fn send_ipi_raw(target_apic_id: u32, icr_low: u32) -> bool {
398    if APIC_X2_MODE.load(Ordering::Relaxed) {
399        // x2APIC: single MSR write, synchronous (CPU blocks until dispatched).
400        // APIC is initialized when IPIs are sent.
401        super::wrmsr(0x830, ((target_apic_id as u64) << 32) | icr_low as u64);
402        return true;
403    }
404
405    // xAPIC: two-step MMIO write (destination high, then command low).
406    // IRQs are disabled for the whole sequence so no interrupt handler can
407    // insert a competing ICR write between the two registers.
408    crate::sync::with_irqs_disabled(|_| {
409        // SAFETY: APIC is initialized when IPIs are sent; IRQs are disabled.
410        unsafe {
411            if !wait_icr_idle() {
412                log::warn!(
413                    "LAPIC: ICR still pending, dropping send to APIC ID {}",
414                    target_apic_id
415                );
416                return false;
417            }
418            write_reg(REG_ICR_HIGH, target_apic_id << 24);
419            write_reg(REG_ICR_LOW, icr_low);
420            if !wait_icr_idle() {
421                log::warn!(
422                    "LAPIC: ICR did not complete for send to APIC ID {}",
423                    target_apic_id
424                );
425                return false;
426            }
427            true
428        }
429    })
430}
431
432/// Send a "reschedule now" IPI to the CPU identified by `target_apic_id`.
433///
434/// Uses Fixed delivery mode (vector `IPI_RESCHED_VECTOR`), physical destination.
435/// This is fire-and-forget : no delivery status wait is needed for reschedule
436/// IPIs because a missed IPI only delays preemption by at most one timer tick.
437///
438/// # Safety
439/// APIC must be initialized (`APIC_INITIALIZED == true`).
440///
441/// Returns `true` when the LAPIC accepted the command.
442pub fn send_resched_ipi(target_apic_id: u32) -> bool {
443    // Fixed delivery, edge-triggered, physical destination, no shorthand.
444    // Level bit = 0 (reserved for Fixed mode per Intel SDM Vol. 3A Table 10-1).
445    send_ipi_raw(target_apic_id, IPI_RESCHED_VECTOR as u32)
446}
447
448/// Send the reschedule IPI to the CURRENT CPU.
449///
450/// Used by timer IRQ handlers that must not switch context from inside an
451/// `extern "x86-interrupt"` frame (Ring-3-origin timer ticks): the IPI
452/// handler owns its own full context-save frame, so the preemption is done
453/// there instead, and the timer frame simply unwinds with iretq.
454///
455/// Returns `false` if the APIC was not initialized or the send was rejected.
456pub fn self_ipi_resched() -> bool {
457    if !is_initialized() {
458        return false;
459    }
460    send_resched_ipi(lapic_id())
461}