From 5caa519bec2e261146260149e2a8aa1708d79940 Mon Sep 17 00:00:00 2001 From: boa <42885162+boa-z@users.noreply.github.com> Date: Mon, 9 Nov 2026 10:19:30 -0500 Subject: [libcpu][risc-v] Fix PLIC completion order in non-DM mode handler_plic_irq() completes a claimed interrupt before dispatching its handler. If a level-triggered source is still asserted at completion time, the PLIC gateway forwards the request again, so the same interrupt can be dispatched twice. Run the handler first, then complete. Completing after the handler means a handler may have masked its own source; the PLIC ignores a completion for an interrupt that is not enabled for the target, so temporarily enable the source around the completion, as the Linux SiFive PLIC driver does. Link: https://github.com/RT-Thread/rt-thread/issues/12010 --- libcpu/risc-v/common/interrupt.c | 5 ++++- libcpu/risc-v/common/pic/pic-sifive-plic.c | 32 +++++++++++++++++++++++++++++- 2 files changed, 35 insertions(+), 2 deletions(-) (limited to 'libcpu') diff --git a/libcpu/risc-v/common/interrupt.c b/libcpu/risc-v/common/interrupt.c index c571616e18..3c4e886eda 100644 --- a/libcpu/risc-v/common/interrupt.c +++ b/libcpu/risc-v/common/interrupt.c @@ -430,9 +430,12 @@ static rt_bool_t handler_irq(int hwirq, void *data) #if INTC_TYPE != INTC_TYPE_CLIC static rt_bool_t handler_plic_irq(int hwirq, void *data) { + rt_bool_t res = handler_irq(hwirq, data); + + /* Complete after handling to avoid re-pending level interrupts. */ plic_irq_ack_or_eoi(rt_hw_cpu_id(), hwirq); - return handler_irq(hwirq, data); + return res; } void plic_init(void) diff --git a/libcpu/risc-v/common/pic/pic-sifive-plic.c b/libcpu/risc-v/common/pic/pic-sifive-plic.c index 393b64a8a0..ce46485b4e 100644 --- a/libcpu/risc-v/common/pic/pic-sifive-plic.c +++ b/libcpu/risc-v/common/pic/pic-sifive-plic.c @@ -170,11 +170,41 @@ static void plic_irq_mask_raw(int cpu, int hwirq) static void plic_irq_ack_or_eoi(int cpu, int hwirq) { struct plic_percpu *percpu = &plic_percpu[cpu]; + rt_uint32_t *enable_reg, enable_mask; - if (percpu->valid) + if (!percpu->valid) + { + return; + } + + enable_reg = percpu->enable_base + (hwirq / 32) * sizeof(rt_uint32_t); + enable_mask = 1U << (hwirq % 32); + + /* + * The PLIC ignores completion for a disabled source. + * Temporarily enable it if the handler masked the interrupt. + */ + if (HWREG32(enable_reg) & enable_mask) { HWREG32(percpu->hart_base + CONTEXT_CLAIM) = hwirq; } + else + { + rt_ubase_t level = rt_spin_lock_irqsave(&percpu->enable_lock); + + if (HWREG32(enable_reg) & enable_mask) + { + HWREG32(percpu->hart_base + CONTEXT_CLAIM) = hwirq; + } + else + { + HWREG32(enable_reg) |= enable_mask; + HWREG32(percpu->hart_base + CONTEXT_CLAIM) = hwirq; + HWREG32(enable_reg) &= ~enable_mask; + } + + rt_spin_unlock_irqrestore(&percpu->enable_lock, level); + } } static rt_bool_t plic_handler_isr_raw(struct plic *plic, -- cgit v1.3.1