The Debug Module on the Bus

A debugger shows registers and memory side by side. They come by two different routes, and only one of them needs the processor.

You Will Be Able To

  • Name the two routes from the debug module, and say what each one reaches.
  • Explain why a memory read by the debugger needs no hart, and what it shares with the hart.
  • Explain why the lock on debug access sits in the debug module and not in software.
Lesson
S8.3
Time
26 min
Runs on
Your browser
Check
5 questions

The board has power and the terminal is blank. The processor is stuck somewhere in boot code. You still want one word from the SRAM. The processor cannot fetch it for you, and it does not have to.

Before You Start

You need What a Debugger Needs From the Chip: the debug module, the hart, and halted.

You need A Bus in Six Wires and Two Buses and the Bridge. From them come a transfer, the manager, the address phase, the data phase and ready.

The lab sends its requests as scans. A scan is explained in JTAG.

Five questions this page answers
Question
1What are the two routes from the debug module into the chip?
2Which route needs a halted hart, and why?
3Who is the manager of a memory read that the debugger asks for?
4Why can the software of the chip not refuse the debugger, and what can?
5A reply of 0 comes back from a locked chip. How do you know that no read took place?

The Idea: Registers Through the Hart, Memory Through the Bus

A debugger shows two kinds of state. Registers live inside the hart. They have no address, and nothing outside the hart can reach them. Memory and devices live on the bus, each at an address.

So the debug module has two routes. For a register it asks the hart, and the hart must be halted to answer. That is the register route. For anything with an address it makes a bus transfer itself, through a bus port of its own. That is the bus route.

The bus route has a property that the hook needs. It does not use the hart at all. The hart may be running, halted or stuck. The debug module is a manager in its own right, and the SRAM answers it like any other manager.

That same property is a danger. A second manager can read every secret in memory, and the program never sees it happen. So a product has a debug lock. It sits in the debug module, the one place that every request must pass.

New Words

New words on this page
WordMeaning
Register routeA request that the debug module hands to the halted hart: read or write one register.
Bus routeA bus transfer that the debug module makes itself, as a manager.
Debug bus portThe port through which the debug module is a manager on the bus. The hart has a bus port of its own.
Debug lockA gate in the debug module. While it is closed, no request of the debugger is carried out.
Debug keyWhat a debugger must show before the debug lock opens. How it is shown is a matter for each product.
Read with a side effectA read that changes the device, such as one that takes a byte out of a queue.

One Picture: Two Routes and a Lock

Two Routes from the Debug Module, and One LockStep through the picture. It starts with the route to a register and ends with the lock.
  • Control / FSM
  • Debug
  • Processor
  • Power
  • Bus
  • Memory
Two Routes From the Debug Module, and One LockStep through the picture. It starts with the route to a register and ends with the lock. component Debugger with its probe,outside the chip component Debug module serves the debugger component Hart holds the registers component Debug lock open only for adebugger that hasshown its key component Bus carries transfersfrom two managers component SRAM and devices everything that hasan address requestsregister routeloads and storesbus routea transferopen or closed
  1. component Debuggerwith its probe, outside the chip
    • requests → Debug module
  2. component Debug moduleserves the debugger
    • register route → Hart
    • bus route → Bus
  3. component Hartholds the registers
    • loads and stores → Bus
  4. component Buscarries transfers from two managers
    • a transfer → SRAM and devices
  5. component SRAM and deviceseverything that has an address
  6. component Debug lockopen only for a debugger that has shown its key
    • open or closed → Debug module
  1. The register route

    A register has no address on the bus. It lives inside the hart. So the debug module asks the hart for it, and the hart must be halted to answer.

  2. The way the program uses

    Memory and devices are on the bus. The hart reaches them with loads and stores, as the manager of its bus port.

  3. The bus route

    The debug module has a bus port of its own. It is a second manager. It can read and write any address without any help from the hart.

  4. Two managers, one memory

    The hart may be running while the debugger reads. The bus lets one manager at a time reach the SRAM, as it does for any two managers.

  5. The lock

    The program never sees the transfers of the debug module, so it cannot refuse them. The refusal must sit in the debug module itself. With the lock closed, no request goes further.

Read the diagram as text
  • Debugger: with its probe, outside the chip
  • Debug module: serves the debugger
  • Hart: holds the registers
  • Debug lock: open only for a debugger that has shown its key
  • Bus: carries transfers from two managers
  • SRAM and devices: everything that has an address
  • Debugger → Debug module: requests
  • Debug module → Hart: register route
  • Hart → Bus: loads and stores
  • Debug module → Bus: bus route
  • Bus → SRAM and devices: a transfer
  • Debug lock → Debug module: open or closed

The two routes of access. The register route ends in the hart. The bus route never enters it.

The Smallest Example, Worked by Hand

Take five requests of a debugger, one after another. No simulator yet. For each one, name the route, and count the bus transfers that the SRAM sees.

Five requests, by hand
RequestRouteNeeds a halted hartWhat comes backTransfers so far
Read a register, hart runningRegisterYes, and it is not haltedNothing of use0
Write a word to the SRAMBusNoDone1
Read that word backBusNoThe word2
Read a register, hart haltedRegisterYes, and it is haltedThe register2
Read the SRAM, lock closedNoneNoNothing2

Read the last column. It moves only on the bus route. A register read leaves it alone, and so does a request that the lock stops.

Now look inside one of those transfers. Our SRAM takes one extra clock edge to answer, so a read needs three edges.

One read by the debug module, edge by edge
EdgePhaseReadyWhat happens
1Address1The SRAM accepts the address 80000010
2Data0The SRAM is not ready. The debug module waits.
3Data1The word arrives. The transfer is complete.

Three edges, one transfer. This is the transfer of the bus pages, with one new thing: its manager is not the processor.

