idle.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /* CPU idle: use mwait for deep C-states when available, hlt fallback. */
  2. #include "idle.h"
  3. static int has_mwait = 0;
  4. static int has_mwait_ext = 0;
  5. static unsigned int mwait_cstate_hint = 0x00;
  6. static void cpuid_idle(unsigned int leaf, unsigned int *eax, unsigned int *ebx,
  7. unsigned int *ecx, unsigned int *edx)
  8. {
  9. __asm__ volatile ("cpuid"
  10. : "=a"(*eax), "=b"(*ebx), "=c"(*ecx), "=d"(*edx)
  11. : "a"(leaf), "c"(0));
  12. }
  13. void idle_init(void)
  14. {
  15. unsigned int eax, ebx, ecx, edx;
  16. unsigned int max_leaf;
  17. cpuid_idle(0, &max_leaf, &ebx, &ecx, &edx);
  18. if (max_leaf < 1)
  19. return;
  20. cpuid_idle(1, &eax, &ebx, &ecx, &edx);
  21. has_mwait = (ecx & (1u << 3)) ? 1 : 0;
  22. if (has_mwait && max_leaf >= 5) {
  23. cpuid_idle(5, &eax, &ebx, &ecx, &edx);
  24. has_mwait_ext = (ecx & 1u) ? 1 : 0;
  25. }
  26. mwait_cstate_hint = 0x10;
  27. }
  28. void cpu_idle(void)
  29. {
  30. if (has_mwait && has_mwait_ext) {
  31. volatile unsigned int dummy = 0;
  32. __asm__ volatile (
  33. "monitor"
  34. :
  35. : "a"(&dummy), "c"(0), "d"(0)
  36. );
  37. __asm__ volatile (
  38. "mwait"
  39. :
  40. : "a"(mwait_cstate_hint), "c"(1)
  41. );
  42. } else {
  43. __asm__ volatile ("hlt");
  44. }
  45. }