idle.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 idle_set_cstate(unsigned int level)
  29. {
  30. switch (level) {
  31. case 0:
  32. mwait_cstate_hint = 0x00;
  33. break;
  34. case 1:
  35. mwait_cstate_hint = 0x10;
  36. break;
  37. case 2:
  38. mwait_cstate_hint = 0x20;
  39. break;
  40. case 3:
  41. mwait_cstate_hint = 0x30;
  42. break;
  43. default:
  44. mwait_cstate_hint = 0x10;
  45. break;
  46. }
  47. }
  48. unsigned int idle_get_cstate(void)
  49. {
  50. return (mwait_cstate_hint >> 4) & 0xF;
  51. }
  52. int idle_has_mwait(void)
  53. {
  54. return has_mwait;
  55. }
  56. void cpu_idle(void)
  57. {
  58. if (has_mwait && has_mwait_ext) {
  59. volatile unsigned int dummy = 0;
  60. __asm__ volatile (
  61. "monitor"
  62. :
  63. : "a"(&dummy), "c"(0), "d"(0)
  64. );
  65. __asm__ volatile (
  66. "mwait"
  67. :
  68. : "a"(mwait_cstate_hint), "c"(1)
  69. );
  70. } else {
  71. __asm__ volatile ("hlt");
  72. }
  73. }