//! x86-64 registers and instructions the rest of the kernel asks for. /// This core's index (0 boots, the others count up as they start): where /// its GS base points (`smp::set_core`). pub fn core_id() -> usize { let id: usize; // SAFETY: GS points at the core's entry of `smp`'s table from the // first Rust instruction on. unsafe { core::arch::asm!("mov {}, gs:[0]", out(reg) id, options(readonly, nostack, preserves_flags)) }; id } /// Sleeps until an interrupt arrives. A compiler barrier (no `nomem`): the /// interrupt's handler changes memory a waiting loop reads. pub fn wait_for_interrupt() { // SAFETY: HLT only pauses the core. unsafe { core::arch::asm!("hlt", options(nostack)) }; } /// CPUID leaf `leaf` (sub-leaf 0): EAX, EBX, ECX, EDX. pub fn cpuid(leaf: u32) -> [u32; 4] { // CPUID only reads; every x86-64 core has it. let r = core::arch::x86_64::__cpuid_count(leaf, 0); [r.eax, r.ebx, r.ecx, r.edx] } /// The core's maker and model, as CPUID names them. pub fn cpu_name() -> alloc::string::String { let mut bytes = alloc::vec::Vec::new(); if cpuid(0x8000_0000)[0] >= 0x8000_0004 { for leaf in 0x8000_0002..=0x8000_0004 { for word in cpuid(leaf) { bytes.extend_from_slice(&word.to_le_bytes()); } } } let name = core::str::from_utf8(&bytes) .unwrap_or("") .trim_matches(['\0', ' ']); alloc::string::String::from(if name.is_empty() { "an x86-64 core" } else { name }) } /// Lets this core run SSE, which the crypto instructions need (the kernel /// itself is built without it): no FPU emulation, FXSAVE and SIMD /// exceptions known to the OS. pub fn enable_sse() { // SAFETY: CR0.EM off and MP on, CR4.OSFXSR and OSXMMEXCPT on. unsafe { core::arch::asm!( "mov {t}, cr0", "and {t}, ~(1 << 2)", "or {t}, 1 << 1", "mov cr0, {t}", "mov {t}, cr4", "or {t}, (1 << 9) | (1 << 10)", "mov cr4, {t}", t = out(reg) _, options(nostack), ); } } /// Whether the core has SHA-NI (with SSSE3 and SSE4.1, its shuffles) and /// AES-NI. pub fn crypto_features() -> (bool, bool) { let one = cpuid(1)[2]; let (ssse3, sse41, aes) = (one & (1 << 9) != 0, one & (1 << 19) != 0, one & (1 << 25) != 0); let sha = cpuid(0)[0] >= 7 && cpuid(7)[1] & (1 << 29) != 0; (sha && ssse3 && sse41, aes) } /// The time-stamp counter. pub fn tsc() -> u64 { // SAFETY: RDTSC only reads the counter. #[allow(unused_unsafe)] unsafe { core::arch::x86_64::_rdtsc() } } /// Writes `value` to I/O port `port`. pub fn out8(port: u16, value: u8) { // SAFETY: the callers name ports of devices the PC has at fixed places. unsafe { core::arch::asm!("out dx, al", in("dx") port, in("al") value, options(nomem, nostack)) }; } /// Writes `value` to the 16-bit I/O port `port`. pub fn out16(port: u16, value: u16) { // SAFETY: as in `out8`. unsafe { core::arch::asm!("out dx, ax", in("dx") port, in("ax") value, options(nomem, nostack)) }; } /// Reads I/O port `port`. pub fn in8(port: u16) -> u8 { let value: u8; // SAFETY: as in `out8`. unsafe { core::arch::asm!("in al, dx", in("dx") port, out("al") value, options(nomem, nostack)) }; value } /// Writes `value` to the 32-bit I/O port `port`. pub fn out32(port: u16, value: u32) { // SAFETY: as in `out8`. unsafe { core::arch::asm!("out dx, eax", in("dx") port, in("eax") value, options(nomem, nostack)) }; } /// Reads the 16-bit I/O port `port`. pub fn in16(port: u16) -> u16 { let value: u16; // SAFETY: as in `out8`. unsafe { core::arch::asm!("in ax, dx", in("dx") port, out("ax") value, options(nomem, nostack)) }; value } /// Reads the 32-bit I/O port `port`. pub fn in32(port: u16) -> u32 { let value: u32; // SAFETY: as in `out8`. unsafe { core::arch::asm!("in eax, dx", in("dx") port, out("eax") value, options(nomem, nostack)) }; value } /// Reads model-specific register `msr`. pub fn read_msr(msr: u32) -> u64 { let (low, high): (u32, u32); // SAFETY: the callers name registers every x86-64 core has, or ones // CPUID said this one has. unsafe { core::arch::asm!("rdmsr", in("ecx") msr, out("eax") low, out("edx") high, options(nomem, nostack)) }; u64::from(high) << 32 | u64::from(low) } /// Writes model-specific register `msr`. pub fn write_msr(msr: u32, value: u64) { // SAFETY: as in `read_msr`. unsafe { core::arch::asm!( "wrmsr", in("ecx") msr, in("eax") value as u32, in("edx") (value >> 32) as u32, options(nostack) ) }; } /// 64 random bits from the core's own generator (RDSEED, else RDRAND), /// or None when it has neither or they keep failing. pub fn hardware_random() -> Option { let seed = cpuid(0)[0] >= 7 && cpuid(7)[1] & (1 << 18) != 0; let rand = cpuid(1)[2] & (1 << 30) != 0; for _ in 0..32 { let (value, ok): (u64, u8); // SAFETY: CPUID said the instruction is there; it only writes the // register and the carry. unsafe { if seed { core::arch::asm!("rdseed {}", "setc {}", out(reg) value, out(reg_byte) ok, options(nomem, nostack)); } else if rand { core::arch::asm!("rdrand {}", "setc {}", out(reg) value, out(reg_byte) ok, options(nomem, nostack)); } else { return None; } } if ok != 0 { return Some(value); } core::hint::spin_loop(); } None } /// The machine a program's ELF must be built for: EM_X86_64. pub const ELF_MACHINE: u16 = 62; /// Nothing to do on a PC: table writes are seen by the walk as they are. pub fn tables_written() {} /// Nothing to do on a PC: the instruction cache follows stores. pub fn make_executable(_start: usize, _len: usize) {} /// A system call from kernel code (sleeping, yielding, ending a kernel /// task): `int 0x80`, whose stub saves and restores every register but /// the results'. pub fn kernel_call(call: u64, argument: u64) { // SAFETY: the kernel answers it like a program's, perhaps with a switch. unsafe { core::arch::asm!( "int 0x80", inout("rax") call => _, in("rdi") argument, lateout("rdx") _, lateout("rcx") _, ); } } /// The scheduler is about to run the task whose kernel stack ends at /// `top`: an interrupt from its program lands there. pub fn entering_task(top: u64) { crate::gdt::set_kernel_stack(top); } /// Whether a program's FP/SIMD use goes ahead (CR0.TS clear) or traps with /// #NM (`sched::fp_trap`). pub fn fp_access(open: bool) { // SAFETY: only CR0.TS changes. unsafe { if open { core::arch::asm!("clts", options(nomem, nostack)); } else { core::arch::asm!( "mov {t}, cr0", "or {t}, 1 << 3", "mov cr0, {t}", t = out(reg) _, options(nomem, nostack), ); } } } /// Saves the core's x87, MMX and SSE registers into `state` (FXSAVE's 512 /// bytes; the rest of the 528 is ARM's). pub fn save_fp(state: &mut [u8; 528]) { // SAFETY: writes 512 bytes at a 16-byte aligned address (the state's // type is aligned so); TS is clear, as the caller opened access. unsafe { core::arch::asm!("fxsave64 [{}]", in(reg) state.as_mut_ptr(), options(nostack)) }; } /// Loads them from `state`, as [`save_fp`] wrote it; a task that never /// saved any starts from the defaults FXRSTOR takes from zeros, with MXCSR /// set to its reset value. pub fn load_fp(state: &[u8; 528]) { #[repr(C, align(16))] struct Aligned([u8; 528]); let mut start = Aligned([0; 528]); let state = if state[24..28] == [0; 4] { // MXCSR at offset 24: 0x1f80, every exception masked; the x87 // control word at 0: 0x037f. start.0[24..28].copy_from_slice(&0x1f80u32.to_le_bytes()); start.0[0..2].copy_from_slice(&0x037fu16.to_le_bytes()); &start.0 } else { state }; // SAFETY: reads 512 bytes at a 16-byte aligned address; TS is clear. unsafe { core::arch::asm!("fxrstor64 [{}]", in(reg) state.as_ptr(), options(nostack)) }; } /// What the crypto instructions are, as ARM's ID_AA64ISAR0_EL1 would say /// it (SHA-256 in bits 12–15, AES in 4–7): the form the CPU_FEATURES call /// hands programs. pub fn isar0() -> u64 { let (sha, aes) = crypto_features(); (u64::from(sha) << 12) | (u64::from(aes) << 4) } /// The time-stamp counter: the finest clock there is. pub fn counter() -> u64 { tsc() }