garage44.eu/jeroen/pinnacle

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

.. /kernel/src/x86_64/interrupts.rs

raw

//! The interrupt descriptor table, the PC's twin of ARM's exception
//! vectors: 256 entry stubs that save every register into a [`Frame`] and
//! call [`handle`], which returns the frame to resume; the scheduler
//! answers with another task's, which is the whole context switch. The
//! CPU's own exceptions (0–31) panic when the kernel causes them and end
//! the program when a program does; from 32 up come the APIC's timer, the
//! cores' IPIs (`gic::SGI_BASE`) and, at [`SYSCALL`], system calls (`int
//! 0x80`, the one gate a program may use).

use core::sync::atomic::{AtomicU64, Ordering};

/// The registers an interrupt saved, lowest address first: the general
/// registers as the stub pushed them, then the vector and the error code,
/// then what the CPU pushed.
#[repr(C)]
pub struct Frame {
    pub r15: u64,
    pub r14: u64,
    pub r13: u64,
    pub r12: u64,
    pub r11: u64,
    pub r10: u64,
    pub r9: u64,
    pub r8: u64,
    pub rbp: u64,
    pub rdi: u64,
    pub rsi: u64,
    pub rdx: u64,
    pub rcx: u64,
    pub rbx: u64,
    pub rax: u64,
    pub vector: u64,
    pub error: u64,
    pub rip: u64,
    pub cs: u64,
    pub rflags: u64,
    pub rsp: u64,
    pub ss: u64,
}

// Each stub is 16 bytes apart, so the table is filled by arithmetic: it
// pushes an error code where the CPU pushes none (all but 8, 10–14, 17, 21,
// 29 and 30), then its vector, and joins the common part. Every frame is
// 176 bytes, which keeps the stack 16-byte aligned for the call.
core::arch::global_asm!(
    ".pushsection .text.interrupts, \"ax\"",
    ".balign 16",
    ".global interrupt_stubs",
    "interrupt_stubs:",
    ".set n, 0",
    ".rept 256",
    ".balign 16",
    ".if (n == 8) | (n == 10) | (n == 11) | (n == 12) | (n == 13) | (n == 14) | (n == 17) | (n == 21) | (n == 29) | (n == 30)",
    ".else",
    ".byte 0x6a, 0", // push 0
    ".endif",
    // push n: as a byte while it fits one signed, else as four. (Written
    // out: in Intel syntax a bare symbol would be read as memory.)
    ".if n < 128",
    ".byte 0x6a, n",
    ".else",
    ".byte 0x68",
    ".long n",
    ".endif",
    "jmp interrupt_common",
    ".set n, n + 1",
    ".endr",
    "interrupt_common:",
    "push rax",
    "push rbx",
    "push rcx",
    "push rdx",
    "push rsi",
    "push rdi",
    "push rbp",
    "push r8",
    "push r9",
    "push r10",
    "push r11",
    "push r12",
    "push r13",
    "push r14",
    "push r15",
    "mov rdi, rsp",
    "cld",
    "call {handle}",
    "mov rsp, rax",
    "pop r15",
    "pop r14",
    "pop r13",
    "pop r12",
    "pop r11",
    "pop r10",
    "pop r9",
    "pop r8",
    "pop rbp",
    "pop rdi",
    "pop rsi",
    "pop rdx",
    "pop rcx",
    "pop rbx",
    "pop rax",
    "add rsp, 16",
    "iretq",
    ".popsection",
    handle = sym handle,
);

unsafe extern "C" {
    static interrupt_stubs: u8;
}

#[repr(C, packed)]
struct Pointer {
    limit: u16,
    base: u64,
}

/// One gate: the handler's address in three parts, the kernel's code
/// segment (boot's 0x08), present, an interrupt gate (IF cleared on entry).
#[derive(Clone, Copy)]
#[repr(C)]
struct Gate {
    low: u64,
    high: u64,
}

impl Gate {
    /// `user`: a program may raise it with `int` (DPL 3).
    fn new(handler: u64, user: bool) -> Self {
        let kind: u64 = if user { 0xee } else { 0x8e };
        let low = (handler & 0xffff) | (0x08 << 16) | (kind << 40) | ((handler >> 16) & 0xffff) << 48;
        Gate {
            low,
            high: handler >> 32,
        }
    }
}

/// A system call: `int 0x80`, the number in RAX, the arguments in RDI,
/// RSI, RDX, R10, R8, R9 and R12, the results in RAX, RDX and RCX.
pub const SYSCALL: u64 = 0x80;

/// The rflags a task starts with: interrupts on (and bit 1, always set).
const RFLAGS_START: u64 = 0x202;

/// What the scheduler and the system calls ask of a frame, as ARM's
/// `exceptions::Frame` answers it.
impl Frame {
    fn empty() -> Frame {
        // SAFETY: a frame is plain integers; all zero is a valid one.
        unsafe { core::mem::zeroed() }
    }

    /// A kernel task's first frame: `entry` on the task's own stack, which
    /// returns into `ret`. Its stack pointer is set when it is placed
    /// ([`placed_at`](Self::placed_at)); until then RSP holds `ret`.
    pub fn kernel_task(entry: u64, ret: u64) -> Frame {
        Frame {
            rip: entry,
            cs: u64::from(crate::gdt::KERNEL_CODE),
            rflags: RFLAGS_START,
            rsp: ret,
            ss: u64::from(crate::gdt::KERNEL_DATA),
            ..Frame::empty()
        }
    }

