Support to multi-threading and pthread interface (POSIX.1-2008) (#23)
[lunaix-os.git] / lunaix-os / hal / rng / rngx86.c
1 #include <lunaix/device.h>
2 #include <lunaix/mm/page.h>
3
4 #include <klibc/string.h>
5
6 static inline void
7 rng_fill(void* data, size_t len)
8 {
9     asm volatile("1:\n"
10                  "rdrand %%eax\n"
11                  "movl %%eax, (%0)\n"
12                  "addl $4, %%eax\n"
13                  "subl $4, %1\n"
14                  "jnz 1b" ::"r"((ptr_t)data),
15                  "r"((len & ~0x3))
16                  : "%eax");
17 }
18
19 static int
20 __rand_rd_pg(struct device* dev, void* buf, size_t offset)
21 {
22     rng_fill(buf, PG_SIZE);
23     return PG_SIZE;
24 }
25
26 static int
27 __rand_rd(struct device* dev, void* buf, size_t offset, size_t len)
28 {
29     if (unlikely(len < 4)) {
30         int tmp_buf = 0;
31         rng_fill(&tmp_buf, 4);
32         memcpy(buf, &tmp_buf, len);
33     } else {
34         rng_fill(buf, len);
35     }
36     return len;
37 }
38
39 int
40 pdev_randdev_init(struct device_def* devdef)
41 {
42     // FIXME add check on cpuid for presence of rdrand
43     struct device* devrand = device_allocseq(NULL, NULL);
44     devrand->ops.read = __rand_rd;
45     devrand->ops.read_page = __rand_rd_pg;
46
47     register_device(devrand, &devdef->class, "rand");
48
49     return 0;
50 }
51
52 static struct device_def devrandx86_def = {
53     .name = "x86 On-Chip RNG",
54     .class = DEVCLASS(DEVIF_SOC, DEVFN_CHAR, DEV_RNG),
55     .init = pdev_randdev_init};
56 EXPORT_DEVICE(randdev, &devrandx86_def, load_onboot);