1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2014, 2015 Linaro Limited
4  */
5 
6 #include <arm.h>
7 #include <crypto/crypto.h>
8 #include <kernel/misc.h>
9 #include <kernel/tee_time.h>
10 #include <kernel/time_source.h>
11 #include <mm/core_mmu.h>
12 #include <stdint.h>
13 #include <tee/tee_cryp_utl.h>
14 #include <trace.h>
15 #include <utee_defines.h>
16 
arm_cntpct_get_sys_time(TEE_Time * time)17 static TEE_Result arm_cntpct_get_sys_time(TEE_Time *time)
18 {
19 	uint64_t cntpct = barrier_read_counter_timer();
20 	uint32_t cntfrq = read_cntfrq();
21 
22 	time->seconds = cntpct / cntfrq;
23 	time->millis = (cntpct % cntfrq) / (cntfrq / TEE_TIME_MILLIS_BASE);
24 
25 	return TEE_SUCCESS;
26 }
27 
28 static const struct time_source arm_cntpct_time_source = {
29 	.name = "arm cntpct",
30 	.protection_level = 1000,
31 	.get_sys_time = arm_cntpct_get_sys_time,
32 };
33 
REGISTER_TIME_SOURCE(arm_cntpct_time_source)34 REGISTER_TIME_SOURCE(arm_cntpct_time_source)
35 
36 /*
37  * We collect jitter using cntpct in 32- or 64-bit mode that is typically
38  * clocked at around 1MHz.
39  *
40  * The first time we are called, we add low 16 bits of the counter as entropy.
41  *
42  * Subsequently, accumulate 2 low bits each time by:
43  *
44  *  - rotating the accumumlator by 2 bits
45  *  - XORing it in 2-bit chunks with the whole CNTPCT contents
46  *
47  * and adding one byte of entropy when we reach 8 rotated bits.
48  */
49 
50 void plat_prng_add_jitter_entropy(enum crypto_rng_src sid, unsigned int *pnum)
51 {
52 	uint64_t tsc = barrier_read_counter_timer();
53 	int bytes = 0, n;
54 	static uint8_t first, bits;
55 	static uint16_t acc;
56 
57 	if (!first) {
58 		acc = tsc;
59 		bytes = 2;
60 		first = 1;
61 	} else {
62 		acc = (acc << 2) | ((acc >> 6) & 3);
63 		for (n = 0; n < 64; n += 2)
64 			acc ^= (tsc >> n) & 3;
65 		bits += 2;
66 		if (bits >= 8) {
67 			bits = 0;
68 			bytes = 1;
69 		}
70 	}
71 	if (bytes) {
72 		FMSG("0x%02X", (int)acc & ((1 << (bytes * 8)) - 1));
73 		crypto_rng_add_event(sid, pnum, (uint8_t *)&acc, bytes);
74 	}
75 }
76