juno_trng.c 1.98 KB
Newer Older
1
/*
Roberto Vargas's avatar
Roberto Vargas committed
2
 * Copyright (c) 2017-2018, ARM Limited and Contributors. All rights reserved.
3
 *
dp-arm's avatar
dp-arm committed
4
 * SPDX-License-Identifier: BSD-3-Clause
5
6
7
 */

#include <assert.h>
8
9
#include <stdbool.h>
#include <stdint.h>
10
#include <string.h>
11
12
13

#include <lib/mmio.h>
#include <lib/utils_def.h>
14
#include <platform_def.h>
15

Roberto Vargas's avatar
Roberto Vargas committed
16
#include "juno_decl.h"
17
18
19
20

#define NSAMPLE_CLOCKS	1 /* min 1 cycle, max 231 cycles */
#define NRETRIES	5

21
22
23
24
/* initialised to false */
static bool juno_trng_initialized;

static bool output_valid(void)
25
26
27
28
29
30
31
32
{
	int i;

	for (i = 0; i < NRETRIES; i++) {
		uint32_t val;

		val = mmio_read_32(TRNG_BASE + TRNG_STATUS);
		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
42
 * Returns 'true' when the buffer has been filled with entropy
 * successfully, or 'false' otherwise.
43
 */
44
bool juno_getentropy(uint64_t *buf)
45
{
46
	uint64_t ret;
47
48

	assert(buf);
49
50
51
52
53
54
55
56
57
58
59
	assert(!check_uptr_overflow((uintptr_t)buf, sizeof(*buf)));

	if (!juno_trng_initialized) {
		/* Disable interrupt mode. */
		mmio_write_32(TRNG_BASE + TRNG_INTMASK, 0);
		/* Program TRNG to sample for `NSAMPLE_CLOCKS`. */
		mmio_write_32(TRNG_BASE + TRNG_CONFIG, NSAMPLE_CLOCKS);
		/* Abort any potentially pending sampling. */
		mmio_write_32(TRNG_BASE + TRNG_CONTROL, 2);
		/* Reset TRNG outputs. */
		mmio_write_32(TRNG_BASE + TRNG_STATUS, 1);
60

61
62
		juno_trng_initialized = true;
	}
63

64
	if (!output_valid()) {
65
66
67
68
		/* Start TRNG. */
		mmio_write_32(TRNG_BASE + TRNG_CONTROL, 1);

		if (!output_valid())
69
			return false;
70
71
	}

72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
	/* XOR each two 32-bit registers together, combine the pairs */
	ret = mmio_read_32(TRNG_BASE + 0);
	ret ^= mmio_read_32(TRNG_BASE + 4);
	ret <<= 32;

	ret |= mmio_read_32(TRNG_BASE + 8);
	ret ^= mmio_read_32(TRNG_BASE + 12);
	*buf = ret;

	/* Acknowledge current cycle, clear output registers. */
	mmio_write_32(TRNG_BASE + TRNG_STATUS, 1);
	/* Trigger next TRNG cycle. */
	mmio_write_32(TRNG_BASE + TRNG_CONTROL, 1);

	return true;
87
}