entropy_hardware_poll.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Hardware entropy collector for the K64F, using Freescale's RNGA
  3. *
  4. * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  5. * SPDX-License-Identifier: Apache-2.0
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  8. * not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * This file is part of mbed TLS (https://tls.mbed.org)
  20. */
  21. /*
  22. * WARNING: this is temporary!
  23. * This should be in a separate yotta module which would be a target
  24. * dependency of mbedtls (see IOTSSL-313)
  25. */
  26. #if defined(TARGET_LIKE_K64F)
  27. /*
  28. * Reference: "K64 Sub-Family Reference Manual, Rev. 2", chapter 34
  29. */
  30. #include "fsl_clock_manager.h"
  31. /*
  32. * Get one byte of entropy from the RNG, assuming it is up and running.
  33. * As recommended (34.1.1), get only one bit of each output.
  34. */
  35. static void rng_get_byte( unsigned char *byte )
  36. {
  37. size_t bit;
  38. /* 34.5 Steps 3-4-5: poll SR and read from OR when ready */
  39. for( bit = 0; bit < 8; bit++ )
  40. {
  41. while( ( RNG->SR & RNG_SR_OREG_LVL_MASK ) == 0 );
  42. *byte |= ( RNG->OR & 1 ) << bit;
  43. }
  44. }
  45. /*
  46. * Get len bytes of entropy from the hardware RNG.
  47. */
  48. int mbedtls_hardware_poll( void *data,
  49. unsigned char *output, size_t len, size_t *olen )
  50. {
  51. size_t i;
  52. int ret;
  53. ((void) data);
  54. CLOCK_SYS_EnableRngaClock( 0 );
  55. /* Set "Interrupt Mask", "High Assurance" and "Go",
  56. * unset "Clear interrupt" and "Sleep" */
  57. RNG->CR = RNG_CR_INTM_MASK | RNG_CR_HA_MASK | RNG_CR_GO_MASK;
  58. for( i = 0; i < len; i++ )
  59. rng_get_byte( output + i );
  60. /* Just be extra sure that we didn't do it wrong */
  61. if( ( RNG->SR & RNG_SR_SECV_MASK ) != 0 )
  62. {
  63. ret = -1;
  64. goto cleanup;
  65. }
  66. *olen = len;
  67. ret = 0;
  68. cleanup:
  69. /* Disable clock to save power - assume we're the only users of RNG */
  70. CLOCK_SYS_DisableRngaClock( 0 );
  71. return( ret );
  72. }
  73. #endif