machine: implement RNG for esp32s3 based on the onboard hardware random number generator.

Signed-off-by: deadprogram <ron@hybridgroup.com>
This commit is contained in:
deadprogram
2026-02-27 19:05:47 +01:00
parent 69a4dda8c8
commit 3c590e36ad
4 changed files with 38 additions and 3 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build nrf || (stm32 && !(stm32f103 || stm32l0x1)) || (sam && atsamd51) || (sam && atsame5x) || esp32c3 || tkey || (tinygo.riscv32 && virt)
//go:build nrf || (stm32 && !(stm32f103 || stm32l0x1)) || (sam && atsamd51) || (sam && atsame5x) || esp32c3 || esp32s3 || tkey || (tinygo.riscv32 && virt)
// If you update the above build constraint, you'll probably also need to update
// src/runtime/rand_hwrng.go.
+35
View File
@@ -312,3 +312,38 @@ func (uart *UART) writeByte(b byte) error {
}
func (uart *UART) flush() {}
// GetRNG returns 32-bit random numbers using the ESP32-S3 true random number generator,
// Random numbers are generated based on the thermal noise in the system and the
// asynchronous clock mismatch.
// For maximum entropy also make sure that the SAR_ADC is enabled.
// See esp32-s3_technical_reference_manual_en.pdf p.920
func GetRNG() (ret uint32, err error) {
// ensure ADC clock is initialized
initADCClock()
// ensure fast RTC clock is enabled
if esp.RTC_CNTL.GetCLK_CONF_DIG_CLK8M_EN() == 0 {
esp.RTC_CNTL.SetCLK_CONF_DIG_CLK8M_EN(1)
}
return esp.RNG.DATA.Get(), nil
}
func initADCClock() {
if esp.APB_SARADC.GetCLKM_CONF_CLK_EN() == 1 {
return
}
// only support ADC_CTRL_CLK set to 1
esp.APB_SARADC.SetCLKM_CONF_CLK_SEL(1)
esp.APB_SARADC.SetCTRL_SARADC_SAR_CLK_GATED(1)
esp.APB_SARADC.SetCLKM_CONF_CLKM_DIV_NUM(15)
esp.APB_SARADC.SetCLKM_CONF_CLKM_DIV_B(1)
esp.APB_SARADC.SetCLKM_CONF_CLKM_DIV_A(0)
esp.APB_SARADC.SetCTRL_SARADC_SAR_CLK_DIV(1)
esp.APB_SARADC.SetCLKM_CONF_CLK_EN(1)
}
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build baremetal && (nrf || (stm32 && !(stm32f103 || stm32l0x1 || stm32g0)) || (sam && atsamd51) || (sam && atsame5x) || esp32c3 || tkey || (tinygo.riscv32 && virt) || rp2040 || rp2350)
//go:build baremetal && (nrf || (stm32 && !(stm32f103 || stm32l0x1 || stm32g0)) || (sam && atsamd51) || (sam && atsame5x) || esp32c3 || esp32s3 || tkey || (tinygo.riscv32 && virt) || rp2040 || rp2350)
// If you update the above build constraint, you'll probably also need to update
// src/crypto/rand/rand_baremetal.go.
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build baremetal && !(nrf || (stm32 && !(stm32f103 || stm32l0x1 || stm32g0)) || (sam && atsamd51) || (sam && atsame5x) || esp32c3 || tkey || (tinygo.riscv32 && virt) || rp2040 || rp2350)
//go:build baremetal && !(nrf || (stm32 && !(stm32f103 || stm32l0x1 || stm32g0)) || (sam && atsamd51) || (sam && atsame5x) || esp32c3 || esp32s3 || tkey || (tinygo.riscv32 && virt) || rp2040 || rp2350)
package runtime