X-Git-Url: https://scm.lunaixsky.com/lunaix-os.git/blobdiff_plain/6c506d8916fb114675e93d0e2cb20831d4022294..d1b1c8d9119229dbeed06cd252917e54a1cb77f6:/lunaix-os/arch/i386/hal/rngx86.c diff --git a/lunaix-os/arch/i386/hal/rngx86.c b/lunaix-os/arch/i386/hal/rngx86.c new file mode 100644 index 0000000..b108740 --- /dev/null +++ b/lunaix-os/arch/i386/hal/rngx86.c @@ -0,0 +1,56 @@ +#include +#include + +#include + +static inline void +rng_fill(void* data, size_t len) +{ + asm volatile("1:\n" + "rdrand %%eax\n" + "movl %%eax, (%0)\n" + "addl $4, %%eax\n" + "subl $4, %1\n" + "jnz 1b" ::"r"((ptr_t)data), + "r"((len & ~0x3)) + : "%eax"); +} + +static int +__rand_rd_pg(struct device* dev, void* buf, size_t offset) +{ + rng_fill(buf, PAGE_SIZE); + return PAGE_SIZE; +} + +static int +__rand_rd(struct device* dev, void* buf, size_t offset, size_t len) +{ + if (unlikely(len < 4)) { + int tmp_buf = 0; + rng_fill(&tmp_buf, 4); + memcpy(buf, &tmp_buf, len); + } else { + rng_fill(buf, len); + } + return len; +} + +int +pdev_randdev_init(struct device_def* devdef) +{ + // FIXME add check on cpuid for presence of rdrand + struct device* devrand = device_allocseq(NULL, NULL); + devrand->ops.read = __rand_rd; + devrand->ops.read_page = __rand_rd_pg; + + register_device(devrand, &devdef->class, "rand"); + + return 0; +} + +static struct device_def devrandx86_def = { + .name = "x86 On-Chip RNG", + .class = DEVCLASS(DEVIF_SOC, DEVFN_CHAR, DEV_RNG), + .init = pdev_randdev_init}; +EXPORT_DEVICE(randdev, &devrandx86_def, load_onboot); \ No newline at end of file