cpu.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. void cpu_enable_sse(void)
  15. {
  16. unsigned int eax, ebx, ecx, edx, cr4;
  17. if (!cpu_has_cpuid())
  18. return;
  19. eax = 1;
  20. __asm__ volatile ("cpuid"
  21. : "+a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx));
  22. if (!(edx & (1u << 24))) /* FXSR */
  23. return;
  24. __asm__ volatile ("mov %%cr4, %0" : "=r"(cr4));
  25. cr4 |= (1u << 9) | (1u << 10); /* OSFXSR | OSXMMEXCPT */
  26. __asm__ volatile ("mov %0, %%cr4" :: "r"(cr4) : "memory");
  27. }
  28. int cpu_has_sse2(void)
  29. {
  30. unsigned int eax, ebx, ecx, edx;
  31. if (sse2 >= 0)
  32. return sse2;
  33. sse2 = 0;
  34. if (cpu_has_cpuid()) {
  35. eax = 1;
  36. __asm__ volatile ("cpuid"
  37. : "+a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx));
  38. if (edx & (1u << 26)) {
  39. /* SSE instructions #UD unless CR4 enables the state
  40. * (OSFXSR). The kernel is built -mno-sse, so the
  41. * registers are only used inside a single helper and
  42. * need no per-process save. */
  43. if (edx & (1u << 24)) { /* FXSR */
  44. unsigned int cr4;
  45. __asm__ volatile ("mov %%cr4, %0" : "=r"(cr4));
  46. cr4 |= (1u << 9) | (1u << 10); /* OSFXSR | OSXMMEXCPT */
  47. __asm__ volatile ("mov %0, %%cr4" :: "r"(cr4)
  48. : "memory");
  49. }
  50. sse2 = 1;
  51. }
  52. }
  53. return sse2;
  54. }