summaryrefslogtreecommitdiff
path: root/src/kernel/random.c
blob: 404223a0102f2c45dbcc2d8ff623b5a2287a27c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <stdbool.h>
#include <cpuid.h>
#include <printf.h>
#include <stdint.h>

static bool hw_random = false;
static unsigned long int seed = -1;

void randinit() {
  unsigned int unused, eax, ecx;
  eax = 0;
  ecx = 0;
  __get_cpuid(1, &eax, &unused, &ecx, &unused); 
  hw_random = (ecx >> 30) & 1;
  printf("Kernel random source: %s.\n", (hw_random) ? "rdrand" : "pseudo");
}

//As of now, this function isn't nessesarily meant to be fast.
unsigned int randint() {
  uint64_t random_long = 0;
  if(hw_random) {
    asm("rand:\n"
        "rdrand %0\n"
        "jc finished\n"
        "pause\n"
        "jmp rand\n"
        "finished:" :"=r"(random_long)::"rax" );
  }
  else {
    //TODO FUCKING ENTROPY!!!!!!!111
    seed = 1103515245 * seed + 12345;
    return(unsigned int)(seed / 65536) % 32768;
  }
  return 0;
}