From 827f8bf26b23c0a492b9883592b6c9bdd3e704a7 Mon Sep 17 00:00:00 2001 From: Fengwei Tan Date: Sat, 3 Oct 2026 23:18:06 +0800 Subject: [PATCH] lib: sbi_pmu: fix mapping reset for already stopped counters Linux stops a counter before issuing another stop with RESET flag when deleting an event [1]. Returning early on SBI_EALREADY_STOPPED skips counter-to-event mapping reset, eventually exhausting the hardware counters. Continue the stop and reset process for the remaining counters when a counter in the set is already stopped. Preserve SBI_EALREADY_STOPPED in the final result, while still returning immediately on other errors. [1] https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/perf/riscv_pmu.c?id=72d3fcf802c45d00b300f25b848a93c3a2bd7c7e#n318 Fixes: c5077d497d0f ("lib: sbi_pmu: Fix counter and event info error codes as per SBI v3.0 spec") Signed-off-by: Fengwei Tan Reviewed-by: Anup Patel Link: https://lore.kernel.org/r/SY8P300MB00410B44E7D55CB5CF7B276AB5882@SY8P300MB0041.AUSP300.PROD.OUTLOOK.COM Signed-off-by: Anup Patel --- lib/sbi/sbi_pmu.c | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/lib/sbi/sbi_pmu.c b/lib/sbi/sbi_pmu.c index a043dc7c..f33238d8 100644 --- a/lib/sbi/sbi_pmu.c +++ b/lib/sbi/sbi_pmu.c @@ -694,15 +694,15 @@ int sbi_pmu_ctr_stop(unsigned long cbase, unsigned long cmask, unsigned long flag) { struct sbi_pmu_hart_state *phs = pmu_thishart_state_ptr(); - - if (unlikely(!phs)) - return SBI_EINVAL; - + bool any_already_stopped = false; int ret = SBI_EINVAL; int event_idx_type; uint32_t event_code; int i, cidx; + if (unlikely(!phs)) + return SBI_EINVAL; + if (!pmu_ctr_idx_validate(cbase, cmask)) return ret; @@ -724,8 +724,11 @@ int sbi_pmu_ctr_stop(unsigned long cbase, unsigned long cmask, else ret = pmu_ctr_stop_hw(cidx); - if(ret) + if (ret == SBI_EALREADY_STOPPED) { + any_already_stopped = true; + } else if (ret) { return ret; + } if (cidx > (CSR_INSTRET - CSR_CYCLE) && flag & SBI_PMU_STOP_FLAG_RESET) { phs->active_events[cidx] = SBI_PMU_EVENT_IDX_INVALID; @@ -737,6 +740,10 @@ int sbi_pmu_ctr_stop(unsigned long cbase, unsigned long cmask, if (phs->sse_enabled) csr_clear(CSR_MIP, sbi_pmu_irq_mask()); + if (!ret && any_already_stopped) { + ret = SBI_EALREADY_STOPPED; + } + return ret; }