use alloc::collections::BTreeMap;
use core::sync::atomic::{AtomicBool, Ordering};
use spin::Once;
use crate::{
arch::boot::smp::{bringup_all_aps, get_num_processors},
cpu,
mm::{
paddr_to_vaddr,
page::{self, meta::KernelMeta, ContPages},
PAGE_SIZE,
},
};
pub(crate) static AP_BOOT_INFO: Once<ApBootInfo> = Once::new();
const AP_BOOT_STACK_SIZE: usize = PAGE_SIZE * 64;
pub(crate) struct ApBootInfo {
pub(crate) boot_stack_array: ContPages<KernelMeta>,
per_ap_info: BTreeMap<u32, PerApInfo>,
}
struct PerApInfo {
is_started: AtomicBool,
boot_stack_pages: ContPages<KernelMeta>,
}
static AP_LATE_ENTRY: Once<fn() -> !> = Once::new();
pub fn boot_all_aps() {
let Some(num_cpus) = get_num_processors() else {
log::warn!("No processor information found. The kernel operates with a single processor.");
return;
};
log::info!("Found {} processors.", num_cpus);
AP_BOOT_INFO.call_once(|| {
let mut per_ap_info = BTreeMap::new();
let boot_stack_array =
page::allocator::alloc_contiguous(2 * PAGE_SIZE, |_| KernelMeta::default()).unwrap();
assert!(num_cpus < 1024);
for ap in 1..num_cpus {
let boot_stack_pages =
page::allocator::alloc_contiguous(AP_BOOT_STACK_SIZE, |_| KernelMeta::default())
.unwrap();
let boot_stack_ptr = paddr_to_vaddr(boot_stack_pages.end_paddr());
let stack_array_ptr = paddr_to_vaddr(boot_stack_array.start_paddr()) as *mut u64;
unsafe {
stack_array_ptr
.add(ap as usize)
.write_volatile(boot_stack_ptr as u64);
}
per_ap_info.insert(
ap,
PerApInfo {
is_started: AtomicBool::new(false),
boot_stack_pages,
},
);
}
ApBootInfo {
boot_stack_array,
per_ap_info,
}
});
log::info!("Booting all application processors...");
bringup_all_aps();
wait_for_all_aps_started();
log::info!("All application processors started. The BSP continues to run.");
}
pub fn register_ap_entry(entry: fn() -> !) {
AP_LATE_ENTRY.call_once(|| entry);
}
#[no_mangle]
fn ap_early_entry(local_apic_id: u32) -> ! {
crate::arch::enable_cpu_features();
unsafe {
cpu::local::init_on_ap(local_apic_id);
cpu::set_this_cpu_id(local_apic_id);
}
unsafe {
crate::arch::trap::init(false);
}
unsafe {
crate::arch::init_on_ap();
}
crate::arch::irq::enable_local();
unsafe {
crate::mm::kspace::activate_kernel_page_table();
}
let ap_boot_info = AP_BOOT_INFO.get().unwrap();
ap_boot_info
.per_ap_info
.get(&local_apic_id)
.unwrap()
.is_started
.store(true, Ordering::Release);
log::info!("Processor {} started. Spinning for tasks.", local_apic_id);
let ap_late_entry = AP_LATE_ENTRY.wait();
ap_late_entry();
}
fn wait_for_all_aps_started() {
fn is_all_aps_started() -> bool {
let ap_boot_info = AP_BOOT_INFO.get().unwrap();
ap_boot_info
.per_ap_info
.values()
.all(|info| info.is_started.load(Ordering::Acquire))
}
while !is_all_aps_started() {
core::hint::spin_loop();
}
}