kaslr.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Entropy functions used on early boot for KASLR base and memory
  4. * randomization. The base randomization is done in the compressed
  5. * kernel and memory randomization is done early when the regular
  6. * kernel starts. This file is included in the compressed kernel and
  7. * normally linked in the regular.
  8. */
  9. #include <asm/asm.h>
  10. #include <asm/kaslr.h>
  11. #include <asm/msr.h>
  12. #include <asm/archrandom.h>
  13. #include <asm/e820/api.h>
  14. #include <asm/shared/io.h>
  15. /*
  16. * When built for the regular kernel, several functions need to be stubbed out
  17. * or changed to their regular kernel equivalent.
  18. */
  19. #ifndef KASLR_COMPRESSED_BOOT
  20. #include <asm/cpufeature.h>
  21. #include <asm/setup.h>
  22. #define debug_putstr(v) early_printk("%s", v)
  23. #define has_cpuflag(f) boot_cpu_has(f)
  24. #define get_boot_seed() kaslr_offset()
  25. #endif
  26. #define I8254_PORT_CONTROL 0x43
  27. #define I8254_PORT_COUNTER0 0x40
  28. #define I8254_CMD_READBACK 0xC0
  29. #define I8254_SELECT_COUNTER0 0x02
  30. #define I8254_STATUS_NOTREADY 0x40
  31. static inline u16 i8254(void)
  32. {
  33. u16 status, timer;
  34. do {
  35. outb(I8254_CMD_READBACK | I8254_SELECT_COUNTER0,
  36. I8254_PORT_CONTROL);
  37. status = inb(I8254_PORT_COUNTER0);
  38. timer = inb(I8254_PORT_COUNTER0);
  39. timer |= inb(I8254_PORT_COUNTER0) << 8;
  40. } while (status & I8254_STATUS_NOTREADY);
  41. return timer;
  42. }
  43. unsigned long kaslr_get_random_long(const char *purpose)
  44. {
  45. #ifdef CONFIG_X86_64
  46. const unsigned long mix_const = 0x5d6008cbf3848dd3UL;
  47. #else
  48. const unsigned long mix_const = 0x3f39e593UL;
  49. #endif
  50. unsigned long raw, random = get_boot_seed();
  51. bool use_i8254 = true;
  52. if (purpose) {
  53. debug_putstr(purpose);
  54. debug_putstr(" KASLR using");
  55. }
  56. if (has_cpuflag(X86_FEATURE_RDRAND)) {
  57. if (purpose)
  58. debug_putstr(" RDRAND");
  59. if (rdrand_long(&raw)) {
  60. random ^= raw;
  61. use_i8254 = false;
  62. }
  63. }
  64. if (has_cpuflag(X86_FEATURE_TSC)) {
  65. if (purpose)
  66. debug_putstr(" RDTSC");
  67. raw = rdtsc();
  68. random ^= raw;
  69. use_i8254 = false;
  70. }
  71. if (use_i8254) {
  72. if (purpose)
  73. debug_putstr(" i8254");
  74. random ^= i8254();
  75. }
  76. /* Circular multiply for better bit diffusion */
  77. asm(_ASM_MUL "%3"
  78. : "=a" (random), "=d" (raw)
  79. : "a" (random), "rm" (mix_const));
  80. random += raw;
  81. if (purpose)
  82. debug_putstr("...\n");
  83. return random;
  84. }