xref: /linux/arch/x86/lib/kaslr.c (revision 74ce1896c6c65b2f8cccbf59162d542988835835)
1 /*
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  */
8 #include <asm/asm.h>
9 #include <asm/kaslr.h>
10 #include <asm/msr.h>
11 #include <asm/archrandom.h>
12 #include <asm/e820/api.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 
23 #define debug_putstr(v) early_printk("%s", v)
24 #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
33 static inline u16 i8254(void)
34 {
35 	u16 status, timer;
36 
37 	do {
38 		outb(I8254_PORT_CONTROL,
39 		     I8254_CMD_READBACK | I8254_SELECT_COUNTER0);
40 		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 
48 unsigned 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 */
83 	asm(_ASM_MUL "%3"
84 	    : "=a" (random), "=d" (raw)
85 	    : "a" (random), "rm" (mix_const));
86 	random += raw;
87 
88 	debug_putstr("...\n");
89 
90 	return random;
91 }
92