lib: sbi: Fix stale prev_context in RNMI handler

An earlier SBI trap may have already used the same M-mode exception
stack slot to save its trap context before an RNMI is taken.
sbi_trap_rnmi_handler() never initializes prev_context before
sbi_trap_error() walks it to print trap diagnostics, so it can read
whatever stale value happens to be left in that slot.

Link prev_context on entry and restore it on exit, the same way
sbi_trap_handler() does. This also lets an exception taken while
already inside RNMI handling chain back to the RNMI's own trap
context instead of dropping it, so sbi_trap_error() prints every
nested context correctly, including the RNMI's.

Fixes: 00fec20b49 ("firmware: Add RNMI handler infrastructure")
Suggested-by: Nick Hu <nick.hu@sifive.com>
Signed-off-by: Nia Su <nia.su@sifive.com>
Reviewed-by: Evgeny Voevodin <evvoevod@tenstorrent.com>
Reviewed-by: Anup Patel <anup@brainfault.org>
Link: https://lore.kernel.org/r/20260914-trap-context-fix-v2-2-3a6bedc6fcf0@sifive.com
Signed-off-by: Anup Patel <anup@brainfault.org>
This commit is contained in:
Nia Su authored and Anup Patel committed 2026-10-27 13:26:22 +05:30
1 parent f84bdb9877
commit a0531af7ad
1 file changed
+8 -2
+8 -2
View File
@@ -394,9 +394,14 @@ trap_done:
struct sbi_trap_context *sbi_trap_rnmi_handler(struct sbi_trap_context *tcntx)
{
int rc;
struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
const struct sbi_platform *plat = sbi_platform_thishart_ptr();
const struct sbi_platform_operations *ops = sbi_platform_ops(plat);
/* Update trap context pointer so nested traps chain correctly */
tcntx->prev_context = sbi_trap_get_context(scratch);
sbi_trap_set_context(scratch, tcntx);
/* Call platform-specific NMI handler if registered */
if (ops && ops->rnmi_handler) {
rc = ops->rnmi_handler(tcntx);
@@ -404,14 +409,15 @@ struct sbi_trap_context *sbi_trap_rnmi_handler(struct sbi_trap_context *tcntx)
/* Platform handler failed to handle NMI */
sbi_trap_error("platform NMI handler failed", rc, tcntx);
}
return tcntx;
goto done;
}
/* No platform handler - treat as unhandled NMI */
sbi_trap_error("unhandled NMI (no platform rnmi_handler)",
SBI_ENOTSUPP, tcntx);
/* Never returns */
done:
sbi_trap_set_context(scratch, tcntx->prev_context);
return tcntx;
}