#include "idt.h" #include #include #include "../io/serial/serial.h" #include "../io/kbd/ps2.h" #include struct interrupt_descriptor idt[256]; struct idtr idt_reg; // Address to our first interrupt handler extern char vector_0_handler[]; // Timer ticks extern uint64_t ticks; void idt_set_entry(uint8_t vector, void* handler, uint8_t dpl) { uint64_t handler_addr = (uint64_t)handler; struct interrupt_descriptor* entry = &idt[vector]; // Address is split in three parts so we right-shift progressively to get it all entry->address_low = handler_addr & 0xFFFF; entry->address_mid = (handler_addr >> 16) & 0xFFFF; entry->address_high = handler_addr >> 32; // Kernel code selector (as set in GDT) entry->selector = 0x8; // Interrupt gate, present, DPL (having: max DPL = 3) entry->flags = 0b1110 | ((dpl & 0b11) << 5) | (1 << 7); // We won't use IST for now entry->ist = 0; } void idt_load(void* idt_addr) { // "limit" = "size" = Size of the IDT - 1 byte = (16*256)-1 = 0xFFF idt_reg.limit = 0xFFF; idt_reg.base = (uint64_t)idt_addr; asm volatile("lidt %0" :: "m"(idt_reg)); } void idt_init() { // We set 256 entries, but we have only the first few stubs. // Undefined behavior? for (size_t i=0; i<256; i++) { // Each vector handler is 16-byte aligned, so *16 = address of that handler idt_set_entry(i, vector_0_handler + (i*16), 0); } idt_load(&idt); DEBUG("IDT initialized"); } struct cpu_status_t* interrupt_dispatch(struct cpu_status_t* context) { switch(context->vector_number) { case 0: DEBUG("Divide Error!"); break; case 1: DEBUG("Debug Exception!"); break; case 2: DEBUG("NMI Interrupt!"); break; case 3: DEBUG("Breakpoint Interrupt!"); break; case 4: DEBUG("Overflow Trap!"); break; case 5: DEBUG("BOUND Range Exceeded!"); break; case 6: DEBUG("Invalid Opcode!"); break; case 7: DEBUG("Device Not Available!"); break; case 8: DEBUG("Double Fault!"); break; case 9: DEBUG("Coprocessor Segment Overrun!"); break; case 10: DEBUG("Invalid TSS!"); break; case 11: DEBUG("Segment Not Present!"); break; case 12: DEBUG("Stack-Segment Fault!"); break; case 13: DEBUG("General Protection Fault!"); break; case 14: DEBUG("Page Fault!"); break; case 15: DEBUG("Intel Reserved Interrupt! (Achievement unlocked: How Did We Get Here?)"); break; case 16: DEBUG("x87 Floating-Point Error!"); break; case 17: DEBUG("Alignment Check Fault!"); break; case 18: DEBUG("Machine Check!"); break; case 19: DEBUG("SIMD Floating-Point Exception!"); break; case 20: DEBUG("Virtualization Exception!"); break; case 21: DEBUG("Control Protection Exception!"); break; case 32: //DEBUG("Tick!"); ticks++; // Send an EOI so that we can continue having interrupts outb(0x20, 0x20); break; case 33: keyboard_handler(); break; default: DEBUG("Unexpected interrupt"); break; } return context; }