cpu.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* CPU feature detection (see cpu.h). */
  2. #include "cpu.h"
  3. static int sse2 = -1; /* -1 = not probed yet, 0 = no, 1 = yes */
  4. /* CPUID exists only if the ID bit in EFLAGS can be toggled (i586+). */
  5. int cpu_has_cpuid(void)
  6. {
  7. unsigned int a, b;
  8. __asm__ volatile ("pushfl; popl %0" : "=r"(a));
  9. b = a ^ (1u << 21);
  10. __asm__ volatile ("pushl %0; popfl" :: "r"(b));
  11. __asm__ volatile ("pushfl; popl %0" : "=r"(b));
  12. return ((a ^ b) & (1u << 21)) != 0;
  13. }
  14. unsigned int cpu_family_model(void)
  15. {
  16. unsigned int a, b, c, d, family, model;
  17. if (!cpu_has_cpuid())
  18. return 0;
  19. a = 0;
  20. __asm__ volatile ("cpuid" : "+a"(a), "=b"(b), "=c"(c), "=d"(d));
  21. if (a < 1)
  22. return 0;
  23. a = 1;
  24. __asm__ volatile ("cpuid" : "+a"(a), "=b"(b), "=c"(c), "=d"(d));
  25. family = (a >> 8) & 0xFu;
  26. model = (a >> 4) & 0xFu;
  27. if (family == 0xFu)
  28. family += (a >> 20) & 0xFFu;
  29. if (family == 0x6u || family == 0xFu)
  30. model |= ((a >> 16) & 0xFu) << 4;
  31. return (family << 8) | model;
  32. }
  33. void cpu_enable_sse(void)
  34. {
  35. unsigned int eax, ebx, ecx, edx, cr4;
  36. if (!cpu_has_cpuid())
  37. return;
  38. eax = 1;
  39. __asm__ volatile ("cpuid"
  40. : "+a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx));
  41. if (!(edx & (1u << 24))) /* FXSR */
  42. return;
  43. __asm__ volatile ("mov %%cr4, %0" : "=r"(cr4));
  44. cr4 |= (1u << 9) | (1u << 10); /* OSFXSR | OSXMMEXCPT */
  45. __asm__ volatile ("mov %0, %%cr4" :: "r"(cr4) : "memory");
  46. }
  47. int cpu_has_sse2(void)
  48. {
  49. unsigned int eax, ebx, ecx, edx;
  50. if (sse2 >= 0)
  51. return sse2;
  52. sse2 = 0;
  53. if (cpu_has_cpuid()) {
  54. eax = 1;
  55. __asm__ volatile ("cpuid"
  56. : "+a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx));
  57. if (edx & (1u << 26)) {
  58. /* SSE instructions #UD unless CR4 enables the state
  59. * (OSFXSR). The kernel is built -mno-sse, so the
  60. * registers are only used inside a single helper and
  61. * need no per-process save. */
  62. if (edx & (1u << 24)) { /* FXSR */
  63. unsigned int cr4;
  64. __asm__ volatile ("mov %%cr4, %0" : "=r"(cr4));
  65. cr4 |= (1u << 9) | (1u << 10); /* OSFXSR | OSXMMEXCPT */
  66. __asm__ volatile ("mov %0, %%cr4" :: "r"(cr4)
  67. : "memory");
  68. }
  69. sse2 = 1;
  70. }
  71. }
  72. return sse2;
  73. }