blob: d8d868070e24043a3da331f677dc4e76c7511499 [file] [log] [blame]
Thomas Garnierd899a7d2016-06-21 17:46:58 -07001/*
2 * Entropy functions used on early boot for KASLR base and memory
3 * randomization. The base randomization is done in the compressed
4 * kernel and memory randomization is done early when the regular
5 * kernel starts. This file is included in the compressed kernel and
6 * normally linked in the regular.
7 */
Matthias Kaehlckec4989202017-05-01 15:47:41 -07008#include <asm/asm.h>
Thomas Garnierd899a7d2016-06-21 17:46:58 -07009#include <asm/kaslr.h>
10#include <asm/msr.h>
11#include <asm/archrandom.h>
12#include <asm/e820.h>
13#include <asm/io.h>
14
15/*
16 * When built for the regular kernel, several functions need to be stubbed out
17 * or changed to their regular kernel equivalent.
18 */
19#ifndef KASLR_COMPRESSED_BOOT
20#include <asm/cpufeature.h>
21#include <asm/setup.h>
22
Nicolas Iooss62d16b52016-08-06 12:20:39 +020023#define debug_putstr(v) early_printk("%s", v)
Thomas Garnierd899a7d2016-06-21 17:46:58 -070024#define has_cpuflag(f) boot_cpu_has(f)
25#define get_boot_seed() kaslr_offset()
26#endif
27
28#define I8254_PORT_CONTROL 0x43
29#define I8254_PORT_COUNTER0 0x40
30#define I8254_CMD_READBACK 0xC0
31#define I8254_SELECT_COUNTER0 0x02
32#define I8254_STATUS_NOTREADY 0x40
33static inline u16 i8254(void)
34{
35 u16 status, timer;
36
37 do {
Daniel Drake3cfc8a22019-01-07 11:40:24 +080038 outb(I8254_CMD_READBACK | I8254_SELECT_COUNTER0,
39 I8254_PORT_CONTROL);
Thomas Garnierd899a7d2016-06-21 17:46:58 -070040 status = inb(I8254_PORT_COUNTER0);
41 timer = inb(I8254_PORT_COUNTER0);
42 timer |= inb(I8254_PORT_COUNTER0) << 8;
43 } while (status & I8254_STATUS_NOTREADY);
44
45 return timer;
46}
47
48unsigned long kaslr_get_random_long(const char *purpose)
49{
50#ifdef CONFIG_X86_64
51 const unsigned long mix_const = 0x5d6008cbf3848dd3UL;
52#else
53 const unsigned long mix_const = 0x3f39e593UL;
54#endif
55 unsigned long raw, random = get_boot_seed();
56 bool use_i8254 = true;
57
58 debug_putstr(purpose);
59 debug_putstr(" KASLR using");
60
61 if (has_cpuflag(X86_FEATURE_RDRAND)) {
62 debug_putstr(" RDRAND");
63 if (rdrand_long(&raw)) {
64 random ^= raw;
65 use_i8254 = false;
66 }
67 }
68
69 if (has_cpuflag(X86_FEATURE_TSC)) {
70 debug_putstr(" RDTSC");
71 raw = rdtsc();
72
73 random ^= raw;
74 use_i8254 = false;
75 }
76
77 if (use_i8254) {
78 debug_putstr(" i8254");
79 random ^= i8254();
80 }
81
82 /* Circular multiply for better bit diffusion */
Matthias Kaehlckec4989202017-05-01 15:47:41 -070083 asm(_ASM_MUL "%3"
Thomas Garnierd899a7d2016-06-21 17:46:58 -070084 : "=a" (random), "=d" (raw)
85 : "a" (random), "rm" (mix_const));
86 random += raw;
87
88 debug_putstr("...\n");
89
90 return random;
91}