PIC.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #include "types.h"
  2. #include "i386.h"
  3. #include "IO.h"
  4. #include "VGA.h"
  5. #include "PIC.h"
  6. #include "Assertions.h"
  7. // The slave 8259 is connected to the master's IRQ2 line.
  8. // This is really only to enhance clarity.
  9. #define SLAVE_INDEX 2
  10. #define PIC0_CTL 0x20
  11. #define PIC0_CMD 0x21
  12. #define PIC1_CTL 0xA0
  13. #define PIC1_CMD 0xA1
  14. #ifdef DEBUG_PIC
  15. static bool initialized;
  16. #endif
  17. namespace PIC {
  18. void disable(BYTE irq)
  19. {
  20. BYTE imr;
  21. if (irq & 8) {
  22. imr = IO::in8(PIC1_CMD);
  23. imr |= 1 << (irq - 8);
  24. IO::out8(PIC1_CMD, imr);
  25. } else {
  26. imr = IO::in8(PIC0_CMD);
  27. imr |= 1 << irq;
  28. IO::out8(PIC0_CMD, imr);
  29. }
  30. }
  31. void enable(BYTE irq)
  32. {
  33. BYTE imr;
  34. if (irq & 8) {
  35. imr = IO::in8(PIC1_CMD);
  36. imr &= ~(1 << (irq - 8));
  37. IO::out8(PIC1_CMD, imr);
  38. } else {
  39. imr = IO::in8(PIC0_CMD);
  40. imr &= ~(1 << irq);
  41. IO::out8(PIC0_CMD, imr);
  42. }
  43. }
  44. void eoi(BYTE irq)
  45. {
  46. if (irq & 8)
  47. IO::out8(PIC1_CTL, 0x20);
  48. IO::out8(PIC0_CTL, 0x20);
  49. }
  50. void initialize()
  51. {
  52. #ifdef DEBUG_PIC
  53. ASSERT(!initialized);
  54. #endif
  55. /* ICW1 (edge triggered mode, cascading controllers, expect ICW4) */
  56. IO::out8(PIC0_CTL, 0x11);
  57. IO::out8(PIC1_CTL, 0x11);
  58. /* ICW2 (upper 5 bits specify ISR indices, lower 3 idunno) */
  59. IO::out8(PIC0_CMD, IRQ_VECTOR_BASE);
  60. IO::out8(PIC1_CMD, IRQ_VECTOR_BASE + 0x08);
  61. /* ICW3 (configure master/slave relationship) */
  62. IO::out8(PIC0_CMD, 1 << SLAVE_INDEX);
  63. IO::out8(PIC1_CMD, SLAVE_INDEX);
  64. /* ICW4 (set x86 mode) */
  65. IO::out8(PIC0_CMD, 0x01);
  66. IO::out8(PIC1_CMD, 0x01 );
  67. // Mask -- start out with all IRQs disabled.
  68. IO::out8(PIC0_CMD, 0xff);
  69. IO::out8(PIC1_CMD, 0xff);
  70. // ...except IRQ2, since that's needed for the master to let through slave interrupts.
  71. enable(2);
  72. kprintf("PIC(i8259): cascading mode, vectors 0x%b-0x%b\n", IRQ_VECTOR_BASE, IRQ_VECTOR_BASE + 0x08);
  73. #ifdef DEBUG_PIC
  74. initialized = true;
  75. #endif
  76. }
  77. word getISR()
  78. {
  79. IO::out8(PIC0_CTL, 0x0b);
  80. IO::out8(PIC1_CTL, 0x0b);
  81. byte isr0 = IO::in8(PIC0_CTL);
  82. byte isr1 = IO::in8(PIC1_CTL);
  83. return (isr1 << 8) | isr0;
  84. }
  85. word get_irr()
  86. {
  87. IO::out8(PIC0_CTL, 0x0a);
  88. IO::out8(PIC1_CTL, 0x0a);
  89. byte irr0 = IO::in8(PIC0_CTL);
  90. byte irr1 = IO::in8(PIC1_CTL);
  91. return (irr1 << 8) | irr0;
  92. }
  93. }