ec.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /* ACPI embedded-controller access; see ec.h. */
  2. #include "ec.h"
  3. #include "pci.h"
  4. #define EC_DATA 0x62
  5. #define EC_STS 0x66
  6. #define EC_OBF 0x01 /* output buffer full */
  7. #define EC_IBF 0x02 /* input buffer full */
  8. #define EC_READ 0x80
  9. #define EC_WRITE 0x81
  10. /* Enough for a slow EC command (tens of milliseconds of port polls) but
  11. * short enough that a dead controller cannot stall the boot or a syscall. */
  12. #define EC_POLL_MAX 20000
  13. static int ec_wait(unsigned char mask, int set)
  14. {
  15. unsigned int i;
  16. for (i = 0; i < EC_POLL_MAX; i++) {
  17. unsigned char st = port_inb(EC_STS);
  18. if (st == 0xFF) /* no controller on these ports */
  19. return -1;
  20. if (set ? (st & mask) != 0 : (st & mask) == 0)
  21. return 0;
  22. }
  23. return -1;
  24. }
  25. /* Keep a stale output byte (a hotkey event) from shadowing the register we
  26. * are about to read. */
  27. static int ec_drain(void)
  28. {
  29. unsigned int i;
  30. for (i = 0; i < 64; i++) {
  31. unsigned char st = port_inb(EC_STS);
  32. if (st == 0xFF)
  33. return -1;
  34. if (!(st & EC_OBF))
  35. return 0;
  36. (void)port_inb(EC_DATA);
  37. }
  38. return -1;
  39. }
  40. int ec_read(unsigned char reg, unsigned char *out)
  41. {
  42. if (ec_drain())
  43. return -1;
  44. if (ec_wait(EC_IBF, 0))
  45. return -1;
  46. port_outb(EC_STS, EC_READ);
  47. if (ec_wait(EC_IBF, 0))
  48. return -1;
  49. port_outb(EC_DATA, reg);
  50. if (ec_wait(EC_OBF, 1))
  51. return -1;
  52. *out = port_inb(EC_DATA);
  53. return 0;
  54. }
  55. int ec_write(unsigned char reg, unsigned char val)
  56. {
  57. if (ec_drain())
  58. return -1;
  59. if (ec_wait(EC_IBF, 0))
  60. return -1;
  61. port_outb(EC_STS, EC_WRITE);
  62. if (ec_wait(EC_IBF, 0))
  63. return -1;
  64. port_outb(EC_DATA, reg);
  65. if (ec_wait(EC_IBF, 0))
  66. return -1;
  67. port_outb(EC_DATA, val);
  68. if (ec_wait(EC_IBF, 0))
  69. return -1;
  70. return 0;
  71. }
  72. int ec_read16(unsigned char reg, unsigned int *out)
  73. {
  74. unsigned char lo, hi;
  75. if (ec_read(reg, &lo) != 0 || ec_read((unsigned char)(reg + 1), &hi) != 0)
  76. return -1;
  77. *out = (unsigned int)lo | ((unsigned int)hi << 8);
  78. return 0;
  79. }