Performance Counters

One counter counts clock edges and one counts finished instructions. Read both before and after a routine, and you know how long it took for the work it did. A third counter says how often one chosen event happened.

You Will Be Able To

  • Measure a routine as a window: read the counters before and after, and subtract.
  • Compute cycles per instruction, and say what that average hides.
  • Tell a count of events from a count of waiting time, and count a write on the edge that completes it.
Lesson
S8.6
Time
25 min
Runs on
Your browser
Check
5 questions

The console test prints the letter h on two mornings. Both runs are correct, and one of them is late. A colleague wants a faster UART. Before anyone changes a clock, can you show where the extra time went?

Before You Start

You need A Processor in One Picture: an instruction, the PC, and a store that becomes a bus transfer.

You need Memory and Caches in One Picture: a miss, and the wait that follows it.

You need One Access, End to End: a write through the bridge takes several clock edges, and one of them completes it.

You need Registers: the read of a 64-bit counter in two halves.

One thing is assumed that no earlier page teaches: a fast processor may start work at an address that turns out wrong. "At Scale" says more. No quiz item depends on it.

Five questions this page answers
Question
1What do you subtract to measure one routine?
2What is CPI, and what does a CPI of 4.00 not tell you?
3Does an event counter say how often, or how long?
4On which clock edge is a write counted?
5One wait edge is removed from a measured routine: what do the counters read?

The Idea: Count Time, Count Work, Subtract

A chip that is too slow gives no error message. Everything is correct, only late. To find the lost time you need numbers from inside the chip, and the cheapest instrument is a counter.

Two counters go a long way. One adds 1 on every clock edge: it counts time. The other adds 1 each time an instruction is complete: it counts work. An instruction that is complete has retired. A stalled instruction adds to the first counter and not to the second.

Neither total means much alone: both have run since reset. So you measure a measurement window. Read both counters before the routine and again after it, and subtract. Divide the cycles by the instructions and you have CPI, cycles per instruction, for that window.

CPI says that time was lost. It does not say where. For that, a third counter watches one kind of event at a time. It may be a miss, a wait on the bus or a finished write. Such an event counter tells you how often the event happened. How long each one took is a different measurement.

New Words

New words on this page
WordMeaning
Performance counterA counter inside the chip that software can read to see how time was spent.
Retired instructionAn instruction that is complete: its result is now part of the state of the program.
Measurement windowThe stretch of time between two readings of the counters. This page calls it a window.
CPICycles per instruction: the clock cycles of a window divided by the instructions retired in it.
Event counterA counter that adds 1 each time one chosen kind of event happens.
Event selectorA register field that chooses which kind of event the event counter watches.
Fetch missA miss on the way to fetch an instruction. The instruction must wait for memory.
RedirectThe processor drops the address it was fetching from and starts again at another one.
Wait edgeA clock edge on which a bus transfer is in progress and not yet complete.

One Picture: Counters Around a Routine

Two Counters, a Window and One QuestionStep through the picture. It starts with one counter and ends with a measurement that can be trusted.
  • Clock / reset
  • Processor
  • Peripheral
  • Memory
  • Control / FSM
Two Counters, a Window and One QuestionStep through the picture. It starts with one counter and ends with a measurement that can be trusted. component Clock one edge afteranother, whateverthe processor does component Processor says "retired" eachtime an instruction iscomplete component Event sources a fetch miss, aredirect, a finishedwrite, a wait edge component Cycle counter adds 1 on every clockedge component Retired counter adds 1 for everyretired instruction component Event counter adds 1 for each eventof the selected kind component Software reads the countersbefore and after, andsubtracts every edgeretiredone kind, chosen by aselectorreadreadread
  1. component Clockone edge after another, whatever the processor does
    • every edge → Cycle counter
  2. component Cycle counteradds 1 on every clock edge
    • read → Software
  3. component Processorsays "retired" each time an instruction is complete
    • retired → Retired counter
  4. component Retired counteradds 1 for every retired instruction
    • read → Software
  5. component Softwarereads the counters before and after, and subtracts
  6. component Event sourcesa fetch miss, a redirect, a finished write, a wait edge
    • one kind, chosen by a selector → Event counter
  7. component Event counteradds 1 for each event of the selected kind
    • read → Software
  1. Time

    The cycle counter adds 1 on every clock edge. It measures time in clock periods.

  2. Work

    The retired counter adds 1 each time an instruction is complete. It measures work done.

  3. A window

    Software reads both counters before a routine and again after it. The two differences belong to that routine alone.

  4. One question

    A third counter can watch one kind of event, chosen by a selector. It answers one question for each run: how often did this happen?

