hw_random.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 "esp_attr.h"
  18. #include "soc/wdev_reg.h"
  19. #include "freertos/FreeRTOSConfig.h"
  20. #include "xtensa/core-macros.h"
  21. uint32_t IRAM_ATTR esp_random(void)
  22. {
  23. /* The PRNG which implements WDEV_RANDOM register gets 2 bits
  24. * of extra entropy from a hardware randomness source every APB clock cycle.
  25. * To make sure entropy is not drained faster than it is added,
  26. * this function needs to wait for at least 16 APB clock cycles after reading
  27. * previous word. This implementation may actually wait a bit longer
  28. * due to extra time spent in arithmetic and branch statements.
  29. *
  30. * As a (probably unncessary) precaution to avoid returning the
  31. * RNG state as-is, the result is XORed with additional
  32. * WDEV_RND_REG reads while waiting.
  33. */
  34. static uint32_t last_ccount = 0;
  35. uint32_t ccount;
  36. uint32_t result = 0;
  37. do {
  38. ccount = XTHAL_GET_CCOUNT();
  39. result ^= REG_READ(WDEV_RND_REG);
  40. } while (ccount - last_ccount < XT_CLOCK_FREQ / APB_CLK_FREQ * 16);
  41. last_ccount = ccount;
  42. return result ^ REG_READ(WDEV_RND_REG);
  43. }