bootloader_random.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2010-2020 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 "sdkconfig.h"
  15. #include "bootloader_random.h"
  16. #include "soc/cpu.h"
  17. #include "soc/wdev_reg.h"
  18. #ifndef BOOTLOADER_BUILD
  19. #include "esp_system.h"
  20. #include "driver/periph_ctrl.h"
  21. void bootloader_fill_random(void *buffer, size_t length)
  22. {
  23. return esp_fill_random(buffer, length);
  24. }
  25. #else
  26. void bootloader_fill_random(void *buffer, size_t length)
  27. {
  28. uint8_t *buffer_bytes = (uint8_t *)buffer;
  29. uint32_t random;
  30. uint32_t start, now;
  31. assert(buffer != NULL);
  32. for (int i = 0; i < length; i++) {
  33. if (i == 0 || i % 4 == 0) { /* redundant check is for a compiler warning */
  34. /* in bootloader with ADC feeding HWRNG, we accumulate 1
  35. bit of entropy per 40 APB cycles (==80 CPU cycles.)
  36. To avoid reading the entire RNG hardware state out
  37. as-is, we repeatedly read the RNG register and XOR all
  38. values.
  39. */
  40. random = REG_READ(WDEV_RND_REG);
  41. RSR(CCOUNT, start);
  42. do {
  43. random ^= REG_READ(WDEV_RND_REG);
  44. RSR(CCOUNT, now);
  45. } while (now - start < 80 * 32 * 2); /* extra factor of 2 is precautionary */
  46. }
  47. buffer_bytes[i] = random >> ((i % 4) * 8);
  48. }
  49. }
  50. #endif // BOOTLOADER_BUILD