[kvm-unit-tests PATCH v2] riscv: sbi: Fix timer delay measurement race
Andrew Jones
andrew.jones at linux.dev
Fri Nov 20 06:50:28 PST 2026
On Mon, Oct 26, 2026 at 11:37:38AM +0800, Qingwei Hu wrote:
> The timer test samples the counter before checking timer_works in the
> wait loop. If the timer interrupt arrives between these operations, the
> handler sets timer_works and the loop exits with a timestamp taken before
> the interrupt. That timestamp can precede the deadline, causing a false
> "timer delay honored" failure in both the normal and masked IRQ tests.
>
> Check timer_works first in the wait loop and sample the counter again
> after the loop exits. Use this timestamp to calculate the elapsed time
> so that an interrupt cannot cause the test to use a stale timestamp.
>
> Fixes: 14fa12b1351c ("riscv: sbi: Add test for timer extension")
> Suggested-by: Andrew Jones <andrew.jones at linux.dev>
> Signed-off-by: Qingwei Hu <qingwei.hu at bytedance.com>
> ---
> Changes in v2:
> - Check timer_works first and sample the counter after the wait loop,
> as suggested by Andrew Jones.
> - Drop the timestamp field and counter read from the interrupt handler.
>
> Testing:
> - Cross-built riscv/sbi.flat and built it natively on a RISC-V host.
> - Ran the SBI tests with KVM five times each with 1 and 32 vCPUs.
> All runs passed, with 15 tests skipped per run. Both timer delay
> checks passed in all runs.
>
> riscv/sbi.c | 3 ++-
> 1 file changed, 2 insertions(+), 1 deletion(-)
>
> diff --git a/riscv/sbi.c b/riscv/sbi.c
> index 3b8aadce..5633b1f9 100644
> --- a/riscv/sbi.c
> +++ b/riscv/sbi.c
> @@ -292,8 +292,9 @@ static void timer_check_set_timer(bool mask_timer_irq)
> if (ret.error)
> report_info("set timer%s failed with %ld\n", mask_test_str, ret.error);
>
> - while ((end = timer_get_cycles()) <= (begin + d + margin) && !timer_info.timer_works)
> + while (!timer_info.timer_works && timer_get_cycles() <= begin + d + margin)
> cpu_relax();
> + end = timer_get_cycles();
>
> report(timer_info.timer_works, "timer interrupt received%s", mask_test_str);
> report(timer_info.timer_irq_set, "pending timer interrupt bit set in irq handler%s", mask_test_str);
> --
> 2.39.5
>
Queued. https://gitlab.com/jones-drew/kvm-unit-tests/-/commits/riscv/queue
Thanks,
drew
More information about the kvm-riscv
mailing list