summaryrefslogtreecommitdiff
path: root/src/interrupt.c
blob: c4171172d5021d9abc18810d53e0c880f2d9a693 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

#include "interrupt.h"
#include "string.h"
#include "vga.h"
#include "bees.h"
#include "printf.h"
#include "keyboard.h"

struct port pic_master_command = {0x20, port8bit_slow};
struct port pic_master_data = {0x21, port8bit_slow};
struct port pic_slave_command = {0xA0, port8bit_slow};
struct port pic_slave_data = {0xA1, port8bit_slow}; 

struct port ps2_port = {0x60, port8bit};

struct gate_desc idt[256] = {0};

#define PIC_EOI 0x20

void irq_end(uint8_t int_number) {
	if (int_number >= 0x28)
		port_write(pic_slave_command, PIC_EOI);
	port_write(pic_master_command, PIC_EOI);
}

uint8_t ps2_read() {
	return port_read(ps2_port);
}

uint32_t handle_int(uint8_t int_number, uint32_t idk, uint32_t esp) {
	switch (int_number) {
		case 0x0D:
			// bye
			bees("general protection fault");
			break;
		case 0x21:
			keyboard_event(&ps2_read);
			irq_end(int_number);
			break;
	}

	return esp;
}

void set_int_desc_entry(uint8_t int_number, uint16_t gdt_code_seg,
						void (*handler)(), uint8_t privilege_level,
						uint8_t desc_type) {
	const uint8_t IDT_DESC_PRESENT = 0x80;
	
	idt[int_number].handler_low = ((uint32_t) handler) & 0xFFFF;
	idt[int_number].handler_high = ((uint32_t) handler >> 16) & 0xFFFF;
	idt[int_number].gdt_code_seg = gdt_code_seg;
	idt[int_number].access = IDT_DESC_PRESENT | desc_type | ((privilege_level&3) << 5);
	idt[int_number].reserved = 0;
}

void interrupt_init() {
	uint16_t code_seg = 0x08;
	const uint8_t IDT_INTERRUPT_GATE = 0xE;

	for (uint16_t i = 0; i < 256; i++)
		set_int_desc_entry(i, code_seg, &int_ignore, 0, IDT_INTERRUPT_GATE);
	
	// Put the interrupt handlers in the IDT
	set_int_desc_entry(0x20, code_seg, &handle_irq0x00, 0, IDT_INTERRUPT_GATE);
	set_int_desc_entry(0x21, code_seg, &handle_irq0x01, 0, IDT_INTERRUPT_GATE);
	set_int_desc_entry(0x0D, code_seg, &handle_irq0x0D, 0, IDT_INTERRUPT_GATE);

	port_write(pic_master_command, 0x11);
	port_write(pic_slave_command, 0x11);
	
	// (I actually don't understand how this works)
	// Remap the PIC
	port_write(pic_master_data, 0x20);  // Interrupt vector offsets 
	port_write(pic_slave_data, 0x28); 
	
	port_write(pic_master_data, 0x04);  // There is a slave PIC at IRQ2
	port_write(pic_slave_data, 0x02);   // Slave PIC cascade identity

	port_write(pic_master_data, 0x01);
	port_write(pic_slave_data, 0x01);

	port_write(pic_master_data, 0xFD);  
	port_write(pic_slave_data, 0xFF);   

	// Load the IDT
	struct idt_pointer i;
	i.size = 256 * sizeof(struct gate_desc) - 1;
	i.base = (uint32_t) idt;
	
	asm volatile("lidt %0" : : "m" (i));
}

void start_interrupts() {
	asm("sti");
}