hw_random.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * SPDX-FileCopyrightText: 2016-2021 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <stdint.h>
  7. #include <stddef.h>
  8. #include <string.h>
  9. #include <sys/param.h>
  10. #include "esp_attr.h"
  11. #include "esp_cpu.h"
  12. #include "soc/wdev_reg.h"
  13. #include "esp_private/esp_clk.h"
  14. #if defined CONFIG_IDF_TARGET_ESP32S3
  15. #define APB_CYCLE_WAIT_NUM (1778) /* If APB clock is 80 MHz, maximum sampling frequency is around 45 KHz*/
  16. /* 45 KHz reading frequency is the maximum we have tested so far on S3 */
  17. #else
  18. #define APB_CYCLE_WAIT_NUM (16)
  19. #endif
  20. uint32_t IRAM_ATTR esp_random(void)
  21. {
  22. /* The PRNG which implements WDEV_RANDOM register gets 2 bits
  23. * of extra entropy from a hardware randomness source every APB clock cycle
  24. * (provided WiFi or BT are enabled). To make sure entropy is not drained
  25. * faster than it is added, this function needs to wait for at least 16 APB
  26. * clock cycles after reading previous word. This implementation may actually
  27. * wait a bit longer due to extra time spent in arithmetic and branch statements.
  28. *
  29. * As a (probably unncessary) precaution to avoid returning the
  30. * RNG state as-is, the result is XORed with additional
  31. * WDEV_RND_REG reads while waiting.
  32. */
  33. /* This code does not run in a critical section, so CPU frequency switch may
  34. * happens while this code runs (this will not happen in the current
  35. * implementation, but possible in the future). However if that happens,
  36. * the number of cycles spent on frequency switching will certainly be more
  37. * than the number of cycles we need to wait here.
  38. */
  39. uint32_t cpu_to_apb_freq_ratio = esp_clk_cpu_freq() / esp_clk_apb_freq();
  40. static uint32_t last_ccount = 0;
  41. uint32_t ccount;
  42. uint32_t result = 0;
  43. do {
  44. ccount = esp_cpu_get_cycle_count();
  45. result ^= REG_READ(WDEV_RND_REG);
  46. } while (ccount - last_ccount < cpu_to_apb_freq_ratio * APB_CYCLE_WAIT_NUM);
  47. last_ccount = ccount;
  48. return result ^ REG_READ(WDEV_RND_REG);
  49. }
  50. void esp_fill_random(void *buf, size_t len)
  51. {
  52. assert(buf != NULL);
  53. uint8_t *buf_bytes = (uint8_t *)buf;
  54. while (len > 0) {
  55. uint32_t word = esp_random();
  56. uint32_t to_copy = MIN(sizeof(word), len);
  57. memcpy(buf_bytes, &word, to_copy);
  58. buf_bytes += to_copy;
  59. len -= to_copy;
  60. }
  61. }