hw_random.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2016 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <stdint.h>
  15. #include <stddef.h>
  16. #include <string.h>
  17. #include <sys/param.h>
  18. #include "esp_attr.h"
  19. #include "hal/cpu_hal.h"
  20. #include "esp32s2/clk.h"
  21. #include "soc/wdev_reg.h"
  22. uint32_t IRAM_ATTR esp_random(void)
  23. {
  24. /* The PRNG which implements WDEV_RANDOM register gets 2 bits
  25. * of extra entropy from a hardware randomness source every APB clock cycle
  26. * (provided WiFi or BT are enabled). To make sure entropy is not drained
  27. * faster than it is added, this function needs to wait for at least 16 APB
  28. * clock cycles after reading previous word. This implementation may actually
  29. * wait a bit longer due to extra time spent in arithmetic and branch statements.
  30. *
  31. * As a (probably unncessary) precaution to avoid returning the
  32. * RNG state as-is, the result is XORed with additional
  33. * WDEV_RND_REG reads while waiting.
  34. */
  35. /* This code does not run in a critical section, so CPU frequency switch may
  36. * happens while this code runs (this will not happen in the current
  37. * implementation, but possible in the future). However if that happens,
  38. * the number of cycles spent on frequency switching will certainly be more
  39. * than the number of cycles we need to wait here.
  40. */
  41. uint32_t cpu_to_apb_freq_ratio = esp_clk_cpu_freq() / esp_clk_apb_freq();
  42. static uint32_t last_ccount = 0;
  43. uint32_t ccount;
  44. uint32_t result = 0;
  45. do {
  46. ccount = cpu_hal_get_cycle_count();
  47. result ^= REG_READ(WDEV_RND_REG);
  48. } while (ccount - last_ccount < cpu_to_apb_freq_ratio * 16);
  49. last_ccount = ccount;
  50. return result ^ REG_READ(WDEV_RND_REG);
  51. }
  52. void esp_fill_random(void *buf, size_t len)
  53. {
  54. assert(buf != NULL);
  55. uint8_t *buf_bytes = (uint8_t *)buf;
  56. while (len > 0) {
  57. uint32_t word = esp_random();
  58. uint32_t to_copy = MIN(sizeof(word), len);
  59. memcpy(buf_bytes, &word, to_copy);
  60. buf_bytes += to_copy;
  61. len -= to_copy;
  62. }
  63. }