hw_random.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 "hal/cpu_hal.h"
  12. #include "soc/wdev_reg.h"
  13. #if CONFIG_IDF_TARGET_ESP32
  14. #include "esp32/clk.h"
  15. #elif CONFIG_IDF_TARGET_ESP32S2
  16. #include "esp32s2/clk.h"
  17. #elif CONFIG_IDF_TARGET_ESP32S3
  18. #include "esp32s3/clk.h"
  19. #elif CONFIG_IDF_TARGET_ESP32C3
  20. #include "esp32c3/clk.h"
  21. #elif CONFIG_IDF_TARGET_ESP32H2
  22. #include "esp32h2/clk.h"
  23. #endif
  24. uint32_t IRAM_ATTR esp_random(void)
  25. {
  26. /* The PRNG which implements WDEV_RANDOM register gets 2 bits
  27. * of extra entropy from a hardware randomness source every APB clock cycle
  28. * (provided WiFi or BT are enabled). To make sure entropy is not drained
  29. * faster than it is added, this function needs to wait for at least 16 APB
  30. * clock cycles after reading previous word. This implementation may actually
  31. * wait a bit longer due to extra time spent in arithmetic and branch statements.
  32. *
  33. * As a (probably unncessary) precaution to avoid returning the
  34. * RNG state as-is, the result is XORed with additional
  35. * WDEV_RND_REG reads while waiting.
  36. */
  37. /* This code does not run in a critical section, so CPU frequency switch may
  38. * happens while this code runs (this will not happen in the current
  39. * implementation, but possible in the future). However if that happens,
  40. * the number of cycles spent on frequency switching will certainly be more
  41. * than the number of cycles we need to wait here.
  42. */
  43. uint32_t cpu_to_apb_freq_ratio = esp_clk_cpu_freq() / esp_clk_apb_freq();
  44. static uint32_t last_ccount = 0;
  45. uint32_t ccount;
  46. uint32_t result = 0;
  47. do {
  48. ccount = cpu_hal_get_cycle_count();
  49. result ^= REG_READ(WDEV_RND_REG);
  50. } while (ccount - last_ccount < cpu_to_apb_freq_ratio * 16);
  51. last_ccount = ccount;
  52. return result ^ REG_READ(WDEV_RND_REG);
  53. }
  54. void esp_fill_random(void *buf, size_t len)
  55. {
  56. assert(buf != NULL);
  57. uint8_t *buf_bytes = (uint8_t *)buf;
  58. while (len > 0) {
  59. uint32_t word = esp_random();
  60. uint32_t to_copy = MIN(sizeof(word), len);
  61. memcpy(buf_bytes, &word, to_copy);
  62. buf_bytes += to_copy;
  63. len -= to_copy;
  64. }
  65. }