PCI 16x50 UART Controller, O2 Enablement (#39)
[lunaix-os.git] / lunaix-os / arch / x86 / hal / rngx86.c
1 #include <lunaix/device.h>
2 #include <lunaix/mm/pagetable.h>
3
4 #include <klibc/string.h>
5
6 static inline void
7 rng_fill(void* data, size_t len)
8 {
9 #ifdef CONFIG_ARCH_X86_64
10     asm volatile("1:\n"
11                  "rdrand %%rax\n"
12                  "movq   %%rax, (%0)\n"
13                  "addq   $8, %%rax\n"
14                  "subq   $8, %1\n"
15                  "jnz    1b" 
16                  ::
17                  "r"((ptr_t)data),
18                  "r"((len & ~0x7))
19                  : 
20                  "%eax");
21 #else
22     asm volatile("1:\n"
23                  "rdrand %%eax\n"
24                  "movl %%eax, (%0)\n"
25                  "addl $4, %%eax\n"
26                  "subl $4, %1\n"
27                  "jnz 1b" 
28                  ::
29                  "r"((ptr_t)data),
30                  "r"((len & ~0x3))
31                  : 
32                  "%eax");
33 #endif
34 }
35
36 static int
37 __rand_rd_pg(struct device* dev, void* buf, size_t offset)
38 {
39     rng_fill(buf, PAGE_SIZE);
40     return PAGE_SIZE;
41 }
42
43 static int
44 __rand_rd(struct device* dev, void* buf, size_t offset, size_t len)
45 {
46     if (unlikely(len < sizeof(ptr_t))) {
47         int tmp_buf = 0;
48         rng_fill(&tmp_buf, sizeof(ptr_t));
49         memcpy(buf, &tmp_buf, len);
50     } else {
51         rng_fill(buf, len);
52     }
53     return len;
54 }
55
56 int
57 pdev_randdev_init(struct device_def* devdef)
58 {
59     // FIXME add check on cpuid for presence of rdrand
60     struct device* devrand = device_allocseq(NULL, NULL);
61     devrand->ops.read = __rand_rd;
62     devrand->ops.read_page = __rand_rd_pg;
63
64     register_device(devrand, &devdef->class, "rand");
65
66     return 0;
67 }
68
69 static struct device_def devrandx86_def = {
70     .name = "x86 On-Chip RNG",
71     .class = DEVCLASS(DEVIF_SOC, DEVFN_CHAR, DEV_RNG),
72     .init = pdev_randdev_init};
73 EXPORT_DEVICE(randdev, &devrandx86_def, load_onboot);