x86_64: generate a seed for the RNG with RDRAND when available

This commit is contained in:
2026-03-14 22:18:47 +00:00
parent d2203d9a65
commit 72145257de
3 changed files with 67 additions and 0 deletions

View File

@@ -0,0 +1,10 @@
#ifndef KERNEL_X86_64_RANDOM_H_
#define KERNEL_X86_64_RANDOM_H_
#include <stdbool.h>
#include <stdint.h>
extern bool ml_hwrng_available(void);
extern uint64_t ml_hwrng_generate(void);
#endif

View File

@@ -10,12 +10,14 @@
#include <kernel/init.h> #include <kernel/init.h>
#include <kernel/libc/stdio.h> #include <kernel/libc/stdio.h>
#include <kernel/machine/cpu.h> #include <kernel/machine/cpu.h>
#include <kernel/machine/random.h>
#include <kernel/memblock.h> #include <kernel/memblock.h>
#include <kernel/object.h> #include <kernel/object.h>
#include <kernel/percpu.h> #include <kernel/percpu.h>
#include <kernel/pmap.h> #include <kernel/pmap.h>
#include <kernel/printk.h> #include <kernel/printk.h>
#include <kernel/types.h> #include <kernel/types.h>
#include <kernel/util.h>
#include <kernel/vm.h> #include <kernel/vm.h>
#define PTR32(x) ((void *)((uintptr_t)(x))) #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; 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); early_vm_init(reserve_end);
e820_scan(PTR32(mb->mmap_addr), mb->mmap_length); e820_scan(PTR32(mb->mmap_addr), mb->mmap_length);

43
arch/x86_64/random.S Normal file
View File

@@ -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