juno_trng.c 2.17 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 <arm_acle.h>
8
#include <assert.h>
9
10
#include <stdbool.h>
#include <stdint.h>
11
#include <string.h>
12
13
14

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

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

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

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

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

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

		val = mmio_read_32(TRNG_BASE + TRNG_STATUS);
		if (val & 1U)
34
			return true;
35
	}
36
	return false; /* No output data available. */
37
38
}

39
40
static uint32_t crc_value = ~0U;

41
/*
42
 * This function fills `buf` with 8 bytes of entropy.
43
 * It uses the Trusted Entropy Source peripheral on Juno.
44
45
 * Returns 'true' when the buffer has been filled with entropy
 * successfully, or 'false' otherwise.
46
 */
47
bool juno_getentropy(uint64_t *buf)
48
{
49
	uint64_t ret;
50
51

	assert(buf);
52
53
54
55
56
57
58
59
60
61
62
	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);
63

64
65
		juno_trng_initialized = true;
	}
66

67
	if (!output_valid()) {
68
69
70
71
		/* Start TRNG. */
		mmio_write_32(TRNG_BASE + TRNG_CONTROL, 1);

		if (!output_valid())
72
			return false;
73
74
	}

75
76
77
78
	/* CRC each two 32-bit registers together, combine the pairs */
	crc_value = __crc32w(crc_value, mmio_read_32(TRNG_BASE + 0));
	crc_value = __crc32w(crc_value, mmio_read_32(TRNG_BASE + 4));
	ret = (uint64_t)crc_value << 32;
79

80
81
82
	crc_value = __crc32w(crc_value, mmio_read_32(TRNG_BASE + 8));
	crc_value = __crc32w(crc_value, mmio_read_32(TRNG_BASE + 12));
	*buf = ret | crc_value;
83
84
85
86
87
88
89

	/* 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;
90
}