2 * Copyright (c) 2014, 2015 Linaro Limited
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
19 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25 * POSSIBILITY OF SUCH DAMAGE.
28 #include <kernel/misc.h>
29 #include <kernel/tee_time.h>
31 #include <kernel/time_source.h>
32 #include <mm/core_mmu.h>
33 #include <utee_defines.h>
35 #include <tee/tee_cryp_utl.h>
41 static TEE_Result arm_cntpct_get_sys_time(TEE_Time *time)
43 uint64_t cntpct = read_cntpct();
44 uint32_t cntfrq = read_cntfrq();
46 time->seconds = cntpct / cntfrq;
47 time->millis = (cntpct % cntfrq) / (cntfrq / TEE_TIME_MILLIS_BASE);
52 static const struct time_source arm_cntpct_time_source = {
54 .protection_level = 1000,
55 .get_sys_time = arm_cntpct_get_sys_time,
58 REGISTER_TIME_SOURCE(arm_cntpct_time_source)
61 * We collect jitter using cntpct in 32- or 64-bit mode that is typically
62 * clocked at around 1MHz.
64 * The first time we are called, we add low 16 bits of the counter as entropy.
66 * Subsequently, accumulate 2 low bits each time by:
68 * - rotating the accumumlator by 2 bits
69 * - XORing it in 2-bit chunks with the whole CNTPCT contents
71 * and adding one byte of entropy when we reach 8 rotated bits.
74 void plat_prng_add_jitter_entropy(void)
76 uint64_t tsc = read_cntpct();
78 static uint8_t first, bits;
86 acc = (acc << 2) | ((acc >> 6) & 3);
87 for (n = 0; n < 64; n += 2)
88 acc ^= (tsc >> n) & 3;
96 DMSG("%s: 0x%02X\n", __func__,
97 (int)acc & ((1 << (bytes * 8)) - 1));
98 tee_prng_add_entropy((uint8_t *)&acc, bytes);