axhal/platform/x86_pc/
mp.rs

1use crate::mem::{PAGE_SIZE_4K, PhysAddr, phys_to_virt};
2use crate::time::{Duration, busy_wait};
3
4const START_PAGE_IDX: u8 = 6;
5const START_PAGE_PADDR: PhysAddr = pa!(START_PAGE_IDX as usize * PAGE_SIZE_4K);
6
7core::arch::global_asm!(
8    include_str!("ap_start.S"),
9    start_page_paddr = const START_PAGE_PADDR.as_usize(),
10);
11
12unsafe fn setup_startup_page(stack_top: PhysAddr) {
13    unsafe extern "C" {
14        fn ap_entry32();
15        fn ap_start();
16        fn ap_end();
17    }
18    const U64_PER_PAGE: usize = PAGE_SIZE_4K / 8;
19
20    let start_page_ptr = phys_to_virt(START_PAGE_PADDR).as_mut_ptr() as *mut u64;
21    let start_page = core::slice::from_raw_parts_mut(start_page_ptr, U64_PER_PAGE);
22    core::ptr::copy_nonoverlapping(
23        ap_start as *const u64,
24        start_page_ptr,
25        (ap_end as usize - ap_start as usize) / 8,
26    );
27    start_page[U64_PER_PAGE - 2] = stack_top.as_usize() as u64; // stack_top
28    start_page[U64_PER_PAGE - 1] = ap_entry32 as usize as _; // entry
29}
30
31/// Starts the given secondary CPU with its boot stack.
32pub fn start_secondary_cpu(apic_id: usize, stack_top: PhysAddr) {
33    unsafe { setup_startup_page(stack_top) };
34
35    let apic_id = super::apic::raw_apic_id(apic_id as u8);
36    let lapic = super::apic::local_apic();
37
38    // INIT-SIPI-SIPI Sequence
39    // Ref: Intel SDM Vol 3C, Section 8.4.4, MP Initialization Example
40    unsafe { lapic.send_init_ipi(apic_id) };
41    busy_wait(Duration::from_millis(10)); // 10ms
42    unsafe { lapic.send_sipi(START_PAGE_IDX, apic_id) };
43    busy_wait(Duration::from_micros(200)); // 200us
44    unsafe { lapic.send_sipi(START_PAGE_IDX, apic_id) };
45}