esp_hw_support/bootloader: made ESP32-C6 and ESP32-H2 RNG available

This commit is contained in:
Jakob Hasse
2023-02-10 14:13:20 +08:00
committed by Mahavir Jain
parent 0ed8499898
commit b0e2f33082
7 changed files with 270 additions and 14 deletions

View File

@@ -8,6 +8,10 @@
#include "esp_cpu.h"
#include "soc/wdev_reg.h"
#if defined CONFIG_IDF_TARGET_ESP32C6
#include "hal/lp_timer_hal.h"
#endif
#ifndef BOOTLOADER_BUILD
#include "esp_random.h"
#include "esp_private/periph_ctrl.h"
@@ -20,9 +24,27 @@
#else
#if !defined CONFIG_IDF_TARGET_ESP32S3
#define RNG_CPU_WAIT_CYCLE_NUM (80 * 32 * 2) /* extra factor of 2 is precautionary */
#if (defined CONFIG_IDF_TARGET_ESP32C6 || defined CONFIG_IDF_TARGET_ESP32H2)
#define RNG_CPU_WAIT_CYCLE_NUM (80 * 12) // higher frequency because we are reading bytes instead of words
#else
#define RNG_CPU_WAIT_CYCLE_NUM (80 * 32 * 2) /* extra factor of 2 is precautionary */
#endif
#else
#define RNG_CPU_WAIT_CYCLE_NUM (80 * 23) /* 45 KHz reading frequency is the maximum we have tested so far on S3 */
#define RNG_CPU_WAIT_CYCLE_NUM (80 * 23) /* 45 KHz reading frequency is the maximum we have tested so far on S3 */
#endif
#if defined CONFIG_IDF_TARGET_ESP32H2
// TODO: temporary definition until IDF-6270 is implemented
#include "soc/lp_timer_reg.h"
static inline uint32_t lp_timer_hal_get_cycle_count(void)
{
REG_SET_BIT(LP_TIMER_UPDATE_REG, LP_TIMER_MAIN_TIMER_UPDATE);
uint32_t lo = REG_GET_FIELD(LP_TIMER_MAIN_BUF0_LOW_REG, LP_TIMER_MAIN_TIMER_BUF0_LOW);
return lo;
}
#endif
__attribute__((weak)) void bootloader_fill_random(void *buffer, size_t length)
@@ -34,6 +56,21 @@
assert(buffer != NULL);
for (size_t i = 0; i < length; i++) {
#if (defined CONFIG_IDF_TARGET_ESP32C6 || defined CONFIG_IDF_TARGET_ESP32H2)
random = REG_READ(WDEV_RND_REG);
start = esp_cpu_get_cycle_count();
do {
random ^= REG_READ(WDEV_RND_REG);
now = esp_cpu_get_cycle_count();
} while (now - start < RNG_CPU_WAIT_CYCLE_NUM);
// XOR the RT slow clock, which is asynchronous, to add some entropy and improve
// the distribution
uint32_t current_rtc_timer_counter = (lp_timer_hal_get_cycle_count() & 0xFF);
random = random ^ current_rtc_timer_counter;
buffer_bytes[i] = random & 0xFF;
#else
if (i == 0 || i % 4 == 0) { /* redundant check is for a compiler warning */
/* in bootloader with ADC feeding HWRNG, we accumulate 1
bit of entropy per 40 APB cycles (==80 CPU cycles.)
@@ -50,6 +87,7 @@
} while (now - start < RNG_CPU_WAIT_CYCLE_NUM);
}
buffer_bytes[i] = random >> ((i % 4) * 8);
#endif
}
}