From 72145257dec43b9f9ffdccdb41d6ab4891a7e28e Mon Sep 17 00:00:00 2001 From: Max Wash Date: Sat, 14 Mar 2026 22:18:47 +0000 Subject: [PATCH] x86_64: generate a seed for the RNG with RDRAND when available --- arch/x86_64/include/kernel/machine/random.h | 10 +++++ arch/x86_64/init.c | 14 +++++++ arch/x86_64/random.S | 43 +++++++++++++++++++++ 3 files changed, 67 insertions(+) create mode 100644 arch/x86_64/include/kernel/machine/random.h create mode 100644 arch/x86_64/random.S diff --git a/arch/x86_64/include/kernel/machine/random.h b/arch/x86_64/include/kernel/machine/random.h new file mode 100644 index 0000000..95aa8f6 --- /dev/null +++ b/arch/x86_64/include/kernel/machine/random.h @@ -0,0 +1,10 @@ +#ifndef KERNEL_X86_64_RANDOM_H_ +#define KERNEL_X86_64_RANDOM_H_ + +#include +#include + +extern bool ml_hwrng_available(void); +extern uint64_t ml_hwrng_generate(void); + +#endif diff --git a/arch/x86_64/init.c b/arch/x86_64/init.c index 05cd9fd..a4e6d98 100644 --- a/arch/x86_64/init.c +++ b/arch/x86_64/init.c @@ -10,12 +10,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include #define PTR32(x) ((void *)((uintptr_t)(x))) @@ -123,6 +125,18 @@ int ml_init(uintptr_t arg) reserve_end = bsp.mod_base + bsp.mod_size; } + if (ml_hwrng_available()) { + printk("cpu: ardware RNG available"); + uint64_t seed = ml_hwrng_generate(); + printk("cpu: RNG seed=%zx", seed); + init_random(seed); + } else { + printk("cpu: hardware RNG unavailable"); + uint64_t seed = 0xeddc4c8a679dc23f; + printk("cpu: RNG seed=%zx", seed); + init_random(seed); + } + early_vm_init(reserve_end); e820_scan(PTR32(mb->mmap_addr), mb->mmap_length); diff --git a/arch/x86_64/random.S b/arch/x86_64/random.S new file mode 100644 index 0000000..28cc254 --- /dev/null +++ b/arch/x86_64/random.S @@ -0,0 +1,43 @@ +.code64 + +.global ml_hwrng_available +.type ml_hwrng_available, @function + +ml_hwrng_available: + push %rbp + mov %rsp, %rbp + push %rbx + push %rdx + + mov $1, %eax + mov $0, %ecx + + cpuid + + shr $30, %ecx + and $1, %ecx + mov %ecx, %eax + + pop %rdx + pop %rbx + pop %rbp + ret + +.global ml_hwrng_generate +.type ml_hwrng_generate, @function + +ml_hwrng_generate: + push %rbp + mov %rsp, %rbp + + mov $100, %rcx +.retry: + rdrand %rax + jc .done + loop .retry + +.fail: + mov $0, %rax +.done: + pop %rbp + ret