//! 当前处理器 ID 的读写（per-arch 寄存器）
#![no_std]
#![allow(unsafe_code)]

use moa_cpumask::CpuId;

/// 设置当前处理器 ID
///
/// 寄存器约定：CPU ID 放在 aarch64 `sp_el0` / riscv64 `gp`，
/// 与 task 锚点（aarch64 `tpidr_el1` / riscv64 `tp`）分离。
#[inline(always)]
pub fn set_this_cpuid(id: CpuId) {
    core::cfg_select! {
        aarch64_moana => {
            unsafe { core::arch::asm!("msr sp_el0, {0}", in(reg) id.raw()) };
        }
        riscv64_moana => {
            unsafe { core::arch::asm!("mv gp, {0}", in(reg) id.raw()) };
        }
        _ => {
            let _ = id;
        }
    }
}

/// 获取当前处理器 ID
#[inline(always)]
pub fn this_cpuid() -> CpuId {
    core::cfg_select! {
        aarch64_moana => {
            let id: usize;
            unsafe { core::arch::asm!("mrs {0}, sp_el0", out(reg) id) };
            CpuId::from_raw(id)
        }
        riscv64_moana => {
            let id: usize;
            unsafe { core::arch::asm!("mv {0}, gp", out(reg) id) };
            CpuId::from_raw(id)
        }
        _ => {
            unreachable!()
        }
    }
}