    /// A program thread's first frame: `entry` in ring 3 with `stack`, and
    /// `argument` in RDI. The stack is entered as a call leaves it, 8 bytes
    /// below a 16-byte boundary, as the ABI has a function find it.
    pub fn program(entry: u64, stack: u64, argument: u64) -> Frame {
        Frame {
            rdi: argument,
            rip: entry,
            cs: u64::from(crate::gdt::USER_CODE),
            rflags: RFLAGS_START,
            rsp: (stack & !15) - 8,
            ss: u64::from(crate::gdt::USER_DATA),
            ..Frame::empty()
        }
    }

    /// Told where the scheduler put the frame, at the top of the task's
    /// stack: a kernel task's stack is what lies below it, the return
    /// address pushed as a call would have.
    pub fn placed_at(&mut self, at: u64) {
        if self.is_kernel() {
            let ret = self.rsp;
            self.rsp = at - 8;
            // SAFETY: the word below the frame, on the task's own stack.
            unsafe { (self.rsp as *mut u64).write(ret) };
        }
    }

    pub fn call(&self) -> u64 {
        self.rax
    }

    pub fn args(&self) -> [u64; 7] {
        [self.rdi, self.rsi, self.rdx, self.r10, self.r8, self.r9, self.r12]
    }

    pub fn set_result(&mut self, (a, b, c): (u64, u64, u64)) {
        (self.rax, self.rdx, self.rcx) = (a, b, c);
    }

    pub fn set_first_result(&mut self, a: u64) {
        self.rax = a;
    }

    /// Back to the `int 0x80` (two bytes), to make the call again.
    pub fn repeat_call(&mut self) {
        self.rip -= 2;
    }

    pub fn is_kernel(&self) -> bool {
        self.cs & 3 == 0
    }

    pub fn pc(&self) -> u64 {
        self.rip
    }

    pub fn status(&self) -> u64 {
        self.rflags
    }
}

static mut TABLE: [Gate; 256] = [Gate { low: 0, high: 0 }; 256];

/// Fills the table (once) and loads it on this core.
pub fn init() {
    static FILLED: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
    if FILLED.swap(true, Ordering::AcqRel) {
        load();
        return;
    }
    let stubs = &raw const interrupt_stubs as u64;
    let table = &raw mut TABLE;
    for vector in 0..256 {
        // SAFETY: written once, before any core takes an interrupt
        // through it.
        unsafe { (*table)[vector] = Gate::new(stubs + 16 * vector as u64, vector as u64 == SYSCALL) };
    }
    load();
}

/// Loads the table on this core.
pub fn load() {
    let pointer = Pointer {
        limit: (size_of::<[Gate; 256]>() - 1) as u16,
        base: &raw const TABLE as u64,
    };
    // SAFETY: the table is complete and lives for ever.
    unsafe { core::arch::asm!("lidt [{}]", in(reg) &pointer, options(readonly, nostack)) };
}

/// Breakpoints taken (`int3`): the self-check's proof the path works.
pub static BREAKPOINTS: AtomicU64 = AtomicU64::new(0);

const BREAKPOINT: u64 = 3;
/// #NM: FP/SIMD used while CR0.TS says another task's registers are loaded.
const DEVICE_NOT_AVAILABLE: u64 = 7;
const RESCHEDULE: u64 = (crate::gic::SGI_BASE + crate::sched::RESCHEDULE) as u64;

extern "C" fn handle(frame: *mut Frame) -> *mut Frame {
    // SAFETY: the stub just wrote this frame on the stack.
    let f = unsafe { &mut *frame };
    match f.vector {
        BREAKPOINT => {
            BREAKPOINTS.fetch_add(1, Ordering::Relaxed);
            frame
        }
        // The kernel's own SSE (the crypto routines, which keep every
        // register as they found it): let it, and leave the owner alone.
        DEVICE_NOT_AVAILABLE if f.is_kernel() => {
            crate::arch::fp_access(true);
            frame
        }
        DEVICE_NOT_AVAILABLE => crate::sched::fp_trap(frame),
        // A program's fault ends the program, not the kernel.
        vector @ 0..32 if !f.is_kernel() => {
            crate::println!(
                "task {} killed: exception {vector} (error {:#x}) at {:#x}, cr2 {:#x}",
                crate::sched::current(),
                f.error,
                f.rip,
                cr2()
            );
            crate::sched::exit_process(frame, pinnacle_abi::KILLED + vector)
        }
        0..32 => panic!(
            "exception {} (error {:#x}) at {:#x}, cr2 {:#x}",
            f.vector,
            f.error,
            f.rip,
            cr2()
        ),
        SYSCALL => crate::syscall::handle(frame),
        crate::apic::TIMER => {
            crate::timer::tick();
            // The network's timers ride on core 0's tick, as on ARM.
            if crate::arch::core_id() == 0 {
                crate::drivers::net::tick();
                crate::drivers::ps2::poll();
            }
            crate::apic::end();
            crate::sched::preempt(frame)
        }
        RESCHEDULE => {
            crate::apic::end();
            crate::sched::preempt(frame)
        }
        crate::apic::SPURIOUS => frame,
        vector if crate::gic::is_device(vector as u32) => {
            if !crate::drivers::interrupt(vector as u32) {
                crate::println!("interrupt {vector}: no driver's");
            }
            crate::apic::end();
            frame
        }
        vector => {
            crate::println!("interrupt {vector} has no handler; ignored");
            crate::apic::end();
            frame
        }
    }
}

fn cr2() -> u64 {
    let cr2: u64;
    // SAFETY: reading CR2 has no side effects.
    unsafe { core::arch::asm!("mov {}, cr2", out(reg) cr2, options(nomem, nostack)) };
    cr2
}