PS2MouseDevice.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. #include "PS2MouseDevice.h"
  2. #include "IO.h"
  3. //#define PS2MOUSE_DEBUG
  4. static PS2MouseDevice* s_the;
  5. PS2MouseDevice::PS2MouseDevice()
  6. : IRQHandler(12)
  7. , CharacterDevice(10, 1)
  8. {
  9. s_the = this;
  10. initialize();
  11. }
  12. PS2MouseDevice::~PS2MouseDevice()
  13. {
  14. }
  15. PS2MouseDevice& PS2MouseDevice::the()
  16. {
  17. return *s_the;
  18. }
  19. void PS2MouseDevice::handle_irq()
  20. {
  21. byte data = IO::in8(0x60);
  22. m_data[m_data_state] = data;
  23. switch (m_data_state) {
  24. case 0:
  25. ASSERT(data & 0x08);
  26. ++m_data_state;
  27. break;
  28. case 1:
  29. ++m_data_state;
  30. break;
  31. case 2:
  32. m_data_state = 0;
  33. #ifdef PS2MOUSE_DEBUG
  34. dbgprintf("PS2Mouse: %d, %d %s %s\n",
  35. m_data[1],
  36. m_data[2],
  37. (m_data[0] & 1) ? "Left" : "",
  38. (m_data[0] & 2) ? "Right" : ""
  39. );
  40. #endif
  41. m_buffer.write((const byte*)m_data, 3);
  42. break;
  43. }
  44. }
  45. void PS2MouseDevice::wait_then_write(byte port, byte data)
  46. {
  47. prepare_for_output();
  48. IO::out8(port, data);
  49. }
  50. byte PS2MouseDevice::wait_then_read(byte port)
  51. {
  52. prepare_for_input();
  53. return IO::in8(port);
  54. }
  55. void PS2MouseDevice::initialize()
  56. {
  57. // Enable PS aux port
  58. wait_then_write(0x64, 0xa8);
  59. // Enable interrupts
  60. wait_then_write(0x64, 0x20);
  61. byte status = wait_then_read(0x60) | 2;
  62. wait_then_write(0x64, 0x60);
  63. wait_then_write(0x60, status);
  64. // Set default settings.
  65. mouse_write(0xf6);
  66. byte ack1 = mouse_read();
  67. ASSERT(ack1 == 0xfa);
  68. // Enable.
  69. mouse_write(0xf4);
  70. byte ack2 = mouse_read();
  71. ASSERT(ack2 == 0xfa);
  72. enable_irq();
  73. }
  74. void PS2MouseDevice::prepare_for_input()
  75. {
  76. for (;;) {
  77. if (IO::in8(0x64) & 1)
  78. return;
  79. }
  80. }
  81. void PS2MouseDevice::prepare_for_output()
  82. {
  83. for (;;) {
  84. if (!(IO::in8(0x64) & 2))
  85. return;
  86. }
  87. }
  88. void PS2MouseDevice::mouse_write(byte data)
  89. {
  90. prepare_for_output();
  91. IO::out8(0x64, 0xd4);
  92. prepare_for_output();
  93. IO::out8(0x60, data);
  94. }
  95. byte PS2MouseDevice::mouse_read()
  96. {
  97. prepare_for_input();
  98. return IO::in8(0x60);
  99. }
  100. bool PS2MouseDevice::can_read(Process&) const
  101. {
  102. return !m_buffer.is_empty();
  103. }
  104. ssize_t PS2MouseDevice::read(Process&, byte* buffer, size_t size)
  105. {
  106. return m_buffer.read(buffer, size);
  107. }
  108. ssize_t PS2MouseDevice::write(Process&, const byte*, size_t)
  109. {
  110. return 0;
  111. }