1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright IBM Corp. 2019
5 #include <asm/mem_detect.h>
9 #include "compressed/decompressor.h"
11 #define PRNG_MODE_TDES 1
12 #define PRNG_MODE_SHA512 2
13 #define PRNG_MODE_TRNG 3
29 static int check_prng(void)
31 if (!cpacf_query_func(CPACF_KMC
, CPACF_KMC_PRNG
)) {
32 sclp_early_printk("KASLR disabled: CPU has no PRNG\n");
35 if (cpacf_query_func(CPACF_PRNO
, CPACF_PRNO_TRNG
))
36 return PRNG_MODE_TRNG
;
37 if (cpacf_query_func(CPACF_PRNO
, CPACF_PRNO_SHA512_DRNG_GEN
))
38 return PRNG_MODE_SHA512
;
40 return PRNG_MODE_TDES
;
43 static unsigned long get_random(unsigned long limit
)
45 struct prng_parm prng
= {
46 /* initial parameter block for tdes mode, copied from libica */
48 0x0F, 0x2B, 0x8E, 0x63, 0x8C, 0x8E, 0xD2, 0x52,
49 0x64, 0xB7, 0xA0, 0x7B, 0x75, 0x28, 0xB8, 0xF4,
50 0x75, 0x5F, 0xD2, 0xA6, 0x8D, 0x97, 0x11, 0xFF,
51 0x49, 0xD8, 0x23, 0xF3, 0x7E, 0x21, 0xEC, 0xA0
54 unsigned long seed
, random
;
55 struct prno_parm prno
;
60 seed
= get_tod_clock_fast();
63 cpacf_trng(NULL
, 0, (u8
*) &random
, sizeof(random
));
65 case PRNG_MODE_SHA512
:
66 cpacf_prno(CPACF_PRNO_SHA512_DRNG_SEED
, &prno
, NULL
, 0,
67 (u8
*) &seed
, sizeof(seed
));
68 cpacf_prno(CPACF_PRNO_SHA512_DRNG_GEN
, &prno
, (u8
*) &random
,
69 sizeof(random
), NULL
, 0);
73 *(unsigned long *) prng
.parm_block
^= seed
;
74 for (i
= 0; i
< 16; i
++) {
75 cpacf_kmc(CPACF_KMC_PRNG
, prng
.parm_block
,
76 (char *) entropy
, (char *) entropy
,
78 memcpy(prng
.parm_block
, entropy
, sizeof(entropy
));
81 cpacf_kmc(CPACF_KMC_PRNG
, prng
.parm_block
, (u8
*) &random
,
82 (u8
*) &random
, sizeof(random
));
87 return random
% limit
;
90 unsigned long get_random_base(unsigned long safe_addr
)
92 unsigned long base
, start
, end
, kernel_size
;
93 unsigned long block_sum
, offset
;
96 if (IS_ENABLED(CONFIG_BLK_DEV_INITRD
) && INITRD_START
&& INITRD_SIZE
) {
97 if (safe_addr
< INITRD_START
+ INITRD_SIZE
)
98 safe_addr
= INITRD_START
+ INITRD_SIZE
;
100 safe_addr
= ALIGN(safe_addr
, THREAD_SIZE
);
102 kernel_size
= vmlinux
.image_size
+ vmlinux
.bss_size
;
104 for_each_mem_detect_block(i
, &start
, &end
) {
105 if (memory_end_set
) {
106 if (start
>= memory_end
)
108 if (end
> memory_end
)
111 if (end
- start
< kernel_size
)
113 block_sum
+= end
- start
- kernel_size
;
116 sclp_early_printk("KASLR disabled: not enough memory\n");
120 base
= get_random(block_sum
);
123 if (base
< safe_addr
)
125 block_sum
= offset
= 0;
126 for_each_mem_detect_block(i
, &start
, &end
) {
127 if (memory_end_set
) {
128 if (start
>= memory_end
)
130 if (end
> memory_end
)
133 if (end
- start
< kernel_size
)
135 block_sum
+= end
- start
- kernel_size
;
136 if (base
<= block_sum
) {
137 base
= start
+ base
- offset
;
138 base
= ALIGN_DOWN(base
, THREAD_SIZE
);