This question is regarding the machine timer of risc-v. I'd like to use the timer to generate an accurate frequency interrupt. My timer clock runs at 50MHz and I'd like to get an interrupt every 1ms.
I therefore set the mtimecmp = 50000;
. As soon as mtime >= mtimecmp
there's going to be an interrupt, according to the risc-v specification.
In my interrupt handler I do this:
mtime -= 50000;
This should prime the timer for the next interrupt at precisely 1kHz. The problem I'm facing is that the execution of above statement does require more than 0 clocks, which means the mtime register is set to a value a little bit too low, leading to an average interrupt frequency of slightly less than 1kHz. I'm wondering if there's a solution to this. Is it possible to get an accurate interrupt frequency using the stock risc-v mtimer? How?
I'd suggest trying mtimecmp += 50000;
instead, and leave mtime
alone. (You can touch mtimecmp
, I believe, to reset MTIP
, so no need to touch mtime
.)
Even on 32-bit machines, these counters are 64 bits wide, so wrap around will take thousands of years.
(The privileged spec also provides a sequence for updating mtimecmp
on a 32-bit machine such that an intermediate value when written using multiple 32-bit writes does not generate an erroneous interrupt.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With