Fix race using fence.
[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 fence
36
37 # Restore s1.
38 csrr s1, CSR_MISA
39 bltz s1, restore_not_32
40 restore_32:
41 lw s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 4)(zero)
42 j check_halt
43 restore_not_32:
44 slli s1, s1, 1
45 bltz s1, restore_128
46 restore_64:
47 ld s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 8)(zero)
48 j check_halt
49 restore_128:
50 nop #lq s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 16)(zero)
51
52 check_halt:
53 csrr s0, DCSR
54 andi s0, s0, (1<<DCSR_HALT_OFFSET)
55 beqz s0, exit
56 j wait_for_interrupt
57
58 exit:
59 # Restore s0.
60 csrr s0, DSCRATCH
61 eret
62
63
64 _entry:
65 # Save s0 in DSCRATCH
66 csrw DSCRATCH, s0
67
68 # Check why we're here
69 csrr s0, DCSR
70 # cause is in bits 2:0 of dcsr
71 andi s0, s0, 7
72 addi s0, s0, -DCSR_CAUSE_DEBINT
73 bnez s0, spontaneous_halt
74
75 jdebugram:
76 # Save s1 so that the debug program can use two registers.
77 csrr s0, CSR_MISA
78 bltz s0, save_not_32
79 save_32:
80 sw s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 4)(zero)
81 jr zero, DEBUG_RAM
82 save_not_32:
83 slli s0, s0, 1
84 bltz s0, save_128
85 save_64:
86 sd s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 8)(zero)
87 jr zero, DEBUG_RAM
88 save_128:
89 nop #sq s1, (DEBUG_RAM + DEBUG_RAM_SIZE - 16)(zero)
90 jr zero, DEBUG_RAM
91
92 spontaneous_halt:
93 csrr s0, CSR_MHARTID
94 sw s0, SETHALTNOT(zero)
95 csrsi DCSR, (1<<DCSR_HALT_OFFSET)
96
97 wait_for_interrupt:
98 csrr s0, DCSR
99 andi s0, s0, (1<<DCSR_DEBUGINT_OFFSET)
100 beqz s0, wait_for_interrupt
101
102 j jdebugram