Repository navigation
sw: re-read mtime high word in clint_get_mtime - #142
Merged
Merged
Conversation
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
approved these changes
Nov 13, 2026
Collaborator
|
Thanks for the fix! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
clint_get_mtime()readsMTIME_HIGHand thenMTIME_LOW, once each. The CLINT returns the livemtime_qon 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 anmtimecmpthat 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.cfor the host against a Verilator model ofrtl/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.