From 3eb80535932d06d1034342ba984a1cf46ef11a07 Mon Sep 17 00:00:00 2001 From: Sid Chaudhary Date: Sun, 8 Nov 2026 02:22:46 +0000 Subject: [PATCH] sw: re-read mtime high word in clint_get_mtime The CLINT returns the live counter on both mtime registers, so if the low word wraps between the two loads, clint_get_mtime() pairs the old high word with the new low word and returns a value 2^32 ticks too small. clint_sleep_ticks() then programs mtimecmp in the past and the sleep returns immediately. Read the high word again and retry if it changed. --- sw/lib/src/clint.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/sw/lib/src/clint.c b/sw/lib/src/clint.c index 0ac0cf609..04462f414 100644 --- a/sw/lib/src/clint.c +++ b/sw/lib/src/clint.c @@ -9,10 +9,13 @@ #include "config.h" uint64_t clint_get_mtime() { - uint64_t mtime; - mtime = ((uint64_t)*reg32(CLINT_BASE_ADDR, CLINT_MTIME_HIGH_REG_OFFSET)) << 32; - mtime |= ((uint64_t)*reg32(CLINT_BASE_ADDR, CLINT_MTIME_LOW_REG_OFFSET)); - return mtime; + uint32_t mtime_high, mtime_low; + // Read the high register again in case the low register wrapped in between + do { + mtime_high = *reg32(CLINT_BASE_ADDR, CLINT_MTIME_HIGH_REG_OFFSET); + mtime_low = *reg32(CLINT_BASE_ADDR, CLINT_MTIME_LOW_REG_OFFSET); + } while (mtime_high != *reg32(CLINT_BASE_ADDR, CLINT_MTIME_HIGH_REG_OFFSET)); + return ((uint64_t)mtime_high << 32) | mtime_low; } void clint_set_mtimecmp(uint64_t value) {