fsl_rng.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Copyright 2017, 2019 NXP
  3. * All rights reserved.
  4. *
  5. * SPDX-License-Identifier: BSD-3-Clause
  6. */
  7. #include "fsl_rng.h"
  8. /* Component ID definition, used by tools. */
  9. #ifndef FSL_COMPONENT_ID
  10. #define FSL_COMPONENT_ID "platform.drivers.rng_1"
  11. #endif
  12. /*******************************************************************************
  13. * Definitions
  14. *******************************************************************************/
  15. /*******************************************************************************
  16. * Prototypes
  17. *******************************************************************************/
  18. /*******************************************************************************
  19. * Code
  20. ******************************************************************************/
  21. void RNG_Init(RNG_Type *base)
  22. {
  23. /* Clear ring oscilator disable bit*/
  24. PMC->PDRUNCFGCLR0 = PMC_PDRUNCFG0_PDEN_RNG_MASK;
  25. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  26. CLOCK_EnableClock(kCLOCK_Rng);
  27. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  28. }
  29. void RNG_Deinit(RNG_Type *base)
  30. {
  31. /* Set ring oscilator disable bit*/
  32. PMC->PDRUNCFGSET0 = PMC_PDRUNCFG0_PDEN_RNG_MASK;
  33. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  34. CLOCK_DisableClock(kCLOCK_Rng);
  35. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  36. }
  37. status_t RNG_GetRandomData(RNG_Type *base, void *data, size_t dataSize)
  38. {
  39. status_t result = kStatus_Fail;
  40. uint32_t random32;
  41. uint32_t randomSize;
  42. uint8_t *pRandom;
  43. uint8_t *pData = (uint8_t *)data;
  44. uint32_t i;
  45. /* Check input parameters.*/
  46. if (!((base != NULL) && (data != NULL) && (dataSize != 0U)))
  47. {
  48. result = kStatus_InvalidArgument;
  49. }
  50. else
  51. {
  52. /* Check that ring oscilator is enabled */
  53. if (0U == (PMC->PDRUNCFG0 & PMC_PDRUNCFG0_PDEN_RNG_MASK))
  54. {
  55. do
  56. {
  57. /* Read Entropy.*/
  58. random32 = base->RANDOM_NUMBER;
  59. pRandom = (uint8_t *)&random32;
  60. if (dataSize < sizeof(random32))
  61. {
  62. randomSize = dataSize;
  63. }
  64. else
  65. {
  66. randomSize = sizeof(random32);
  67. }
  68. for (i = 0; i < randomSize; i++)
  69. {
  70. *pData++ = *pRandom++;
  71. }
  72. dataSize -= randomSize;
  73. } while (dataSize > 0U);
  74. result = kStatus_Success;
  75. }
  76. }
  77. return result;
  78. }