Read the diagram as text
  • Clock: one edge after another, whatever the processor does
  • Processor: says "retired" each time an instruction is complete
  • Event sources: a fetch miss, a redirect, a finished write, a wait edge
  • Cycle counter: adds 1 on every clock edge
  • Retired counter: adds 1 for every retired instruction
  • Event counter: adds 1 for each event of the selected kind
  • Software: reads the counters before and after, and subtracts
  • Clock → Cycle counter: every edge
  • Processor → Retired counter: retired
  • Event sources → Event counter: one kind, chosen by a selector
  • Cycle counter → Software: read
  • Retired counter → Software: read
  • Event counter → Software: read

The counters of this page. Time and work are always counted. The event counter is pointed at one kind of event at a time.

The Smallest Example, Worked by Hand

Take a routine of three instructions. No simulator yet. The table follows it for six clock edges, with the two counters at 0 when the window opens.

Six clock edges of one routine
EdgeWhat happensCycles so farRetired so far
1The fetch of the first instruction misses. The processor waits.10
2The first instruction, a load, is complete.21
3The second instruction, an add, is complete.32
4The third instruction is a store to a slow device. A wait edge.42
5A second wait edge of the same store.52
6The store is complete.63

The window holds 6 cycles and 3 retired instructions. CPI is 6 divided by 3: 2.00. The load took 2 cycles, the add 1 and the store 3. CPI is an average over the window; it does not say what any one instruction took.

Now count events. One fetch miss. One finished write. Two wait edges. The miss count says how often a fetch missed: once. It does not say that the miss cost one cycle.

To learn what the waits cost, change one thing. Give the store a device that never waits. Edges 4 and 5 are gone: 4 cycles, 3 instructions, CPI 1.33. The two waits cost exactly two cycles of this routine.

The Rules

  1. Rule 1: Measure a window.

    Read the counters before and after, and subtract. A total since reset says nothing about one routine.

  2. Rule 2: CPI is cycles divided by retired instructions, for one window.

    It is an average. It does not say what any single instruction took.

  3. Rule 3: An event counter says how often, not how long.

    One miss is one count, whether it costs 2 cycles or 200.

  4. Rule 4: Count an event on the edge that defines it.

    A write is counted on the one edge that completes it. The wait edges before it are counted apart.

  5. Rule 5: Compare two runs only if they did the same work.

    Then change one thing, and measure again. The difference is the cost of that one thing.

  6. Rule 6: Read a counter that is wider than the bus as high, low, high again.

    If the two high halves differ, a carry came in between: read again.

Sources for These Rules

Time of a program as instructions times cycles for each instruction times the clock period, and CPI as an average: Patterson and Hennessy, Computer Organization and Design, ARM edition, section 1.6.

What a miss costs: the same book, section 5.4. A branch that sends the processor to another address: section 4.8.

A write is complete on the edge where the select, the enable and the ready are all high: Arm AMBA APB Protocol Specification, IHI 0024 issue E, sections 3.1.1 and 3.1.2.

Rule 6 is the read taught in the lesson on registers. Rules 1, 3 and 5 are common practice in measurement, stated here in our own words.

Which events exist, their selector codes and the routine of three instructions are choices of our lab.

Now Run It

The lab at the end of this page measures one short routine twice. The routine is a load, a branch and a store that prints the letter h through UART0. The event selector is 0 on the first pass and 1 on the second. Selector 0 counts fetch misses. Selector 1 counts redirects.

Printed by the lab on Icarus: one row of differences for each pass. The lab also prints six bus rows and two reads of the counter, shown below.
selector=0 cycles=12 retired=3 events=2 writes=1 waits=2 CPI=4.00
selector=1 cycles=12 retired=3 events=1 writes=1 waits=2 CPI=4.00

