Timers: The Machine Timer
An alarm rings on time, yet the log says time went backward. The timer did nothing wrong. Follow one alarm, and one read of the clock, across a rollover.
You Will Be Able To
- Explain what raises the request of the machine timer, and the one thing that lowers it.
- Read a 64-bit counter over a 32-bit bus without getting a time that never existed.
- Tell the machine timer in ap_clint from the Timer and PWM block.
- Lesson
- S6.10
- Time
- 24 min
- Runs on
- Your browser
- Check
- 6 questions
Your board stamps the time beside every alarm. The first stamp looks right. The next one says zero. Did the timer reset, or did the log put together a time that never existed?
Before You Start
You need S0.8: an interrupt, a handler and a return. You need The Interrupt Path: a core-local interrupt has a wire of its own to the processor.
You need Registers: a register is read and written 32 bits at a time on this chip.
| Question | |
|---|---|
| 1 | What are the two registers of the machine timer? |
| 2 | When is its interrupt request 1? |
| 3 | What must a handler do to lower the request? |
| 4 | How can two correct 32-bit reads give a wrong 64-bit time? |
| 5 | Which order of reads gives a time that is always right? |
The Idea: An Alarm Is a Comparison
A kitchen timer counts down to zero and rings once. The timer of a processor works the other way, and the difference matters. It has a counter that only counts up and never stops. It has a second register, the deadline, that holds a time. The request is nothing but a comparison: has the counter reached the deadline?
Two things follow. First, the counter is never disturbed by an alarm, so it stays a true account of time. A late handler does not make the next alarm late.
Second, the request does not go away by itself. Once the counter is past the deadline it stays past it. The request is 1 until software writes a later deadline.
The counter is 64 bits wide so that it never runs out. But this chip reads 32 bits at a time. So one reading of the clock takes two reads, and the counter does not wait between them. That is where the log of the hook went wrong.
New Words
| Word | Meaning |
|---|---|
| Machine timer | The timer that belongs to the processor. On ap_soc it is inside the block ap_clint. |
| Free-running counter | A counter that counts up at every tick and is never stopped or cleared by its own alarm. |
| Tick | One step of the counter. |
| Timer deadline | A time, written by software, at which the request shall rise. A deadline for short. |
| mtime | The name of the 64-bit counter of the machine timer. A RISC-V name. |
| mtimecmp | The name of its 64-bit deadline register. A RISC-V name. |
| Low word | Bits 31 to 0 of a 64-bit value. The high word is bits 63 to 32. |
| Rollover | The tick at which the low word passes its largest value and starts again at 0. The high word gains 1. |
| Torn read | A value put together from two reads that were taken at two different times. |
One Picture: Counter, Deadline, Comparison
- Clock / reset
- Memory
- Control / FSM
- Processor
- A counter that never stops
The counter adds 1 at every tick. No alarm changes it, so it is the one account of time on the chip.
- A deadline
Software writes a time into the deadline register: "call me then". After that it can do other work.
- A comparison
A comparator watches both. Its output is 1 at the deadline and stays 1 after it, for as long as nobody moves the deadline.
- The request
That output is the interrupt request. It is core-local: it has a wire of its own to the processor.
- The way to end it
The handler writes a later deadline. The comparison turns false and the request falls. Nothing else lowers it.
Read the diagram as text
- Counter: 64 bits; it only counts up
- Deadline register: 64 bits; software writes it
- Comparator: counter at or past the deadline?
- Processor: a wire of its own for this request
- Handler: writes a later deadline
- Counter → Comparator: time now
- Deadline register → Comparator: time wanted
- Comparator → Processor: timer request
- Processor → Handler: forced jump
- Handler → Deadline register: new deadline
The machine timer of ap_soc, inside the block ap_clint. The lab below is this picture, with test code in the place of the processor.
The machine timer is not the only timer of ap_soc. The Timer and PWM block is a device on APB with a different job. The next page is about that one.
| Address | Word | Access |
|---|---|---|
| 0x02004000 | mtimecmp, low word | read and write |
| 0x02004004 | mtimecmp, high word | read and write |
| 0x0200BFF8 | mtime, low word | read; a write sets the time |
| 0x0200BFFC | mtime, high word | read; a write sets the time |
In ap_clint, at base 0x02000000, on AHB.
The Smallest Example, Worked by Hand
Shrink the timer to two decimal digits. The counter runs 00, 01, 02 and so on. The deadline is 09.
| Counter | What software does | Deadline | Is the counter at or past it? | Request |
|---|---|---|---|---|
| 07 | nothing | 09 | no | 0 |
| 08 | nothing | 09 | no | 0 |
| 09 | nothing | 09 | yes | 1 |
| 10 | the handler runs, and returns | 09 | yes | 1 |
| 11 | the handler writes deadline 19 | 19 | no | 0 |
At 10 the handler has run and returned, and the request is still 1. Only the new deadline in the last row lowers it.
Now read the clock. The bus carries one digit for each read, and the counter ticks from 09 to 10 between two reads.
| Order of reads | First read | Tick | Second read | Third read | Result |
|---|---|---|---|---|---|
| High, then low | high = 0 | 09 to 10 | low = 0 | 00: nine too early | |
| Low, then high | low = 9 | 09 to 10 | high = 1 | 19: nine too late | |
| High, low, high | high = 0 | 09 to 10 | low = 0 | high = 1 | The two highs differ: read again |
| High, low, high, second try | high = 1 | none | low = 0 | high = 1 | 10: correct |
Each single read was correct. The two wrong results are torn reads: halves of two different times. The time 00 is what the log of the hook printed.
The Rules
Rule 1: The counter only counts.
No alarm, and no handler, stops or clears it.
Rule 2: The request is a comparison.
It is 1 whenever the counter is at or past the deadline, both read as unsigned 64-bit numbers.
Rule 3: Only a later deadline lowers the request.
A return from the handler changes neither the counter nor the deadline.
Rule 4: A 64-bit value crosses a 32-bit bus in two transfers.
The counter can tick between them.
Rule 5: Read high, low, high.
Keep the low word only if the two high words are equal. If not, read again.
Sources for These Rules
Timers as counters with compare registers: Harris and Harris, Digital Design and Computer Architecture, ARM edition, section 9.3.5.
One transfer carries at most the width of the data bus: Arm AMBA AHB Protocol Specification, IHI 0033 issue C, section 3.1.
Rules 1 to 3 are read from our own machine timer, and every row on this page is recorded from it. The names mtime and mtimecmp, and the comparison, follow RISC-V practice. Our reference library does not hold the RISC-V specifications, so treat them as RISC-V facts.
Rule 5 is practice. It holds while the counter only counts up and no other writer changes it.
The addresses and the core-local wire are our own choices for ap_soc.
Now Run It
The lab at the end of this page has the machine timer. Test code, a bus-functional model, stands in for the processor and makes the reads and writes. The lab starts the counter two ticks below a rollover, so you need not wait four billion ticks.
mtime=00000000fffffffe cmp=00000000ffffffff irq=0
mtime=00000000ffffffff cmp=00000000ffffffff irq=1
mtime=0000000100000000 cmp=00000000ffffffff irq=1
first high=00000000 low=00000000 last high=00000001
snapshot=0000000100000000
rearmed mtime=0000000100000000 cmp=00000001ffffffff irq=0Rule 2 at work: in row 1 the counter is one below the deadline and irq=0. In row 2 they are equal and irq=1. In row 3 the low word has rolled over to 00000000, and irq is still 1. The carry went into the high word.
Rule 4 at work: the row "first" has high=00000000 and low=00000000. Put together, that is time zero. The counter was never there. The last high read, 00000001, gives it away.
Rule 5 at work: the second try returns the row "snapshot", 0000000100000000. Rule 3 at work: in the row "rearmed" the deadline is 00000001ffffffff and irq=0.
Four moments of the lab run, in hexadecimal. The columns are not evenly spaced in time.
This lab leaves things out. Ticks come from the test code, one at a time, not from a clock. No handler runs: the test code writes the new deadline directly. The interrupt enable bits inside the processor are not here.
Why It Is Built This Way
| Design choice | The alternative | What the choice buys, and costs |
|---|---|---|
| A counter that only counts, and a deadline | A counter that counts down and is loaded again by software | A late handler does not shift later alarms. Software must do the sum for the next deadline. |
| A request that is a comparison | A pulse at the moment of the match | A request that arrives while interrupts are off is still there afterwards. It must be ended on purpose. |
| 64 bits | 32 bits | At a million ticks a second, 32 bits roll over in 72 minutes and 64 bits in over 500,000 years. One reading needs three reads. |
| A wire of its own to the processor | A source of the interrupt controller | The most frequent interrupt needs no claim and no completion. The processor has one more input. |
The two times are arithmetic. Divide 2 to the power 32, and 2 to the power 64, by a million ticks a second.
The Trap: A Time That Never Existed
Back to the log that went backward. The handler read the high word, then the low word, and wrote both down. For four billion ticks that works. Then one read lands on a rollover, and the log shows a stamp of zero between two large ones.
It is a nasty fault for three reasons. It is rare: one tick in four billion is dangerous. Every bus transfer in it is perfect, so a bus checker sees nothing. And the wrong value is a plausible one. Rule 5 costs one more read and removes it.
Writing has the mirror problem. The deadline is written in two halves too, and the comparator looks at it all the time. Between the two writes the register holds half of the old deadline and half of the new one. If that mixture lies in the past, the request rises for no reason. The practice problem "The Machine Timer" asks you for an order of writes that is safe.
At Scale
This section looks ahead. A large chip has many counters, and they agree on very little.
A steady tick
An operating system wants an interrupt every N ticks. Add N to the old deadline, not to the time the handler happened to run. A late handler then does not move every later tick.
Which clock wrote the stamp
Two counters in two clock domains can show equal numbers at different moments. Write down the clock, the unit and the starting point of each.
Time while the board sleeps
A counter whose clock stops in sleep cannot say how long the sleep was. A real-time clock, with a clock and a supply of its own, keeps counting. ap_soc has none.
The other timer
For a pulse on a pin, or the time of an edge on a pin, a chip has timer devices. The next page has one.
Try It
Run the lab. Find the row in which the high word changes.
Compare the row that starts with "first" with the row "snapshot". One is a time that never existed.
Delete the two writes after the snapshot, so the deadline never moves. Predict irq in the last row.
Names Printed by the Lab
| Name | Meaning |
|---|---|
| mtime | The 64-bit counter, in hexadecimal. |
| cmp | The 64-bit deadline register, mtimecmp. |
| irq | The timer request to the processor. |
| first high, low, last high | Three reads of 32 bits each: the high word, the low word, the high word again. |
| snapshot | The 64-bit time after a second try, when both high reads agreed. |
| rearmed | The row printed after the handler has written a later deadline. |
mtime=00000000fffffffe cmp=00000000ffffffff irq=0 mtime=00000000ffffffff cmp=00000000ffffffff irq=1 mtime=0000000100000000 cmp=00000000ffffffff irq=1 first high=00000000 low=00000000 last high=00000001 snapshot=0000000100000000 rearmed mtime=0000000100000000 cmp=00000001ffffffff irq=0Read included file: ahb_apb_bridge.sv
`timescale 1ns/1ns
// ahb_apb_bridge.sv: an AHB subordinate that turns each accepted transfer into one APB transfer
// (read-only). The address phase is registered when HSEL, HREADY and a NONSEQ or SEQ transfer are
// all present. During SETUP and unfinished ACCESS the bridge keeps HREADYOUT low. A successful APB
// completion ends the AHB data phase with OKAY and HRDATA = PRDATA. A failed APB completion starts
// the two-cycle ERROR (HREADYOUT low then high, HRESP high in both). HWDATA and HWSTRB are data-phase signals the manager holds
// through the wait states, so PWDATA and PSTRB are driven from them directly; PADDR is the aligned
// word address (IHI 0024E 2.1.1 leaves an unaligned PADDR unpredictable). HPROT maps onto PPROT:
// privileged from HPROT[1], instruction from HPROT[0] = 0, and the access is Secure.
// A write therefore costs one setup and one access cycle: two cycles of data phase with no APB wait.
module ahb_apb_bridge (
input logic hclk,
input logic hresetn,
input logic hsel,
input logic [31:0] haddr,
input logic [1:0] htrans,
input logic hwrite,
input logic [3:0] hprot,
input logic [31:0] hwdata,
input logic [3:0] hwstrb,
input logic hready,
output logic hreadyout,
output logic hresp,
output logic [31:0] hrdata,
output logic psel,
output logic penable,
output logic pwrite,
output logic [31:0] paddr,
output logic [31:0] pwdata,
output logic [3:0] pstrb,
output logic [2:0] pprot,
input logic pready,
input logic [31:0] prdata,
input logic pslverr);
localparam int IDLE = 0, SETUP = 1, ACCESS = 2, ERR1 = 3, ERR2 = 4;
bit trace = 0;
int st = IDLE;
logic wr = 0;
logic [31:0] a = 0;
logic [2:0] prot = 0;
wire take = hsel && hready && htrans[1];
assign psel = (st == SETUP || st == ACCESS);
assign penable = (st == ACCESS);
assign pwrite = wr;
assign paddr = {a[31:2], 2'b00}; // APB leaves an unaligned PADDR unpredictable: the word, and PSTRB picks the bytes
assign pwdata = wr ? hwdata : 32'h0;
assign pstrb = wr ? hwstrb : 4'h0;
assign pprot = prot;
assign hreadyout = (st == IDLE || st == ERR2) ? 1'b1 : (st == ACCESS) ? (pready === 1'b1 && pslverr !== 1'b1) : 1'b0;
assign hresp = (st == ERR1 || st == ERR2);
assign hrdata = (st == ACCESS) ? prdata : 32'h0;
always @(posedge hclk or negedge hresetn) begin
if (!hresetn) st <= IDLE;
else begin
case (st)
SETUP: st <= ACCESS;
ACCESS: if (pready === 1'b1) begin
if (trace) $display("apb e%0d: %0s 0x%03h%0s", ($time - 5) / 10, wr ? "write" : "read", a[11:0], pslverr === 1'b1 ? " PSLVERR" : "");
st <= (pslverr === 1'b1) ? ERR1 : IDLE;
end
ERR1: st <= ERR2;
default: st <= IDLE;
endcase
// A new address phase can be taken whenever HREADY is 1: in IDLE, in the last cycle of ERROR,
// or at the edge an access completes with OKAY.
if (take && (st == IDLE || st == ERR2 || (st == ACCESS && pready === 1'b1 && pslverr !== 1'b1))) begin
wr <= hwrite; a <= haddr; prot <= {~hprot[0], 1'b0, hprot[1]}; st <= SETUP;
end
end
end
endmodule
Read included file: time_bus_bfm.svh
// One manager issues aligned words. The P4 bridge and local time slice share HCLK.
// Only the lesson's implemented, always-ready register words are accessed.
logic clk = 0, reset_n = 0;
always #5 clk = ~clk;
logic [31:0] haddr = 0, hwdata = 0;
logic hwrite = 0;
logic [1:0] htrans = 0;
wire bridge_window = haddr[31:16] == 16'h1000;
wire [31:0] local_data, bridge_data, paddr, pwdata, prdata;
wire bridge_ready, hresp, psel, penable, pwrite;
logic bridge_response;
wire hready = !bridge_response || bridge_ready;
logic [31:0] result;
bit trace_access = 0;
always_ff @(posedge clk) begin
if (!reset_n) bridge_response <= 0;
else if (hready) bridge_response <= htrans[1] && bridge_window;
end
ahb_apb_bridge bridge (
.hclk(clk), .hresetn(reset_n), .hsel(bridge_window), .haddr, .htrans, .hwrite,
.hprot(4'b0011), .hwdata, .hwstrb(4'hf), .hready, .hreadyout(bridge_ready),
.hresp, .hrdata(bridge_data), .psel, .penable, .pwrite, .paddr, .pwdata,
.pstrb(), .pprot(), .pready(1'b1), .prdata, .pslverr(1'b0)
);
always @(posedge clk)
if (trace_access && psel)
if (penable) $display("access addr=%08h sel=%b enable=%b data=%08h",paddr,psel,penable,pwdata);
else $display("setup addr=%08h sel=%b enable=%b data=%08h",paddr,psel,penable,pwdata);
task automatic bus_word(input bit wr, input logic [31:0] addr, data,
output logic [31:0] sample);
if (!modeled_word(wr,addr))
$fatal(1,"This target slice does not model that word operation at %08h",addr);
@(negedge clk);
haddr = addr;
hwrite = wr;
htrans = 2'b10;
@(negedge clk);
haddr = 0;
htrans = 0;
hwdata = data;
do @(posedge clk); while (!hready);
if (bridge_response && hresp) $fatal(1,"Bus error at %08h",addr);
sample = bridge_response ? bridge_data : local_data;
@(negedge clk);
endtask
task automatic apb_word(input bit wr, input logic [31:0] addr, data);
bus_word(wr,addr,data,result);
endtask
Read included file: timer_demo.svh
`include "time_bus_bfm.svh"
localparam TIMER = 32'h1000_2000, CLINT = 32'h0200_0000;
logic tick = 0, capture = 0;
wire hsel = hready && htrans[1] && haddr[31:16] == CLINT[31:16];
wire [63:0] mtime, mtimecmp;
wire timer_irq, pwm, match;
wire [1:0] phase;
machine_time #(.START(64'hffff_fffe)) ap_clint(
.clk, .reset_n, .tick, .hsel, .hwrite, .haddr(haddr[15:0]), .hwdata,
.hrdata(local_data), .mtime, .mtimecmp, .timer_irq
);
capture_pwm peripheral(
.clk, .reset_n, .psel(psel && paddr[31:12] == TIMER[31:12]),
.penable, .pwrite, .capture, .offset(paddr[11:0]), .pwdata, .prdata,
.phase, .pwm, .match
);
function automatic bit modeled_word(input bit wr, input logic [31:0] addr);
case (addr)
CLINT+'hbff8, CLINT+'hbffc, CLINT+'h4000, CLINT+'h4004: return 1;
TIMER, TIMER+4, TIMER+12, TIMER+16: return wr;
TIMER+8: return !wr;
default: return 0;
endcase
endfunction
task automatic machine_word(input bit wr, input logic [15:0] offset,
input logic [31:0] data, output logic [31:0] sample);
bus_word(wr,CLINT + offset,data,sample);
endtask
task automatic advance_time;
tick = 1;
@(negedge clk);
tick = 0;
$display("mtime=%016h cmp=%016h irq=%b",mtime,mtimecmp,timer_irq);
endtask
task automatic pwm_frame(input integer duty);
logic [7:0] pins, match_samples;
apb_word(1,TIMER+4,duty);
// Align each frame to the transition from slot three into slot zero.
wait (phase == 3);
wait (phase == 0);
for (int i=7; i>=0; i--) begin
@(negedge clk);
pins[i] = pwm;
match_samples[i] = match;
end
$display("duty=%0d pwm=%08b compare=%08b",duty,pins,match_samples);
endtask
Read included file: machine_time.sv
// ap_soc timer slice. Word offsets follow the CLINT layout.
// The parent supplies an accepted, aligned word address on HSEL.
module machine_time #(parameter logic [63:0] START = 0) (
input logic clk, reset_n, tick, hsel, hwrite,
input logic [15:0] haddr,
input logic [31:0] hwdata,
output logic [31:0] hrdata,
output logic [63:0] mtime, mtimecmp,
output logic timer_irq
);
logic selected, writing;
logic [15:0] offset;
always_ff @(posedge clk) begin
if (!reset_n) begin
selected <= 0;
writing <= 0;
offset <= 0;
mtime <= START;
mtimecmp <= '1;
end else begin
selected <= hsel;
writing <= hwrite;
offset <= haddr;
// A time write replaces the addressed half and suppresses that edge's tick.
if (selected && writing && offset == 16'hbff8)
mtime <= {mtime[63:32],hwdata};
else if (selected && writing && offset == 16'hbffc)
mtime <= {hwdata,mtime[31:0]};
else if (tick) mtime <= mtime + 1'b1;
if (selected && writing) begin
case (offset)
16'h4000: mtimecmp[31:0] <= hwdata;
16'h4004: mtimecmp[63:32] <= hwdata;
default: ;
endcase
end
end
end
always_comb begin
hrdata = 0;
if (selected && !writing)
case (offset)
16'h4000: hrdata = mtimecmp[31:0];
16'h4004: hrdata = mtimecmp[63:32];
16'hbff8: hrdata = mtime[31:0];
16'hbffc: hrdata = mtime[63:32];
default: ;
endcase
end
assign timer_irq = mtime >= mtimecmp;
endmodule
Read included file: capture_pwm.sv
// Four-slot peripheral timer. The prescaler top is the last count before a step.
// capture is a synchronous event strobe from the input front end.
module capture_pwm (
input logic clk, reset_n, psel, penable, pwrite, capture,
input logic [11:0] offset,
input logic [31:0] pwdata,
output logic [31:0] prdata,
output logic [1:0] phase,
output logic pwm, match
);
localparam RUN = 0, DUTY = 4, CAPTURED = 8, DIV_TOP = 12, COMPARE = 16;
logic running;
logic [7:0] divider, prescale_top;
logic [2:0] duty;
logic [1:0] captured, compare_phase;
wire write_word = psel && penable && pwrite;
always_ff @(posedge clk) begin
if (!reset_n) begin
running <= 0;
divider <= 0;
prescale_top <= 0;
phase <= 0;
duty <= 0;
compare_phase <= 0;
captured <= 0;
end else begin
if (write_word && offset == RUN) running <= pwdata[0];
if (write_word && offset == DUTY) duty <= pwdata[2:0];
if (write_word && offset == COMPARE) compare_phase <= pwdata[1:0];
if (write_word && offset == DIV_TOP) begin
prescale_top <= pwdata[7:0];
divider <= 0;
end else if (running) begin
if (divider == prescale_top) begin
divider <= 0;
phase <= phase + 1'b1;
end else divider <= divider + 1'b1;
end
if (capture) captured <= phase;
end
end
assign prdata = offset == CAPTURED ? {30'b0,captured} : 0;
assign pwm = running && phase < duty;
assign match = running && phase == compare_phase;
endmodule
Check Yourself
Common Mistakes
Wrong End the alarm by returning from the handler.
The counter is still past the deadline, so the request is still 1.
Fix Write a later deadline, and see the request fall.
Wrong Trust two reads because both completed without error.
The two words can belong to two different times.
Fix Read high, low, high, and try again if the high words differ.
Wrong Look for the machine timer in the Timer and PWM block.
They are two blocks, at two addresses, on two buses.
Fix The machine timer is in ap_clint. Its request is core-local.
Remember
- The machine timer is a counter that only counts, a deadline register and a comparison.
- Its request is 1 whenever the counter is at or past the deadline. Only a later deadline lowers it.
- Two reads of 32 bits can give a 64-bit time that never existed. Read high, low, high.
- The machine timer is in ap_clint and is core-local. The Timer and PWM block is a different device.