Skip to content

sw: re-read mtime high word in clint_get_mtime - #142

Merged
phsauter merged 1 commit into
pulp-platform:mainfrom
sidcraftscode:clint-mtime-read
Nov 13, 2026
Merged

phsauter merged 1 commit into
pulp-platform:mainfrom
sidcraftscode:clint-mtime-read

Conversation

@sidcraftscode

Copy link
Copy Markdown
Contributor

clint_get_mtime() reads MTIME_HIGH and then MTIME_LOW, once each. The CLINT returns the live mtime_q on both offsets and nothing is latched between the two reads, so if the low word wraps from 0xFFFFFFFF to 0 in between, the function returns the old high word with the new low word, 2^32 ticks too small. clint_sleep_ticks() then writes an mtimecmp that is already in the past and the sleep returns right away.

At 32.768 kHz the low word only wraps every ~36 hours, so it is rare, but the fix is cheap: read the high word again after the low word and retry if it changed (the same loop the RISC-V spec uses for rdcycleh/rdcycle).

To check it I built clint.c for the host against a Verilator model of rtl/clint/clint.sv, preset mtime to 0xFFFFFFFF and moved the RTC edge across the reads. The old code returned 0 in 6 of 120 runs; with the change every read was either 0xFFFFFFFF or 0x1_0000_0000. clang-format is clean.

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.
@phsauter
phsauter merged commit 4707c33 into pulp-platform:main Nov 13, 2026
2 checks passed
@phsauter

Copy link
Copy Markdown
Collaborator

Thanks for the fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants