garage44.eu/jeroen/pinnacle

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

.. /kernel/src/x86_64/smp.rs

raw

//! Cores on a PC: every one ACPI's MADT names, woken by its APIC with INIT
//! and two STARTUPs, as Intel's MP specification has it. A woken core
//! starts in 16-bit real mode at the page the STARTUP names, so a
//! trampoline is copied below 1 MiB (to [`TRAMPOLINE`]); it climbs through
//! protected mode into long mode on the boot core's tables and jumps to
//! [`secondary_main`] on a stack of its own.
//!
//! Each core finds its index through GS: its base points at the core's
//! entry in [`IDS`], read by `arch::core_id` in one load.

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

/// The most cores the kernel's per-core tables hold, as on ARM.
pub const MAX_CORES: usize = 64;

/// Where the trampoline runs: a page in the first MiB, which the allocator
/// never hands out. STARTUP takes its page number.
const TRAMPOLINE: usize = 0x8000;

/// Each core's index, for its GS base to point at.
static IDS: [usize; MAX_CORES] = {
    let mut ids = [0; MAX_CORES];
    let mut i = 0;
    while i < MAX_CORES {
        ids[i] = i;
        i += 1;
    }
    ids
};

/// Cores running, as a bit mask, the boot core among them.
static ONLINE: AtomicU64 = AtomicU64::new(1);

/// Each core's APIC ID, by index: where an IPI for it goes.
static APIC_IDS: [AtomicU32; MAX_CORES] = [const { AtomicU32::new(0) }; MAX_CORES];

/// Core `core`'s APIC ID.
pub fn apic_id(core: usize) -> u32 {
    APIC_IDS[core].load(Ordering::Relaxed)
}

/// Notes the boot core's APIC ID, once its APIC is on: message interrupts
/// and the I/O APIC's pins are aimed at it before the other cores start.
pub fn set_boot_apic_id(id: u32) {
    APIC_IDS[0].store(id, Ordering::Relaxed);
}

/// Points this core's GS base at its index.
pub fn set_core(core: usize) {
    let address = &raw const IDS[core] as u64;
    // SAFETY: IA32_GS_BASE; the kernel uses GS for nothing else.
    unsafe {
        core::arch::asm!(
            "wrmsr",
            in("ecx") 0xc000_0101u32,
            in("eax") address as u32,
            in("edx") (address >> 32) as u32,
            options(nostack),
        );
    }
}

// The trampoline: assembled here, copied to TRAMPOLINE, so every address
// in it is its offset from `ap_start` plus TRAMPOLINE, and the far jumps
// are written out as bytes. The boot core fills the four slots at its end
// before each STARTUP.
core::arch::global_asm!(
    ".pushsection .rodata.trampoline, \"a\"",
    ".global ap_start",
    ".global ap_end",
    ".global ap_cr3",
    ".global ap_stack",
    ".global ap_entry",
    ".global ap_core",
    ".code16",
    "ap_start:",
    "cli",
    "xor ax, ax",
    "mov ds, ax",
    // lgdt [disp16]
    ".byte 0x0f, 0x01, 0x16",
    ".word ap_gdtr - ap_start + {at}",
    "mov eax, cr0",
    "or eax, 1",
    "mov cr0, eax",
    // ljmp 0x18:ap_32, with a 32-bit offset
    ".byte 0x66, 0xea",
    ".long ap_32 - ap_start + {at}",
    ".word 0x18",
    ".code32",
    "ap_32:",
    "mov ax, 0x10",
    "mov ds, ax",
    "mov es, ax",
    "mov ss, ax",
    "mov eax, cr4",
    "or eax, 1 << 5",
    "mov cr4, eax",
    ".byte 0xa1", // mov eax, [ap_cr3]
    ".long ap_cr3 - ap_start + {at}",
    "mov cr3, eax",
    "mov ecx, 0xc0000080",
    "rdmsr",
    "or eax, (1 << 8) | (1 << 11)",
    "wrmsr",
    "mov eax, cr0",
    "or eax, 1 << 31",
    "mov cr0, eax",
    // ljmp 0x08:ap_64
    ".byte 0xea",
    ".long ap_64 - ap_start + {at}",
    ".word 0x08",
    ".code64",
    "ap_64:",
    "mov ax, 0x10",
    "mov ds, ax",
    "mov es, ax",
    "mov ss, ax",
    "xor eax, eax",
    "mov fs, ax",
    "mov gs, ax",
    ".byte 0x48, 0x8b, 0x24, 0x25", // mov rsp, [ap_stack]
    ".long ap_stack - ap_start + {at}",
    ".byte 0x48, 0x8b, 0x3c, 0x25", // mov rdi, [ap_core]
    ".long ap_core - ap_start + {at}",
    ".byte 0x48, 0x8b, 0x04, 0x25", // mov rax, [ap_entry]
    ".long ap_entry - ap_start + {at}",
    "jmp rax",
    ".balign 8",
    "ap_gdt:",
    ".quad 0",
    // As boot's, so the interrupt table's 0x08 is 64-bit code here too.
    ".quad 0x00af9a000000ffff", // 0x08: 64-bit code
    ".quad 0x00cf92000000ffff", // 0x10: data
    ".quad 0x00cf9a000000ffff", // 0x18: 32-bit code, for the climb
    "ap_gdtr:",
    ".word ap_gdtr - ap_gdt - 1",
    ".long ap_gdt - ap_start + {at}",
    ".balign 8",
    "ap_cr3: .quad 0",
    "ap_stack: .quad 0",
    "ap_entry: .quad 0",
    "ap_core: .quad 0",
    "ap_end:",
    ".popsection",
    at = const TRAMPOLINE,
);