The Rules

  1. Rule 1: Registers are reached through the hart.

    The hart must be halted. A register has no address on the bus.

  2. Rule 2: Memory and devices are reached through the bus.

    The debug module is the manager of those transfers, through its own bus port.

  3. Rule 3: The bus route needs no hart.

    It works while the hart runs, while it is halted, and when it is stuck.

  4. Rule 4: A transfer from the debug module is an ordinary transfer.

    It waits for ready, it can end in an error, and it takes its turn with the transfers of the hart.

  5. Rule 5: A read by the debugger can change a device.

    A read with a side effect acts the same, whoever the manager is.

  6. Rule 6: The debug lock sits in the debug module.

    While it is closed, no request becomes a transfer and no reply carries data.

How two managers take turns is the subject of Many Managers. A register with a side effect was met in the UART.

Sources for These Rules

Rule 4: the address phase, the data phase and a transfer that waits: Arm AMBA AHB Protocol Specification, IHI 0033 issue C, sections 3.1 and 3.7. The response of a subordinate: section 5.1.

Rules 1 to 3 and 6 follow the RISC-V External Debug Support specification. There a register command needs a halted hart, and access to the system bus does not. A debug module may also demand authentication. That document is not in our reference library. These are well-known facts about it and were not checked against its text.

Rule 5 follows from the register of the UART: a read of its receive register removes a byte.

The address 80000010, the word, the one extra edge of the SRAM and the form of the lock are choices of our lab.

Now Run It

The lab at the end of this page has three parts. They are a debug module with a bus port, an SRAM and a model of the hart. Test code plays the debugger and sends the five requests of the hand example, in that order.

Printed by the lab on Icarus. The lab calls the hart the core.
register route, core running: reply=00000000 transfers=0
address 80000010 write=1 ready=1
data    write=1 ready=0 response=0
data    write=1 ready=1 response=0
address 80000010 write=0 ready=1
data    write=0 ready=0 response=0
data    write=0 ready=1 response=0
bus route, core running: reply=5349474e transfers=2
register route, core halted: reply=00000040 transfers=2
locked, bus route: reply=00000000 transfers=2

Rule 1 at work, in the first row. The core runs, the debugger asks for a register, and the reply is 00000000. The count of transfers is 0.

Rule 4, in the six rows that follow. Each transfer has one address row and two data rows. The first data row has ready=0: the debug module waits, like any manager.

Rule 3, in the row "bus route, core running". The reply is 5349474e, the word that was written, and the count is 2. The core was running all the time.

Rule 1 again, in the row "core halted". Now the register arrives: 00000040. The count is still 2, so no transfer was made for it.

Rule 6, in the last row. The lock is closed and the debugger asks for the same word again. The reply is 00000000 and the count is still 2. The request never became a transfer.

This lab leaves things out. The hart is a model with one register, and the lab can halt it only at the end of its reset. The lock is one input that test code sets: no key is checked. The cable and the bus share one clock. And the 00000000 of the first row is an empty reply register. A real debug module reports an error for that request.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
A bus port for the debug moduleAsk the halted hart to do each load and storeMemory can be read when the hart is stuck or running. The bus gets one more manager, and the chip one more door.
The same bus for both managersA private path from the debug module into each memoryThe debugger sees the map that the program sees. Its transfers wait their turn.
A lock in the debug moduleLet boot code decide what the debugger may doIt holds even when the program is replaced or stuck. Someone must keep the keys.

The Trap: A Zero That Proved Nothing

A test engineer checks that a locked chip is safe. She asks for a word of the SRAM and gets 00000000. She signs the report. But a word of the SRAM may be 0 by right. The reply alone cannot tell "refused" from "read, and it was 0".

The proof is at the other end. Count the transfers that the SRAM accepts, as the lab does. A locked request must not move that count. And the reply must stay empty when the word is known not to be 0.

A second trap sits in rule 5. A debugger keeps a window open on the registers of a UART and reads them again every second. One of them is the receive register. Each refresh takes a byte out of the queue, and the program never sees those bytes.

The third trap is a memory that changes under a halted hart. The hart is halted, and yet a word of the SRAM is different on the second read. A halted hart writes nothing. Another manager, such as a DMA block, still does.

At Scale

This page2 managers, 1 lock
A phone chipdozens of managers

This section looks ahead. One lock and two managers become a policy for a whole product.

  1. More than open and closed

    A product often has several levels. The factory gets all of debug, the field gets part of it, and nobody gets the secret keys.

  2. A lock that changes with the life of the chip

    A chip is open while it is developed and closed when it is sold. The change is made once and cannot be undone.

  3. Who wrote this word?

    With many managers, a changed word has many suspects. The bus can record which manager made each write.

  4. Halt before the first instruction

    To catch boot code, the halt is armed during reset. Halt, Resume and Step names that tool.

Try It

Run the lab. Read the four rows that end in "transfers=" first: each is one answer that reached the debugger.

Change ram.waits from 1 to 2. Which rows are added, and does any count of transfers change?

Move the line "authenticated = 0" up, above the write. What do the four replies become?

