hw_random.c 2.6 KB

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