Rules 1 and 2 at work, in the first row. The window holds 12 cycles and 3 retired instructions, so CPI is 4.00. That is an average over a load, a branch and a slow store.

Rule 3: events=2 on the first pass and events=1 on the second. Fetch missed twice, and there was one redirect. Neither number is a time.

Rule 5: both rows show cycles=12, retired=3, writes=1 and waits=2. The two passes did the same work, so their event counts can sit side by side.

Which Edge Counts as a Write?
  • Processor
  • Bus
  • Peripheral
AHB requestAPB accessBus modelAHB/APB bridgeUART0
AHB request→ AHB/APB bridgeAPB access→ UART0Bus modelAHB/APB bridgeUART0

A lit wire carries a 1. A pill is a transfer in that cycle.

012345clkreqselenablereadyhready
Scroll horizontally ↔
  1. Cycle 1

    The bridge takes the address of the write.

  2. Cycle 2

    The bridge selects UART0. Enable is still 0: this is the setup phase.

  3. Cycle 3

    Enable is 1 and ready is 0. One wait edge is counted. The write is not done.

  4. Cycle 4

    A second wait edge for the same write.

  5. Cycle 5

    Enable and ready are both 1. UART0 takes the letter h. One write is counted, here and only here.

Recorded by the lab at rising clock edges e0 to e5, during the one write of the measured routine.

Rule 4, in the picture of the write. The select is high on four edges, e2 to e5. Edges e3 and e4 are wait edges: waits=2. Only e5 has enable and ready both high, and only e5 counts as a write: writes=1.

Rule 5 again, as an experiment. Set the waits of UART0 to zero and run once more. The lab then reports cycles=10 and CPI=3.33 for the same three instructions. Two waits cost two cycles: the faster UART would buy exactly that, and no more.

The two reads of the 64-bit cycle counter that the lab makes first. Each row is high, low, high again.
split high=00000000 low=00000000 high_again=00000001
split high=00000001 low=00000002 high_again=00000001

Rule 6, in these two rows. In the first, the high half changed from 00000000 to 00000001 between the reads: the pair is thrown away. In the second, both high halves agree, so the low half 00000002 belongs with them.

This lab leaves things out. No processor runs here. Test code says when an instruction retires, when a fetch misses and when a redirect happens. The counters live in test code too, not in registers on the bus. Only the write of the letter h goes through a real bridge and a real register.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
Count retired instructionsCount fetched instructionsOnly work that the program keeps is counted. The count comes from the end of the processor, not the front.
A few event counters and a selectorOne counter for every kind of eventLittle area. One question for each run, so runs must be repeatable.
Counters of 64 bitsCounters of 32 bitsAt 100 MHz a counter of 32 bits wraps after about 43 seconds. The wide one needs the read of rule 6.

The Trap: Four Letters That Were One

A monitor on the peripheral bus reported four writes of the letter h. The terminal showed one. The team spent a day looking for the three lost letters.

The monitor had counted every edge on which UART0 was selected. Look at the picture of the write again: the select is high on e2, e3, e4 and e5. That is one setup edge, two wait edges and one completing edge. One write.

A second trap is to price events without an experiment. Two misses and one redirect do not cost three cycles, or any fixed number. An event counter has no idea how long an event lasted. Change one cause, and measure the window again.

The third is a comparison of two CPI values from different work. A routine with CPI 4.00 can finish before one with CPI 2.00. It may retire fewer instructions, or run on a faster clock.

At Scale

This page3 counters, 1 routine
A phone chipdozens of counters in each core

This section looks ahead. A real processor and a real chip make the window harder to fence in.

  1. The wrong path

    You know from A Processor in One Picture that a jump writes the PC. A fast processor does not wait for a branch to decide. It guesses, and fetches ahead. After a wrong guess that work is thrown away, and fetch is redirected. Such work is never retired.

  2. Events that overlap

    In our lab the address after the redirect missed in the cache as well. One wrong guess led to a miss, so the two counts cannot simply be added as costs.

  3. An interrupt inside the window

    A handler adds cycles and retired instructions to a window. Mark its entry and its return, or the routine looks slower than it is.

  4. Many clocks

    A counter on a gated clock stops while time goes on. To compare two blocks, capture one common time with both readings.

