summaryrefslogtreecommitdiff
path: root/src/pic.c
blob: ad2c15d0ee42725d59f184a2f469c8d22a573398 (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
97
98
99
100
101
102
103
104
105
106
107
#include <nrvn.h>
#include <pic.h>
#include <idt.h>
#include <vga.h>

extern void toggle_interrupts(bool enable);

#define pic1 0x20
#define pic2 0xA0
#define pic1_d (pic1 + 1)
#define pic2_d (pic2 + 2)

void pic_remap(uint32_t offset1, uint32_t offset2) {
	uint8_t a1, a2;

	a1 = inb(pic1_d);
	a2 = inb(pic2_d);

	outb(pic1, 0x10 | 0x01);
	io_wait();
	outb(pic2, 0x10 | 0x01);
	io_wait();
	outb(pic1_d, offset1);
	io_wait();
	outb(pic2_d, offset2);
	io_wait();
	outb(pic1_d, 4);
	io_wait();
	outb(pic2_d, 2);
	io_wait();

	outb(pic1_d, 0x01);
	io_wait();
	outb(pic2_d, 0x01);
	io_wait();

	outb(pic1_d, a1);
	outb(pic2_d, a2);
}

void pic_set_mask(uint8_t irq_line) {
	uint32_t port;
	uint8_t value;

	if (irq_line < 8)
		port = pic1_d;
	else {
		port = pic2_d;
		irq_line -= 8;
	}
	value = inb(port) | (1 << irq_line);
	outb(port, value);
}

void pic_clear_mask(uint8_t irq_line) {
	uint32_t port;
	uint8_t value;

	if (irq_line < 8)
		port = pic1_d;
	else {
		port = pic2_d;
		irq_line -= 8;
	}
	value = inb(port) & ~(1 << irq_line);
	outb(port, value);
}

void pic_set_all_masks(void) {
	outb(pic1_d, 0xFF);
	outb(pic2_d, 0xFF);
}

void pic_clear_all_masks(void) {
	outb(pic1_d, 0x00);
	outb(pic2_d, 0x00);
}

void pic_eoi(uint8_t irq) {
	if (irq >= 8)
		outb(pic2, 0x20);
	outb(pic1, 0x20);
}

void keyboard_handler(uint64_t num, uint64_t _unused) {
	(void)num;
	(void)_unused;
	uint8_t key = inb(0x60);
	vga_puts("key pressed: ");
	vga_putx(key);
	vga_putc('\n');
	pic_eoi(0x1);
}

void pic_init(void) {
	pic_set_all_masks();
	pic_clear_mask(1);
	//pic_clear_mask(12);
	pic_remap(32, 40);

	for (size_t i = 32; i < 48; i++)
		idt_set_isr(i, isr_table[i], 0x08, 0x8E);

	idt_register_isr(33, keyboard_handler);

	toggle_interrupts(true);
}