This repository has been archived by the owner on Aug 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrap.c
129 lines (113 loc) · 2.74 KB
/
trap.c
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include "defs.h"
/*
Analyze and handle traps.
Privileged operations which can not be exposed to user.
*/
regis trap_handler(regis mepc, regis mcause, Context context)
{
// kprintf("Start to handle the trap!\n");
int trap_type = mcause >> 31;
// if (trap_type == 1)
// {
// // MSB of `mcause` is 1, interrupt
// kprintf("\tTrap type: Interrupt\n");
// }
// else
// {
// // MSB of `mcause` is 0, exception
// kprintf("\tTrap type: Exception\n");
// }
regis trap_code = (mcause << 1) >> 1;
// kprintf("\tTrap code: %d\n", trap_code);
regis rpc = mepc;
if (trap_type)
{
// handle interrupts
switch (trap_code)
{
case 3:
// kprintf("Machine software interruption!\n");
software_interrupt_handler();
break;
case 7:
// kprintf("Machine timer interruption!\n");
timer_interrupt_handler();
break;
case 11:
// uart_puts("External interruption!\n");
external_interrupt_handler();
break;
default:
panic("Unhandled interrupt!\n");
break;
}
}
else
{
// handle exceptions
switch (trap_code)
{
case 1:
kprintf("Instruction access fault!\n");
kprintf("PC is at %p", rpc);
panic("...");
break;
case 5:
kprintf("Load access fault!\n");
rpc += 4; // skip the instruction
break;
case 7:
kprintf("Store/AMO access fault!\n");
rpc += 4; // skip the instruction
break;
case 8:
// kprintf("Environment call from U-mode!\n");
syscall_handler(&context);
rpc += 4;
break;
default:
kprintf("mepc @ %p with trap code %d", rpc, trap_code);
panic("Unhandled exception!\n");
break;
}
}
return rpc;
}
/*
Handle external interruption.
*/
void external_interrupt_handler(void)
{
int irq_id = plic_claim();
// kprintf("External interrupt source %d\n", irq_id);
if (irq_id == UART0_IRQ)
{
uart_interrupt();
}
else
{
panic("Unexpected interrupt!\n");
}
plic_complete(irq_id);
return;
}
/*
Handle software interrupt,
AKA cooperative multitasking.
*/
void software_interrupt_handler(void)
{
write_clint_msip_zero(read_mhartid());
task_scheduler();
}
/*
A test case of exception handling.
*/
void test_exception(void)
{
kprintf("Going to have an exception!\n");
// try to assign value pointed by NULL
*(int *)NULL = 1;
kprintf("Exception handled successfully!\n");
return;
}