From 70d78d86be89b7e2651d2b79235eaa43f7552520 Mon Sep 17 00:00:00 2001 From: apio Date: Mon, 31 Oct 2022 16:18:05 +0100 Subject: [PATCH] Kernel: Add CPU functions in a portable way --- moon/src/arch/cpu.rs | 2 ++ moon/src/arch/mod.rs | 4 ++++ moon/src/arch/x86_64/cpu.rs | 27 +++++++++++++++++++++++++++ moon/src/arch/x86_64/mod.rs | 1 + moon/src/init.rs | 9 +++++++++ moon/src/main.rs | 10 +++++++++- 6 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 moon/src/arch/cpu.rs create mode 100644 moon/src/arch/mod.rs create mode 100644 moon/src/arch/x86_64/cpu.rs create mode 100644 moon/src/arch/x86_64/mod.rs diff --git a/moon/src/arch/cpu.rs b/moon/src/arch/cpu.rs new file mode 100644 index 00000000..7f6a1368 --- /dev/null +++ b/moon/src/arch/cpu.rs @@ -0,0 +1,2 @@ +#![cfg(target_arch = "x86_64")] +pub use super::x86_64::cpu::*; \ No newline at end of file diff --git a/moon/src/arch/mod.rs b/moon/src/arch/mod.rs new file mode 100644 index 00000000..a704f875 --- /dev/null +++ b/moon/src/arch/mod.rs @@ -0,0 +1,4 @@ +pub mod cpu; + +#[cfg(target_arch = "x86_64")] +mod x86_64; \ No newline at end of file diff --git a/moon/src/arch/x86_64/cpu.rs b/moon/src/arch/x86_64/cpu.rs new file mode 100644 index 00000000..ff8e4f44 --- /dev/null +++ b/moon/src/arch/x86_64/cpu.rs @@ -0,0 +1,27 @@ +#![cfg(target_arch = "x86_64")] +#![allow(dead_code)] + +use core::arch::x86_64::{__cpuid as do_cpuid, CpuidResult}; +use core::arch::asm; + +fn safe_cpuid(leaf: u32) -> CpuidResult { + return unsafe { do_cpuid(leaf) }; +} + +pub fn get_processor_id() -> u32 { + let cpuid_result = safe_cpuid(1); + return cpuid_result.ebx >> 24; +} + +pub fn halt() -> ! { + loop { + unsafe { + asm!("cli"); + asm!("hlt"); + } + } +} + +pub fn wait_for_interrupt() -> () { + unsafe { asm!("hlt"); } +} \ No newline at end of file diff --git a/moon/src/arch/x86_64/mod.rs b/moon/src/arch/x86_64/mod.rs new file mode 100644 index 00000000..374e8ae6 --- /dev/null +++ b/moon/src/arch/x86_64/mod.rs @@ -0,0 +1 @@ +pub mod cpu; \ No newline at end of file diff --git a/moon/src/init.rs b/moon/src/init.rs index 2fa10f43..dea50760 100644 --- a/moon/src/init.rs +++ b/moon/src/init.rs @@ -1,6 +1,15 @@ use crate::bootboot::{BOOTBOOT, BOOTBOOT_MAGIC}; use crate::util::get_bootboot; +use crate::arch::cpu; + +pub fn halt_other_cores() -> () { + let boot: BOOTBOOT = get_bootboot(); + if cpu::get_processor_id() != boot.bspid as u32 { + cpu::halt(); + } +} + pub fn check_magic() -> () { let boot: BOOTBOOT = get_bootboot(); assert_eq!(boot.magic, BOOTBOOT_MAGIC[..4]); diff --git a/moon/src/main.rs b/moon/src/main.rs index 8b2cbc21..c09d2071 100644 --- a/moon/src/main.rs +++ b/moon/src/main.rs @@ -6,12 +6,20 @@ mod bootboot; mod panic; mod util; mod init; +mod arch; + +use arch::cpu; use video::Color; #[no_mangle] pub extern "C" fn _start() -> ! { + + init::halt_other_cores(); init::check_magic(); + video::clear(Color::White); - loop {} + + cpu::halt(); + } \ No newline at end of file