Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use risc-v timer for accurate timing generation

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?

like image 416
dsula Avatar asked Sep 06 '25 22:09

dsula


1 Answers

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.)

like image 109
Erik Eidt Avatar answered Sep 10 '25 11:09

Erik Eidt