kaslr.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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/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. debug_putstr(purpose);
  53. debug_putstr(" KASLR using");
  54. if (has_cpuflag(X86_FEATURE_RDRAND)) {
  55. debug_putstr(" RDRAND");
  56. if (rdrand_long(&raw)) {
  57. random ^= raw;
  58. use_i8254 = false;
  59. }
  60. }
  61. if (has_cpuflag(X86_FEATURE_TSC)) {
  62. debug_putstr(" RDTSC");
  63. raw = rdtsc();
  64. random ^= raw;
  65. use_i8254 = false;
  66. }
  67. if (use_i8254) {
  68. debug_putstr(" i8254");
  69. random ^= i8254();
  70. }
  71. /* Circular multiply for better bit diffusion */
  72. asm(_ASM_MUL "%3"
  73. : "=a" (random), "=d" (raw)
  74. : "a" (random), "rm" (mix_const));
  75. random += raw;
  76. debug_putstr("...\n");
  77. return random;
  78. }