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.

Five questions this page answers
Question
1What are the two registers of the machine timer?
2When is its interrupt request 1?
3What must a handler do to lower the request?
4How can two correct 32-bit reads give a wrong 64-bit time?
5Which 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

New words on this page
WordMeaning
Machine timerThe timer that belongs to the processor. On ap_soc it is inside the block ap_clint.
Free-running counterA counter that counts up at every tick and is never stopped or cleared by its own alarm.
TickOne step of the counter.
Timer deadlineA time, written by software, at which the request shall rise. A deadline for short.
mtimeThe name of the 64-bit counter of the machine timer. A RISC-V name.
mtimecmpThe name of its 64-bit deadline register. A RISC-V name.
Low wordBits 31 to 0 of a 64-bit value. The high word is bits 63 to 32.
RolloverThe tick at which the low word passes its largest value and starts again at 0. The high word gains 1.
Torn readA value put together from two reads that were taken at two different times.

One Picture: Counter, Deadline, Comparison

A Counter, a Deadline and a ComparisonStep through the picture. It builds the machine timer from one counter to a request that software can end.
  • Clock / reset
  • Memory
  • Control / FSM
  • Processor
A Counter, a Deadline and a ComparisonStep through the picture. It builds the machine timer from one counter to a request that software can end. component Counter 64 bits; it onlycounts up component Deadline register 64 bits; softwarewrites it component Comparator counter at or pastthe deadline? component Processor a wire of its own forthis request component Handler writes a laterdeadline time nowtime wantedtimer requestforced jumpnew deadline
  1. component Counter64 bits; it only counts up
    • time now → Comparator
  2. component Deadline register64 bits; software writes it
    • time wanted → Comparator
  3. component Comparatorcounter at or past the deadline?
    • timer request → Processor
  4. component Processora wire of its own for this request
    • forced jump → Handler
  5. component Handlerwrites a later deadline
    • new deadline → Deadline register
  1. 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.

  2. A deadline

    Software writes a time into the deadline register: "call me then". After that it can do other work.

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

  4. The request

    That output is the interrupt request. It is core-local: it has a wire of its own to the processor.

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

The four words of the machine timer
AddressWordAccess
0x02004000mtimecmp, low wordread and write
0x02004004mtimecmp, high wordread and write
0x0200BFF8mtime, low wordread; a write sets the time
0x0200BFFCmtime, high wordread; 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.

A deadline of 09, by hand
CounterWhat software doesDeadlineIs the counter at or past it?Request
07nothing09no0
08nothing09no0
09nothing09yes1
10the handler runs, and returns09yes1
11the handler writes deadline 1919no0

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.

Reading 09 and 10, one digit at a time
Order of readsFirst readTickSecond readThird readResult
High, then lowhigh = 009 to 10low = 000: nine too early
Low, then highlow = 909 to 10high = 119: nine too late
High, low, highhigh = 009 to 10low = 0high = 1The two highs differ: read again
High, low, high, second tryhigh = 1nonelow = 0high = 110: 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

  1. Rule 1: The counter only counts.

    No alarm, and no handler, stops or clears it.

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

  3. Rule 3: Only a later deadline lowers the request.

    A return from the handler changes neither the counter nor the deadline.

  4. Rule 4: A 64-bit value crosses a 32-bit bus in two transfers.

    The counter can tick between them.

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

Printed by the lab on Icarus. All values are hexadecimal. The names are listed with the lab.
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=0

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

The Deadline Across the Rollover
0123momentone shortdeadlinerollovernew deadlinecounter high0000000000000001counter lowfffffffeffffffff00000000deadline high0000000000000001deadline lowffffffffirq
Scroll horizontally ↔

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 choiceThe alternativeWhat the choice buys, and costs
A counter that only counts, and a deadlineA counter that counts down and is loaded again by softwareA late handler does not shift later alarms. Software must do the sum for the next deadline.
A request that is a comparisonA pulse at the moment of the matchA request that arrives while interrupts are off is still there afterwards. It must be ended on purpose.
64 bits32 bitsAt 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 processorA source of the interrupt controllerThe 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 page1 counter, 1 deadline
A large chipone machine timer for each processor

This section looks ahead. A large chip has many counters, and they agree on very little.

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

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

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

  4. 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
NameMeaning
mtimeThe 64-bit counter, in hexadecimal.
cmpThe 64-bit deadline register, mtimecmp.
irqThe timer request to the processor.
first high, low, last highThree reads of 32 bits each: the high word, the low word, the high word again.
snapshotThe 64-bit time after a second try, when both high reads agreed.
rearmedThe row printed after the handler has written a later deadline.
RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: 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=0
Read 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

Predict the outputIn this run the handler never writes a new deadline. The counter ticks three times. What is the last row the lab prints?
`timescale 1ns/1ns
module tb;
  `include "timer_demo.svh"
  logic [31:0] high_before, low, high_after, unused;
  initial begin
    repeat (2) @(negedge clk);
    reset_n = 1;
    machine_word(1,'h4000,'hffff_ffff,unused);
    machine_word(1,'h4004,0,unused);
    $display("mtime=%016h cmp=%016h irq=%b",mtime,mtimecmp,timer_irq);
    repeat (3) advance_time;
    $finish;
  end
endmodule
Read 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
ConceptWhat are the two registers of the machine timer?
ConceptWhen is the request of the machine timer 1?
ConceptWhat must a handler do to lower the request?
ConceptHow can two correct 32-bit reads give a wrong 64-bit time?
ConceptWhich order of reads gives a time that is always right?

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.

Practice

Report a problem with this page