Names Printed by the Lab
NameMeaning
coreThe lab calls the hart the core.
replyThe word that came back to the debugger, in hexadecimal.
transfersHow many bus transfers the SRAM has accepted since the start. The SRAM model counts them.
address ... write=The SRAM accepts the address of a transfer. write=1 is a write, write=0 a read.
data ... ready=One clock edge of the data phase of a transfer. ready=0 means: wait.
response0 means: no error.
lockedThe debug lock is closed.
RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: register route, core running: reply=00000000 transfers=0 address 80000010 write=1 ready=1 data write=1 ready=0 response=0 data write=1 ready=1 response=0 address 80000010 write=0 ready=1 data write=0 ready=0 response=0 data write=0 ready=1 response=0 bus route, core running: reply=5349474e transfers=2 register route, core halted: reply=00000040 transfers=2 locked, bus route: reply=00000000 transfers=2
Read included file: ahb_pkg.sv
`timescale 1ns/1ns
// ahb_pkg.sv: the encodings and the arithmetic of a burst (read-only).
// The memory, the driver, the checker and the lesson text all use these functions, so they never
// disagree about the address of a beat or the lanes it uses.
package ahb_pkg;
  localparam logic [1:0] IDLE = 2'b00, BUSY = 2'b01, NONSEQ = 2'b10, SEQ = 2'b11;
  localparam logic [2:0] SINGLE = 3'b000, INCR = 3'b001, WRAP4 = 3'b010, INCR4 = 3'b011,
                         WRAP8 = 3'b100, INCR8 = 3'b101, WRAP16 = 3'b110, INCR16 = 3'b111;
  localparam logic OKAY = 1'b0, ERROR = 1'b1;

  function automatic string trans_name(input logic [1:0] t);
    case (t) IDLE: return "IDLE"; BUSY: return "BUSY"; NONSEQ: return "NONSEQ"; default: return "SEQ"; endcase
  endfunction
  function automatic string burst_name(input logic [2:0] b);
    case (b)
      SINGLE: return "SINGLE"; INCR: return "INCR"; WRAP4: return "WRAP4"; INCR4: return "INCR4";
      WRAP8: return "WRAP8"; INCR8: return "INCR8"; WRAP16: return "WRAP16"; default: return "INCR16";
    endcase
  endfunction
  function automatic string resp_name(input logic r);
    return r ? "ERROR" : "OKAY";
  endfunction
  // s when c is 1, else the empty string (a string-typed result prints the same on every simulator).
  function automatic string opt(input bit c, input string s);
    if (c) return s;
    return "";
  endfunction

  // Beats in a burst: 1 for SINGLE, 4, 8 or 16 for the fixed bursts, 0 for INCR (undefined length).
  function automatic int beats_of(input logic [2:0] b);
    case (b) SINGLE: return 1; INCR: return 0; WRAP4, INCR4: return 4; WRAP8, INCR8: return 8; default: return 16; endcase
  endfunction
  function automatic bit is_wrap(input logic [2:0] b);
    return b == WRAP4 || b == WRAP8 || b == WRAP16;
  endfunction

  // The address of the beat after the one at a: the size in bytes further on; a wrapping burst
  // returns to the start of its window (beats x size bytes, aligned to that total) at the window's end.
  function automatic int unsigned next_addr(input int unsigned a, input logic [2:0] size, input logic [2:0] b);
    int unsigned nb = 1 << size;
    int unsigned window = nb * beats_of(b);
    int unsigned base;
    if (!is_wrap(b)) return a + nb;
    base = (a / window) * window;
    if (a + nb >= base + window) return base;
    return a + nb;
  endfunction

  // The address of beat n of a burst that starts at start.
  function automatic int unsigned beat_addr(input int unsigned start, input logic [2:0] size, input logic [2:0] b, input int n);
    int unsigned a = start;
    for (int k = 0; k < n; k++) a = next_addr(a, size, b);
    return a;
  endfunction

  // The lanes a transfer at address a uses on a bus of bus_bytes bytes, packed as {upper, lower}.
  // Every AHB transfer is aligned to its size, so it uses size bytes from its own lane upwards.
  function automatic logic [15:0] beat_lanes(input int unsigned a, input logic [2:0] size, input int bus_bytes);
    int lower = a % bus_bytes;
    int upper = lower + (1 << size) - 1;
    if (upper > bus_bytes - 1) upper = bus_bytes - 1;
    return {upper[7:0], lower[7:0]};
  endfunction

  // The strobe of a transfer: a 1 for every lane it uses (bit l is lane l).
  function automatic logic [63:0] beat_strb(input int unsigned a, input logic [2:0] size, input int bus_bytes);
    logic [15:0] lanes = beat_lanes(a, size, bus_bytes);
    logic [63:0] s = 0;
    for (int l = lanes[7:0]; l <= lanes[15:8]; l++) s[l] = 1'b1;
    return s;
  endfunction

  function automatic bit aligned(input int unsigned a, input logic [2:0] size);
    return (a % (1 << size)) == 0;
  endfunction

  // True when an incrementing burst of n beats (n is used only for INCR) crosses a 1 KB boundary.
  function automatic bit crosses_1k(input int unsigned start, input logic [2:0] size, input logic [2:0] b, input int n);
    int beats = beats_of(b) ? beats_of(b) : n;
    if (is_wrap(b) || beats < 2) return 0;
    return (start / 1024) != ((start + beats * (1 << size) - 1) / 1024);
  endfunction
endpackage
Read included file: ahb_mem.sv
`timescale 1ns/1ns
// ahb_mem.sv: an AHB subordinate with a byte-addressed memory behind it (read-only in this lesson).
// It registers an address phase at an edge where HSEL is 1, HTRANS is NONSEQ or SEQ and HREADY is 1,
// then runs the data phase: wait states with HREADYOUT low, a write takes HWDATA (and HWSTRB) at the
// edge that ends the data phase, a read drives HRDATA for the cycle that ends it. IDLE and BUSY get a
// zero-wait OKAY and change nothing. The switches below are plain variables: the stimulus sets them by
// name (mem.waits = 2;).
//   waits          wait states inserted in every data phase
//   waits_at[k]    wait states for the k-th transfer this memory takes (from 0; -1 = use waits)
//   err_above      transfers at or above this address get the two-cycle ERROR (and write nothing)
//   excl_on        AHB5 exclusive access: one monitor per HMASTER, HEXOKAY on success
//   trace          print every transfer the memory takes and every byte it writes
// Broken twins, each off by default:
//   ignore_hready    registers an address phase while HREADY is low (another subordinate is stretching),
//                    so it acts on a transfer the manager may still change or cancel
//   wdata_in_addr    takes HWDATA in the address phase, so a write stores the previous transfer's data
//   act_on_idle      treats IDLE and BUSY as transfers (waits, reads, writes HWDATA); this twin is an
//                    AHB-Lite design without an HWSTRB input, so it writes the lanes HSIZE selects
//   one_cycle_error  answers ERROR in one cycle (HRESP high with HREADYOUT high)
//   ignore_size      writes every lane of the bus word, whatever HSIZE and HWSTRB say
module ahb_mem #(parameter int DATA_W = 32, parameter int DEPTH = 65536) (
  input  logic              hclk,
  input  logic              hresetn,
  input  logic              hsel,
  input  logic [31:0]       haddr,
  input  logic [1:0]        htrans,
  input  logic              hwrite,
  input  logic [2:0]        hsize,
  input  logic [2:0]        hburst,
  input  logic [3:0]        hprot,
  input  logic              hmastlock,
  input  logic [DATA_W-1:0] hwdata,
  input  logic [DATA_W/8-1:0] hwstrb,
  input  logic              hexcl,
  input  logic [3:0]        hmaster,
  input  logic              hready,
  output logic              hreadyout,
  output logic              hresp,
  output logic [DATA_W-1:0] hrdata,
  output logic              hexokay
);
  import ahb_pkg::*;
  localparam int BUS = DATA_W / 8;

  // ---- switches ----
  int waits = 0;
  int waits_at [0:63];
  int unsigned err_above = 32'hffff_ffff;
  bit excl_on = 0, trace = 0;
  bit ignore_hready = 0, wdata_in_addr = 0, act_on_idle = 0, one_cycle_error = 0, ignore_size = 0;

  // ---- the memory ----
  logic [7:0] mem [0:DEPTH-1];
  int cycle = -1;
  int taken = 0;                              // transfers taken so far

  // ---- the data phase in progress ----
  bit              d_valid = 0, d_write = 0, d_err = 0, d_exok = 0, d_xfail = 0;
  int unsigned     d_addr = 0;
  logic [2:0]      d_size = 0;
  logic [1:0]      d_trans = 0;
  logic [DATA_W-1:0] d_wd = 0;                // HWDATA seen in the address phase (the wdata_in_addr twin)
  int              d_cnt = 0;                 // wait states still to insert
  bit              e_two = 0;                 // the ERROR response is in its second cycle

  // ---- exclusive monitors, one per HMASTER ----
  bit          mon_use [0:15];
  int unsigned mon_addr [0:15];
  int          mon_bytes [0:15];

  initial begin
    for (int i = 0; i < DEPTH; i++) mem[i] = 8'h00;
    for (int k = 0; k < 64; k++) waits_at[k] = -1;
    for (int m = 0; m < 16; m++) mon_use[m] = 0;
    hreadyout = 1; hresp = 0; hrdata = 0; hexokay = 0;
  end

  function automatic logic [DATA_W-1:0] read_word(input int unsigned a);
    logic [DATA_W-1:0] w = 0;
    int unsigned word = (a / BUS) * BUS;
    for (int l = 0; l < BUS; l++) w[8*l +: 8] = mem[(word + l) % DEPTH];
    return w;
  endfunction

  // Write the lanes of one transfer: the lanes its address and size select, where the strobe is 1.
  task automatic write_bytes(input int unsigned a, input logic [2:0] size, input logic [DATA_W-1:0] data, input logic [BUS-1:0] strb);
    logic [15:0] lanes = beat_lanes(a, size, BUS);
    int unsigned word = (a / BUS) * BUS;
    int lo = ignore_size ? 0 : lanes[7:0];
    int hi = ignore_size ? BUS - 1 : lanes[15:8];
    for (int l = lo; l <= hi; l++)
      if (ignore_size || act_on_idle || strb[l]) begin
        mem[(word + l) % DEPTH] = data[8*l +: 8];
        if (trace) $display("mem e%0d:   byte 0x%0h <= %02h (lane %0d)", cycle, word + l, data[8*l +: 8], l);
      end
    // any write ends the exclusive monitors that cover one of its bytes
    for (int m = 0; m < 16; m++)
      if (mon_use[m] && a < mon_addr[m] + mon_bytes[m] && mon_addr[m] < a + (1 << size)) mon_use[m] = 0;
  endtask

  always @(posedge hclk) begin
    cycle = cycle + 1;
    if (!hresetn) begin
      d_valid = 0; e_two = 0;
      hreadyout <= 1; hresp <= 0; hexokay <= 0;
    end else begin
      // 1. the data phase that ends or waits at this edge
      if (d_valid) begin
        if (hreadyout && hready) begin
          if (d_write && !d_err && !d_xfail)
            write_bytes(d_addr, d_size, wdata_in_addr ? d_wd : hwdata, hwstrb);
          d_valid = 0;
        end else if (!hreadyout) begin
          if (d_cnt > 0) d_cnt = d_cnt - 1;
          else if (d_err) e_two = 1;
        end
      end
      // 2. the address phase on the wires at this edge
      if (hsel && (htrans[1] || act_on_idle) && (hready || (ignore_hready && !d_valid))) begin
        d_valid = 1; d_addr = haddr; d_write = hwrite; d_size = hsize; d_trans = htrans; d_wd = hwdata;
        d_cnt = (taken < 64 && waits_at[taken] >= 0) ? waits_at[taken] : waits;
        taken = taken + 1;
        d_err = (haddr >= err_above); e_two = 0;
        d_exok = 0; d_xfail = 0;
        if (excl_on && hexcl && htrans[1] && !d_err) begin
          if (!hwrite) begin
            mon_use[hmaster] = 1; mon_addr[hmaster] = haddr; mon_bytes[hmaster] = 1 << hsize; d_exok = 1;
          end else if (mon_use[hmaster] && mon_addr[hmaster] == haddr && mon_bytes[hmaster] == (1 << hsize)) begin
            d_exok = 1; mon_use[hmaster] = 0;
          end else d_xfail = 1;
        end
        if (trace) $display("mem e%0d: %0s %0s 0x%0h size %0d%0s%0s%0s", cycle, trans_name(htrans), hwrite ? "write" : "read", haddr, hsize,
                            opt(!hready, " (taken while HREADY is low)"), opt(d_err, " -> ERROR"),
                            opt(d_xfail, " -> exclusive failed"));
      end
      // 3. the response for the cycle that starts now
      if (d_valid && d_cnt > 0) begin
        hreadyout <= 0; hresp <= 0; hexokay <= 0;
      end else if (d_valid && d_err) begin
        hreadyout <= one_cycle_error ? 1'b1 : e_two; hresp <= 1; hexokay <= 0;
      end else begin
        hreadyout <= 1; hresp <= 0; hexokay <= d_valid && d_exok;
      end
      if (d_valid && !d_write) hrdata <= d_err ? '0 : read_word(d_addr);
    end
  end
