5-malloc.md (#25)
[lunaix-os.git] / lunaix-os / hal / rng / rngx86.c
index aea9b691cd7b6e7a169890cd33a1c7baba0f2c19..0b8a586cd7e057228c2965d4b23ec55f1005577d 100644 (file)
@@ -1,6 +1,8 @@
 #include <lunaix/device.h>
 #include <lunaix/mm/page.h>
 
+#include <klibc/string.h>
+
 static inline void
 rng_fill(void* data, size_t len)
 {
@@ -24,15 +26,31 @@ __rand_rd_pg(struct device* dev, void* buf, size_t offset)
 static int
 __rand_rd(struct device* dev, void* buf, size_t offset, size_t len)
 {
-    rng_fill(buf, 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;
 }
 
-void
-pdev_randdev_init()
+int
+pdev_randdev_init(struct device_def* devdef)
 {
-    struct device* devrand = device_addseq(NULL, NULL, "rand");
+    // 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;
 }
-EXPORT_PSEUDODEV(randdev, pdev_randdev_init);
\ No newline at end of file
+
+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