Exceptions in Debug Mode, stay in Debug Mode.
[riscv-isa-sim.git] / debug_rom / debug_rom.S
1 # This code should be functional. Doesn't have to be optimal.
2 # I'm writing it to prove that it can be done.
3
4 #include "riscv/encoding.h"
5
6 # TODO: Update these constants once they're finalized in the doc.
7
8 #define DCSR 0x790
9 #define DCSR_CAUSE_DEBINT 3
10 #define DCSR_HALT_OFFSET 3
11 #define DCSR_DEBUGINT_OFFSET 10
12
13 #define DSCRATCH 0x792
14
15 #define DEBUG_RAM 0x400
16 #define DEBUG_RAM_SIZE 64
17
18 #define SETHALTNOT 0x100
19 #define CLEARDEBINT 0x108
20
21 .global entry
22 .global resume
23 .global exception
24
25 # Automatically called when Debug Mode is first entered.
26 entry: j _entry
27 # Should be called by Debug RAM code that has finished execution and
28 # wants to return to Debug Mode.
29 resume:
30 j _resume
31 exception:
32 # Flip the LSB of the first word in Debug RAM so the debugger can know
33 # that we hit an exception.
34 lw s1, (DEBUG_RAM)(zero)
35 xori s1, s1, 1
36 sw s1, (DEBUG_RAM)(zero)
37
38 # Fall through to resume.
39
40 _resume:
41 # Clear debug interrupt.
42 csrr s1, CSR_MHARTID
43 sw s1, CLEARDEBINT(zero)
44 fence
45
46 # Restore s1.
47 csrr s1, CSR_MISA
48 bltz s1, restore_not_32
49 restore_32:
50 lw s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 4)(zero)
51 j check_halt
52 restore_not_32:
53 slli s1, s1, 1
54 bltz s1, restore_128
55 restore_64:
56 ld s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 8)(zero)
57 j check_halt
58 restore_128:
59 nop #lq s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 16)(zero)
60
61 check_halt:
62 csrr s0, DCSR
63 andi s0, s0, (1<<DCSR_HALT_OFFSET)
64 beqz s0, exit
65 j wait_for_interrupt
66
67 exit:
68 # Restore s0.
69 csrr s0, DSCRATCH
70 # TODO: dret?
71 mret
72
73
74 _entry:
75 # Save s0 in DSCRATCH
76 csrw DSCRATCH, s0
77
78 # Check why we're here
79 csrr s0, DCSR
80 # cause is in bits 2:0 of dcsr
81 andi s0, s0, 7
82 addi s0, s0, -DCSR_CAUSE_DEBINT
83 bnez s0, spontaneous_halt
84
85 jdebugram:
86 # Save s1 so that the debug program can use two registers.
87 csrr s0, CSR_MISA
88 bltz s0, save_not_32
89 save_32:
90 sw s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 4)(zero)
91 jr zero, DEBUG_RAM
92 save_not_32:
93 slli s0, s0, 1
94 bltz s0, save_128
95 save_64:
96 sd s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 8)(zero)
97 jr zero, DEBUG_RAM
98 save_128:
99 nop #sq s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 16)(zero)
100 jr zero, DEBUG_RAM
101
102 spontaneous_halt:
103 csrr s0, CSR_MHARTID
104 sw s0, SETHALTNOT(zero)
105 csrsi DCSR, (1<<DCSR_HALT_OFFSET)
106
107 wait_for_interrupt:
108 csrr s0, DCSR
109 andi s0, s0, (1<<DCSR_DEBUGINT_OFFSET)
110 beqz s0, wait_for_interrupt
111
112 j jdebugram