trng.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // SPDX-License-Identifier: GPL-2.0
  2. // Copyright (C) 2020 Arm Ltd.
  3. #include <linux/arm-smccc.h>
  4. #include <linux/kvm_host.h>
  5. #include <asm/kvm_emulate.h>
  6. #include <kvm/arm_hypercalls.h>
  7. #define ARM_SMCCC_TRNG_VERSION_1_0 0x10000UL
  8. /* Those values are deliberately separate from the generic SMCCC definitions. */
  9. #define TRNG_SUCCESS 0UL
  10. #define TRNG_NOT_SUPPORTED ((unsigned long)-1)
  11. #define TRNG_INVALID_PARAMETER ((unsigned long)-2)
  12. #define TRNG_NO_ENTROPY ((unsigned long)-3)
  13. #define TRNG_MAX_BITS64 192
  14. static const uuid_t arm_smc_trng_uuid __aligned(4) = UUID_INIT(
  15. 0x0d21e000, 0x4384, 0x11eb, 0x80, 0x70, 0x52, 0x44, 0x55, 0x4e, 0x5a, 0x4c);
  16. static int kvm_trng_do_rnd(struct kvm_vcpu *vcpu, int size)
  17. {
  18. DECLARE_BITMAP(bits, TRNG_MAX_BITS64);
  19. u32 num_bits = smccc_get_arg1(vcpu);
  20. int i;
  21. if (num_bits > 3 * size) {
  22. smccc_set_retval(vcpu, TRNG_INVALID_PARAMETER, 0, 0, 0);
  23. return 1;
  24. }
  25. /* get as many bits as we need to fulfil the request */
  26. for (i = 0; i < DIV_ROUND_UP(num_bits, BITS_PER_LONG); i++)
  27. bits[i] = get_random_long();
  28. bitmap_clear(bits, num_bits, TRNG_MAX_BITS64 - num_bits);
  29. if (size == 32)
  30. smccc_set_retval(vcpu, TRNG_SUCCESS, lower_32_bits(bits[1]),
  31. upper_32_bits(bits[0]), lower_32_bits(bits[0]));
  32. else
  33. smccc_set_retval(vcpu, TRNG_SUCCESS, bits[2], bits[1], bits[0]);
  34. memzero_explicit(bits, sizeof(bits));
  35. return 1;
  36. }
  37. int kvm_trng_call(struct kvm_vcpu *vcpu)
  38. {
  39. const __le32 *u = (__le32 *)arm_smc_trng_uuid.b;
  40. u32 func_id = smccc_get_function(vcpu);
  41. unsigned long val = TRNG_NOT_SUPPORTED;
  42. int size = 64;
  43. switch (func_id) {
  44. case ARM_SMCCC_TRNG_VERSION:
  45. val = ARM_SMCCC_TRNG_VERSION_1_0;
  46. break;
  47. case ARM_SMCCC_TRNG_FEATURES:
  48. switch (smccc_get_arg1(vcpu)) {
  49. case ARM_SMCCC_TRNG_VERSION:
  50. case ARM_SMCCC_TRNG_FEATURES:
  51. case ARM_SMCCC_TRNG_GET_UUID:
  52. case ARM_SMCCC_TRNG_RND32:
  53. case ARM_SMCCC_TRNG_RND64:
  54. val = TRNG_SUCCESS;
  55. }
  56. break;
  57. case ARM_SMCCC_TRNG_GET_UUID:
  58. smccc_set_retval(vcpu, le32_to_cpu(u[0]), le32_to_cpu(u[1]),
  59. le32_to_cpu(u[2]), le32_to_cpu(u[3]));
  60. return 1;
  61. case ARM_SMCCC_TRNG_RND32:
  62. size = 32;
  63. fallthrough;
  64. case ARM_SMCCC_TRNG_RND64:
  65. return kvm_trng_do_rnd(vcpu, size);
  66. }
  67. smccc_set_retval(vcpu, val, 0, 0, 0);
  68. return 1;
  69. }