summaryrefslogtreecommitdiff
path: root/src/kernel/arch/amd64/interrupts/isr.c
blob: 75e9dc6de8c4b5e6945bb9d756fe4b38ead7ce13 (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
#include <kernel/arch/amd64/interrupts.h>
#include <kernel/arch/amd64/port_io.h>
#include <kernel/arch/generic.h>
#include <kernel/malloc.h>
#include <kernel/panic.h>
#include <kernel/proc.h>
#include <stdbool.h>
#include <stdint.h>

enum {
	Nmi = 0x02,
	GpFault = 0x0d,
	PageFault = 0x0e,
};

typedef struct {
	uint64_t ip, cs, flags;
	/* only valid if switching from/into user mode */
	uint64_t sp, ss;
} IretFrame;

typedef struct IsrFrame {
	UserRegs regs; /* doesn't include ip, flags, sp */
	uint64_t _retaddr;
	uint64_t errcode;
	IretFrame iret;
} __attribute__((packed)) IsrFrame;

void (*irq_fn[16])(void) = {0};

static uint64_t
getcr2(void)
{
	uint64_t cr2;
	asm("mov %%cr2, %0" : "=r"(cr2));
	return cr2;
}

static void
log_interrupt(uint8_t inr, IsrFrame *sf)
{
	IretFrame *iret = &sf->iret;
	kprintf("interrupt %d, rip = k/%08x, cs 0x%x, code 0x%x\n",
			inr, iret->ip, iret->cs, sf->errcode);
	if ((iret->cs & 0x3) == 0) { /* ring 0? */
		uint64_t *stack = (void*)iret->sp;
		kprintf("kernel rsp = %p, *rsp = %p\n", stack, *stack);
	}
	if (inr == PageFault) {
		kprintf("addr 0x%x\n", getcr2());
	}
}

void
isr_stage3(uint8_t inr, IsrFrame *sf)
{
	IretFrame *iret = &sf->iret;
	uint8_t irqn = inr - IRQ_IBASE;
	if (irqn < 16) {
		if (irq_fn[irqn]) {
			irq_fn[irqn]();
			irq_eoi(irqn);
			return;
		}
	}

	if (inr == Nmi) { /* print some debugging information */
		log_interrupt(inr, sf);
		mem_debugprint();
		return;
	}

	if ((iret->cs & 0x3) == 0) { /* ring 0? */
		log_interrupt(inr, sf);
		cpu_halt();
	} else { /* in user */
		if (inr == PageFault) {
			char buf[64];
			int len = snprintf(
				buf, sizeof(buf),
				"sys: fault %s ip=%p cr2=%p", /* format inspired by plan9 */
				(sf->errcode & 2) ? "write" : "read",
				sf->iret.ip,
				getcr2()
			);

			/* save registers (ignoring SSE) */
			proc_cur->regs = sf->regs;
			proc_cur->regs.rsp = sf->iret.sp;
			proc_cur->regs.rip = sf->iret.ip;
			proc_cur->regs.flags = sf->iret.flags;

			proc_intr(proc_cur, buf, len);
			proc_intr_deliver(proc_cur);

			/* restore */
			sf->regs = proc_cur->regs;
			sf->iret.sp = proc_cur->regs.rsp;
			sf->iret.ip = proc_cur->regs.rip;
			sf->iret.flags = proc_cur->regs.flags;
			return;
		}
		proc_kill(proc_cur, inr);
		proc_switch_any();
	}
}