Try It

Run the lab. Compare the two rows that start with "selector": which numbers are the same, and which one differs?

Set waits to zero. Predict which numbers of those rows can change before you run it.

Names Printed by the Lab
NameMeaning
selectorThe code in the event selector: 0 for fetch misses, 1 for redirects.
cycles, retiredThe differences of the cycle counter and of the retired counter over the window.
eventsThe difference of the event counter: events of the selected kind.
writes, waitsFinished writes to UART0, and wait edges of those writes.
splitOne read of the 64-bit cycle counter: its high half, its low half, and the high half again.
e0 to e5Six rising clock edges during the write. Each row lists the bus signals at that edge.
RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: split high=00000000 low=00000000 high_again=00000001 split high=00000001 low=00000002 high_again=00000001 e0 req=0 window=0 sel=0 gpio=0 uart=0 enable=0 ready=0 hready=1 prdata=00000000 hrdata=00000000 pwdata=00000000 haddr=00000000 paddr=00000000 hresp=0 e1 req=1 window=1 sel=0 gpio=0 uart=0 enable=0 ready=0 hready=1 prdata=00000000 hrdata=00000000 pwdata=00000000 haddr=10000000 paddr=00000000 hresp=0 e2 req=0 window=0 sel=1 gpio=0 uart=1 enable=0 ready=0 hready=0 prdata=00000000 hrdata=00000000 pwdata=00000068 haddr=00000000 paddr=10000000 hresp=0 e3 req=0 window=0 sel=1 gpio=0 uart=1 enable=1 ready=0 hready=0 prdata=00000000 hrdata=00000000 pwdata=00000068 haddr=00000000 paddr=10000000 hresp=0 e4 req=0 window=0 sel=1 gpio=0 uart=1 enable=1 ready=0 hready=0 prdata=00000000 hrdata=00000000 pwdata=00000068 haddr=00000000 paddr=10000000 hresp=0 e5 req=0 window=0 sel=1 gpio=0 uart=1 enable=1 ready=1 hready=1 prdata=00000000 hrdata=00000000 pwdata=00000068 haddr=00000000 paddr=10000000 hresp=0 UART TX byte=68 character=h selector=0 cycles=12 retired=3 events=2 writes=1 waits=2 CPI=4.00 UART TX byte=68 character=h selector=1 cycles=12 retired=3 events=1 writes=1 waits=2 CPI=4.00
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: io_lab_regs.sv
// Two word registers for the S1 labs. Inputs have already crossed into PCLK.
// The UART model exposes accepted bytes; it does not model the serial shifter.
module io_lab_regs (
  input  logic        pclk, presetn,
  input  logic        psel, penable, pwrite,
  input  logic [31:0] paddr, pwdata,
  input  logic [3:0]  pstrb,
  input  logic [15:0] pins,
  input  logic [31:0] wait_edges,
  output logic        pready, pslverr,
  output logic [31:0] prdata,
  output logic        uart_selected, gpio_selected,
  output logic        tx_accepted,
  output logic [7:0]  tx_byte
);
  localparam logic [19:0] UART_PAGE = 20'h10000, GPIO_PAGE = 20'h10001;
  logic [31:0] elapsed;
  wire tx_word = uart_selected && paddr[11:0] == 12'h000 && pwrite;
  wire input_word = gpio_selected && paddr[11:0] == 12'h004 && !pwrite;

  assign uart_selected = psel && paddr[31:12] == UART_PAGE;
  assign gpio_selected = psel && paddr[31:12] == GPIO_PAGE;
  assign prdata = input_word ? {16'b0, pins} : 32'b0;
  assign pready = psel && penable && elapsed >= wait_edges;
  assign pslverr = pready && !(tx_word || input_word);
  assign tx_accepted = tx_word && pready && pstrb[0];
  assign tx_byte = pwdata[7:0];

  always_ff @(posedge pclk or negedge presetn) begin
    if (!presetn) elapsed <= 0;
    else if (psel && penable && !pready) elapsed <= elapsed + 1;
    else elapsed <= 0;
  end
endmodule
Read included file: io_lab.svh
// Include inside the lesson's testbench. One manager, one clock, aligned words.
// The exercise drives only the UART TX and GPIO input registers.
`ifndef AP_SOC_EXTERNAL_HCLK
logic hclk = 0;
always #5 hclk = ~hclk;
`endif
logic hresetn = 0;
logic [31:0] haddr = 0, hwdata = 0;
logic [1:0] htrans = 0;
logic hwrite = 0;
wire hsel = haddr[31:16] == 16'h1000;
wire hready, hresp, psel, penable, pwrite;
wire [31:0] hrdata, paddr, pwdata;
wire [3:0] pstrb;

localparam logic [31:0] TX = 32'h1000_0000, INPUT_WORD = 32'h1000_1004;
logic [15:0] pins = 0; // Stable, already synchronized GPIO inputs.
integer waits = 0;
wire pready, pslverr, uart_selected, gpio_selected, tx_accepted;
wire [31:0] prdata;
wire [7:0] tx_byte;

io_lab_regs registers (
  .pclk(hclk), .presetn(hresetn), .psel(psel), .penable(penable),
  .pwrite(pwrite), .paddr(paddr), .pwdata(pwdata), .pstrb(pstrb),
  .pins(pins), .wait_edges(waits), .pready(pready), .pslverr(pslverr),
  .prdata(prdata), .uart_selected(uart_selected), .gpio_selected(gpio_selected),
  .tx_accepted(tx_accepted), .tx_byte(tx_byte)
);

ahb_apb_bridge bridge (
  .hclk(hclk), .hresetn(hresetn), .hsel(hsel), .haddr(haddr),
  .htrans(htrans), .hwrite(hwrite), .hprot(4'b0011), .hwdata(hwdata),
  .hwstrb(4'hf), .hready(hready), .hreadyout(hready), .hresp(hresp),
  .hrdata(hrdata), .psel(psel), .penable(penable), .pwrite(pwrite),
  .paddr(paddr), .pwdata(pwdata), .pstrb(pstrb), .pprot(),
  .pready(pready), .prdata(prdata), .pslverr(pslverr)
);

logic [39:0] console_text = 0;
bit trace_bus = 0;
int cycle = 0;
always @(posedge hclk) begin
  if (trace_bus) begin
    $display("e%0d req=%b window=%b sel=%b gpio=%b uart=%b enable=%b ready=%b hready=%b prdata=%08h hrdata=%08h pwdata=%08h haddr=%08h paddr=%08h hresp=%b",
             cycle, htrans[1], hsel, psel, gpio_selected, uart_selected, penable,
             pready, hready, prdata, hrdata, pwdata, haddr, paddr, hresp);
    cycle++;
  end
  if (tx_accepted) begin
    console_text = {console_text[31:0], tx_byte};
    $display("UART TX byte=%02h character=%c", tx_byte, tx_byte);
  end
end

task automatic access_word(input bit writing, input logic [31:0] address,
                           input logic [31:0] data, output logic [31:0] result);
  if (address[31:16] != 16'h1000 || address[1:0] != 0)
    $fatal(1, "This lab models aligned words in the APB window");
  @(negedge hclk);
  haddr = address;
  hwrite = writing;
  htrans = 2'b10;
  @(negedge hclk); // The address was accepted on the intervening rising edge.
  htrans = 0;
  haddr = 0;
  hwdata = data;
  do @(posedge hclk); while (!hready);
  if (hresp) $fatal(1, "Access failed at %08h", address);
  result = hrdata;
  #1;
endtask

Check Yourself

Predict the outputIn this run UART0 makes each write wait for one edge, not two. What is the last row? Its form is: selector=1 cycles=.. retired=3 events=1 writes=1 waits=. CPI=....
`timescale 1ns/1ns
module tb;
  `include "io_lab.svh"
  // The driver supplies retirement and front-end events until the core exists.
  bit retired, miss, redirect;
  bit select_redirect;
  logic [63:0] clocks = 64'hffff_fff8;
  int instructions = 0, events = 0, writes = 0, wait_edges = 0;
  always @(posedge hclk) if (hresetn) begin
    clocks <= clocks + 1;
    instructions <= instructions + retired;
    events <= events + (select_redirect ? redirect : miss);
    writes <= writes + tx_accepted;
    wait_edges <= wait_edges + (psel && penable && !pready);
  end

  task automatic step(input bit commit, cache_miss, wrong_branch);
    @(negedge hclk);
    retired = commit;
    miss = cache_miss;
    redirect = wrong_branch;
  endtask

  task automatic message(input bit selector);
    logic [63:0] start_cycles, elapsed;
    int start_inst, start_event, start_write, start_wait;
    logic [31:0] result;
    select_redirect = selector;
    start_cycles = clocks;
    start_inst = instructions;
    start_event = events;
    start_write = writes;
    start_wait = wait_edges;
    // Fetch misses once. A load retires after refill.
    step(0,1,0);
    step(0,0,0);
    step(1,0,0);
    // The branch retires and redirects fetch. Drop the wrong-path work.
    step(1,0,1);
    step(0,1,0); // The redirect target also misses.
    trace_bus = !selector;
    @(posedge hclk);
    #1 miss = 0;
    access_word(1, TX, "h", result);
    trace_bus = 0;
    step(1,0,0);
    step(0,0,0);
    elapsed = clocks - start_cycles;
    $display("selector=%0d cycles=%0d retired=%0d events=%0d writes=%0d waits=%0d CPI=%0.2f",
             selector, elapsed, instructions-start_inst, events-start_event,
             writes-start_write, wait_edges-start_wait, real'(elapsed)/(instructions-start_inst));
  endtask

  logic [31:0] high_a, low, high_b;
  initial begin
    waits = 1;
    repeat (2) @(negedge hclk);
    hresetn = 1;
    // Force a low-half rollover between reads by starting near the boundary.
    repeat (7) @(negedge hclk);
    do begin
      high_a = clocks[63:32];
      @(negedge hclk);
      low = clocks[31:0];
      @(negedge hclk);
      high_b = clocks[63:32];
      $display("split high=%08h low=%08h high_again=%08h",high_a,low,high_b);
    end while (high_a != high_b);
    message(0);
    message(1);
    $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: io_lab_regs.sv
// Two word registers for the S1 labs. Inputs have already crossed into PCLK.
// The UART model exposes accepted bytes; it does not model the serial shifter.
module io_lab_regs (
  input  logic        pclk, presetn,
  input  logic        psel, penable, pwrite,
  input  logic [31:0] paddr, pwdata,
  input  logic [3:0]  pstrb,
  input  logic [15:0] pins,
  input  logic [31:0] wait_edges,
  output logic        pready, pslverr,
  output logic [31:0] prdata,
  output logic        uart_selected, gpio_selected,
  output logic        tx_accepted,
  output logic [7:0]  tx_byte
);
  localparam logic [19:0] UART_PAGE = 20'h10000, GPIO_PAGE = 20'h10001;
  logic [31:0] elapsed;
  wire tx_word = uart_selected && paddr[11:0] == 12'h000 && pwrite;
  wire input_word = gpio_selected && paddr[11:0] == 12'h004 && !pwrite;

  assign uart_selected = psel && paddr[31:12] == UART_PAGE;
  assign gpio_selected = psel && paddr[31:12] == GPIO_PAGE;
  assign prdata = input_word ? {16'b0, pins} : 32'b0;
  assign pready = psel && penable && elapsed >= wait_edges;
  assign pslverr = pready && !(tx_word || input_word);
  assign tx_accepted = tx_word && pready && pstrb[0];
  assign tx_byte = pwdata[7:0];

  always_ff @(posedge pclk or negedge presetn) begin
    if (!presetn) elapsed <= 0;
    else if (psel && penable && !pready) elapsed <= elapsed + 1;
    else elapsed <= 0;
  end
endmodule
Read included file: io_lab.svh
// Include inside the lesson's testbench. One manager, one clock, aligned words.
// The exercise drives only the UART TX and GPIO input registers.
`ifndef AP_SOC_EXTERNAL_HCLK
logic hclk = 0;
always #5 hclk = ~hclk;
`endif
logic hresetn = 0;
logic [31:0] haddr = 0, hwdata = 0;
logic [1:0] htrans = 0;
logic hwrite = 0;
wire hsel = haddr[31:16] == 16'h1000;
wire hready, hresp, psel, penable, pwrite;
wire [31:0] hrdata, paddr, pwdata;
wire [3:0] pstrb;

localparam logic [31:0] TX = 32'h1000_0000, INPUT_WORD = 32'h1000_1004;
logic [15:0] pins = 0; // Stable, already synchronized GPIO inputs.
integer waits = 0;
wire pready, pslverr, uart_selected, gpio_selected, tx_accepted;
wire [31:0] prdata;
wire [7:0] tx_byte;

io_lab_regs registers (
  .pclk(hclk), .presetn(hresetn), .psel(psel), .penable(penable),
  .pwrite(pwrite), .paddr(paddr), .pwdata(pwdata), .pstrb(pstrb),
  .pins(pins), .wait_edges(waits), .pready(pready), .pslverr(pslverr),
  .prdata(prdata), .uart_selected(uart_selected), .gpio_selected(gpio_selected),
  .tx_accepted(tx_accepted), .tx_byte(tx_byte)
);

ahb_apb_bridge bridge (
  .hclk(hclk), .hresetn(hresetn), .hsel(hsel), .haddr(haddr),
  .htrans(htrans), .hwrite(hwrite), .hprot(4'b0011), .hwdata(hwdata),
  .hwstrb(4'hf), .hready(hready), .hreadyout(hready), .hresp(hresp),
  .hrdata(hrdata), .psel(psel), .penable(penable), .pwrite(pwrite),
  .paddr(paddr), .pwdata(pwdata), .pstrb(pstrb), .pprot(),
  .pready(pready), .prdata(prdata), .pslverr(pslverr)
);

logic [39:0] console_text = 0;
bit trace_bus = 0;
int cycle = 0;
always @(posedge hclk) begin
  if (trace_bus) begin
    $display("e%0d req=%b window=%b sel=%b gpio=%b uart=%b enable=%b ready=%b hready=%b prdata=%08h hrdata=%08h pwdata=%08h haddr=%08h paddr=%08h hresp=%b",
             cycle, htrans[1], hsel, psel, gpio_selected, uart_selected, penable,
             pready, hready, prdata, hrdata, pwdata, haddr, paddr, hresp);
    cycle++;
  end
  if (tx_accepted) begin
    console_text = {console_text[31:0], tx_byte};
    $display("UART TX byte=%02h character=%c", tx_byte, tx_byte);
  end
end

task automatic access_word(input bit writing, input logic [31:0] address,
                           input logic [31:0] data, output logic [31:0] result);
  if (address[31:16] != 16'h1000 || address[1:0] != 0)
    $fatal(1, "This lab models aligned words in the APB window");
  @(negedge hclk);
  haddr = address;
  hwrite = writing;
  htrans = 2'b10;
  @(negedge hclk); // The address was accepted on the intervening rising edge.
  htrans = 0;
  haddr = 0;
  hwdata = data;
  do @(posedge hclk); while (!hready);
  if (hresp) $fatal(1, "Access failed at %08h", address);
  result = hrdata;
  #1;
endtask
ConceptWhat do you subtract to measure one routine?
ConceptA window has a CPI of 4.00. What does that not tell you?
ConceptWhat does an event counter tell you about fetch misses?
ConceptOn which clock edge is a write to UART0 counted?

Common Mistakes

Wrong Count every selected edge as a write.

A write with waits is selected on several edges.

Fix Count the one edge on which enable and ready are both high.

Wrong Charge every miss one lost cycle.

An event counter says how often, not how long.

Fix Change one cause and measure the window again.

Wrong Read a CPI as the time of each instruction.

It is an average over the window.

Fix Use it to compare two runs of the same work.

Remember

  • Read the counters before and after a routine, and subtract.
  • CPI is cycles divided by retired instructions: an average over one window.
  • An event counter says how often. Waiting time is counted apart, edge by edge.
  • Compare runs of the same work, and change one thing at a time.

Practice

Report a problem with this page