Add debug_module bus device.
[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 # TODO: Should be 0x400
16 #define DEBUG_RAM (-0x400)
17 #define DEBUG_RAM_SIZE 64
18
19 # TODO: Should be 0x100, 0x108
20 #define SETHALTNOT (-0x100)
21 #define CLEARDEBINT (-0x108)
22
23 .global entry
24 .global resume
25
26 # Automatically called when Debug Mode is first entered.
27 entry: j _entry
28 # Should be called by Debug RAM code that has finished execution and
29 # wants to return to Debug Mode.
30 resume:
31 # Clear debug interrupt.
32 clear_debint:
33 csrr s1, CSR_MHARTID
34 sw s1, CLEARDEBINT(zero)
35 clear_debint_loop:
36 csrr s1, DCSR
37 andi s1, s1, (1<<DCSR_DEBUGINT_OFFSET)
38 bnez s1, clear_debint_loop
39
40 # Restore s1.
41 csrr s1, CSR_MISA
42 bltz s1, restore_not_32
43 restore_32:
44 lw s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 4)(zero)
45 j check_halt
46 restore_not_32:
47 slli s1, s1, 1
48 bltz s1, restore_128
49 restore_64:
50 ld s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 8)(zero)
51 j check_halt
52 restore_128:
53 nop #lq s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 16)(zero)
54
55 check_halt:
56 csrr s0, DCSR
57 andi s0, s0, (1<<DCSR_HALT_OFFSET)
58 beqz s0, exit
59 j wait_for_interrupt
60
61 exit:
62 # Restore s0.
63 csrr s0, DSCRATCH
64 eret
65
66
67 _entry:
68 # Save s0 in DSCRATCH
69 csrw DSCRATCH, s0
70
71 # Check why we're here
72 csrr s0, DCSR
73 # cause is in bits 2:0 of dcsr
74 andi s0, s0, 7
75 addi s0, s0, -DCSR_CAUSE_DEBINT
76 bnez s0, spontaneous_halt
77
78 jdebugram:
79 # Save s1 so that the debug program can use two registers.
80 csrr s0, CSR_MISA
81 bltz s0, save_not_32
82 save_32:
83 sw s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 4)(zero)
84 jr zero, DEBUG_RAM
85 save_not_32:
86 slli s0, s0, 1
87 bltz s0, save_128
88 save_64:
89 sd s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 8)(zero)
90 jr zero, DEBUG_RAM
91 save_128:
92 nop #sq s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 16)(zero)
93 jr zero, DEBUG_RAM
94
95 spontaneous_halt:
96 csrr s0, CSR_MHARTID
97 sw s0, SETHALTNOT(zero)
98 csrsi DCSR, DCSR_HALT_OFFSET
99
100 wait_for_interrupt:
101 csrr s0, DCSR
102 andi s0, s0, (1<<DCSR_DEBUGINT_OFFSET)
103 beqz s0, wait_for_interrupt
104
105 j jdebugram