unsafe extern "C" {
    static ap_start: u8;
    static ap_end: u8;
    static ap_cr3: u8;
    static ap_stack: u8;
    static ap_entry: u8;
    static ap_core: u8;
}

/// Where a trampoline slot is, once copied.
fn slot(symbol: *const u8) -> *mut u64 {
    let offset = symbol as usize - &raw const ap_start as usize;
    crate::mmu::virt(TRAMPOLINE + offset) as *mut u64
}

/// Wakes every core in `apic_ids` but this one, one at a time, each on a
/// 16 KiB stack; returns how many run in all.
pub fn start_cores(apic_ids: &[u32]) -> usize {
    let (start, end) = (&raw const ap_start, &raw const ap_end);
    let len = end as usize - start as usize;
    // SAFETY: the trampoline's bytes, to a page of the first MiB no one
    // else uses.
    unsafe { core::ptr::copy_nonoverlapping(start, crate::mmu::virt(TRAMPOLINE) as *mut u8, len) };
    let cr3: u64;
    // SAFETY: reading CR3 has no side effects.
    unsafe { core::arch::asm!("mov {}, cr3", out(reg) cr3, options(nomem, nostack)) };
    let me = crate::apic::id();
    APIC_IDS[0].store(me, Ordering::Relaxed);
    let mut core = 1;
    for &id in apic_ids.iter().filter(|&&id| id != me) {
        if core == MAX_CORES {
            crate::println!("smp: more cores than the kernel's {MAX_CORES}; the rest stay off");
            break;
        }
        // Its idle task's stack, as on ARM.
        let stack = crate::sched::stack_top(core);
        APIC_IDS[core].store(id, Ordering::Relaxed);
        // SAFETY: the copied trampoline's slots, read by the core woken next.
        unsafe {
            slot(&raw const ap_cr3).write_volatile(cr3);
            slot(&raw const ap_stack).write_volatile(stack);
            slot(&raw const ap_entry).write_volatile(secondary_main as *const () as u64);
            slot(&raw const ap_core).write_volatile(core as u64);
        }
        crate::apic::wake(id, (TRAMPOLINE >> 12) as u8);
        let deadline = crate::timer::now_ms() + 200;
        while online() & (1 << core) == 0 && crate::timer::now_ms() < deadline {
            core::hint::spin_loop();
        }
        if online() & (1 << core) == 0 {
            crate::println!("smp: the core with APIC ID {id} did not start");
            continue;
        }
        core += 1;
    }
    online().count_ones() as usize
}

/// Cores that run, as a bit mask.
pub fn online() -> u64 {
    ONLINE.load(Ordering::Acquire)
}

/// Each woken core, from the trampoline: in long mode on the boot core's
/// tables and its idle task's stack. It takes its index, its segments, the
/// interrupt table, its APIC and its timer, says it runs, and idles.
extern "C" fn secondary_main(core: usize) -> ! {
    set_core(core);
    // The page types as the boot core has them, before this core draws.
    crate::mmu::set_pat();
    crate::arch::enable_sse();
    crate::gdt::load(core);
    crate::exceptions::init();
    crate::apic::init_core();
    crate::timer::start();
    ONLINE.fetch_or(1 << core, Ordering::Release);
    crate::irq::enable();
    crate::sched::idle()
}