lib: sbi: Install the next-stage entry as a direct-mode xtvec

sbi_hart_switch_mode() writes next_addr unmasked into stvec (vstvec,
utvec).  Bits [1:0] of xtvec are the MODE field, so a 2-byte aligned
entry, legal with the C extension, selects a reserved mode: QEMU drops
the write, the Sail model keeps the old mode, and the next stage starts
with a trap vector that is not its entry.

Mask the mode bits and install the entry as a direct-mode vector; mepc
still receives the exact address.

Signed-off-by: Nickolai Zeldovich <nickolai.zeldovich@gmail.com>
Assisted-by: Claude Fable 5.1
Tested-by: Chen Pei <cp0613@linux.alibaba.com>
Reviewed-by: Anup Patel <anup@brainfault.org>
Link: https://lore.kernel.org/r/20261006193619.735580-1-nickolai@csail.mit.edu
Signed-off-by: Anup Patel <anup@brainfault.org>
This commit is contained in:
Nickolai Zeldovich authored and Anup Patel committed 2026-11-03 18:19:37 +05:30
1 parent 00b9807b78
commit 6e0338f425
1 file changed
+15 -3
+15 -3
View File
@@ -774,6 +774,7 @@ sbi_hart_switch_mode(unsigned long arg0, unsigned long arg1,
#else
unsigned long val;
#endif
unsigned long tvec;
switch (next_mode) {
case PRV_M:
@@ -806,21 +807,32 @@ sbi_hart_switch_mode(unsigned long arg0, unsigned long arg1,
csr_write(CSR_MSTATUS, val);
csr_write(CSR_MEPC, next_addr);
/*
* The xtvec registers encode the trap mode in bits [1:0]: 0 is
* direct, 1 is vectored, 2 and 3 are reserved. next_addr is an
* instruction address and may be only 2-byte aligned when the C
* extension is in use, in which case writing it unmasked asks
* for a reserved mode and the result is implementation-defined
* (the write is ignored, or the old mode is kept). Install the
* entry as a direct-mode vector instead.
*/
tvec = next_addr & ~MTVEC_MODE;
if (next_mode == PRV_S) {
if (next_virt) {
csr_write(CSR_VSTVEC, next_addr);
csr_write(CSR_VSTVEC, tvec);
csr_write(CSR_VSSCRATCH, 0);
csr_write(CSR_VSIE, 0);
csr_write(CSR_VSATP, 0);
} else {
csr_write(CSR_STVEC, next_addr);
csr_write(CSR_STVEC, tvec);
csr_write(CSR_SSCRATCH, 0);
csr_write(CSR_SIE, 0);
csr_write(CSR_SATP, 0);
}
} else if (next_mode == PRV_U) {
if (misa_extension('N')) {
csr_write(CSR_UTVEC, next_addr);
csr_write(CSR_UTVEC, tvec);
csr_write(CSR_USCRATCH, 0);
csr_write(CSR_UIE, 0);
}