endmodule
Read included file: soc-s83-debug.svh
// Single-clock bench slice. The host starts in Run-Test/Idle with the lab
// data register selected. Only the direct DR scan path is exercised.
bit tck, tms, tdi, reset_n, authenticated, core_reset = 1;
logic [34:0] shift_dr = 0;
wire tdo = shift_dr[0];
typedef enum {IDLE, SELECT_DR, CAPTURE_DR, SHIFT_DR, EXIT_DR, UPDATE_DR} tap_state;
tap_state tap = IDLE;
logic [31:0] reply = 0, address = 32'h80000000, payload = 0;
logic halt_on_reset = 0, halted = 0, was_reset = 1;
logic [31:0] boot_marker = 32'h00000040;
typedef enum {FREE, ADDRESS, DATA} bus_state;
bus_state bus = FREE;
logic writing = 0;
wire selected = address[31:16] == 16'h8000;
wire ready, error_response;
wire [31:0] read_data;
ahb_mem ram(.hclk(tck), .hresetn(reset_n), .hsel(selected),
  .haddr(address), .htrans(bus == ADDRESS ? 2'b10 : 2'b00),
  .hwrite(writing), .hsize(3'd2), .hburst(3'b0), .hprot(4'b0011),
  .hmastlock(1'b0), .hwdata(payload), .hwstrb(4'hf), .hexcl(1'b0),
  .hmaster(4'd1), .hready(ready), .hreadyout(ready), .hresp(error_response),
  .hrdata(read_data), .hexokay());

always @(posedge tck) begin
  case (tap)
    IDLE: if (tms) tap <= SELECT_DR;
    SELECT_DR: tap <= CAPTURE_DR;
    CAPTURE_DR: begin
      shift_dr <= {authenticated ? reply : 32'b0, 3'b0};
      tap <= SHIFT_DR;
    end
    SHIFT_DR: begin
      shift_dr <= {tdi, shift_dr[34:1]};
      if (tms) tap <= EXIT_DR;
    end
    EXIT_DR: tap <= UPDATE_DR;
    UPDATE_DR: begin
      tap <= IDLE;
      if (authenticated) begin
        case (shift_dr[2:0])
          1: address <= shift_dr[34:3];
          2,3: if (bus == FREE && selected && address[1:0] == 0) begin
            payload <= shift_dr[34:3];
            writing <= shift_dr[2:0] == 2;
            bus <= ADDRESS;
          end
          4: halt_on_reset <= shift_dr[3];
          5: if (halted) reply <= boot_marker;
          default: ;
        endcase
      end
    end
  endcase
  was_reset <= core_reset;
  if (core_reset) halted <= 0;
  else if (was_reset && halt_on_reset) halted <= 1;
  if (bus == ADDRESS && ready) begin
    $display("address %08h write=%b ready=%b", address, writing, ready);
    bus <= DATA;
  end
  if (bus == DATA) begin
    $display("data    write=%b ready=%b response=%b", writing, ready, error_response);
    if (ready) begin
      if (!writing && !error_response) reply <= read_data;
      bus <= FREE;
    end
  end
end

task automatic tick(input bit mode, serial_in);
  tms = mode; tdi = serial_in;
  #2; tck = 1; #2; tck = 0;
endtask

task automatic scan(input logic [2:0] op, input logic [31:0] value,
                    output logic [31:0] returned);
  logic [34:0] outgoing, incoming;
  outgoing = {value, op};
  tick(1,0); tick(0,0); tick(0,0);
  for (int i=0; i<35; i++) begin
    incoming[i] = tdo;
    tick(i == 34, outgoing[i]);
  end
  tick(1,0); tick(0,0);
  returned = incoming[34:3];
endtask

Check Yourself

Predict the outputIn this run the debugger writes the word 0badc0de, and the lock stays open to the end. What is the last row? Its form is: unlocked, bus route: reply=........ transfers=.
`timescale 1ns/1ns
module tb;
  `include "soc-s83-debug.svh"
  // Command numbers of this lab: 1 set the address, 2 write memory, 3 read memory,
  // 4 arm "halt at reset", 5 read the register of the core, 0 nothing (fetch the reply).
  logic [31:0] reply_word;
  initial begin
    tick(0,0); reset_n = 1; ram.waits = 1;
    authenticated = 1;                         // the debugger has shown its key
    core_reset = 0; tick(0,0);                 // the core model runs

    scan(5,0,reply_word); scan(0,0,reply_word);
    $display("register route, core running: reply=%08h transfers=%0d", reply_word, ram.taken);

    scan(1,32'h80000010,reply_word);           // an address in the SRAM
    scan(2,32'h0badc0de,reply_word);            // write one word there
    repeat (4) tick(0,0);
    scan(3,0,reply_word);                      // read it back
    repeat (4) tick(0,0);
    scan(0,0,reply_word);
    $display("bus route, core running: reply=%08h transfers=%0d", reply_word, ram.taken);

    scan(4,1,reply_word);                      // stop the core model: arm, then pulse its reset
    core_reset = 1; tick(0,0); core_reset = 0; tick(0,0);
    scan(5,0,reply_word); scan(0,0,reply_word);
    $display("register route, core halted: reply=%08h transfers=%0d", reply_word, ram.taken);

    authenticated = 1;                         // the lock stays open
    scan(3,0,reply_word);
    repeat (4) tick(0,0);
    scan(0,0,reply_word);
    $display("unlocked, bus route: reply=%08h transfers=%0d", reply_word, ram.taken);
    $finish;
  end
endmodule
Read included file: ahb_pkg.sv
`timescale 1ns/1ns
// ahb_pkg.sv: the encodings and the arithmetic of a burst (read-only).
// The memory, the driver, the checker and the lesson text all use these functions, so they never
// disagree about the address of a beat or the lanes it uses.
package ahb_pkg;
  localparam logic [1:0] IDLE = 2'b00, BUSY = 2'b01, NONSEQ = 2'b10, SEQ = 2'b11;
  localparam logic [2:0] SINGLE = 3'b000, INCR = 3'b001, WRAP4 = 3'b010, INCR4 = 3'b011,
                         WRAP8 = 3'b100, INCR8 = 3'b101, WRAP16 = 3'b110, INCR16 = 3'b111;
  localparam logic OKAY = 1'b0, ERROR = 1'b1;

  function automatic string trans_name(input logic [1:0] t);
    case (t) IDLE: return "IDLE"; BUSY: return "BUSY"; NONSEQ: return "NONSEQ"; default: return "SEQ"; endcase
  endfunction
  function automatic string burst_name(input logic [2:0] b);
    case (b)
      SINGLE: return "SINGLE"; INCR: return "INCR"; WRAP4: return "WRAP4"; INCR4: return "INCR4";
      WRAP8: return "WRAP8"; INCR8: return "INCR8"; WRAP16: return "WRAP16"; default: return "INCR16";
    endcase
  endfunction
  function automatic string resp_name(input logic r);
    return r ? "ERROR" : "OKAY";
  endfunction
  // s when c is 1, else the empty string (a string-typed result prints the same on every simulator).
  function automatic string opt(input bit c, input string s);
    if (c) return s;
    return "";
  endfunction

  // Beats in a burst: 1 for SINGLE, 4, 8 or 16 for the fixed bursts, 0 for INCR (undefined length).
  function automatic int beats_of(input logic [2:0] b);
    case (b) SINGLE: return 1; INCR: return 0; WRAP4, INCR4: return 4; WRAP8, INCR8: return 8; default: return 16; endcase
  endfunction
  function automatic bit is_wrap(input logic [2:0] b);
    return b == WRAP4 || b == WRAP8 || b == WRAP16;
  endfunction

  // The address of the beat after the one at a: the size in bytes further on; a wrapping burst
  // returns to the start of its window (beats x size bytes, aligned to that total) at the window's end.
  function automatic int unsigned next_addr(input int unsigned a, input logic [2:0] size, input logic [2:0] b);
    int unsigned nb = 1 << size;
    int unsigned window = nb * beats_of(b);
    int unsigned base;
    if (!is_wrap(b)) return a + nb;
    base = (a / window) * window;
    if (a + nb >= base + window) return base;
    return a + nb;
  endfunction

  // The address of beat n of a burst that starts at start.
  function automatic int unsigned beat_addr(input int unsigned start, input logic [2:0] size, input logic [2:0] b, input int n);
    int unsigned a = start;
    for (int k = 0; k < n; k++) a = next_addr(a, size, b);
    return a;
  endfunction

  // The lanes a transfer at address a uses on a bus of bus_bytes bytes, packed as {upper, lower}.
  // Every AHB transfer is aligned to its size, so it uses size bytes from its own lane upwards.
  function automatic logic [15:0] beat_lanes(input int unsigned a, input logic [2:0] size, input int bus_bytes);
    int lower = a % bus_bytes;
    int upper = lower + (1 << size) - 1;
    if (upper > bus_bytes - 1) upper = bus_bytes - 1;
    return {upper[7:0], lower[7:0]};
  endfunction

  // The strobe of a transfer: a 1 for every lane it uses (bit l is lane l).
  function automatic logic [63:0] beat_strb(input int unsigned a, input logic [2:0] size, input int bus_bytes);
    logic [15:0] lanes = beat_lanes(a, size, bus_bytes);
    logic [63:0] s = 0;
    for (int l = lanes[7:0]; l <= lanes[15:8]; l++) s[l] = 1'b1;
    return s;
  endfunction

  function automatic bit aligned(input int unsigned a, input logic [2:0] size);
    return (a % (1 << size)) == 0;
  endfunction

  // True when an incrementing burst of n beats (n is used only for INCR) crosses a 1 KB boundary.
  function automatic bit crosses_1k(input int unsigned start, input logic [2:0] size, input logic [2:0] b, input int n);
    int beats = beats_of(b) ? beats_of(b) : n;
    if (is_wrap(b) || beats < 2) return 0;
    return (start / 1024) != ((start + beats * (1 << size) - 1) / 1024);
  endfunction
endpackage
Read included file: ahb_mem.sv
`timescale 1ns/1ns
// ahb_mem.sv: an AHB subordinate with a byte-addressed memory behind it (read-only in this lesson).
// It registers an address phase at an edge where HSEL is 1, HTRANS is NONSEQ or SEQ and HREADY is 1,
// then runs the data phase: wait states with HREADYOUT low, a write takes HWDATA (and HWSTRB) at the
// edge that ends the data phase, a read drives HRDATA for the cycle that ends it. IDLE and BUSY get a
// zero-wait OKAY and change nothing. The switches below are plain variables: the stimulus sets them by
// name (mem.waits = 2;).
//   waits          wait states inserted in every data phase
//   waits_at[k]    wait states for the k-th transfer this memory takes (from 0; -1 = use waits)
//   err_above      transfers at or above this address get the two-cycle ERROR (and write nothing)
//   excl_on        AHB5 exclusive access: one monitor per HMASTER, HEXOKAY on success
//   trace          print every transfer the memory takes and every byte it writes
// Broken twins, each off by default:
//   ignore_hready    registers an address phase while HREADY is low (another subordinate is stretching),
//                    so it acts on a transfer the manager may still change or cancel
//   wdata_in_addr    takes HWDATA in the address phase, so a write stores the previous transfer's data
//   act_on_idle      treats IDLE and BUSY as transfers (waits, reads, writes HWDATA); this twin is an
//                    AHB-Lite design without an HWSTRB input, so it writes the lanes HSIZE selects
//   one_cycle_error  answers ERROR in one cycle (HRESP high with HREADYOUT high)
//   ignore_size      writes every lane of the bus word, whatever HSIZE and HWSTRB say
module ahb_mem #(parameter int DATA_W = 32, parameter int DEPTH = 65536) (
  input  logic              hclk,
  input  logic              hresetn,
  input  logic              hsel,
  input  logic [31:0]       haddr,
  input  logic [1:0]        htrans,
  input  logic              hwrite,
  input  logic [2:0]        hsize,
  input  logic [2:0]        hburst,
  input  logic [3:0]        hprot,
  input  logic              hmastlock,
  input  logic [DATA_W-1:0] hwdata,
  input  logic [DATA_W/8-1:0] hwstrb,
  input  logic              hexcl,
  input  logic [3:0]        hmaster,
  input  logic              hready,
  output logic              hreadyout,
  output logic              hresp,
  output logic [DATA_W-1:0] hrdata,
  output logic              hexokay
);
  import ahb_pkg::*;
  localparam int BUS = DATA_W / 8;

  // ---- switches ----
  int waits = 0;
  int waits_at [0:63];
  int unsigned err_above = 32'hffff_ffff;
  bit excl_on = 0, trace = 0;
  bit ignore_hready = 0, wdata_in_addr = 0, act_on_idle = 0, one_cycle_error = 0, ignore_size = 0;

  // ---- the memory ----
  logic [7:0] mem [0:DEPTH-1];
  int cycle = -1;
  int taken = 0;                              // transfers taken so far

  // ---- the data phase in progress ----
  bit              d_valid = 0, d_write = 0, d_err = 0, d_exok = 0, d_xfail = 0;
  int unsigned     d_addr = 0;
  logic [2:0]      d_size = 0;
  logic [1:0]      d_trans = 0;
  logic [DATA_W-1:0] d_wd = 0;                // HWDATA seen in the address phase (the wdata_in_addr twin)
  int              d_cnt = 0;                 // wait states still to insert
  bit              e_two = 0;                 // the ERROR response is in its second cycle

  // ---- exclusive monitors, one per HMASTER ----
  bit          mon_use [0:15];
  int unsigned mon_addr [0:15];
  int          mon_bytes [0:15];

  initial begin
    for (int i = 0; i < DEPTH; i++) mem[i] = 8'h00;
    for (int k = 0; k < 64; k++) waits_at[k] = -1;
    for (int m = 0; m < 16; m++) mon_use[m] = 0;
    hreadyout = 1; hresp = 0; hrdata = 0; hexokay = 0;
  end

  function automatic logic [DATA_W-1:0] read_word(input int unsigned a);
    logic [DATA_W-1:0] w = 0;
    int unsigned word = (a / BUS) * BUS;
    for (int l = 0; l < BUS; l++) w[8*l +: 8] = mem[(word + l) % DEPTH];
    return w;
  endfunction

  // Write the lanes of one transfer: the lanes its address and size select, where the strobe is 1.
  task automatic write_bytes(input int unsigned a, input logic [2:0] size, input logic [DATA_W-1:0] data, input logic [BUS-1:0] strb);
    logic [15:0] lanes = beat_lanes(a, size, BUS);
    int unsigned word = (a / BUS) * BUS;
    int lo = ignore_size ? 0 : lanes[7:0];
    int hi = ignore_size ? BUS - 1 : lanes[15:8];
    for (int l = lo; l <= hi; l++)
      if (ignore_size || act_on_idle || strb[l]) begin
        mem[(word + l) % DEPTH] = data[8*l +: 8];
        if (trace) $display("mem e%0d:   byte 0x%0h <= %02h (lane %0d)", cycle, word + l, data[8*l +: 8], l);
      end
    // any write ends the exclusive monitors that cover one of its bytes
    for (int m = 0; m < 16; m++)
      if (mon_use[m] && a < mon_addr[m] + mon_bytes[m] && mon_addr[m] < a + (1 << size)) mon_use[m] = 0;
  endtask

  always @(posedge hclk) begin
    cycle = cycle + 1;
    if (!hresetn) begin
      d_valid = 0; e_two = 0;
      hreadyout <= 1; hresp <= 0; hexokay <= 0;
    end else begin
      // 1. the data phase that ends or waits at this edge
      if (d_valid) begin
        if (hreadyout && hready) begin
          if (d_write && !d_err && !d_xfail)
            write_bytes(d_addr, d_size, wdata_in_addr ? d_wd : hwdata, hwstrb);
          d_valid = 0;
        end else if (!hreadyout) begin
          if (d_cnt > 0) d_cnt = d_cnt - 1;
          else if (d_err) e_two = 1;
        end
      end
      // 2. the address phase on the wires at this edge
      if (hsel && (htrans[1] || act_on_idle) && (hready || (ignore_hready && !d_valid))) begin
        d_valid = 1; d_addr = haddr; d_write = hwrite; d_size = hsize; d_trans = htrans; d_wd = hwdata;
        d_cnt = (taken < 64 && waits_at[taken] >= 0) ? waits_at[taken] : waits;
        taken = taken + 1;
        d_err = (haddr >= err_above); e_two = 0;
        d_exok = 0; d_xfail = 0;
        if (excl_on && hexcl && htrans[1] && !d_err) begin
          if (!hwrite) begin
            mon_use[hmaster] = 1; mon_addr[hmaster] = haddr; mon_bytes[hmaster] = 1 << hsize; d_exok = 1;
          end else if (mon_use[hmaster] && mon_addr[hmaster] == haddr && mon_bytes[hmaster] == (1 << hsize)) begin
            d_exok = 1; mon_use[hmaster] = 0;
          end else d_xfail = 1;
        end
        if (trace) $display("mem e%0d: %0s %0s 0x%0h size %0d%0s%0s%0s", cycle, trans_name(htrans), hwrite ? "write" : "read", haddr, hsize,
                            opt(!hready, " (taken while HREADY is low)"), opt(d_err, " -> ERROR"),
                            opt(d_xfail, " -> exclusive failed"));
      end
      // 3. the response for the cycle that starts now
      if (d_valid && d_cnt > 0) begin
        hreadyout <= 0; hresp <= 0; hexokay <= 0;
      end else if (d_valid && d_err) begin
        hreadyout <= one_cycle_error ? 1'b1 : e_two; hresp <= 1; hexokay <= 0;
      end else begin
        hreadyout <= 1; hresp <= 0; hexokay <= d_valid && d_exok;
      end
      if (d_valid && !d_write) hrdata <= d_err ? '0 : read_word(d_addr);
    end
  end
endmodule
Read included file: soc-s83-debug.svh
// Single-clock bench slice. The host starts in Run-Test/Idle with the lab
// data register selected. Only the direct DR scan path is exercised.
bit tck, tms, tdi, reset_n, authenticated, core_reset = 1;
logic [34:0] shift_dr = 0;
wire tdo = shift_dr[0];
typedef enum {IDLE, SELECT_DR, CAPTURE_DR, SHIFT_DR, EXIT_DR, UPDATE_DR} tap_state;
tap_state tap = IDLE;
logic [31:0] reply = 0, address = 32'h80000000, payload = 0;
logic halt_on_reset = 0, halted = 0, was_reset = 1;
logic [31:0] boot_marker = 32'h00000040;
typedef enum {FREE, ADDRESS, DATA} bus_state;
bus_state bus = FREE;
logic writing = 0;
wire selected = address[31:16] == 16'h8000;
wire ready, error_response;
wire [31:0] read_data;
ahb_mem ram(.hclk(tck), .hresetn(reset_n), .hsel(selected),
  .haddr(address), .htrans(bus == ADDRESS ? 2'b10 : 2'b00),
  .hwrite(writing), .hsize(3'd2), .hburst(3'b0), .hprot(4'b0011),
  .hmastlock(1'b0), .hwdata(payload), .hwstrb(4'hf), .hexcl(1'b0),
  .hmaster(4'd1), .hready(ready), .hreadyout(ready), .hresp(error_response),
  .hrdata(read_data), .hexokay());

always @(posedge tck) begin
  case (tap)
    IDLE: if (tms) tap <= SELECT_DR;
    SELECT_DR: tap <= CAPTURE_DR;
    CAPTURE_DR: begin
      shift_dr <= {authenticated ? reply : 32'b0, 3'b0};
      tap <= SHIFT_DR;
    end
    SHIFT_DR: begin
      shift_dr <= {tdi, shift_dr[34:1]};
      if (tms) tap <= EXIT_DR;
    end
    EXIT_DR: tap <= UPDATE_DR;
    UPDATE_DR: begin
      tap <= IDLE;
      if (authenticated) begin
        case (shift_dr[2:0])
          1: address <= shift_dr[34:3];
          2,3: if (bus == FREE && selected && address[1:0] == 0) begin
            payload <= shift_dr[34:3];
            writing <= shift_dr[2:0] == 2;
            bus <= ADDRESS;
          end
          4: halt_on_reset <= shift_dr[3];
          5: if (halted) reply <= boot_marker;
          default: ;
        endcase
      end
    end
  endcase
  was_reset <= core_reset;
  if (core_reset) halted <= 0;
  else if (was_reset && halt_on_reset) halted <= 1;
  if (bus == ADDRESS && ready) begin
    $display("address %08h write=%b ready=%b", address, writing, ready);
    bus <= DATA;
  end
  if (bus == DATA) begin
    $display("data    write=%b ready=%b response=%b", writing, ready, error_response);
    if (ready) begin
      if (!writing && !error_response) reply <= read_data;
      bus <= FREE;
    end
  end
end

task automatic tick(input bit mode, serial_in);
  tms = mode; tdi = serial_in;
  #2; tck = 1; #2; tck = 0;
endtask

task automatic scan(input logic [2:0] op, input logic [31:0] value,
                    output logic [31:0] returned);
  logic [34:0] outgoing, incoming;
  outgoing = {value, op};
  tick(1,0); tick(0,0); tick(0,0);
  for (int i=0; i<35; i++) begin
    incoming[i] = tdo;
    tick(i == 34, outgoing[i]);
  end
  tick(1,0); tick(0,0);
  returned = incoming[34:3];
endtask
ConceptWhat are the two routes from the debug module into the chip?
ConceptWhich route needs a halted hart, and why?
ConceptWho is the manager of a memory read that the debugger asks for?
ConceptA locked chip replies 0 to a memory read. What shows that no read took place?

Common Mistakes

Wrong Take a reply of 0 as proof that the chip is locked.

0 is also a legal content of memory.

Fix Check that the memory accepted no transfer.

Wrong Expect a halted hart to freeze memory.

Other managers can still write.

Fix Find every manager that can reach the word.

Wrong Let a debugger read device registers again and again.

A read with a side effect changes the device.

Fix Read such a register once, and know what the read does.

Remember

  • Registers are reached through the halted hart. Memory and devices are reached through the bus.
  • The debug module is a bus manager of its own. Its transfers are ordinary transfers and need no hart.
  • A read by the debugger can change a device.
  • The debug lock sits in the debug module. A locked request makes no transfer and returns no data.

Practice

Report a problem with this page