From 055478740dc2bec30fb6f20df0bcb7e723720c20 Mon Sep 17 00:00:00 2001 From: good-circle Date: Wed, 25 Nov 2026 16:50:22 +0800 Subject: [PATCH] CSR: preserve trap values when interrupts win An interrupt can win trap selection while a pending page fault or misaligned access still writes its trap-value CSR. When the interrupt targets M-mode and the exception is delegated to S-mode, this corrupts stval even though no S-mode trap is taken. Gate those exception writes with !raiseIntr so they follow the same priority as cause, delegation and trap-target selection. --- src/main/scala/nutcore/backend/fu/CSR.scala | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/scala/nutcore/backend/fu/CSR.scala b/src/main/scala/nutcore/backend/fu/CSR.scala index 08dfef01..eaf48200 100644 --- a/src/main/scala/nutcore/backend/fu/CSR.scala +++ b/src/main/scala/nutcore/backend/fu/CSR.scala @@ -593,7 +593,10 @@ class CSR(implicit val p: NutCoreConfig) extends NutCoreModule with HasCSRConst{ dmemAddrMisalignedAddr := lsuAddr } - when(hasInstrPageFault || hasLoadPageFault || hasStorePageFault){ + // Only the selected trap may update a trap-value CSR. Interrupts win. + val raiseIntr = io.cfIn.intrVec.asUInt.orR + + when(!raiseIntr && (hasInstrPageFault || hasLoadPageFault || hasStorePageFault)){ val tval = Mux(hasInstrPageFault, Mux(io.cfIn.crossPageIPFFix, SignExt((io.cfIn.pc + 2.U)(VAddrBits-1,0), XLEN), SignExt(io.cfIn.pc(VAddrBits-1,0), XLEN)), SignExt(dmemPagefaultAddr, XLEN)) val pfCause = Mux(hasInstrPageFault, instrPageFault.U, Mux(hasLoadPageFault, loadPageFault.U, storePageFault.U)) val pfDelegS = medeleg(pfCause) && (privilegeMode < ModeM) @@ -605,7 +608,7 @@ class CSR(implicit val p: NutCoreConfig) extends NutCoreModule with HasCSRConst{ Debug("[PF] %d: ipf %b tval %x := addr %x pc %x privilegeMode %x\n", GTimer(), hasInstrPageFault, tval, SignExt(dmemPagefaultAddr, XLEN), io.cfIn.pc, privilegeMode) } - when(hasLoadAddrMisaligned || hasStoreAddrMisaligned) + when(!raiseIntr && (hasLoadAddrMisaligned || hasStoreAddrMisaligned)) { val misalignTval = SignExt(dmemAddrMisalignedAddr, XLEN) val maCause = Mux(hasLoadAddrMisaligned, loadAddrMisaligned.U, storeAddrMisaligned.U) @@ -650,7 +653,6 @@ class CSR(implicit val p: NutCoreConfig) extends NutCoreModule with HasCSRConst{ val intrNO = IntPriority.foldRight(0.U)((i: Int, sum: UInt) => Mux(io.cfIn.intrVec(i), i.U, sum)) // val intrNO = PriorityEncoder(io.cfIn.intrVec) - val raiseIntr = io.cfIn.intrVec.asUInt.orR // exceptions