• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2017-2018, ARM Limited and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include <assert.h>
8 #include <stdbool.h>
9 #include <stdint.h>
10 #include <string.h>
11 
12 #include <lib/mmio.h>
13 #include <lib/utils_def.h>
14 #include <platform_def.h>
15 
16 #include "juno_decl.h"
17 
18 #define NSAMPLE_CLOCKS	1 /* min 1 cycle, max 231 cycles */
19 #define NRETRIES	5
20 
21 /* initialised to false */
22 static bool juno_trng_initialized;
23 
output_valid(void)24 static bool output_valid(void)
25 {
26 	int i;
27 
28 	for (i = 0; i < NRETRIES; i++) {
29 		uint32_t val;
30 
31 		val = mmio_read_32(TRNG_BASE + TRNG_STATUS);
32 		if (val & 1U)
33 			return true;
34 	}
35 	return false; /* No output data available. */
36 }
37 
38 /*
39  * This function fills `buf` with 8 bytes of entropy.
40  * It uses the Trusted Entropy Source peripheral on Juno.
41  * Returns 'true' when the buffer has been filled with entropy
42  * successfully, or 'false' otherwise.
43  */
juno_getentropy(uint64_t * buf)44 bool juno_getentropy(uint64_t *buf)
45 {
46 	uint64_t ret;
47 
48 	assert(buf);
49 	assert(!check_uptr_overflow((uintptr_t)buf, sizeof(*buf)));
50 
51 	if (!juno_trng_initialized) {
52 		/* Disable interrupt mode. */
53 		mmio_write_32(TRNG_BASE + TRNG_INTMASK, 0);
54 		/* Program TRNG to sample for `NSAMPLE_CLOCKS`. */
55 		mmio_write_32(TRNG_BASE + TRNG_CONFIG, NSAMPLE_CLOCKS);
56 		/* Abort any potentially pending sampling. */
57 		mmio_write_32(TRNG_BASE + TRNG_CONTROL, 2);
58 		/* Reset TRNG outputs. */
59 		mmio_write_32(TRNG_BASE + TRNG_STATUS, 1);
60 
61 		juno_trng_initialized = true;
62 	}
63 
64 	if (!output_valid()) {
65 		/* Start TRNG. */
66 		mmio_write_32(TRNG_BASE + TRNG_CONTROL, 1);
67 
68 		if (!output_valid())
69 			return false;
70 	}
71 
72 	/* XOR each two 32-bit registers together, combine the pairs */
73 	ret = mmio_read_32(TRNG_BASE + 0);
74 	ret ^= mmio_read_32(TRNG_BASE + 4);
75 	ret <<= 32;
76 
77 	ret |= mmio_read_32(TRNG_BASE + 8);
78 	ret ^= mmio_read_32(TRNG_BASE + 12);
79 	*buf = ret;
80 
81 	/* Acknowledge current cycle, clear output registers. */
82 	mmio_write_32(TRNG_BASE + TRNG_STATUS, 1);
83 	/* Trigger next TRNG cycle. */
84 	mmio_write_32(TRNG_BASE + TRNG_CONTROL, 1);
85 
86 	return true;
87 }
88