Skip to main content

strat9_kernel/arch/x86_64/
idt.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//! Interrupt Descriptor Table (IDT) for Strat9-OS
24//!
25//! Handles CPU exceptions and hardware IRQs.
26//! Inspired by MaestroOS `idt.rs` and Redox-OS kernel.
27
28use super::{pic, tss};
29use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
30use x86_64::{
31    structures::{
32        gdt::SegmentSelector,
33        idt::{InterruptDescriptorTable, InterruptStackFrame, PageFaultErrorCode},
34    },
35    VirtAddr,
36};
37
38/// Kernel code segment selector for IDT entries.
39///
40/// At IDT init time the kernel runs under the UEFI firmware's GDT (CS=0x38),
41/// but we intentionally use the **kernel's** selector (0x08) so that once
42/// `gdt::init()` loads the real GDT the IDT entries are immediately valid.
43///
44/// Before `gdt::init()`, any exception will triple-fault because CS=0x08
45/// references a non-existent descriptor in the UEFI GDT.  That is acceptable:
46/// there should be no exceptions before the kernel GDT is live (the only
47/// known early #UD from `init_serial` / `uart_16550` is already disabled).
48const KERNEL_CODE_SELECTOR: SegmentSelector = SegmentSelector(0x08);
49
50#[repr(C, packed)]
51struct Idtr {
52    limit: u16,
53    base: u64,
54}
55
56#[derive(Clone, Copy, Debug)]
57pub struct LiveIdtGateInfo {
58    pub vector: u8,
59    pub selector: u16,
60    pub options: u16,
61    pub offset: u64,
62}
63
64/// IRQ interrupt vector numbers (PIC1_OFFSET + IRQ number)
65#[allow(dead_code)]
66pub mod irq {
67    pub const TIMER: u8 = super::pic::PIC1_OFFSET; // IRQ0 = 0x20
68    pub const KEYBOARD: u8 = super::pic::PIC1_OFFSET + 1; // IRQ1 = 0x21
69    pub const CASCADE: u8 = super::pic::PIC1_OFFSET + 2; // IRQ2 = 0x22
70    pub const MOUSE: u8 = super::pic::PIC1_OFFSET + 12; // IRQ12 = 0x2C
71    pub const COM2: u8 = super::pic::PIC1_OFFSET + 3; // IRQ3 = 0x23
72    pub const COM1: u8 = super::pic::PIC1_OFFSET + 4; // IRQ4 = 0x24
73    pub const FLOPPY: u8 = super::pic::PIC1_OFFSET + 6; // IRQ6 = 0x26
74    pub const ATA_PRIMARY: u8 = super::pic::PIC1_OFFSET + 14; // IRQ14 = 0x2E
75    pub const ATA_SECONDARY: u8 = super::pic::PIC1_OFFSET + 15; // IRQ15 = 0x2F
76}
77
78/// RAII guard: swap GS to kernel on entry if we came from Ring 3, and restore
79/// user GS automatically on drop (covers every exit path including early returns).
80///
81/// # Why this is needed
82/// After `swapgs ; iretq` in the Ring-3 trampoline:
83///   - `IA32_GS_BASE`        = 0  (user GS base, inactive)
84///   - `IA32_KERNEL_GS_BASE` = kernel per-CPU pointer
85/// When an interrupt fires from Ring 3, the CPU does NOT automatically call
86/// swapgs.  The first `gs:[0]` access (e.g. in `current_cpu_index`) would
87/// dereference virtual address 0 => page fault => double fault => triple fault.
88///
89/// # Safety
90/// Must be constructed **before** any `gs:[…]` access in the handler.
91/// `InterruptStackFrame::code_segment` is a plain memory read from the
92/// interrupt stack : it does not access GS.
93struct SwapGsGuard {
94    from_ring3: bool,
95}
96
97impl SwapGsGuard {
98    /// Construct.  If `from_ring3` is true, executes `swapgs` immediately to
99    /// restore the kernel per-CPU GS base.
100    #[inline(always)]
101    fn new(from_ring3: bool) -> Self {
102        if from_ring3 {
103            // SAFETY: we are in Ring 0 with interrupts disabled (standard for
104            // interrupt handlers).  GS_BASE currently points at user space (0);
105            // swapgs gives us the kernel per-CPU block via KERNEL_GS_BASE.
106            unsafe { core::arch::asm!("swapgs", options(nostack, preserves_flags)) };
107            // Userspace can run with AC=1 (SMAP override).  If we entered from
108            // Ring 3, clear it so the kernel cannot inherit a disabled SMAP.
109            // `clac()` is CPUID-gated, so this is a no-op on CPUs without SMAP.
110            crate::arch::clac();
111        }
112        Self { from_ring3 }
113    }
114}
115
116impl Drop for SwapGsGuard {
117    #[inline(always)]
118    fn drop(&mut self) {
119        if self.from_ring3 {
120            // SAFETY: Symmetric to the constructor.  Restores user GS_BASE so
121            // that iretq returns to Ring 3 with the correct GS state.
122            unsafe { core::arch::asm!("swapgs", options(nostack, preserves_flags)) };
123        }
124    }
125}
126
127/// Determine whether `swapgs` is needed at interrupt/exception entry.
128///
129/// In the normal case, `code_segment & 3 == 3` (Ring 3) means we need
130/// swapgs.  However, between `swapgs` and `iretq` in
131/// `elf_ring3_trampoline`, CS is still Ring 0 but `IA32_GS_BASE` is
132/// already the user value (0).  If `iretq` itself faults, the exception
133/// handler sees CS=Ring 0 but GS=user : the simple ring check misses
134/// this.  Reading `IA32_GS_BASE` via `rdmsr` catches both cases.
135///
136/// Cost: ~20-30 cycles for the `rdmsr` : acceptable in exception paths
137/// (not used for high-frequency IRQ handlers where IF=0 prevents
138/// firing in the swapgs=>iretq window).
139#[inline(always)]
140fn needs_swapgs(cs: u16) -> bool {
141    // Fast path: Ring 3 => always need swapgs.
142    if (cs & 3) == 3 {
143        return true;
144    }
145    // Slow path: a low `IA32_GS_BASE` is *not* enough to conclude "user GS":
146    // during early boot (BSP/AP before `percpu::init`) both GS bases are 0.
147    // Misclassifying that as the swapgs window made unrelated faults (e.g. a
148    // `#GP` from a bad WRMSR at 0.01s) take the fatal "SWAPGS-WINDOW" path.
149    // The window only exists when the *kernel* GS base is still installed in
150    // IA32_KERNEL_GS_BASE, i.e. `swapgs` already ran but we are still Ring 0.
151    let gs_base = read_msr(0xC000_0101); // IA32_GS_BASE
152    if gs_base >= 0xFFFF_8000_0000_0000 {
153        return false;
154    }
155    let kernel_gs_base = read_msr(0xC000_0102); // IA32_KERNEL_GS_BASE
156    kernel_gs_base >= 0xFFFF_8000_0000_0000
157}
158
159/// Read a 64-bit MSR. Callers guarantee the MSR is supported at Ring 0.
160#[inline(always)]
161fn read_msr(msr: u32) -> u64 {
162    let lo: u32;
163    let hi: u32;
164    // SAFETY: `rdmsr` is privileged, executed in Ring 0 exception context.
165    unsafe {
166        core::arch::asm!(
167            "rdmsr",
168            in("ecx") msr,
169            out("eax") lo,
170            out("edx") hi,
171            options(nostack, preserves_flags),
172        );
173    }
174    (lo as u64) | ((hi as u64) << 32)
175}
176
177/// Combined IDT storage + lock in a single struct to prevent memory corruption.
178/// The `static mut InterruptDescriptorTable` initialization was corrupting
179/// the adjacent `AtomicBool` lock.
180#[repr(C)]
181struct IdtStorage {
182    lock: AtomicBool,
183    idt: InterruptDescriptorTable,
184}
185
186static mut IDT_STORAGE: IdtStorage = IdtStorage {
187    lock: AtomicBool::new(false),
188    idt: InterruptDescriptorTable::new(),
189};
190static USER_PF_TRACE_BUDGET: AtomicU32 = AtomicU32::new(64);
191static RESCHED_IPI_TRACE_BUDGET: AtomicU32 = AtomicU32::new(32);
192
193pub fn live_gate_info(vector: u8) -> Option<LiveIdtGateInfo> {
194    let mut idtr = Idtr { limit: 0, base: 0 };
195    // SAFETY: `sidt` is a privileged register read with no side effect.
196    unsafe {
197        core::arch::asm!(
198            "sidt [{}]",
199            in(reg) &mut idtr,
200            options(nostack, preserves_flags),
201        );
202    }
203
204    let entry_offset = vector as usize * 16;
205
206    if entry_offset + 16 > idtr.limit as usize + 1 {
207        return None;
208    }
209
210    // SAFETY: The IDTR base/limit were read from the CPU and bounds-checked above.
211    let (low, high) = unsafe {
212        let entry_ptr = (idtr.base + entry_offset as u64) as *const u64;
213        (
214            core::ptr::read_unaligned(entry_ptr),
215            core::ptr::read_unaligned(entry_ptr.add(1)),
216        )
217    };
218
219    let offset = (low & 0xFFFF) | (((low >> 48) & 0xFFFF) << 16) | ((high & 0xFFFF_FFFF) << 32);
220    let selector = ((low >> 16) & 0xFFFF) as u16;
221    let options = ((low >> 32) & 0xFFFF) as u16;
222
223    Some(LiveIdtGateInfo {
224        vector,
225        selector,
226        options,
227        offset,
228    })
229}
230
231/// Decision returned by the raw interrupt trampolines.
232///
233/// Phase 1 of the preemptive scheduler refactor only wires the raw timer/IPI
234/// stubs and returns `next_rsp = 0`, which means "restore the current
235/// interrupt frame and return with iretq". The future interrupt-aware scheduler
236/// path will return a non-zero `next_rsp` and matching FPU buffers.
237#[repr(C)]
238#[derive(Clone, Copy, Debug, Default)]
239pub struct InterruptReturnDecision {
240    pub next_rsp: u64,
241    pub old_fpu: *mut u8,
242    pub new_fpu: *const u8,
243    /// XCR0 mask of the outgoing task. `0` is normalized to `3` in the stub,
244    /// mirroring `switch_context_xsave`.
245    pub old_xcr0: u64,
246    /// XCR0 mask of the incoming task. `0` is normalized to `3` in the stub.
247    pub new_xcr0: u64,
248    /// Non-zero when the CPU supports XSAVE: selects `xsave`/`xrstor` in the
249    /// naked switch epilogue. Zero selects the legacy `fxsave`/`fxrstor`.
250    pub use_xsave: u64,
251}
252
253const _: () = {
254    assert!(core::mem::size_of::<InterruptReturnDecision>() == 48);
255    assert!(core::mem::align_of::<InterruptReturnDecision>() == 8);
256};
257
258/// Raw Local APIC timer interrupt entry.
259///
260/// Saves registers in exactly the same order as `SyscallFrame`, calls the Rust
261/// inner handler, then restores the interrupted context and returns with
262/// `iretq`. This avoids the `extern "x86-interrupt"` ABI mismatch with the
263/// legacy `ret`-based scheduler switch path.
264#[unsafe(naked)]
265unsafe extern "C" fn lapic_timer_entry() -> ! {
266    core::arch::naked_asm!(
267        "cld",
268        // Hardware IRQ stack frame at entry:
269        //   [rsp+0]  = RIP
270        //   [rsp+8]  = CS
271        //   [rsp+16] = RFLAGS
272        //   [rsp+24] = RSP
273        //   [rsp+32] = SS
274        // If interrupted from Ring 3, restore kernel GS before any percpu use.
275        "test qword ptr [rsp + 8], 0x3",
276        "jz 2f",
277        "swapgs",
278        // Coming from Ring 3: userspace may have AC=1 (the SMAP override).
279        // Clear it before running any kernel code. `btr` on memory is legal
280        // on CPUs without SMAP, unlike `clac`.
281        "pushfq",
282        "btr qword ptr [rsp], 18",
283        "popfq",
284        "2:",
285        // Save GPRs in reverse order so that final RSP points at a SyscallFrame.
286        "push rax",
287        "push rcx",
288        "push rdx",
289        "push rdi",
290        "push rsi",
291        "push r8",
292        "push r9",
293        "push r10",
294        "push r11",
295        "push rbx",
296        "push rbp",
297        "push r12",
298        "push r13",
299        "push r14",
300        "push r15",
301        // SysV large-struct return uses an implicit out-pointer in RDI.
302        // Reserve 48 bytes (InterruptReturnDecision) and keep RSP 16-byte
303        // aligned before `call`.
304        "sub rsp, 48",
305        "mov rdi, rsp",
306        "lea rsi, [rsp + 48]",
307        "call {inner}",
308        // Load returned InterruptReturnDecision fields.
309        "mov rax, [rsp + 0]",  // next_rsp
310        "mov rdx, [rsp + 8]",  // old_fpu
311        "mov rcx, [rsp + 16]", // new_fpu
312        "mov r8,  [rsp + 24]", // old_xcr0
313        "mov r9,  [rsp + 32]", // new_xcr0
314        "mov r10, [rsp + 40]", // use_xsave
315        "add rsp, 48",
316        "test rax, rax",
317        "jz 3f",
318        // Context-switch path: save the outgoing task's extended state, pivot
319        // to the incoming task's kernel stack, restore its extended state.
320        // The whole path runs with IF=0, so scratch registers stay intact.
321        "mov rdi, rdx", // old_fpu save area
322        "mov rsi, rcx", // new_fpu save area
323        "mov r11, rax", // preserve next_rsp across the FPU code
324        "test r10, r10",
325        "jz 9f", // use_xsave == 0 -> legacy fxsave/fxrstor
326        // XSAVE path: same sequence as switch_context_xsave. Normalize 0 -> 3.
327        "test r8, r8",
328        "jnz 5f",
329        "mov r8, 3",
330        "5:",
331        "test r9, r9",
332        "jnz 6f",
333        "mov r9, 3",
334        "6:",
335        "mov rbx, r8",  // normalized old_xcr0 (for the xsetbv compare)
336        "mov eax, r8d", // EDX:EAX = old_xcr0
337        "shr r8, 32",
338        "mov edx, r8d",
339        "xsave [rdi]",
340        "mov rsp, r11", // pivot to the incoming task's stack
341        "cmp r9, rbx",  // program new XCR0 only if it differs
342        "je 7f",
343        "mov ecx, 0",
344        "mov eax, r9d",
345        "mov r8, r9",
346        "shr r8, 32",
347        "mov edx, r8d",
348        "xsetbv",
349        "7:",
350        "mov eax, r9d", // EDX:EAX = new_xcr0
351        "mov r8, r9",
352        "shr r8, 32",
353        "mov edx, r8d",
354        "xrstor [rsi]",
355        "call {switch_finish}",
356        "jmp 3f",
357        "9:",
358        // FXSAVE path (XSAVE unavailable): x87/SSE only.
359        "fxsave [rdi]",
360        "mov rsp, r11",
361        "fxrstor [rsi]",
362        "call {switch_finish}",
363        "3:",
364        // No context switch (rax == 0): skip FPU save/restore entirely.
365        // The interrupted task's FPU state remains unchanged.
366        // Restore current SyscallFrame.
367        "pop r15",
368        "pop r14",
369        "pop r13",
370        "pop r12",
371        "pop rbp",
372        "pop rbx",
373        "pop r11",
374        "pop r10",
375        "pop r9",
376        "pop r8",
377        "pop rsi",
378        "pop rdi",
379        "pop rdx",
380        "pop rcx",
381        "pop rax",
382        // Restore user GS iff we are returning to Ring 3.
383        "test qword ptr [rsp + 8], 0x3",
384        "jz 4f",
385        "swapgs",
386        "4:",
387        "iretq",
388        inner = sym lapic_timer_inner,
389        switch_finish = sym crate::process::scheduler::finish_interrupt_switch,
390    );
391}
392
393/// Raw reschedule IPI entry.
394///
395/// Uses the same `SyscallFrame` layout as the timer entry. Phase 1 only marks
396/// a reschedule hint and returns to the interrupted context.
397#[unsafe(naked)]
398unsafe extern "C" fn resched_ipi_entry() -> ! {
399    core::arch::naked_asm!(
400        "cld",
401        "test qword ptr [rsp + 8], 0x3",
402        "jz 2f",
403        "swapgs",
404        // Coming from Ring 3: userspace may have AC=1 (the SMAP override).
405        // Clear it before running any kernel code. `btr` on memory is legal
406        // on CPUs without SMAP, unlike `clac`.
407        "pushfq",
408        "btr qword ptr [rsp], 18",
409        "popfq",
410        "2:",
411        "push rax",
412        "push rcx",
413        "push rdx",
414        "push rdi",
415        "push rsi",
416        "push r8",
417        "push r9",
418        "push r10",
419        "push r11",
420        "push rbx",
421        "push rbp",
422        "push r12",
423        "push r13",
424        "push r14",
425        "push r15",
426        "sub rsp, 48",
427        "mov rdi, rsp",
428        "lea rsi, [rsp + 48]",
429        "call {inner}",
430        "mov rax, [rsp + 0]",
431        "mov rdx, [rsp + 8]",
432        "mov rcx, [rsp + 16]",
433        "add rsp, 48",
434        "test rax, rax",
435        "jz 3f",
436        // Non-fatal diagnostic: next_rsp != 0 in reschedule IPI path.
437        // Phase 1 contract: resched_ipi_hint only, no context switch.
438        "push rax",
439        "mov al, 0x21",   /* '!' : unexpected switch decision */
440        "out 0xe9, al",
441        "pop rax",
442        "jmp 3f",
443        "3:",
444        "pop r15",
445        "pop r14",
446        "pop r13",
447        "pop r12",
448        "pop rbp",
449        "pop rbx",
450        "pop r11",
451        "pop r10",
452        "pop r9",
453        "pop r8",
454        "pop rsi",
455        "pop rdi",
456        "pop rdx",
457        "pop rcx",
458        "pop rax",
459        "test qword ptr [rsp + 8], 0x3",
460        "jz 4f",
461        "swapgs",
462        "4:",
463        "iretq",
464        inner = sym resched_ipi_inner,
465    );
466}
467
468extern "C" fn lapic_timer_inner(
469    frame: &mut crate::syscall::SyscallFrame,
470) -> InterruptReturnDecision {
471    let cpu = crate::arch::x86_64::percpu::current_cpu_index();
472    let ticks = crate::process::scheduler::ticks();
473    // Heartbeat: single byte only. e9_println!/format_args in IRQ can cause issues.
474    let from_ring3 = (frame.iret_cs & 3) == 3;
475    if from_ring3 && (ticks < 5 || ticks % 100 == 0) {
476        if crate::debug_cfg::E9_TRACE { unsafe { core::arch::asm!("mov al, 0x48; out 0xe9, al", out("al") _) } } // 'H'
477    }
478    crate::process::scheduler::timer_tick();
479    crate::arch::x86_64::speaker::speaker_tick();
480    // N3 watchdog: check for stalled migrations every tick.
481    crate::ipc::n3::n3_watchdog_tick();
482    super::apic::eoi();
483
484    // Deliver pending POSIX signals before returning to Ring 3 via iretq.
485    // On this IRQ-return path we only perform deliveries that are safe from
486    // timer interrupt context; fatal/default actions remain deferred to the
487    // normal syscall-side delivery path, which may kill/switch the current
488    // task and is not yet validated on the raw timer-iret path.
489    if from_ring3 {
490        crate::process::signal::deliver_pending_signal_on_interrupt_return(frame);
491    }
492
493    // Ring-3 preemption: a user task that spins without making syscalls
494    // never consumes a posted hint, so the CPU would spin forever and the
495    // shell would never be scheduled again. Run the full pick/switch from
496    // this raw naked timer stub via maybe_preempt_from_interrupt: it saves
497    // the outgoing task's frame pointer, picks the next task, seeds a
498    // kernel interrupt frame for first-launch tasks, and returns an
499    // iretq-compatible decision that the naked epilogue applies
500    // (fxsave -> rsp pivot -> fxrstor -> finish_interrupt_switch -> iretq).
501    //
502    // Ring-3-origin ticks take this path unconditionally. The interrupted
503    // Ring-3 frame is iretq-restorable by construction (the CPU pushed a
504    // clean IRET frame at entry, and SwapGsGuard restored kernel GS).
505    // Ring-0-origin ticks (interrupted kernel code) keep the hint path:
506    // resuming synthetic kernel frames from here is still not validated
507    // (same-CPL iretq does not restore RSP/SS).
508    if from_ring3 {
509        if let Some(decision) = crate::process::scheduler::maybe_preempt_from_interrupt(cpu, frame)
510        {
511            if decision.next_rsp != 0 {
512                // TEMP DEBUG: dump the resume iret frame (rip/rsp) before switching.
513                if crate::debug_cfg::E9_TRACE { unsafe {
514                    let base = decision.next_rsp;
515                    let iret_rip = *(base as *const u64).add(15); // after 15 GPRs
516                    let iret_rsp = *(base as *const u64).add(18); // rip,cs,rflags,rsp
517                    let hex = b"0123456789abcdef";
518                    core::arch::asm!("out 0xe9, al", in("al") b'@', options(nomem, nostack));
519                    core::arch::asm!("out 0xe9, al", in("al") b'R', options(nomem, nostack));
520                    for sh in [28usize, 24, 20, 16, 12, 8, 4, 0] {
521                        let nib = hex[((iret_rip >> sh) & 0xF) as usize];
522                        core::arch::asm!("out 0xe9, al", in("al") nib, options(nomem, nostack));
523                    }
524                    core::arch::asm!("out 0xe9, al", in("al") b'/', options(nomem, nostack));
525                    for sh in [28usize, 24, 20, 16, 12, 8, 4, 0] {
526                        let nib = hex[((iret_rsp >> sh) & 0xF) as usize];
527                        core::arch::asm!("out 0xe9, al", in("al") nib, options(nomem, nostack));
528                    }
529                    core::arch::asm!("out 0xe9, al", in("al") b'\n', options(nomem, nostack));
530                } }
531                return decision;
532            }
533        }
534    }
535    crate::process::scheduler::request_force_resched_hint(cpu);
536    InterruptReturnDecision::default()
537}
538
539#[inline(never)]
540extern "C" fn resched_ipi_inner(
541    frame: &mut crate::syscall::SyscallFrame,
542) -> InterruptReturnDecision {
543    let cpu = crate::arch::x86_64::percpu::current_cpu_index();
544    let should_trace = RESCHED_IPI_TRACE_BUDGET
545        .try_update(Ordering::AcqRel, Ordering::Relaxed, |budget| {
546            budget.checked_sub(1)
547        })
548        .is_ok();
549    if should_trace {
550        let rsp0 = crate::arch::x86_64::tss::kernel_stack_for(cpu)
551            .map(|addr| addr.as_u64())
552            .unwrap_or(0);
553        let (slot_rip, slot_cs, slot_rsp, slot_ss) = if rsp0 >= 40 {
554            // SAFETY: rsp0 points at the top of the current CPU's kernel stack.
555            // During a Ring3->Ring0 interrupt, the CPU-saved IRET frame lives at
556            // [rsp0-40 .. rsp0-8]. We only read those 5 u64 words for diagnosis.
557            unsafe {
558                let frame_base = (rsp0 - 40) as *const u64;
559                (
560                    *frame_base.add(0),
561                    *frame_base.add(1),
562                    *frame_base.add(3),
563                    *frame_base.add(4),
564                )
565            }
566        } else {
567            (0, 0, 0, 0)
568        };
569        crate::e9_println!(
570            "[ipi-rsp0] cpu={} rsp0={:#x} slot_rip={:#x} slot_cs={:#x} slot_rsp={:#x} slot_ss={:#x} frame_rip={:#x} frame_cs={:#x} frame_rsp={:#x} frame_ss={:#x}",
571            cpu,
572            rsp0,
573            slot_rip,
574            slot_cs,
575            slot_rsp,
576            slot_ss,
577            frame.iret_rip,
578            frame.iret_cs,
579            frame.iret_rsp,
580            frame.iret_ss,
581        );
582    }
583    super::apic::eoi();
584    crate::process::scheduler::request_force_resched_hint(cpu);
585    InterruptReturnDecision::default()
586}
587
588#[inline]
589fn lock_idt_storage() {
590    // SAFETY: Only the lock field of the static mut is accessed through a raw
591    // pointer. It is an AtomicBool, so concurrent access is safe by design.
592    let lock = unsafe { core::ptr::addr_of_mut!(IDT_STORAGE.lock) };
593    while unsafe { (*lock).compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) }
594        .is_err()
595    {
596        core::hint::spin_loop();
597    }
598}
599
600#[inline]
601fn unlock_idt_storage() {
602    // SAFETY: Only the lock field of the static mut is accessed through a raw
603    // pointer, and the IDT storage lock is held.
604    let lock = unsafe { core::ptr::addr_of_mut!(IDT_STORAGE.lock) };
605    unsafe { (*lock).store(false, Ordering::Release) };
606}
607
608pub fn init() {
609    lock_idt_storage();
610    unsafe {
611        let idt = &raw mut IDT_STORAGE.idt;
612
613        // CPU exceptions
614        crate::e9_println!("IDT BP");
615        (*idt)
616            .breakpoint
617            .set_handler_fn(breakpoint_handler)
618            .set_code_selector(KERNEL_CODE_SELECTOR);
619        crate::e9_println!("IDT PF");
620        (*idt)
621            .page_fault
622            .set_handler_fn(page_fault_handler)
623            .set_code_selector(KERNEL_CODE_SELECTOR);
624        crate::e9_println!("IDT GP");
625        (*idt)
626            .general_protection_fault
627            .set_handler_fn(general_protection_fault_handler)
628            .set_code_selector(KERNEL_CODE_SELECTOR);
629        (*idt)
630            .stack_segment_fault
631            .set_handler_fn(stack_segment_fault_handler)
632            .set_code_selector(KERNEL_CODE_SELECTOR);
633        (*idt)
634            .non_maskable_interrupt
635            .set_handler_fn(non_maskable_interrupt_handler)
636            .set_code_selector(KERNEL_CODE_SELECTOR);
637        (*idt)
638            .invalid_opcode
639            .set_handler_fn(invalid_opcode_handler)
640            .set_code_selector(KERNEL_CODE_SELECTOR);
641        crate::e9_println!("IDT DF");
642        (*idt)
643            .double_fault
644            .set_handler_fn(double_fault_handler)
645            .set_code_selector(KERNEL_CODE_SELECTOR)
646            .set_stack_index(tss::DOUBLE_FAULT_IST_INDEX);
647
648        // Hardware IRQs (PIC remapped to 0x20+)
649        let idt_ref = &mut *idt;
650        idt_ref[irq::TIMER as u8]
651            .set_handler_fn(legacy_timer_handler)
652            .set_code_selector(KERNEL_CODE_SELECTOR);
653        idt_ref[irq::KEYBOARD as u8]
654            .set_handler_fn(keyboard_handler)
655            .set_code_selector(KERNEL_CODE_SELECTOR);
656        idt_ref[irq::MOUSE as u8]
657            .set_handler_fn(mouse_handler)
658            .set_code_selector(KERNEL_CODE_SELECTOR);
659
660        // Spurious interrupt handler at vector 0xFF (APIC spurious vector)
661        idt_ref[0xFF_u8]
662            .set_handler_fn(spurious_handler)
663            .set_code_selector(KERNEL_CODE_SELECTOR);
664
665        // Cross-CPU reschedule IPI (vector 0xE0)
666
667        idt_ref[super::apic::IPI_RESCHED_VECTOR as u8]
668            .set_handler_addr(VirtAddr::from_ptr(resched_ipi_entry as *const ()))
669            .set_code_selector(KERNEL_CODE_SELECTOR);
670
671        // Cross-CPU TLB shootdown IPI (vector 0xF0)
672        idt_ref[super::apic::IPI_TLB_SHOOTDOWN_VECTOR as u8]
673            .set_handler_fn(tlb_shootdown_handler)
674            .set_code_selector(KERNEL_CODE_SELECTOR);
675
676        // N3 MMU migration sync IPI (vector 0xF1) : naked handler
677        // for full sender context restore via iretq.
678        idt_ref[super::apic::IPI_N3_MIGRATE_VECTOR as u8]
679            .set_handler_addr(VirtAddr::from_ptr(
680                crate::ipc::n3::n3_migrate_ipi_entry as *const (),
681            ))
682            .set_code_selector(KERNEL_CODE_SELECTOR);
683
684        crate::e9_println!("IDT pre-load");
685        (*idt).load_unsafe();
686        crate::e9_println!("IDT loaded");
687    }
688    crate::e9_println!("IDT unlock");
689    unlock_idt_storage();
690    crate::e9_println!("IDT unlocked");
691
692    crate::e9_println!("IDT done");
693}
694
695pub fn load() {
696    lock_idt_storage();
697    unsafe {
698        let idt = &raw const IDT_STORAGE.idt;
699        (*idt).load_unsafe();
700    }
701    unlock_idt_storage();
702}
703
704/// Register the Local APIC timer IRQ vector to use the timer handler.
705pub fn register_lapic_timer_vector(vector: u8) {
706    lock_idt_storage();
707    unsafe {
708        let idt = &raw mut IDT_STORAGE.idt;
709        (&mut *idt)[vector]
710            .set_handler_addr(VirtAddr::from_ptr(lapic_timer_entry as *const ()))
711            .set_code_selector(KERNEL_CODE_SELECTOR);
712        (*idt).load_unsafe();
713    }
714    unlock_idt_storage();
715}
716
717/// Register the AHCI storage controller IRQ handler.
718///
719/// Called after AHCI initialisation once the PCI interrupt line is known.
720pub fn register_ahci_irq(irq: u8) {
721    let vector = if irq < 16 {
722        super::pic::PIC1_OFFSET + irq
723    } else {
724        irq
725    };
726
727    lock_idt_storage();
728    unsafe {
729        let idt = &raw mut IDT_STORAGE.idt;
730        (&mut *idt)[vector]
731            .set_handler_fn(ahci_handler)
732            .set_code_selector(KERNEL_CODE_SELECTOR);
733        (*idt).load_unsafe();
734    }
735    unlock_idt_storage();
736    log::info!("AHCI IRQ {} registered on vector {:#x}", irq, vector);
737}
738
739/// Register the NVMe storage controller IRQ handler for a specific vector.
740///
741/// Used when MSI/MSI-X is active : the vector comes directly from
742/// `msi::probe_and_enable()` instead of being derived from the IRQ line.
743pub fn register_nvme_irq_vector(vector: u8) {
744    lock_idt_storage();
745    unsafe {
746        let idt = &raw mut IDT_STORAGE.idt;
747        (&mut *idt)[vector]
748            .set_handler_fn(nvme_handler)
749            .set_code_selector(KERNEL_CODE_SELECTOR);
750        unlock_idt_storage();
751    }
752    log::info!("NVMe IRQ vector {:#x} registered", vector);
753}
754
755/// Register the NVMe storage controller IRQ handler.
756///
757/// Called after NVMe initialisation once the PCI interrupt line is known.
758pub fn register_nvme_irq(irq: u8) {
759    let vector = if irq < 16 {
760        super::pic::PIC1_OFFSET + irq
761    } else {
762        irq
763    };
764
765    lock_idt_storage();
766    unsafe {
767        let idt = &raw mut IDT_STORAGE.idt;
768        (&mut *idt)[vector]
769            .set_handler_fn(nvme_handler)
770            .set_code_selector(KERNEL_CODE_SELECTOR);
771        (*idt).load_unsafe();
772    }
773    unlock_idt_storage();
774    log::info!("NVMe IRQ {} registered on vector {:#x}", irq, vector);
775}
776
777/// Register the VirtIO block device IRQ handler
778///
779/// Called after VirtIO block device initialization to route the device's
780/// IRQ to the correct handler.
781pub fn register_virtio_block_irq(irq: u8) {
782    // PCI INTx gives an IRQ line number (typically 0..15), while IDT expects
783    // a vector number. Map legacy IRQ lines to the remapped interrupt vectors.
784    let vector = if irq < 16 {
785        super::pic::PIC1_OFFSET + irq
786    } else {
787        irq
788    };
789
790    lock_idt_storage();
791    unsafe {
792        let idt = &raw mut IDT_STORAGE.idt;
793        (&mut *idt)[vector]
794            .set_handler_fn(virtio_block_handler)
795            .set_code_selector(KERNEL_CODE_SELECTOR);
796        (*idt).load_unsafe();
797    }
798    unlock_idt_storage();
799    log::info!("VirtIO-blk IRQ {} registered on vector {:#x}", irq, vector);
800}
801
802/// Register the xHCI USB controller IRQ handler.
803///
804/// Called after xHCI initialization once the PCI interrupt line is known.
805/// Register the xHCI interrupt handler for a specific vector (MSI/MSI-X).
806pub fn register_xhci_irq_vector(vector: u8) {
807    lock_idt_storage();
808    unsafe {
809        let idt = &raw mut IDT_STORAGE.idt;
810        (&mut *idt)[vector]
811            .set_handler_fn(xhci_handler)
812            .set_code_selector(KERNEL_CODE_SELECTOR);
813        (*idt).load_unsafe();
814    }
815    unlock_idt_storage();
816    log::info!("xHCI IRQ vector {:#x} registered", vector);
817}
818
819pub fn register_xhci_irq(irq: u8) {
820    let vector = if irq < 16 {
821        super::pic::PIC1_OFFSET + irq
822    } else {
823        irq
824    };
825
826    lock_idt_storage();
827    unsafe {
828        let idt = &raw mut IDT_STORAGE.idt;
829        (&mut *idt)[vector]
830            .set_handler_fn(xhci_handler)
831            .set_code_selector(KERNEL_CODE_SELECTOR);
832        (*idt).load_unsafe();
833    }
834    unlock_idt_storage();
835    log::info!("xHCI IRQ {} registered on vector {:#x}", irq, vector);
836}
837
838/// Register the NIC IRQ handler.
839///
840/// Called after a NIC driver successfully initialises and has read its
841/// PCI interrupt line.  The handler reads ICR and sends EOI; actual
842/// receive processing is triggered via the driver's `receive()` method
843/// which the network stack calls when `handle_interrupt()` signals
844/// that packets are available.
845pub fn register_nic_irq(irq: u8) {
846    let vector = if irq < 16 {
847        super::pic::PIC1_OFFSET + irq
848    } else {
849        irq
850    };
851
852    lock_idt_storage();
853    unsafe {
854        let idt = &raw mut IDT_STORAGE.idt;
855        (&mut *idt)[vector]
856            .set_handler_fn(nic_handler)
857            .set_code_selector(KERNEL_CODE_SELECTOR);
858        (*idt).load_unsafe();
859    }
860    unlock_idt_storage();
861    log::info!("NIC IRQ {} registered on vector {:#x}", irq, vector);
862}
863
864// =============================================
865// CPU Exception Handlers
866// =============================================
867
868/// Performs the breakpoint handler operation.
869extern "x86-interrupt" fn breakpoint_handler(stack_frame: InterruptStackFrame) {
870    let _gs = SwapGsGuard::new(needs_swapgs(stack_frame.code_segment.0));
871    log::warn!("EXCEPTION: BREAKPOINT\n{:#?}", stack_frame);
872}
873
874/// Performs the invalid opcode handler operation.
875///
876/// SAFETY: This handler uses ONLY raw asm for diagnostic output (no
877/// `log::error!`, no `e9_println!`, no `Port::write`). The `Port::write`
878/// path from the x86_64 crate can trigger re-entrant `#UD` in exception
879/// context, causing an infinite fault loop. Raw `out 0xe9, al` is safe.
880extern "x86-interrupt" fn invalid_opcode_handler(stack_frame: InterruptStackFrame) {
881    let cs = stack_frame.code_segment.0;
882    let is_user = (cs & 3) == 3;
883    let _gs = SwapGsGuard::new(needs_swapgs(cs));
884    if is_user {
885        if let Some(tid) = crate::process::current_task_id() {
886            crate::silo::handle_user_fault(
887                tid,
888                crate::silo::SiloFaultReason::InvalidOpcode,
889                stack_frame.instruction_pointer.as_u64(),
890                0,
891                stack_frame.instruction_pointer.as_u64(),
892            );
893            return;
894        }
895    }
896    // Emit raw e9 marker so we can confirm the handler fires.
897    crate::e9_mark!(b'#');
898    crate::e9_mark!(b'U');
899    crate::e9_mark!(b'D');
900    // Emit the faulting RIP as raw bytes (little-endian u64) for diagnosis.
901    // Use ONLY inline asm : no Rust function calls, no format_args, no
902    // to_le_bytes() : to avoid identity-mapped function pointer issues.
903    let rip: u64 = stack_frame.instruction_pointer.as_u64();
904    unsafe {
905        core::arch::asm!(
906            "out 0xe9, al",
907            "shr rcx, 8",
908            "mov al, cl",
909            "out 0xe9, al",
910            "shr rcx, 8",
911            "mov al, cl",
912            "out 0xe9, al",
913            "shr rcx, 8",
914            "mov al, cl",
915            "out 0xe9, al",
916            "shr rcx, 8",
917            "mov al, cl",
918            "out 0xe9, al",
919            "shr rcx, 8",
920            "mov al, cl",
921            "out 0xe9, al",
922            "shr rcx, 8",
923            "mov al, cl",
924            "out 0xe9, al",
925            "shr rcx, 8",
926            "mov al, cl",
927            "out 0xe9, al",
928            inout("rcx") rip => _,
929            in("al") rip as u8,
930            options(nostack, nomem),
931        );
932    }
933    // Halt forever.
934    loop {
935        crate::arch::hlt();
936    }
937}
938
939extern "x86-interrupt" fn non_maskable_interrupt_handler(stack_frame: InterruptStackFrame) {
940    // NMI can fire at any point : including the swapgs=>iretq window.
941    // Use rdmsr to safely restore kernel GS if needed.
942    let _gs = SwapGsGuard::new(needs_swapgs(stack_frame.code_segment.0));
943    if crate::boot::panic::panic_in_progress() {
944        crate::arch::x86_64::cli();
945        loop {
946            crate::arch::x86_64::hlt();
947        }
948    }
949    // Unexpected NMI (watchdog, PMU, spurious SERR, ...): log and resume.
950    // Halting here would silently kill a healthy CPU. The SwapGsGuard drop
951    // restores user GS on the normal return path.
952    let rip = stack_frame.instruction_pointer.as_u64();
953    let cs = stack_frame.code_segment.0;
954    crate::serial_force_println!("[NMI] rip={:#x} cs={:#x}", rip, cs);
955    log::warn!("[NMI] unexpected NMI rip={:#x} cs={:#x}", rip, cs);
956}
957
958/// Performs the page fault handler operation.
959extern "x86-interrupt" fn page_fault_handler(
960    stack_frame: InterruptStackFrame,
961    error_code: PageFaultErrorCode,
962) {
963    use x86_64::registers::control::Cr2;
964    let cs = stack_frame.code_segment.0;
965    let is_user = (cs & 3) == 3;
966    // SAFETY: must be before any gs:[...] access – GS may point to user memory
967    // if the fault fired from Ring 3 (after swapgs in elf_ring3_trampoline),
968    // OR during the swapgs=>iretq window (CS=Ring0 but GS=user).
969    // needs_swapgs() uses rdmsr to catch both cases.
970    let swapgs_needed = needs_swapgs(cs);
971    let _gs = SwapGsGuard::new(swapgs_needed);
972    {
973        let thr: u16 = 0x3F8;
974        let lsr: u16 = 0x3F8 + 5;
975        for &b in b"[PF]" {
976            let mut s: u8 = 0;
977            let mut i = 0u32;
978            loop {
979                unsafe {
980                    core::arch::asm!("in al, dx", out("al") s, in("dx") lsr, options(nomem, nostack, preserves_flags));
981                }
982                if s & 0x20 != 0 || i > 500000 {
983                    break;
984                }
985                i += 1;
986            }
987            unsafe {
988                core::arch::asm!("out dx, al", in("dx") thr, in("al") b, options(nomem, nostack, preserves_flags));
989            }
990        }
991    }
992
993    // Detect the swapgs=>iretq window: CS=Ring0 but GS was user (0).
994    if swapgs_needed && !is_user {
995        let fault_addr = x86_64::registers::control::Cr2::read()
996            .as_ref()
997            .map(|v| v.as_u64())
998            .unwrap_or(0);
999        crate::serial_force_println!(
1000            "\x1b[31;1m[pagefault]\x1b[0m SWAPGS-WINDOW: CS={:#x} (Ring0) but GS was user! rip={:#x} addr={:#x} err={:#x}",
1001            cs,
1002            stack_frame.instruction_pointer.as_u64(),
1003            fault_addr,
1004            error_code.bits()
1005        );
1006
1007        // Kill the faulting process instead of panicking the kernel.
1008        // The page fault is unrecoverable in this window: we cannot return
1009        // to Ring 3 because the IRETQ frame or a user page is invalid.
1010        // Keep SwapGsGuard alive until AFTER current_task_clone to avoid
1011        // a second #PF from current_cpu_index() reading gs:[0] (kernel GS
1012        // is still needed for percpu access during the kill path).
1013        if let Some(task) = crate::process::current_task_clone() {
1014            crate::process::kill_task(task.id);
1015        }
1016        drop(_gs);
1017        crate::process::scheduler::exit_current_task(-11); // SIGSEGV
1018    }
1019
1020    // Get the faulting address
1021    let fault_addr = Cr2::read();
1022    let fault_vaddr = fault_addr.as_ref().map(|v| v.as_u64()).unwrap_or(0);
1023    let rip = stack_frame.instruction_pointer.as_u64();
1024    let user_rsp = stack_frame.stack_pointer.as_u64();
1025
1026    let mut trace_ctx = crate::trace::TraceTaskCtx::empty();
1027    if is_user {
1028        if let Some(task) = crate::process::current_task_clone() {
1029            let as_ref = task.process.address_space_arc();
1030            trace_ctx = crate::trace::TraceTaskCtx {
1031                task_id: task.id.as_u64(),
1032                pid: task.pid,
1033                tid: task.tid,
1034                cr3: as_ref.cr3().as_u64(),
1035            };
1036        }
1037    }
1038
1039    let do_pf_trace = if is_user {
1040        USER_PF_TRACE_BUDGET
1041            .try_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
1042                if v > 0 {
1043                    Some(v - 1)
1044                } else {
1045                    None
1046                }
1047            })
1048            .is_ok()
1049    } else {
1050        true
1051    };
1052    if do_pf_trace {
1053        crate::trace_mem!(
1054            crate::trace::category::MEM_PF,
1055            crate::trace::TraceKind::MemPageFault,
1056            error_code.bits() as u64,
1057            trace_ctx,
1058            rip,
1059            fault_vaddr,
1060            user_rsp,
1061            0
1062        );
1063    }
1064
1065    // Try COW only for write-protection faults on already-present pages.
1066    // For not-present faults, demand paging should run first.
1067    if error_code.contains(PageFaultErrorCode::PROTECTION_VIOLATION)
1068        && error_code.contains(PageFaultErrorCode::CAUSED_BY_WRITE)
1069        && is_user
1070    {
1071        if let Some(task) = crate::process::current_task_clone() {
1072            let address_space = task.process.address_space_arc();
1073            if let Ok(vaddr) = fault_addr {
1074                match crate::syscall::fork::handle_cow_fault(vaddr.as_u64(), &address_space) {
1075                    Ok(()) => {
1076                        crate::trace_mem!(
1077                            crate::trace::category::MEM_COW,
1078                            crate::trace::TraceKind::MemCow,
1079                            1,
1080                            trace_ctx,
1081                            rip,
1082                            vaddr.as_u64(),
1083                            0,
1084                            0
1085                        );
1086                        return;
1087                    }
1088                    Err(reason) => {
1089                        crate::trace_mem!(
1090                            crate::trace::category::MEM_COW,
1091                            crate::trace::TraceKind::MemCow,
1092                            0,
1093                            trace_ctx,
1094                            rip,
1095                            vaddr.as_u64(),
1096                            0,
1097                            0
1098                        );
1099                        crate::serial_println!(
1100                            "\x1b[31m[pagefault] COW resolve failed\x1b[0m: task={} \x1b[36mpid={}\x1b[0m tid={} \x1b[35maddr={:#x}\x1b[0m \x1b[35mrip={:#x}\x1b[0m err={}",
1101                            task.id.as_u64(),
1102                            task.pid,
1103                            task.tid,
1104                            vaddr.as_u64(),
1105                            stack_frame.instruction_pointer.as_u64(),
1106                            reason
1107                        );
1108                    }
1109                }
1110            }
1111        }
1112    }
1113
1114    if is_user {
1115        if let Some(task) = crate::process::current_task_clone() {
1116            let address_space = task.process.address_space_arc();
1117            if let Ok(vaddr) = fault_addr {
1118                if do_pf_trace {
1119                    // FORCE OUTPUT for the first user faults only; lazy demand paging can
1120                    // legitimately fault thousands of times during boot and flood serial.
1121                    crate::serial_force_println!(
1122                        "\x1b[33m[pagefault] USER fault\x1b[0m: tid={} rip={:#x} addr={:#x} err={:#x}",
1123                        task.tid,
1124                        rip,
1125                        vaddr.as_u64(),
1126                        error_code.bits()
1127                    );
1128                    // Mirror to e9 so the first handled faults stay visible in e9_debug.log.
1129                    crate::e9_println!(
1130                        "[PF] tid={} rip={:#x} addr={:#x} err={:#x}",
1131                        task.tid,
1132                        rip,
1133                        vaddr.as_u64(),
1134                        error_code.bits()
1135                    );
1136                }
1137
1138                // Demand paging only resolves missing pages. A present page
1139                // with forbidden access must not take handle_fault's
1140                // already-mapped success path and retry forever. COW was
1141                // attempted above for recoverable write-protection faults.
1142                let resolution = if error_code.contains(PageFaultErrorCode::PROTECTION_VIOLATION) {
1143                    Err("Unresolved user page protection violation")
1144                } else {
1145                    address_space.handle_fault(vaddr.as_u64())
1146                };
1147                match resolution {
1148                    Ok(()) => {
1149                        if do_pf_trace {
1150                            crate::serial_force_println!(
1151                                "\x1b[32m[pagefault] USER fault resolved\x1b[0m: tid={} addr={:#x}",
1152                                task.tid,
1153                                vaddr.as_u64()
1154                            );
1155                        }
1156                        return;
1157                    }
1158                    Err(e) => {
1159                        crate::serial_force_println!(
1160                            "\x1b[31m[pagefault] USER fault resolution FAILED\x1b[0m: tid={} addr={:#x} err={:?}",
1161                            task.tid,
1162                            vaddr.as_u64(),
1163                            e
1164                        );
1165                        crate::e9_println!(
1166                            "[PF-FAIL] tid={} rip={:#x} addr={:#x}",
1167                            task.tid,
1168                            rip,
1169                            vaddr.as_u64()
1170                        );
1171                        dump_user_pf_context(&address_space, rip, user_rsp);
1172                        // Show the actual permissions at the faulting address,
1173                        // including restrictive intermediate page-table entries.
1174                        let (active_cr3, _) = x86_64::registers::control::Cr3::read();
1175                        crate::serial_force_println!(
1176                            "[pagefault] fault mapping: active_cr3={:#x} task_cr3={:#x}",
1177                            active_cr3.start_address().as_u64(),
1178                            address_space.cr3().as_u64()
1179                        );
1180                        dump_page_table_walk(vaddr.as_u64(), active_cr3.start_address().as_u64());
1181                    }
1182                }
1183            }
1184        }
1185    }
1186
1187    if is_user {
1188        if let Some(tid) = crate::process::current_task_id() {
1189            crate::silo::handle_user_fault(
1190                tid,
1191                crate::silo::SiloFaultReason::PageFault,
1192                fault_addr.as_ref().map(|v| v.as_u64()).unwrap_or(0),
1193                error_code.bits() as u64,
1194                stack_frame.instruction_pointer.as_u64(),
1195            );
1196            return;
1197        }
1198    } else {
1199        // FORCE OUTPUT for kernel fault
1200        crate::serial_force_println!(
1201            "\x1b[31;1m[pagefault] KERNEL fault\x1b[0m: rip={:#x} addr={:#x} err={:#x}",
1202            rip,
1203            fault_addr.as_ref().map(|v| v.as_u64()).unwrap_or(0),
1204            error_code.bits()
1205        );
1206    }
1207
1208    // Capture current task (non-blocking, safe from IRQ context) for the diagnostic dump.
1209    let task_snap = crate::process::scheduler::current_task_clone_try();
1210    dump_page_fault_full(&stack_frame, error_code, fault_addr, &task_snap);
1211}
1212
1213// =============================================================================
1214// CRITICAL: Full page fault diagnostic dump
1215//
1216// Invoked for every non-recoverable page fault (kernel or unhandled user).
1217// Designed to be deadlock-safe:
1218//   - Uses serial_println! (direct UART) instead of the log framework, which
1219//     may itself allocate or acquire locks.
1220//   - All memory reads go through translate_via_raw_pt so no unmapped address
1221//     is ever dereferenced.
1222//   - The buddy allocator lock is acquired with try_lock (non-blocking) for
1223//     memory statistics.
1224//   - Uses current_task_clone_try (non-blocking) instead of current_task_clone.
1225// =============================================================================
1226
1227/// Decodes `PageFaultErrorCode` bits into a human-readable string.
1228fn decode_error_code(ec: PageFaultErrorCode) -> &'static str {
1229    let p = ec.contains(PageFaultErrorCode::PROTECTION_VIOLATION);
1230    let w = ec.contains(PageFaultErrorCode::CAUSED_BY_WRITE);
1231    let u = ec.contains(PageFaultErrorCode::USER_MODE);
1232    // Bit 4 (I/D) is the only way to tell "we tried to *execute* this
1233    // address" from a data access. Ignoring it made a wild jump
1234    // (RIP == CR2) look like a bogus kernel read.
1235    if ec.contains(PageFaultErrorCode::INSTRUCTION_FETCH) {
1236        return match (p, u) {
1237            (false, false) => "kernel instruction fetch of non-present page",
1238            (false, true) => "user instruction fetch of non-present page",
1239            (true, false) => "kernel instruction fetch protection violation (NX / supervisor-only)",
1240            (true, true) => "user instruction fetch protection violation (NX / supervisor-only)",
1241        };
1242    }
1243    match (p, w, u) {
1244        (false, false, false) => "kernel read of non-present page",
1245        (false, true, false) => "kernel write to non-present page",
1246        (false, false, true) => "user read of non-present page",
1247        (false, true, true) => "user write to non-present page",
1248        (true, false, false) => "kernel read protection violation",
1249        (true, true, false) => "kernel write protection violation (COW / RO page)",
1250        (true, false, true) => "user read protection violation (NX / supervisor-only)",
1251        (true, true, true) => "user write protection violation (COW / RO page)",
1252    }
1253}
1254
1255/// Formats page table entry flags into a short human-readable byte string.
1256fn format_pte_flags(entry: u64) -> [u8; 32] {
1257    let mut buf = [b' '; 32];
1258    let mut pos = 0usize;
1259    let flags: &[(&str, u64)] = &[
1260        ("P", 1 << 0),
1261        ("RW", 1 << 1),
1262        ("US", 1 << 2),
1263        ("PWT", 1 << 3),
1264        ("PCD", 1 << 4),
1265        ("A", 1 << 5),
1266        ("D", 1 << 6),
1267        ("PS", 1 << 7),
1268        ("G", 1 << 8),
1269        ("NX", 1 << 63),
1270    ];
1271    for &(name, bit) in flags {
1272        if entry & bit != 0 {
1273            for &b in name.as_bytes() {
1274                if pos < buf.len() {
1275                    buf[pos] = b;
1276                    pos += 1;
1277                }
1278            }
1279            if pos < buf.len() {
1280                buf[pos] = b'|';
1281                pos += 1;
1282            }
1283        }
1284    }
1285    if pos > 0 && buf[pos - 1] == b'|' {
1286        buf[pos - 1] = b' ';
1287    }
1288    buf
1289}
1290
1291/// Translates a virtual address to a physical address via a manual 4-level
1292/// page table walk.  Returns `Some(phys)` or `None` if any level is absent.
1293///
1294/// # SAFETY
1295/// Read-only access to page tables through the HHDM mapping.
1296/// All intermediate addresses are derived from table entries : no pointer
1297/// originating from user-controlled data is ever dereferenced.
1298fn translate_via_raw_pt(vaddr: u64, cr3_phys: u64, hhdm: u64) -> Option<u64> {
1299    unsafe {
1300        let l4_ptr = (cr3_phys + hhdm) as *const u64;
1301        let l4e = *l4_ptr.add(((vaddr >> 39) & 0x1FF) as usize);
1302        if l4e & 1 == 0 {
1303            return None;
1304        }
1305
1306        let l3_ptr = ((l4e & 0x000F_FFFF_FFFF_F000) + hhdm) as *const u64;
1307        let l3e = *l3_ptr.add(((vaddr >> 30) & 0x1FF) as usize);
1308        if l3e & 1 == 0 {
1309            return None;
1310        }
1311        if l3e & 0x80 != 0 {
1312            return Some((l3e & 0x000F_FFFF_C000_0000) + (vaddr & 0x3FFF_FFFF));
1313        }
1314
1315        let l2_ptr = ((l3e & 0x000F_FFFF_FFFF_F000) + hhdm) as *const u64;
1316        let l2e = *l2_ptr.add(((vaddr >> 21) & 0x1FF) as usize);
1317        if l2e & 1 == 0 {
1318            return None;
1319        }
1320        if l2e & 0x80 != 0 {
1321            return Some((l2e & 0x000F_FFFF_FFE0_0000) + (vaddr & 0x1F_FFFF));
1322        }
1323
1324        let l1_ptr = ((l2e & 0x000F_FFFF_FFFF_F000) + hhdm) as *const u64;
1325        let l1e = *l1_ptr.add(((vaddr >> 12) & 0x1FF) as usize);
1326        if l1e & 1 == 0 {
1327            return None;
1328        }
1329        Some((l1e & 0x000F_FFFF_FFFF_F000) + (vaddr & 0xFFF))
1330    }
1331}
1332
1333/// Hex + ASCII dump of `count` bytes at virtual address `vaddr`.
1334/// Each page boundary is translated through the raw page tables.
1335fn dump_memory_bytes(vaddr: u64, cr3_phys: u64, count: usize, prefix: &str) {
1336    let hhdm = crate::memory::hhdm_offset();
1337    let mut offset = 0usize;
1338    while offset < count {
1339        let cur_va = vaddr.wrapping_add(offset as u64);
1340        let page_off = (cur_va & 0xFFF) as usize;
1341        let chunk = core::cmp::min(count - offset, 0x1000 - page_off);
1342        let Some(phys) = translate_via_raw_pt(cur_va, cr3_phys, hhdm) else {
1343            crate::serial_println!("{}(page {:#x} not mapped)", prefix, cur_va);
1344            offset += chunk;
1345            continue;
1346        };
1347        // SAFETY: read-only access to a valid physical page through the HHDM mapping.
1348        let src = (phys - (cur_va & 0xFFF) + hhdm) as *const u8;
1349        let mut line_off = 0usize;
1350        while line_off < chunk {
1351            let ll = core::cmp::min(16, chunk - line_off);
1352            let line_va = cur_va.wrapping_add(line_off as u64);
1353            let mut hex = [0u8; 48];
1354            let mut asc = [b'.'; 16];
1355            for i in 0..ll {
1356                let byte = unsafe { *src.add(page_off + line_off + i) };
1357                let hi = byte >> 4;
1358                let lo = byte & 0xF;
1359                hex[i * 3] = if hi < 10 { b'0' + hi } else { b'a' + hi - 10 };
1360                hex[i * 3 + 1] = if lo < 10 { b'0' + lo } else { b'a' + lo - 10 };
1361                hex[i * 3 + 2] = b' ';
1362                if byte >= 0x20 && byte < 0x7F {
1363                    asc[i] = byte;
1364                }
1365            }
1366            for i in ll..16 {
1367                hex[i * 3] = b' ';
1368                hex[i * 3 + 1] = b' ';
1369                hex[i * 3 + 2] = b' ';
1370            }
1371            crate::serial_println!(
1372                "{}{:#018x}: {} |{}|",
1373                prefix,
1374                line_va,
1375                core::str::from_utf8(&hex[..48]).unwrap_or("???"),
1376                core::str::from_utf8(&asc[..ll]).unwrap_or("???")
1377            );
1378            line_off += ll;
1379        }
1380        offset += chunk;
1381    }
1382}
1383
1384/// Detailed page table walk with flag decoding at every level.
1385fn dump_page_table_walk(vaddr: u64, cr3_phys: u64) {
1386    let hhdm = crate::memory::hhdm_offset();
1387    let l4_idx = ((vaddr >> 39) & 0x1FF) as usize;
1388    let l3_idx = ((vaddr >> 30) & 0x1FF) as usize;
1389    let l2_idx = ((vaddr >> 21) & 0x1FF) as usize;
1390    let l1_idx = ((vaddr >> 12) & 0x1FF) as usize;
1391
1392    // SAFETY: read-only access through the HHDM mapping for diagnostic purposes.
1393    unsafe {
1394        let l4_ptr = (cr3_phys + hhdm) as *const u64;
1395        let l4e = *l4_ptr.add(l4_idx);
1396        let f = format_pte_flags(l4e);
1397        crate::serial_println!(
1398            "  PML4[{:>3}] = {:#018x}  phys={:#014x}  [{}]",
1399            l4_idx,
1400            l4e,
1401            l4e & 0x000F_FFFF_FFFF_F000,
1402            core::str::from_utf8(&f).unwrap_or("?").trim()
1403        );
1404        if l4e & 1 == 0 {
1405            crate::serial_println!("  \x1b[1;31m  ==> STOP: PML4 not present !\x1b[0m");
1406            return;
1407        }
1408
1409        let l3_ptr = ((l4e & 0x000F_FFFF_FFFF_F000) + hhdm) as *const u64;
1410        let l3e = *l3_ptr.add(l3_idx);
1411        let f = format_pte_flags(l3e);
1412        crate::serial_println!(
1413            "  PDPT[{:>3}] = {:#018x}  phys={:#014x}  [{}]",
1414            l3_idx,
1415            l3e,
1416            l3e & 0x000F_FFFF_FFFF_F000,
1417            core::str::from_utf8(&f).unwrap_or("?").trim()
1418        );
1419        if l3e & 1 == 0 {
1420            crate::serial_println!("  \x1b[1;31m ==> STOP: PDPT not present !\x1b[0m");
1421            return;
1422        }
1423        if l3e & 0x80 != 0 {
1424            crate::serial_println!(
1425                "  ==> 1 GiB huge page => phys {:#x}",
1426                l3e & 0x000F_FFFF_C000_0000
1427            );
1428            return;
1429        } // 1 GiB
1430
1431        let l2_ptr = ((l3e & 0x000F_FFFF_FFFF_F000) + hhdm) as *const u64;
1432        let l2e = *l2_ptr.add(l2_idx);
1433        let f = format_pte_flags(l2e);
1434        crate::serial_println!(
1435            "  PD  [{:>3}] = {:#018x}  phys={:#014x}  [{}]",
1436            l2_idx,
1437            l2e,
1438            l2e & 0x000F_FFFF_FFFF_F000,
1439            core::str::from_utf8(&f).unwrap_or("?").trim()
1440        );
1441        if l2e & 1 == 0 {
1442            crate::serial_println!("  \x1b[1;31m ==> STOP: PD not present !\x1b[0m");
1443            return;
1444        }
1445        if l2e & 0x80 != 0 {
1446            crate::serial_println!(
1447                "  ==> 2 MiB huge page => phys {:#x}",
1448                l2e & 0x000F_FFFF_FFE0_0000
1449            );
1450            return;
1451        } // 2 MiB
1452
1453        let l1_ptr = ((l2e & 0x000F_FFFF_FFFF_F000) + hhdm) as *const u64;
1454        let l1e = *l1_ptr.add(l1_idx);
1455        let f = format_pte_flags(l1e);
1456        crate::serial_println!(
1457            "  PT  [{:>3}] = {:#018x}  phys={:#014x}  [{}]",
1458            l1_idx,
1459            l1e,
1460            l1e & 0x000F_FFFF_FFFF_F000,
1461            core::str::from_utf8(&f).unwrap_or("?").trim()
1462        );
1463        if l1e & 1 == 0 {
1464            crate::serial_println!("  \x1b[1;31m ==> STOP: PT not present !\x1b[0m");
1465        } else {
1466            crate::serial_println!(
1467                "  \x1b[1;32m ==> PAGE PRESENT\x1b[0m => phys {:#x} (check RW/US/NX flags)",
1468                l1e & 0x000F_FFFF_FFFF_F000
1469            );
1470        }
1471        // Neighbouring PT entries for context
1472        crate::serial_println!("  --- Neighbouring PT entries ---");
1473        let start = if l1_idx >= 2 { l1_idx - 2 } else { 0 };
1474        for i in start..core::cmp::min(l1_idx + 3, 512) {
1475            let e = *l1_ptr.add(i);
1476            if e != 0 {
1477                let f = format_pte_flags(e);
1478                crate::serial_println!(
1479                    "    PT[{:>3}] = {:#018x}  [{}]{}",
1480                    i,
1481                    e,
1482                    core::str::from_utf8(&f).unwrap_or("?").trim(),
1483                    if i == l1_idx { " <<<" } else { "" }
1484                );
1485            }
1486        }
1487    }
1488}
1489
1490/// Dumps VMA regions near the faulting address.
1491fn dump_nearby_vma_regions(as_ref: &crate::memory::AddressSpace, fault_vaddr: u64) {
1492    let page_start = fault_vaddr & !0xFFF;
1493    let probes = [
1494        page_start,
1495        fault_vaddr & !0x1F_FFFF,
1496        fault_vaddr & !0x3FFF_FFFF,
1497        0x0000_0001_0000_0000,
1498        0x0000_0000_0040_0000,
1499        0x0000_7FFF_F000_0000,
1500    ];
1501    let mut found_any = false;
1502    for &p in &probes {
1503        if let Some(vma) = as_ref.region_by_start(p) {
1504            let end = vma.start + (vma.page_count as u64) * vma.page_size.bytes();
1505            let hit = fault_vaddr >= vma.start && fault_vaddr < end;
1506            crate::serial_println!(
1507                "  VMA {:#014x}..{:#014x}  pages={:<5}  type={:?}  flags={:?}  pgsz={:?}{}",
1508                vma.start,
1509                end,
1510                vma.page_count,
1511                vma.vma_type,
1512                vma.flags,
1513                vma.page_size,
1514                if hit {
1515                    "  \x1b[1;32m<<< FAULT\x1b[0m"
1516                } else {
1517                    ""
1518                }
1519            );
1520            found_any = true;
1521        }
1522    }
1523    if as_ref.has_mapping_in_range(page_start, 0x1000) {
1524        crate::serial_println!(
1525            "  Note: fault page {:#x} IS within a tracked mapping range",
1526            page_start
1527        );
1528    } else {
1529        crate::serial_println!(
1530            "  Note: fault page {:#x} is NOT within any tracked mapping range",
1531            page_start
1532        );
1533    }
1534    if !found_any {
1535        crate::serial_println!("  (no VMA regions found at probed addresses)");
1536    }
1537}
1538
1539/// Full diagnostic dump for a non-recoverable page fault.
1540///
1541/// Uses `serial_println!` directly (lock-free UART) to avoid any deadlock
1542/// with the log framework or the heap allocator.
1543fn dump_page_fault_full(
1544    stack_frame: &InterruptStackFrame,
1545    error_code: PageFaultErrorCode,
1546    fault_addr: Result<x86_64::VirtAddr, x86_64::addr::VirtAddrNotValid>,
1547    task: &Option<alloc::sync::Arc<crate::process::task::Task>>,
1548) -> ! {
1549    use x86_64::registers::control::{Cr0, Cr3, Cr4};
1550
1551    let rip = stack_frame.instruction_pointer.as_u64();
1552    let rsp = stack_frame.stack_pointer.as_u64();
1553    let cs = stack_frame.code_segment.0;
1554    let ss = stack_frame.stack_segment.0;
1555    let rflags = stack_frame.cpu_flags.bits();
1556    let fault_vaddr = fault_addr.as_ref().map(|v| v.as_u64()).unwrap_or(0);
1557    let is_user = (cs & 3) == 3;
1558
1559    crate::serial_println!("\x1b[1;31m");
1560    crate::serial_println!(
1561        "****************************************************************************"
1562    );
1563    crate::serial_println!("*                  KERNEL PAGE FAULT EXCEPTiON                     *");
1564    crate::serial_println!(
1565        "********************************************************************\x1b[0m"
1566    );
1567
1568    // --- Error code ---
1569    crate::serial_println!("\x1b[1;33m--- Error code ---\x1b[0m");
1570    crate::serial_println!("  Raw         : {:#06x}", error_code.bits());
1571    crate::serial_println!(
1572        "  Diagnostic  : \x1b[1;31m{}\x1b[0m",
1573        decode_error_code(error_code)
1574    );
1575    crate::serial_println!(
1576        "  PRESENT     : {} | WRITE : {} | USER : {} | RSVD : {} | FETCH : {}",
1577        error_code.contains(PageFaultErrorCode::PROTECTION_VIOLATION) as u8,
1578        error_code.contains(PageFaultErrorCode::CAUSED_BY_WRITE) as u8,
1579        error_code.contains(PageFaultErrorCode::USER_MODE) as u8,
1580        (error_code.bits() >> 3) & 1,
1581        (error_code.bits() >> 4) & 1
1582    );
1583
1584    // --- Instruction-fetch fault: RIP itself is what is unmapped. -----------
1585    // Nothing "read" here: the CPU was told to execute a bogus address (wild
1586    // call/jmp/ret or a corrupted iretq frame). The frame chain is unusable in
1587    // that case, so dump the words around RSP to expose the return address that
1588    // led to the jump.
1589    if error_code.contains(PageFaultErrorCode::INSTRUCTION_FETCH) {
1590        crate::serial_println!("\x1b[1;33m--- Instruction fetch fault ---\x1b[0m");
1591        crate::serial_println!("  faulting RIP : {:#018x} (no executable mapping)", rip);
1592        crate::serial_println!("  RSP          : {:#018x}", rsp);
1593        crate::serial_println!("  stack words (candidate return addresses):");
1594        let text_lo = 0xffff_ffff_8000_0000u64;
1595        let text_hi = 0xffff_ffff_8060_0000u64;
1596        for i in 0..16u64 {
1597            let addr = rsp.wrapping_add(i * 8);
1598            let virt = x86_64::VirtAddr::new(addr);
1599            if crate::memory::paging::translate(virt).is_none() {
1600                crate::serial_println!("    [rsp+{:#04x}] <unmapped>", i * 8);
1601                break;
1602            }
1603            // SAFETY: translate() proved the page is mapped and readable.
1604            let val = unsafe { *(addr as *const u64) };
1605            let tag = if (text_lo..text_hi).contains(&val) {
1606                "   <- kernel .text"
1607            } else {
1608                ""
1609            };
1610            let sym = match crate::boot::symbols::lookup(val) {
1611                Some((name, 0)) => alloc::format!("   {}", name),
1612                Some((name, off)) => alloc::format!("   {}+{:#x}", name, off),
1613                None => alloc::string::String::new(),
1614            };
1615            crate::serial_println!("    [rsp+{:#04x}] = {:#018x}{}{}", i * 8, val, tag, sym);
1616        }
1617    }
1618
1619    // --- Faulting context ---
1620    crate::serial_println!("\x1b[1;33m--- Faulting context ---\x1b[0m");
1621    crate::serial_println!("  CR2 (addr)  : \x1b[1;35m{:#018x}\x1b[0m", fault_vaddr);
1622    crate::serial_println!("  RIP         : \x1b[1;36m{:#018x}\x1b[0m", rip);
1623    crate::serial_println!("  RSP         : {:#018x}", rsp);
1624    crate::serial_println!(
1625        "  CS          : {:#06x}  (ring={}{}) | SS : {:#06x}",
1626        cs,
1627        cs & 3,
1628        if is_user { " USER" } else { " KERNEL" },
1629        ss
1630    );
1631
1632    // RFLAGS décodé
1633    let mut rf_str = [0u8; 64];
1634    let mut rfp = 0usize;
1635    for &(name, bit) in &[
1636        ("CF", 1u64),
1637        ("PF", 4),
1638        ("AF", 16),
1639        ("ZF", 64),
1640        ("SF", 128),
1641        ("TF", 256),
1642        ("IF", 512),
1643        ("DF", 1024),
1644        ("OF", 2048),
1645    ] {
1646        if rflags & bit != 0 {
1647            for &b in name.as_bytes() {
1648                if rfp < rf_str.len() {
1649                    rf_str[rfp] = b;
1650                    rfp += 1;
1651                }
1652            }
1653            if rfp < rf_str.len() {
1654                rf_str[rfp] = b' ';
1655                rfp += 1;
1656            }
1657        }
1658    }
1659    crate::serial_println!(
1660        "  RFLAGS      : {:#018x}  [{}]",
1661        rflags,
1662        core::str::from_utf8(&rf_str[..rfp]).unwrap_or("?")
1663    );
1664
1665    // --- Control registers ---
1666    crate::serial_println!("\x1b[1;33m--- Control registers ---\x1b[0m");
1667    let cr0 = Cr0::read_raw();
1668    let (cr3_frame, cr3_flags) = Cr3::read();
1669    let cr3_phys = cr3_frame.start_address().as_u64();
1670    let cr4 = Cr4::read_raw();
1671    let efer: u64 = x86_64::registers::model_specific::Efer::read_raw();
1672    crate::serial_println!("  CR0         : {:#018x}", cr0);
1673    crate::serial_println!(
1674        "  CR3         : {:#018x}  (flags={:#x})",
1675        cr3_phys,
1676        cr3_flags.bits()
1677    );
1678    crate::serial_println!("  CR4         : {:#018x}", cr4);
1679    crate::serial_println!(
1680        "  EFER        : {:#018x}  [{}{}{}]",
1681        efer,
1682        if efer & 1 != 0 { "SCE " } else { "" },
1683        if efer & (1 << 8) != 0 { "LME " } else { "" },
1684        if efer & (1 << 11) != 0 { "NXE" } else { "" }
1685    );
1686
1687    // --- CPU context ---
1688    crate::serial_println!("\x1b[1;33m--- CPU context ---\x1b[0m");
1689    crate::serial_println!("  LAPIC ID    : {}", super::apic::lapic_id());
1690    crate::serial_println!("  Ticks sched : {}", crate::process::scheduler::ticks());
1691    crate::serial_println!("  HHDM offset : {:#x}", crate::memory::hhdm_offset());
1692
1693    // --- Task context ---
1694    crate::serial_println!("\x1b[1;33m--- Task context ---\x1b[0m");
1695    if let Some(ref t) = *task {
1696        crate::serial_println!(
1697            "  ID={} PID={} TID={} TGID={} name=\"{}\" prio={:?} ticks={}",
1698            t.id.as_u64(),
1699            t.pid,
1700            t.tid,
1701            t.tgid,
1702            t.name,
1703            t.priority,
1704            t.ticks.load(core::sync::atomic::Ordering::Relaxed)
1705        );
1706        // SAFETY: Read task CR3 safely using the hardware page-table walker
1707        // (translate_via_raw_pt) to prevent recursive page faults if the
1708        // process's Arc<AddressSpace> is partially initialized or corrupted.
1709        //
1710        // Chain: &t.process => Arc<Process> data ptr (Arc::as_ptr)
1711        //      => (*process).address_space.get() => *mut Arc<AddressSpace>
1712        //      => Arc::as_ptr(arc_as) => *const AddressSpace
1713        //      => (*addr_space).cr3_phys
1714        //
1715        // Each step uses translate_via_raw_pt to verify the pointer is mapped
1716        // before dereferencing, using the hardware CR3 (cr3_phys) which always
1717        // maps the kernel's HHDM region.
1718        let task_cr3: u64 = {
1719            let hhdm = crate::memory::hhdm_offset();
1720            // Step 1: Arc<Process> data (Arc::as_ptr is always valid for a live Arc)
1721            let _proc_ptr: u64 = alloc::sync::Arc::as_ptr(&t.process) as u64;
1722            // Step 2: address_space field in Process = SyncUnsafeCell whose .get()
1723            // returns a raw ptr into the Process data : always valid for a live Process.
1724            // However, reading the Arc<AddressSpace> *value* from that pointer may
1725            // fault if the memory is unmapped, so we use translate_via_raw_pt.
1726            let as_cell_addr: u64 =
1727                unsafe { (*alloc::sync::Arc::as_ptr(&t.process)).address_space.get() as u64 };
1728            // Step 3: read the 8-byte Arc<AddressSpace> inner pointer from as_cell_addr
1729            // via raw page table walk with current hardware CR3.
1730            let as_inner_u64: u64 = match translate_via_raw_pt(as_cell_addr, cr3_phys, hhdm) {
1731                Some(phys) => unsafe { *((phys + hhdm) as *const u64) },
1732                None => 0,
1733            };
1734            if as_inner_u64 == 0 {
1735                0u64
1736            } else {
1737                // as_inner_u64 is the NonNull ptr inside Arc<AddressSpace>
1738                // = pointer to ArcInner<AddressSpace>.
1739                // ArcInner = strong(8) + weak(8) + data(AddressSpace).
1740                // So AddressSpace data is at as_inner_u64 + 16.
1741                let as_data_ptr: u64 = as_inner_u64 + 2 * core::mem::size_of::<usize>() as u64;
1742                // cr3_phys is the first field of AddressSpace (PhysAddr = u64, 8 bytes).
1743                match translate_via_raw_pt(as_data_ptr, cr3_phys, hhdm) {
1744                    Some(phys) => unsafe { *((phys + hhdm) as *const u64) },
1745                    None => 0,
1746                }
1747            }
1748        };
1749        if task_cr3 == 0 {
1750            crate::serial_println!(
1751                "  Task CR3    : <unreadable : null/unmapped Arc<AddressSpace>>"
1752            );
1753        } else {
1754            crate::serial_println!(
1755                "  Task CR3    : {:#018x}{}",
1756                task_cr3,
1757                if task_cr3 != cr3_phys {
1758                    " *** DIFFERS from hardware CR3! ***"
1759                } else {
1760                    " (matches hardware CR3)"
1761                }
1762            );
1763        }
1764    } else {
1765        crate::serial_println!("  (no current task : scheduler idle or unavailable)");
1766    }
1767
1768    // --- Memory statistics ---
1769    crate::serial_println!("\x1b[1;33m--- Memory stats ---\x1b[0m");
1770    if let Some(guard) = crate::memory::get_allocator().try_lock() {
1771        if let Some(ref alloc) = *guard {
1772            let (total, allocated) = alloc.page_totals();
1773            let free = total.saturating_sub(allocated);
1774            crate::serial_println!(
1775                "  Total={} pages ({} MiB)  Alloc={} ({} MiB)  Free={} ({} MiB)",
1776                total,
1777                total * 4 / 1024,
1778                allocated,
1779                allocated * 4 / 1024,
1780                free,
1781                free * 4 / 1024
1782            );
1783            let mut zones =
1784                [crate::memory::buddy::ZoneStats::empty(); crate::memory::zone::ZoneType::COUNT];
1785            let n = alloc.zone_snapshot(&mut zones);
1786            for i in 0..n {
1787                let zone = zones[i];
1788                let zone_ref = alloc.get_zone(i);
1789                crate::serial_println!(
1790                    "    Zone {} ({}): base={:#x} managed={} present={} spanned={} reserved={} alloc={} free={} state={:?} seg={}/{} largest={:?}",
1791                    i,
1792                    match zone.zone_type {
1793                        crate::memory::zone::ZoneType::DMA => "DMA",
1794                        crate::memory::zone::ZoneType::Normal => "Normal",
1795                        crate::memory::zone::ZoneType::HighMem => "High",
1796                    },
1797                    zone.base,
1798                    zone.managed_pages,
1799                    zone.present_pages,
1800                    zone.spanned_pages,
1801                    zone.reserved_pages,
1802                    zone.allocated_pages,
1803                    zone.free_pages,
1804                    zone.pressure(),
1805                    zone.segment_count,
1806                    zone.segment_capacity,
1807                    zone.largest_free_order
1808                );
1809                crate::serial_println!(
1810                    "      reserve={} avail={} holes={} cached[u/m]={}/{} free[u/m]={}/{} pageblocks[u/m]={}/{} total={} order={}",
1811                    zone.reserve_floor_pages(),
1812                    zone.available_after_reserve_pages(),
1813                    zone.hole_pages(),
1814                    zone.cached_unmovable_pages,
1815                    zone.cached_movable_pages,
1816                    zone.unmovable_free_pages,
1817                    zone.movable_free_pages,
1818                    zone.unmovable_pageblocks,
1819                    zone.movable_pageblocks,
1820                    zone.pageblock_count,
1821                    crate::memory::zone::PAGEBLOCK_ORDER
1822                );
1823                crate::serial_println!(
1824                    "      frag/order: o1={}%% o4={}%% o{}={}%%",
1825                    zone_ref.fragmentation_score(1, zone.cached_pages),
1826                    zone_ref.fragmentation_score(4, zone.cached_pages),
1827                    crate::memory::zone::PAGEBLOCK_ORDER,
1828                    zone_ref.fragmentation_score(
1829                        crate::memory::zone::PAGEBLOCK_ORDER as u8,
1830                        zone.cached_pages,
1831                    )
1832                );
1833            }
1834        } else {
1835            crate::serial_println!("  (allocator not initialized)");
1836        }
1837    } else {
1838        crate::serial_println!("  (allocator lock contended : skipping)");
1839    }
1840
1841    let quarantine = crate::memory::buddy::poison_quarantine_pages_snapshot();
1842    let fail_counts = crate::memory::buddy::buddy_alloc_fail_counts_snapshot();
1843    let compaction = crate::memory::buddy::compaction_stats_snapshot();
1844    crate::serial_println!("  Poison quarantine : {} pages", quarantine);
1845
1846    let mut printed_fail = false;
1847    for (order, count) in fail_counts.iter().enumerate() {
1848        if *count == 0 {
1849            continue;
1850        }
1851        printed_fail = true;
1852        crate::serial_println!("  Buddy alloc fail  : order={} count={}", order, count);
1853    }
1854    if !printed_fail {
1855        crate::serial_println!("  Buddy alloc fail  : none");
1856    }
1857
1858    if compaction.attempts == 0 {
1859        crate::serial_println!("  Compaction assist : none");
1860    } else {
1861        crate::serial_println!(
1862            "  Compaction assist : attempts={} success={} last_order={:?} migratetype={:?} zone={:?} pressure={:?}",
1863            compaction.attempts,
1864            compaction.successes,
1865            compaction.last_order,
1866            compaction.last_migratetype,
1867            compaction.last_zone,
1868            compaction.last_pressure
1869        );
1870        crate::serial_println!(
1871            "                      frag={}%% req={} avail={} usable={} cached={} drained={} pageblocks={}/{}",
1872            compaction.last_fragmentation_score,
1873            compaction.last_requested_pages,
1874            compaction.last_available_pages,
1875            compaction.last_usable_pages,
1876            compaction.last_cached_pages,
1877            compaction.last_drained_pages,
1878            compaction.last_matching_pageblocks,
1879            compaction.last_pageblock_count
1880        );
1881    }
1882
1883    // --- Code bytes at RIP ---
1884    crate::serial_println!("\x1b[1;33m--- Code at RIP ({:#x}) ---\x1b[0m", rip);
1885    dump_memory_bytes(rip, cr3_phys, 32, "  ");
1886
1887    // --- Stack dump ---
1888    crate::serial_println!("\x1b[1;33m--- Stack dump (RSP={:#x}) ---\x1b[0m", rsp);
1889    dump_memory_bytes(rsp, cr3_phys, 128, "  ");
1890
1891    // --- Page table walk ---
1892    crate::serial_println!(
1893        "\x1b[1;33m--- Page table walk (CR2={:#x}, CR3={:#x}) ---\x1b[0m",
1894        fault_vaddr,
1895        cr3_phys
1896    );
1897    if fault_addr.is_ok() {
1898        dump_page_table_walk(fault_vaddr, cr3_phys);
1899    } else {
1900        crate::serial_println!("  (CR2 is a non-canonical address: {:#x})", fault_vaddr);
1901    }
1902
1903    // --- VMA regions near fault ---
1904    if let Some(ref t) = *task {
1905        crate::serial_println!("\x1b[1;33m--- VMA regions near fault ---\x1b[0m");
1906        // SAFETY: Use the same safe ptr-chain read strategy as the Task CR3 section above:
1907        // Arc::as_ptr gives a valid *const AddressSpace if the Arc is alive, but the
1908        // Arc<AddressSpace> stored inside the SyncUnsafeCell might be corrupted.
1909        // We validate via translate_via_raw_pt before reading the inner ptr.
1910        let hhdm_vma = crate::memory::hhdm_offset();
1911        let safe_as: Option<*const crate::memory::AddressSpace> = unsafe {
1912            let as_cell_addr: u64 =
1913                (*alloc::sync::Arc::as_ptr(&t.process)).address_space.get() as u64;
1914            match translate_via_raw_pt(as_cell_addr, cr3_phys, hhdm_vma) {
1915                Some(phys) => {
1916                    // Read the Arc<AddressSpace> inner pointer (a NonNull ptr stored at this phys)
1917                    let as_inner_u64 = *((phys + hhdm_vma) as *const u64);
1918                    if as_inner_u64 == 0 {
1919                        None
1920                    } else {
1921                        // ArcInner<AddressSpace>.data at +16
1922                        let as_data_ptr = (as_inner_u64 + 2 * core::mem::size_of::<usize>() as u64)
1923                            as *const crate::memory::AddressSpace;
1924                        // Validate the AddressSpace pointer is mapped before returning it
1925                        if translate_via_raw_pt(as_data_ptr as u64, cr3_phys, hhdm_vma).is_some() {
1926                            Some(as_data_ptr)
1927                        } else {
1928                            None
1929                        }
1930                    }
1931                }
1932                None => None,
1933            }
1934        };
1935        if let Some(as_ptr) = safe_as {
1936            // SAFETY: We verified above that as_ptr is mapped and readable.
1937            let as_ref = unsafe { &*as_ptr };
1938            dump_nearby_vma_regions(as_ref, fault_vaddr);
1939        } else {
1940            crate::serial_println!("  (AddressSpace unreadable : skipping VMA dump)");
1941        }
1942    }
1943
1944    crate::serial_println!("\x1b[1;31m***********************************************************");
1945    crate::serial_println!("*                     END OF PAGE FAULT DuMP                      *");
1946    crate::serial_println!(
1947        "*******************************************************************\x1b[0m"
1948    );
1949
1950    panic!(
1951        "PAGE FAULT: {} at {:#x}, RIP={:#x}, CR3={:#x}, err={:#x}",
1952        decode_error_code(error_code),
1953        fault_vaddr,
1954        rip,
1955        cr3_phys,
1956        error_code.bits()
1957    );
1958}
1959
1960/// Performs the dump user pf context operation.
1961fn dump_user_pf_context(as_ref: &crate::memory::AddressSpace, rip: u64, rsp: u64) {
1962    use x86_64::VirtAddr;
1963
1964    let hhdm = crate::memory::hhdm_offset();
1965
1966    if let Some(phys) = as_ref.translate(VirtAddr::new(rip)) {
1967        let off = (rip & 0xfff) as usize;
1968        let mut bytes = [0u8; 8];
1969        // SAFETY: We read at most 8 bytes from a mapped user instruction page via HHDM.
1970        unsafe {
1971            let src = (phys.as_u64() - (rip & 0xfff) + hhdm + off as u64) as *const u8;
1972            core::ptr::copy_nonoverlapping(src, bytes.as_mut_ptr(), bytes.len());
1973        }
1974        crate::serial_println!(
1975            "[pagefault] ctx: rsp={:#x} rip-bytes={:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x}",
1976            rsp,
1977            bytes[0],
1978            bytes[1],
1979            bytes[2],
1980            bytes[3],
1981            bytes[4],
1982            bytes[5],
1983            bytes[6],
1984            bytes[7],
1985        );
1986    } else {
1987        crate::serial_println!("[pagefault] ctx: rsp={:#x} rip page unmapped", rsp);
1988    }
1989
1990    if let Some(phys) = as_ref.translate(VirtAddr::new(rsp)) {
1991        crate::serial_println!(
1992            "[pagefault] stack-top: rsp mapped (phys={:#x})",
1993            phys.as_u64()
1994        );
1995    } else {
1996        crate::serial_println!("[pagefault] stack-top: rsp unmapped");
1997    }
1998}
1999
2000/// Performs the general protection fault handler operation.
2001extern "x86-interrupt" fn general_protection_fault_handler(
2002    stack_frame: InterruptStackFrame,
2003    error_code: u64,
2004) {
2005    let cs = stack_frame.code_segment.0;
2006    let is_user = (cs & 3) == 3;
2007    // Use rdmsr-based check: catches the swapgs=>iretq window where
2008    // CS=Ring0 but GS=user (0).
2009    // Without this, #GP from a bad iretq would escalate to double fault => triple fault.
2010    let swapgs_needed = needs_swapgs(cs);
2011    let _gs = SwapGsGuard::new(swapgs_needed);
2012    {
2013        let thr: u16 = 0x3F8;
2014        let lsr: u16 = 0x3F8 + 5;
2015        for &b in b"[GP]" {
2016            let mut s: u8 = 0;
2017            let mut i = 0u32;
2018            loop {
2019                unsafe {
2020                    core::arch::asm!("in al, dx", out("al") s, in("dx") lsr, options(nomem, nostack, preserves_flags));
2021                }
2022                if s & 0x20 != 0 || i > 500000 {
2023                    break;
2024                }
2025                i += 1;
2026            }
2027            unsafe {
2028                core::arch::asm!("out dx, al", in("dx") thr, in("al") b, options(nomem, nostack, preserves_flags));
2029            }
2030        }
2031    }
2032    // Detect the swapgs=>iretq window case: CS says Ring 0 but GS was user.
2033    if swapgs_needed && !is_user {
2034        crate::serial_force_println!(
2035            "\x1b[31;1m[GPF]\x1b[0m SWAPGS-WINDOW: CS={:#x} (Ring0) but GS was user! rip={:#x} err={:#x} rsp={:#x}",
2036            cs,
2037            stack_frame.instruction_pointer.as_u64(),
2038            error_code,
2039            stack_frame.stack_pointer.as_u64()
2040        );
2041        // Keep SwapGsGuard alive through kill path.
2042        if let Some(task) = crate::process::current_task_clone() {
2043            crate::process::kill_task(task.id);
2044        }
2045        drop(_gs);
2046        crate::process::scheduler::exit_current_task(-11); // SIGSEGV
2047    }
2048    if is_user {
2049        if let Some(tid) = crate::process::current_task_id() {
2050            crate::serial_force_println!(
2051                "\x1b[31;1m[GPF]\x1b[0m USER tid={} rip={:#x} err={:#x}",
2052                tid,
2053                stack_frame.instruction_pointer.as_u64(),
2054                error_code
2055            );
2056            crate::silo::handle_user_fault(
2057                tid,
2058                crate::silo::SiloFaultReason::GeneralProtection,
2059                stack_frame.instruction_pointer.as_u64(),
2060                error_code,
2061                stack_frame.instruction_pointer.as_u64(),
2062            );
2063            return;
2064        }
2065    }
2066    let rip = stack_frame.instruction_pointer.as_u64();
2067    crate::serial_force_println!(
2068        "\x1b[31;1m[GPF]\x1b[0m KERNEL rip={:#018x} err={:#06x} cs={:#06x} ss={:#06x} rflags={:#018x} rsp={:#018x}",
2069        rip,
2070        error_code,
2071        stack_frame.code_segment.0,
2072        stack_frame.stack_segment.0,
2073        stack_frame.cpu_flags.bits(),
2074        stack_frame.stack_pointer.as_u64()
2075    );
2076    if let Some((name, offset)) = crate::boot::symbols::lookup(rip) {
2077        crate::serial_force_println!("[GPF] symbol={}+{:#x}", name, offset);
2078    } else {
2079        crate::serial_force_println!(
2080            "[GPF] symbol unavailable (ELF symbol table not loaded or RIP not covered)"
2081        );
2082    }
2083    crate::serial_force_println!(
2084        "[GPF] error-code: EXT={} IDT={} TI={} selector-index={}",
2085        error_code & 1,
2086        (error_code >> 1) & 1,
2087        (error_code >> 2) & 1,
2088        error_code >> 3
2089    );
2090    panic!("General protection fault");
2091}
2092
2093/// Performs the stack segment fault handler operation.
2094extern "x86-interrupt" fn stack_segment_fault_handler(
2095    stack_frame: InterruptStackFrame,
2096    error_code: u64,
2097) {
2098    // Use rdmsr-based check: iretq can trigger #SS if the user SS is bad,
2099    // and at that point GS is already swapped to user.
2100    let _gs = SwapGsGuard::new(needs_swapgs(stack_frame.code_segment.0));
2101    crate::serial_force_println!(
2102        "\x1b[31;1m[STACK_FAULT]\x1b[0m rip={:#x} err={:#x} cs={:#x} rsp={:#x}",
2103        stack_frame.instruction_pointer.as_u64(),
2104        error_code,
2105        stack_frame.code_segment.0,
2106        stack_frame.stack_pointer.as_u64()
2107    );
2108    panic!("Stack segment fault");
2109}
2110
2111/// Performs the double fault handler operation.
2112///
2113/// Uses IST stack so the handler always runs on a known-good stack, even
2114/// when RSP0 is corrupt.  We must still do `swapgs` if the fault originated
2115/// from Ring 3 (or from Ring 0 code that already did `swapgs`, e.g. the
2116/// `iretq` path in `elf_ring3_trampoline`).
2117///
2118/// # Note on divergent handler
2119/// This handler is `-> !`, so `SwapGsGuard::drop` will never run.  That is
2120/// fine because we never return to the interrupted context.
2121extern "x86-interrupt" fn double_fault_handler(
2122    stack_frame: InterruptStackFrame,
2123    error_code: u64,
2124) -> ! {
2125    // RAW serial marker: confirm a double fault fired, bypassing serial_println.
2126    {
2127        let thr: u16 = 0x3F8;
2128        let lsr: u16 = 0x3F8 + 5;
2129        for &b in b"[DF]" {
2130            let mut s: u8 = 0;
2131            let mut i = 0u32;
2132            loop {
2133                unsafe {
2134                    core::arch::asm!("in al, dx", out("al") s, in("dx") lsr, options(nomem, nostack, preserves_flags));
2135                }
2136                if s & 0x20 != 0 || i > 500000 {
2137                    break;
2138                }
2139                i += 1;
2140            }
2141            unsafe {
2142                core::arch::asm!("out dx, al", in("dx") thr, in("al") b, options(nomem, nostack, preserves_flags));
2143            }
2144        }
2145    }
2146    // Best-effort swapgs: if GS currently points at user space (address 0)
2147    // we need to swap to kernel GS so that any code below that touches
2148    // `gs:[0]` (e.g. via `current_cpu_index`) does not page-fault again.
2149    // We use a raw read of IA32_GS_BASE via rdmsr to decide.
2150    //
2151    // During `elf_ring3_trampoline`, `swapgs` is executed *before* `iretq`.
2152    // If `iretq` itself faults, `code_segment` is still Ring 0 (0x08) but
2153    // GS_BASE is already the user value (0).  The normal `cs & 3 == 3` test
2154    // would miss this case.  Reading the MSR catches it.
2155    unsafe {
2156        let lo: u32;
2157        let hi: u32;
2158        core::arch::asm!(
2159            "rdmsr",
2160            in("ecx") 0xC000_0101u32,  // IA32_GS_BASE
2161            out("eax") lo,
2162            out("edx") hi,
2163            options(nostack, preserves_flags),
2164        );
2165        let gs_base = (lo as u64) | ((hi as u64) << 32);
2166        // If GS_BASE is in the low half (user space) or zero, swap to kernel.
2167        if gs_base < 0xFFFF_8000_0000_0000 {
2168            core::arch::asm!("swapgs", options(nostack, preserves_flags));
2169        }
2170    }
2171    crate::serial_force_println!(
2172        "\x1b[31;1m[DOUBLE_FAULT]\x1b[0m rip={:#x} err={:#x} cs={:#x} rsp={:#x}",
2173        stack_frame.instruction_pointer.as_u64(),
2174        error_code,
2175        stack_frame.code_segment.0,
2176        stack_frame.stack_pointer.as_u64()
2177    );
2178    panic!(
2179        "EXCEPTION: DOUBLE FAULT (error code: {:#x})\n{:#?}",
2180        error_code, stack_frame
2181    );
2182}
2183
2184// =============================================
2185// Hardware IRQ handlers
2186// =============================================
2187
2188/// Legacy external timer IRQ handler (PIC/IOAPIC IRQ0 path, vector 0x20).
2189///
2190/// When the LAPIC timer is active, we ignore this source to avoid double-ticking.
2191extern "x86-interrupt" fn legacy_timer_handler(stack_frame: InterruptStackFrame) {
2192    // Restore kernel GS if the timer fired while Ring 3 was running.
2193    let _gs = SwapGsGuard::new((stack_frame.code_segment.0 & 3) == 3);
2194    if crate::arch::x86_64::timer::is_apic_timer_active() {
2195        // Ignore legacy timer source once LAPIC timer is running.
2196        if super::apic::is_initialized() {
2197            super::apic::eoi();
2198        } else {
2199            pic::end_of_interrupt(0);
2200        }
2201        return;
2202    }
2203
2204    // NOTE: serial_force_println! (formatted format_args!) can hang this IRQ
2205    // handler (known vtable issue) : a hung timer handler kills all
2206    // preemption. The tick counter itself is the trace: E9 raw pulses only.
2207    if crate::debug_cfg::E9_TRACE { unsafe {
2208        core::arch::asm!("out 0xe9, al", in("al") b't', options(nomem, nostack));
2209    } }
2210
2211    // Increment tick counter
2212    crate::process::scheduler::timer_tick();
2213    // NOTE: avoid complex rendering/allocation work in IRQ context.
2214    // Status bar refresh is currently done from non-IRQ paths.
2215
2216    // Send EOI first so the timer can fire again on the new task
2217    if super::apic::is_initialized() {
2218        super::apic::eoi();
2219    } else {
2220        pic::end_of_interrupt(0);
2221    }
2222
2223    // Mirror the LAPIC timer policy: do not run maybe_preempt() directly
2224    // from a Ring-3-origin timer IRQ. The extern "x86-interrupt" frame
2225    // must unwind via iretq; switching away from it can corrupt the
2226    // interrupt return state.
2227    //
2228    // A posted hint is NOT enough: a Ring-3 task that spins without making
2229    // syscalls never consumes it (the hint is only taken in maybe_preempt,
2230    // called from syscall paths and kernel-side preemption), so nothing
2231    // else on this CPU ever schedules again. Send a SELF resched IPI
2232    // instead: the IPI handler has its own full context-save frame and can
2233    // run the scheduler safely, then iretq back to whatever was running.
2234    let cpl = stack_frame.code_segment.0 & 3;
2235    if cpl == 3 {
2236        crate::arch::x86_64::apic::self_ipi_resched();
2237    } else {
2238        crate::process::scheduler::maybe_preempt();
2239    }
2240}
2241
2242/// Local APIC timer handler (dedicated vector, e.g. 0xD2).
2243#[allow(dead_code)] // Retained dedicated LAPIC timer vector handler.
2244extern "x86-interrupt" fn lapic_timer_handler(stack_frame: InterruptStackFrame) {
2245    // Restore kernel GS if the timer fired while Ring 3 was running.
2246    let cs = stack_frame.code_segment.0;
2247    let _gs = SwapGsGuard::new((cs & 3) == 3);
2248    let cpu = crate::arch::x86_64::percpu::current_cpu_index();
2249    // Trace first 10 ticks per CPU unconditionally to confirm timer fires
2250    // after Ring-3 entry, then one-per-100 heartbeat to avoid flooding.
2251    if crate::debug_cfg::E9_TRACE { unsafe {
2252        // Raw pulse only : formatted prints hang the IRQ handler.
2253        core::arch::asm!("out 0xe9, al", in("al") b'T', options(nomem, nostack));
2254    } }
2255
2256    // serial_force_println holds FORCE_LOCK (IRQ-disabled spinlock) while writing
2257    // to the UART. At 115200 baud each byte takes ~87 µs; a 60-char message is
2258    // ~5 ms of IRQs-off time : long enough to miss ticks and corrupt scheduling.
2259    // Keep serial output out of the hot IRQ path; use e9 port (µs-range) instead.
2260    crate::process::scheduler::timer_tick();
2261    if crate::debug_cfg::E9_TRACE { unsafe { core::arch::asm!("mov al, '1'; out 0xe9, al", out("al") _) } };
2262    super::apic::eoi();
2263    // IMPORTANT:
2264    // Do not run `maybe_preempt()` directly from a Ring-3-origin timer IRQ.
2265    //
2266    // Current scheduler switch path (`do_switch_context` + `ret`) is built for
2267    // task context frames, while this function is an `extern "x86-interrupt"`
2268    // frame that the compiler expects to unwind with iretq.
2269    //
2270    // On first user-mode preemption (CPU1), switching away from this frame can
2271    // corrupt the interrupt return state and trigger #DF/#TF. Instead, mark a
2272    // lock-free resched hint and return through the normal interrupt epilogue.
2273    // The scheduler will consume the hint on a safe path.
2274    if (cs & 3) == 3 {
2275        crate::process::scheduler::request_force_resched_hint(cpu);
2276    } else {
2277        crate::process::scheduler::maybe_preempt();
2278    }
2279}
2280
2281/// PS/2 Mouse IRQ12 handler.
2282extern "x86-interrupt" fn mouse_handler(stack_frame: InterruptStackFrame) {
2283    let _gs = SwapGsGuard::new((stack_frame.code_segment.0 & 3) == 3);
2284    // TEMP DEBUG: mouse IRQ pulse on E9.
2285    if crate::debug_cfg::E9_TRACE { unsafe {
2286        core::arch::asm!("out 0xe9, al", in("al") b'M', options(nomem, nostack));
2287        core::arch::asm!("out 0xe9, al", in("al") b'\n', options(nomem, nostack));
2288    } }
2289    crate::arch::x86_64::mouse::handle_irq();
2290    // PS/2 mouse IRQ12 is intentionally kept on the remapped legacy PIC path.
2291    // Even when LAPIC/IOAPIC are active for timer/IPI traffic, this source must
2292    // still be acknowledged via the 8259 PIC.
2293    pic::end_of_interrupt(12);
2294}
2295
2296/// Performs the keyboard handler operation.
2297extern "x86-interrupt" fn keyboard_handler(stack_frame: InterruptStackFrame) {
2298    let _gs = SwapGsGuard::new((stack_frame.code_segment.0 & 3) == 3);
2299    let raw = unsafe { super::io::inb(0x60) };
2300    // TEMP DEBUG: echo every scancode byte on the E9 port.
2301    if crate::debug_cfg::E9_TRACE { unsafe {
2302        core::arch::asm!("out 0xe9, al", in("al") b'K', options(nomem, nostack));
2303        core::arch::asm!("out 0xe9, al", in("al") raw, options(nomem, nostack));
2304        core::arch::asm!("out 0xe9, al", in("al") b'\n', options(nomem, nostack));
2305    } }
2306
2307    // Feed scancode + TSC low bits into the entropy pool.
2308    crate::entropy::add_entropy(1, (raw as u64) ^ super::rdtsc());
2309
2310    crate::arch::x86_64::keyboard::add_raw(raw);
2311    for &ch in super::keyboard_layout::handle_scancode_raw(raw).as_bytes() {
2312        crate::arch::x86_64::keyboard::add_to_buffer(ch);
2313    }
2314
2315    // PS/2 keyboard IRQ1 is intentionally kept on the remapped legacy PIC path.
2316    // A LAPIC EOI here leaves the PIC request in service and stalls keyboard
2317    // delivery after the first edge.
2318    pic::end_of_interrupt(1);
2319}
2320
2321/// Spurious interrupt handler (APIC vector 0xFF).
2322/// Per Intel SDM: do NOT send EOI for spurious interrupts.
2323extern "x86-interrupt" fn spurious_handler(_stack_frame: InterruptStackFrame) {
2324    // Intentionally empty : no EOI per Intel SDM
2325}
2326
2327/// AHCI storage controller IRQ handler.
2328///
2329/// Reads `HBA_IS`, processes per-port completions, wakes waiting tasks, then
2330/// sends EOI.  Must not call any function that may block or allocate.
2331extern "x86-interrupt" fn ahci_handler(stack_frame: InterruptStackFrame) {
2332    let _gs = SwapGsGuard::new((stack_frame.code_segment.0 & 3) == 3);
2333    // Feed IRQ timing into entropy pool.
2334    crate::entropy::add_entropy(3, super::rdtsc());
2335
2336    crate::hardware::storage::ahci::handle_interrupt();
2337
2338    if super::apic::is_initialized() {
2339        super::apic::eoi();
2340    } else {
2341        let irq = crate::hardware::storage::ahci::AHCI_IRQ_LINE
2342            .load(core::sync::atomic::Ordering::Relaxed);
2343        pic::end_of_interrupt(irq);
2344    }
2345}
2346
2347/// NVMe storage controller IRQ handler.
2348///
2349/// Processes I/O completion queue entries and wakes waiting tasks.
2350extern "x86-interrupt" fn nvme_handler(stack_frame: InterruptStackFrame) {
2351    let _gs = SwapGsGuard::new((stack_frame.code_segment.0 & 3) == 3);
2352    crate::entropy::add_entropy(3, super::rdtsc());
2353
2354    crate::hardware::storage::nvme::handle_interrupt();
2355
2356    if super::apic::is_initialized() {
2357        super::apic::eoi();
2358    } else {
2359        let irq = crate::hardware::storage::nvme::NVME_IRQ_LINE
2360            .load(core::sync::atomic::Ordering::Relaxed);
2361        pic::end_of_interrupt(irq);
2362    }
2363}
2364
2365/// VirtIO Block device IRQ handler
2366///
2367/// Handles interrupts from the VirtIO block device.
2368/// The IRQ line is determined at runtime from PCI config.
2369extern "x86-interrupt" fn virtio_block_handler(stack_frame: InterruptStackFrame) {
2370    let _gs = SwapGsGuard::new((stack_frame.code_segment.0 & 3) == 3);
2371    // Handle the VirtIO block interrupt
2372    crate::hardware::storage::virtio_block::handle_interrupt();
2373
2374    // Send EOI
2375    if super::apic::is_initialized() {
2376        super::apic::eoi();
2377    } else {
2378        // Get the IRQ number from the device
2379        let irq = crate::hardware::storage::virtio_block::get_irq();
2380        pic::end_of_interrupt(irq);
2381    }
2382}
2383
2384/// xHCI USB controller IRQ handler
2385///
2386/// Handles interrupts from the xHCI host controller.
2387/// Processes event ring completions for control transfers and HID reports.
2388extern "x86-interrupt" fn xhci_handler(stack_frame: InterruptStackFrame) {
2389    let _gs = SwapGsGuard::new((stack_frame.code_segment.0 & 3) == 3);
2390    crate::hardware::usb::xhci::handle_interrupt();
2391
2392    if super::apic::is_initialized() {
2393        super::apic::eoi();
2394    } else {
2395        let irq =
2396            crate::hardware::usb::xhci::XHCI_IRQ_LINE.load(core::sync::atomic::Ordering::Relaxed);
2397        pic::end_of_interrupt(irq);
2398    }
2399}
2400
2401/// NIC IRQ handler
2402///
2403/// Dispatches to the registered NIC device's `handle_interrupt()` which
2404/// reads ICR, tracks link state, and reclaims completed TX buffers.
2405/// The network stack is expected to call `receive()` in response (or a
2406/// future NAPI-style poll can be driven from here).
2407extern "x86-interrupt" fn nic_handler(stack_frame: InterruptStackFrame) {
2408    // SAFETY: SwapGsGuard restores kernel GS if we interrupted Ring 3.
2409    // Without this guard, SpinLock::lock => current_cpu_index() reads gs:[0]
2410    // and #PF if GS is still set to the user value (swapgs=>iretq window).
2411    let _gs = SwapGsGuard::new((stack_frame.code_segment.0 & 3) == 3);
2412
2413    crate::hardware::nic::handle_interrupt();
2414
2415    if super::apic::is_initialized() {
2416        super::apic::eoi();
2417    } else {
2418        let irq = crate::hardware::nic::NIC_IRQ_LINE.load(core::sync::atomic::Ordering::Relaxed);
2419        pic::end_of_interrupt(irq);
2420    }
2421}
2422
2423/// Cross-CPU reschedule IPI handler (vector 0xF0).
2424///
2425/// Sent by another CPU (via `apic::send_resched_ipi`) to request that this
2426/// CPU preempts its current task immediately rather than waiting for the next
2427/// timer tick. This is used when a task running on this CPU is killed or
2428/// suspended by a different CPU.
2429///
2430/// EOI is sent ***before*** ` maybe_preempt()` so the APIC can accept further
2431/// IPIs before the potentially long context-switch path runs.
2432#[allow(dead_code)] // Retained reschedule IPI vector handler.
2433extern "x86-interrupt" fn resched_ipi_handler(stack_frame: InterruptStackFrame) {
2434    // Restore kernel GS if the IPI arrived while Ring 3 was running.
2435    let _gs = SwapGsGuard::new((stack_frame.code_segment.0 & 3) == 3);
2436    super::apic::eoi();
2437    crate::process::scheduler::maybe_preempt();
2438}
2439
2440/// Cross-CPU TLB shootdown IPI handler (vector 0xF0).
2441extern "x86-interrupt" fn tlb_shootdown_handler(stack_frame: InterruptStackFrame) {
2442    // Restore kernel GS if the IPI arrived while Ring 3 was running.
2443    let _gs = SwapGsGuard::new((stack_frame.code_segment.0 & 3) == 3);
2444    // Note: EOI is sent by the architecture-independent handler.
2445    super::tlb::tlb_shootdown_ipi_handler();
2446}