refactor: re-structure the kernel address space for a more integral layout.
[lunaix-os.git] / lunaix-os / hal / ioapic.c
1 #include <arch/x86/interrupts.h>
2 #include <hal/acpi/acpi.h>
3 #include <hal/ioapic.h>
4 #include <lunaix/common.h>
5
6 #define IOAPIC_REG_SEL *((volatile uint32_t*)(MMIO_IOAPIC + IOAPIC_IOREGSEL))
7 #define IOAPIC_REG_WIN *((volatile uint32_t*)(MMIO_IOAPIC + IOAPIC_IOWIN))
8
9 uint8_t
10 ioapic_get_irq(acpi_context* acpi_ctx, uint8_t old_irq);
11
12 void
13 ioapic_init()
14 {
15     // Remapping the IRQs
16
17     acpi_context* acpi_ctx = acpi_get_context();
18
19     // Remap the IRQ 8 (rtc timer's vector) to RTC_TIMER_IV in ioapic
20     //       (Remarks IRQ 8 is pin INTIN8)
21     //       See IBM PC/AT Technical Reference 1-10 for old RTC IRQ
22     //       See Intel's Multiprocessor Specification for IRQ - IOAPIC INTIN
23     //       mapping config.
24
25     // The ioapic_get_irq is to make sure we capture those overriden IRQs
26
27     // grab ourselves these irq numbers
28     uint8_t irq_rtc = ioapic_get_irq(acpi_ctx, PC_AT_IRQ_RTC);
29
30     // PC_AT_IRQ_RTC -> RTC_TIMER_IV, fixed, edge trigged, polarity=high,
31     // physical, APIC ID 0
32     ioapic_redirect(irq_rtc, RTC_TIMER_IV, 0, IOAPIC_DELMOD_FIXED);
33 }
34
35 uint8_t
36 ioapic_get_irq(acpi_context* acpi_ctx, uint8_t old_irq)
37 {
38     if (old_irq >= 24) {
39         return old_irq;
40     }
41     acpi_intso_t* int_override = acpi_ctx->madt.irq_exception[old_irq];
42     return int_override ? (uint8_t)int_override->gsi : old_irq;
43 }
44
45 void
46 ioapic_write(uint8_t sel, uint32_t val)
47 {
48     IOAPIC_REG_SEL = sel;
49     IOAPIC_REG_WIN = val;
50 }
51
52 uint32_t
53 ioapic_read(uint8_t sel)
54 {
55     IOAPIC_REG_SEL = sel;
56     return IOAPIC_REG_WIN;
57 }
58
59 void
60 ioapic_redirect(uint8_t irq, uint8_t vector, uint8_t dest, uint32_t flags)
61 {
62     uint8_t reg_sel = IOAPIC_IOREDTBL_BASE + irq * 2;
63
64     // Write low 32 bits
65     ioapic_write(reg_sel, (vector | flags) & 0x1FFFF);
66
67     // Write high 32 bits
68     ioapic_write(reg_sel + 1, (dest << 24));
69 }