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