kaslr.c 2.1 KB

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