Add dret.
[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 # Set the last word of Debug RAM to all ones, to indicate that we hit
33 # an exception.
34 li s0, ~0
35 j _resume2
36
37 _resume:
38 li s0, 0
39 _resume2:
40 # Clear debug interrupt.
41 csrr s1, CSR_MHARTID
42 sw s1, CLEARDEBINT(zero)
43 fence
44
45 # Restore s1.
46 csrr s1, CSR_MISA
47 bltz s1, restore_not_32
48 restore_32:
49 lw s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 4)(zero)
50 j check_halt
51 restore_not_32:
52 slli s1, s1, 1
53 bltz s1, restore_128
54 restore_64:
55 ld s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 8)(zero)
56 j check_halt
57 restore_128:
58 nop #lq s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 16)(zero)
59
60 # s0 contains ~0 if we got here through an exception, and 0 otherwise.
61 # Store this to the last word in Debug RAM so the debugger can tell if
62 # an exception occurred.
63 sw s0, (DEBUG_RAM + DEBUG_RAM_SIZE - 4)(zero)
64
65 check_halt:
66 csrr s0, DCSR
67 andi s0, s0, (1<<DCSR_HALT_OFFSET)
68 beqz s0, exit
69 j wait_for_interrupt
70
71 exit:
72 # Restore s0.
73 csrr s0, DSCRATCH
74 dret
75
76
77 _entry:
78 # Save s0 in DSCRATCH
79 csrw DSCRATCH, s0
80
81 # Check why we're here
82 csrr s0, DCSR
83 # cause is in bits 2:0 of dcsr
84 andi s0, s0, 7
85 addi s0, s0, -DCSR_CAUSE_DEBINT
86 bnez s0, spontaneous_halt
87
88 jdebugram:
89 # Save s1 so that the debug program can use two registers.
90 csrr s0, CSR_MISA
91 bltz s0, save_not_32
92 save_32:
93 sw s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 4)(zero)
94 jr zero, DEBUG_RAM
95 save_not_32:
96 slli s0, s0, 1
97 bltz s0, save_128
98 save_64:
99 sd s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 8)(zero)
100 jr zero, DEBUG_RAM
101 save_128:
102 nop #sq s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 16)(zero)
103 jr zero, DEBUG_RAM
104
105 spontaneous_halt:
106 csrr s0, CSR_MHARTID
107 sw s0, SETHALTNOT(zero)
108 csrsi DCSR, (1<<DCSR_HALT_OFFSET)
109
110 wait_for_interrupt:
111 csrr s0, DCSR
112 andi s0, s0, (1<<DCSR_DEBUGINT_OFFSET)
113 beqz s0, wait_for_interrupt
114
115 j jdebugram