archrandom.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. /*
  3. * Kernel interface for the RISCV arch_random_* functions
  4. *
  5. * Copyright (c) 2023 Rivos Inc.
  6. *
  7. */
  8. #ifndef ASM_RISCV_ARCHRANDOM_H
  9. #define ASM_RISCV_ARCHRANDOM_H
  10. #include <asm/csr.h>
  11. #include <asm/processor.h>
  12. #define SEED_RETRY_LOOPS 100
  13. static inline bool __must_check csr_seed_long(unsigned long *v)
  14. {
  15. unsigned int retry = SEED_RETRY_LOOPS, valid_seeds = 0;
  16. const int needed_seeds = sizeof(long) / sizeof(u16);
  17. u16 *entropy = (u16 *)v;
  18. do {
  19. /*
  20. * The SEED CSR must be accessed with a read-write instruction.
  21. */
  22. unsigned long csr_seed = csr_swap(CSR_SEED, 0);
  23. unsigned long opst = csr_seed & SEED_OPST_MASK;
  24. switch (opst) {
  25. case SEED_OPST_ES16:
  26. entropy[valid_seeds++] = csr_seed & SEED_ENTROPY_MASK;
  27. if (valid_seeds == needed_seeds)
  28. return true;
  29. break;
  30. case SEED_OPST_DEAD:
  31. pr_err_once("archrandom: Unrecoverable error\n");
  32. return false;
  33. case SEED_OPST_BIST:
  34. case SEED_OPST_WAIT:
  35. default:
  36. cpu_relax();
  37. continue;
  38. }
  39. } while (--retry);
  40. return false;
  41. }
  42. static inline size_t __must_check arch_get_random_longs(unsigned long *v, size_t max_longs)
  43. {
  44. return 0;
  45. }
  46. static inline size_t __must_check arch_get_random_seed_longs(unsigned long *v, size_t max_longs)
  47. {
  48. if (!max_longs)
  49. return 0;
  50. /*
  51. * If Zkr is supported and csr_seed_long succeeds, we return one long
  52. * worth of entropy.
  53. */
  54. if (riscv_has_extension_likely(RISCV_ISA_EXT_ZKR) && csr_seed_long(v))
  55. return 1;
  56. return 0;
  57. }
  58. #endif /* ASM_RISCV_ARCHRANDOM_H */