drv_trng.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**************************************************************************//**
  2. *
  3. * @copyright (C) 2020 Nuvoton Technology Corp. All rights reserved.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0
  6. *
  7. * Change Logs:
  8. * Date Author Notes
  9. * 2020-7-4 YCHuang12 First version
  10. *
  11. ******************************************************************************/
  12. #include <rtconfig.h>
  13. #if (defined(BSP_USING_TRNG) && defined(RT_HWCRYPTO_USING_RNG))
  14. #include <rtdevice.h>
  15. #include "NuMicro.h"
  16. #include <stdlib.h>
  17. #define NU_CRYPTO_TRNG_NAME "nu_TRNG"
  18. /* Private variables ------------------------------------------------------------*/
  19. static struct rt_mutex s_TRNG_mutex;
  20. static int s_i32TRNGEnable = 0;
  21. static rt_uint32_t nu_trng_run(void)
  22. {
  23. uint32_t u32RNGValue;
  24. rt_err_t result;
  25. result = rt_mutex_take(&s_TRNG_mutex, RT_WAITING_FOREVER);
  26. RT_ASSERT(result == RT_EOK);
  27. RNG_Open();
  28. if (RNG_Random(&u32RNGValue, 1) < 0)
  29. {
  30. //Failed, use software rand
  31. u32RNGValue = rand();
  32. }
  33. result = rt_mutex_release(&s_TRNG_mutex);
  34. RT_ASSERT(result == RT_EOK);
  35. return u32RNGValue;
  36. }
  37. rt_err_t nu_trng_init(void)
  38. {
  39. rt_err_t result;
  40. result = rt_mutex_init(&s_TRNG_mutex, NU_CRYPTO_TRNG_NAME, RT_IPC_FLAG_PRIO);
  41. RT_ASSERT(result == RT_EOK);
  42. s_i32TRNGEnable = 1;
  43. SYS_ResetModule(TRNG_RST);
  44. return RT_EOK;
  45. }
  46. void nu_trng_open(void)
  47. {
  48. #if defined(NU_PRNG_USE_SEED)
  49. srand(NU_PRNG_SEED_VALUE);
  50. #else
  51. srand(rt_tick_get());
  52. #endif
  53. }
  54. rt_uint32_t nu_trng_rand(struct hwcrypto_rng *ctx)
  55. {
  56. if (!s_i32TRNGEnable)
  57. {
  58. /* Use software rand */
  59. return (rt_uint32_t)rand();
  60. }
  61. return nu_trng_run();
  62. }
  63. #endif //#if (defined(BSP_USING_TRNG) && defined(RT_HWCRYPTO_USING_RNG))