Sleep and Wake with a Live Copy
Count seven board edges and zero core edges. Then explain why the next instruction can still read the copied sample.
You Will Be Able To
- Find the boundary at which the processor can stop.
- Trace a button edge through the running wake detector.
- Verify resumed execution against the saved address and data.
- Lesson
- S11.7
- Time
- 19 min
- Runs on
- Your browser
- Check
- 5 questions
A button changes while the processor clock is silent. Which part of the chip can notice, and where will execution continue?
Before You Start
Continue the S11.2 timeline after DMA completion. Both SRAM words now hold hexadecimal 4b.
| Question | |
|---|---|
| 1 | Which state change permits sleep here? |
| 2 | Which clock captures the button? |
| 3 | Why is edge 78 still absent from the gated count? |
| 4 | Which word does the resumed code send? |
| 5 | If the input is R and the run continues through wake, what final line appears? |
The Idea
Stopping a clock freezes the state it clocks. A wake event must reach something that can still change.
Here the board keeps a reference clock running. It remembers a button press and opens a gate before the next full core pulse.
New Words
| Word | Meaning |
|---|---|
| Clock-only sleep | A pause in core clock edges while the supplies and stored state remain available. |
| Wake detector | Logic on a running clock that samples the external event and remembers it. |
| Pending wake | A stored event that holds the gate open long enough for service. |
One Picture: Two Sides of a Stopped Clock
- Pads
- Control / FSM
- Clock / reset
- Processor
- Sample
The button passes through two reference-clock samples.
- Remember
Detection sets pending. The gate reads that level on a falling edge.
- Resume
The next complete reference pulse reaches the core.
Read the diagram as text
- Button: board drives a level
- Detector: remembers the rise
- Clock gate: opens on falling edge
- Processor: continues at saved PC
- Button → Detector: Sample
- Detector → Clock gate: Remember
- Clock gate → Processor: Resume
The first two stations keep their clock throughout the pause.
The Smallest Example, Worked by Hand
The board records sleep at edge 71 and wake pending at edge 78. Subtract to get seven reference edges.
Four edges pass before the board presses the button. One samples the press. One propagates it. One detects the synchronized rise.
The gate opens on the falling edge after 78. Rising edge 79 can therefore execute the instruction waiting at 0x94.
The Rules
Rule 1: Finish outstanding work.
Wait for the copy and an idle bus before stopping the core.
Rule 2: Keep a receiver awake.
Sample the button and store its event on the reference clock.
Rule 3: Verify the first resumed action.
Compare the waiting PC and copied word with the first post-wake access.
Sleep: Find the Last Completed Store
The foreground loop has seen the DMA pending bit. Firmware writes one to GPIO OUT. The board uses bit zero as its sleep request.
This GPIO connection belongs to the exercise board. It gives the debugger an ordinary software address for requesting the pause.
The kit completes each bus access within the current step. The sleep slice therefore sees an idle bus at the decision boundary.
On the falling edge, the gate sees sleep requested, bus idle and pending clear. The next rising edge cannot reach the core.
The current PC already points past the GPIO store. Repeating that store on wake would ask the board to sleep again.
Wake: Capture What the Core Cannot See
The board holds the button high. The detector samples it on the reference clock, even while the gate suppresses core pulses.
The first flip-flop captures the level. A second receives that sample. Comparing the synchronized value with its preceding value detects the rise.
The pending bit then stays set until service. A falling edge opens the gate. The following rising edge reaches the core.
t=59 | GPIO OUT = 0001
edge=71 sleep pc=00000094
edge=78 wake pending=1 gated_edges=0 pc=00000094
edge=78 resume pc=00000094 sp=80010000 source=0000004b copy=0000004bThe bench counts edges on the RTL gate output. It pauses instruction steps during the gap and supplies a service acknowledgment on resumption.
The first resumed instruction clears GPIO OUT. That withdraws the sleep request before the pending bit disappears.
Resume: Close the Loop at the Console
The next load reads the destination, four bytes above the source. Only then does firmware write the low byte to UART0.
The console prints K. The stronger check includes the destination word, the parked PC and exactly one delivered interrupt.
R uart=K gpio=0000 ram=0000004b,0000004b stop=000000a0 exceptions=0The cross-check compares architectural results. Wake latency belongs to the board run; the processor cross-check has no gate.
Now Run It
Run the breakpoint at 0x94. Its snapshot falls after wake and before the instruction clears the request.
Set BREAK_PC to -1 and repeat. Compare the final console byte with the low byte already present at the breakpoint.
The trace uses clock-only sleep. It exercises no rail shutdown, state retention cell or reset-based restart.
Why It Is Built This Way
In an interview, connect the three walks with one received byte. Supply good starts the oscillator. A usable reference lets the PLL lock.
The sequencer samples the strap, releases the fabric and waits for ROM readiness. The core fetches its reset jump.
Start-up prepares the stack and vector. Driver setup opens the path from the receive queue through the controller to the core.
The core saves its PC and enters the handler. The claim identifies UART0. A load addresses its receive register.
The fast fabric selects the bridge. The bridge issues peripheral setup and access. The completed read pops the byte and returns its value.
Firmware publishes the sample, completes the claim and returns. That explanation connects the reset, register-read and interrupt questions.
If the button detector used the gated clock, its first sample could never happen. The reference domain gives the board an independent way back.
Sampling the enable on the falling edge protects the next rising pulse. A late change during a high phase could create a short pulse.
The Trap: Adding Incompatible Times
Kit ticks advance with instruction steps. Board edges also advance while the processor is asleep.
Measure the quiet interval with board timestamps. Measure copied bytes with the mover and memory observations.
At Scale
A larger chip can have a separate wake path for every independently stopped domain.
Test arrival boundaries
Place one wake just before the gate closes and another just afterward. Check both delivery and pulse count.
Answer the bring-up interview
Start with supply and ROM readiness. Follow the issued register address through fabric, bridge and peripheral.
Try It
Run the recorded wake stop. Inspect the reference timestamp as well as the kit tick.
Remove the breakpoint and check the returned console byte.
Change SAMPLE and repeat. The return address stays fixed while the payload changes.
edge=2 boot osc=1 pll=0 strap_valid=0 fabric=0 ready=0 core=0 edge=3 boot osc=1 pll=1 strap_valid=0 fabric=0 ready=0 core=0 edge=4 boot osc=1 pll=1 strap_valid=1 fabric=0 ready=0 core=0 edge=5 boot osc=1 pll=1 strap_valid=1 fabric=1 ready=0 core=0 edge=6 boot osc=1 pll=1 strap_valid=1 fabric=1 ready=0 core=0 edge=7 boot osc=1 pll=1 strap_valid=1 fabric=1 ready=0 core=0 edge=8 boot osc=1 pll=1 strap_valid=1 fabric=1 ready=0 core=0 edge=9 boot osc=1 pll=1 strap_valid=1 fabric=1 ready=1 core=0 edge=10 boot osc=1 pll=1 strap_valid=1 fabric=1 ready=1 core=1 edge=11 fetch pc=00000000 jump_target=00000004 edge=12 start pc=00000004 sp=00000000 source=xxxxxxxx copy=xxxxxxxx edge=19 drivers pc=00000020 sp=80010000 source=00001234 copy=00000000 t=36 | UART0 receives 4b "K" t=36 | interrupt, external: mcause=8000000b mepc=00000060, next is 00000180 t=36 | PLIC claim returns 1 t=39 | PLIC complete 1 t=41 | mret: back to 00000060 edge=56 copy pc=00000064 sp=80010000 source=0000004b copy=00000000 t=51 | DMA starts: 4 bytes from 80000000 to 80000004 t=55 | DMA done t=59 | GPIO OUT = 0001 edge=71 sleep pc=00000094 edge=78 wake pending=1 gated_edges=0 pc=00000094 break pc=00000094 ticks=60 sp=80010000 source=0000004b copy=0000004bRead included file: slices.sv
// One machine context, synchronous level sources. Register-side interface:
// commit pulses once at a successful word transfer's data edge.
module ap_plic #(parameter integer SOURCES = 16) (
input logic clk, reset_n, commit, write_en,
input logic [21:0] offset,
input logic [31:0] wdata,
input logic [SOURCES:1] level_irq,
output logic [31:0] rdata,
output logic notify_irq
);
localparam ENABLE = 'h2000, THRESHOLD = 'h200000, CLAIM = 'h200004;
logic [2:0] weight [1:SOURCES];
logic [2:0] threshold, best;
logic [SOURCES:1] pending, busy, enabled;
integer winner;
always_comb begin
best = 0;
winner = 0;
for (int id = 1; id <= SOURCES; id++) begin
if (pending[id] && enabled[id] && weight[id] > best) begin
best = weight[id];
winner = id;
end
end
notify_irq = best > threshold;
rdata = 0;
for (int id = 1; id <= SOURCES; id++) begin
if (offset == 4*id) rdata = weight[id];
if (offset == 'h1000 + 4*(id/32)) rdata[id%32] = pending[id];
if (offset == ENABLE + 4*(id/32)) rdata[id%32] = enabled[id];
end
case (offset)
THRESHOLD: rdata = threshold;
CLAIM: rdata = winner;
endcase
end
always_ff @(posedge clk) begin
if (!reset_n) begin
pending <= '0;
busy <= '0;
enabled <= '0;
threshold <= 0;
for (int id = 1; id <= SOURCES; id++) weight[id] <= 0;
end else begin
for (int id = 1; id <= SOURCES; id++) begin
if (level_irq[id] && !busy[id]) begin
pending[id] <= 1;
busy[id] <= 1;
end
if (commit && write_en && offset == 4*id) weight[id] <= wdata[2:0];
if (commit && write_en && offset == ENABLE + 4*(id/32))
enabled[id] <= wdata[id%32];
if (commit && offset == CLAIM) begin
if (!write_en && winner == id) pending[id] <= 0;
if (write_en && enabled[id] && wdata == id && busy[id] && !pending[id]) busy[id] <= 0;
end
end
if (commit && write_en && offset == THRESHOLD) threshold <= wdata[2:0];
end
end
endmodule
// Timer slice of ap_soc's local interrupt block. One hart, one timebase tick
// per clk and a registered interrupt output. Word strobes arrive at commitment.
module ap_clint_timer #(parameter logic [63:0] RESET_COMPARE = '1) (
input logic clk, reset_n, write_cmp_low, write_cmp_high,
input logic [31:0] wdata,
output logic [63:0] mtime, mtimecmp,
output logic mtip
);
always_ff @(posedge clk) begin
if (!reset_n) begin
mtime <= 0;
mtimecmp <= RESET_COMPARE;
mtip <= 0;
end else begin
mtime <= mtime + 1'b1;
if (write_cmp_low) mtimecmp[31:0] <= wdata;
if (write_cmp_high) mtimecmp[63:32] <= wdata;
mtip <= mtime >= mtimecmp;
end
end
endmodule
// ap_soc teaching policy. Input tick is an enable from the supervision clock.
// A privileged boot writer may arm once. Reset request persists until reset.
module watchdog_supervisor (
input logic clk, reset_n, tick, debug_halt, dev_mode, privileged,
input logic psel, penable, pwrite,
input logic [11:0] offset,
input logic [31:0] pwdata,
output logic armed, irq, reset_req,
output logic [3:0] remaining
);
localparam KEY = 0, CONTROL = 4, SERVICE = 8;
localparam RELOAD = 6, OPEN = 3;
logic first_key, unlocked;
logic [1:0] grace;
wire write_word = psel && penable && pwrite;
wire arm = write_word && privileged && unlocked && offset == CONTROL && pwdata == 1;
wire kick = write_word && offset == SERVICE && pwdata == 1;
always_ff @(posedge clk) begin
if (!reset_n) begin
first_key <= 0;
unlocked <= 0;
armed <= 0;
remaining <= 0;
irq <= 0;
reset_req <= 0;
grace <= 0;
end else begin
if (write_word) begin
first_key <= privileged && offset == KEY && pwdata == 'h51;
unlocked <= privileged && first_key && offset == KEY && pwdata == 'ha2;
end
if (!armed && arm) begin
armed <= 1;
remaining <= RELOAD;
end else if (armed && !reset_req && !(dev_mode && debug_halt)) begin
if (irq) begin
if (tick && grace == 1) reset_req <= 1;
else if (tick) grace <= grace - 1'b1;
end else if ((kick && remaining > OPEN) || (tick && remaining == 1 && !kick)) begin
irq <= 1;
grace <= 2;
remaining <= 0;
end else if (kick) remaining <= RELOAD;
else if (tick) remaining <= remaining - 1'b1;
end
end
end
endmodule
// Startup slice of ap_crg. Each ready input is already qualified in the
// always-on domain. Board supervision handles rail or lock loss after boot.
module ap_crg_boot(
input logic aon_clk, supply_good, osc_ready, pll_locked, boot_pin,
input logic fabric_ready, rom_ready, shorten_wait,
output logic osc_start, pll_start, straps_valid, boot_sel,
output logic fabric_reset_n, core_reset_n
);
always_ff @(posedge aon_clk or negedge supply_good) begin
if (!supply_good) begin
{osc_start, pll_start, straps_valid, boot_sel} <= 0;
{fabric_reset_n, core_reset_n} <= 0;
end else begin
osc_start <= 1;
if (osc_start && osc_ready) pll_start <= 1;
if (pll_start && pll_locked && !straps_valid) begin
boot_sel <= boot_pin;
straps_valid <= 1;
end
if (straps_valid) fabric_reset_n <= 1;
if (fabric_reset_n && fabric_ready && (rom_ready || shorten_wait))
core_reset_n <= 1;
end
end
endmodule
// A one-word boot ROM for the startup lab. Unavailable and unmapped reads
// both complete with an error. START_EDGES counts local edges after release.
module boot_rom_port #(
parameter integer START_EDGES = 4
)(
input logic clk, reset_n, req,
input logic [31:0] addr,
output wire ready,
output logic valid, error,
output logic [31:0] data
);
integer warm_edges;
assign ready = reset_n && warm_edges >= START_EDGES;
always_ff @(posedge clk) begin
if (!reset_n) begin
warm_edges <= 0;
valid <= 0;
error <= 0;
data <= 0;
end else begin
if (!ready) warm_edges <= warm_edges + 1;
valid <= req;
if (req) begin
error <= !ready || addr != 0;
data <= ready && addr == 0 ? 32'h00000013 : 0;
end
end
end
endmodule
// Clock-only sleep slice. The board holds the button until it is serviced.
// Inputs other than button belong to the ungated reference-clock domain.
module sleep_clock(
input logic ref_clk, reset_n, button, sleep_request, bus_idle, serviced,
output logic pending, output wire core_clk
);
logic sample, synced, previous, enabled;
always_ff @(posedge ref_clk or negedge reset_n) begin
if (!reset_n) begin
{sample, synced, previous} <= 0;
pending <= 0;
end else begin
{previous, synced, sample} <= {synced, sample, button};
if (synced && !previous) pending <= 1;
else if (serviced) pending <= 0;
end
end
// Model a gate which changes its decision only during the low phase.
always_ff @(negedge ref_clk or negedge reset_n)
if (!reset_n) enabled <= 1;
else enabled <= !sleep_request || !bus_idle || pending;
assign core_clk = ref_clk && enabled;
endmodule
// 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
// Each 12-bit row holds four three-bit endpoint numbers, indexed by function select.
// The board table is an elaboration parameter. An empty table releases every pad.
module pad_slice #(parameter logic [47:0] ROUTES = 0) (input wire clk,reset_n,psel,penable,pwrite,sample,
input wire [31:0] paddr,pwdata, output wire [31:0] prdata,
input wire [3:0] gpio_data,gpio_oe, input wire uart_tx,pwm,spi_clk,
inout wire [3:0] pad, output logic strap, output wire uart_rx,spi_in,
output wire [3:0] capture,oe);
localparam MUX = 32'h10004010;
logic [7:0] sel;
wire [3:0] rx_lines, spi_lines;
assign prdata = paddr == MUX ? {24'b0,sel} : 0;
always_ff @(posedge clk) begin
if (!reset_n) begin
sel <= 0;
strap <= 0;
end else begin
if (sample) strap <= pad[0];
if (psel && penable && pwrite && paddr == MUX) sel <= pwdata[7:0];
end
end
localparam GPIO=1, UART_TX=2, UART_RX=3, SCLK=4, MISO=5, PWM=6, CAPTURE=7;
for (genvar p=0; p<4; p++) begin : drivers
localparam logic [11:0] ROW = ROUTES[12*p +: 12];
wire [1:0] field = sel[2*p +: 2];
wire [2:0] endpoint = ROW[3*field +: 3];
logic data, drive;
always_comb begin
case (endpoint)
GPIO: {drive,data} = {gpio_oe[p],gpio_data[p]};
UART_TX: {drive,data} = {1'b1,uart_tx};
SCLK: {drive,data} = {1'b1,spi_clk};
PWM: {drive,data} = {1'b1,pwm};
default: {drive,data} = 2'b00;
endcase
end
assign oe[p] = drive;
assign pad[p] = drive ? data : 1'bz;
assign rx_lines[p] = endpoint == UART_RX ? pad[p] : 1'b1;
assign spi_lines[p] = endpoint == MISO ? pad[p] : 1'b0;
assign capture[p] = endpoint == CAPTURE ? pad[p] : 1'b0;
end
// This table assigns at most one source each to UART RX and SPI input.
assign uart_rx = &rx_lines;
assign spi_in = |spi_lines;
endmodule
// APB teaching slice. Aligned word transfers, no waits, one system clock.
// UART receives frame-complete bytes from the P6 receiver. SPI uses mode 0.
module serial_slice(
input wire clk, reset_n, sel, enable, wr,
input wire [31:0] addr, wdata,
output logic [31:0] rdata,
input wire rx_done, input wire [7:0] rx_data,
output wire tx, irq, dma_req, cs_n, mosi,
output logic sclk, input wire miso
);
// UART0: transmit data 0x00 (write), status 0x04 (read), receive data 0x0C (read).
// Status bits: 0 = room to transmit, 1 = a received byte waits, 2 = the receive queue is full.
localparam UART_TXDATA = 32'h10000000, UART_STATUS = 32'h10000004, UART_RXDATA = 32'h1000000c,
SPI_DATA = 32'h10005000, SPI_STATUS = 32'h10005004;
wire access = sel && enable;
logic [7:0] fifo [0:1];
logic head, tail;
logic [1:0] used;
wire pop = access && !wr && addr == UART_RXDATA && used != 0;
wire push = rx_done && (used < 2 || pop);
assign irq = used != 0;
assign dma_req = used == 2;
logic [9:0] frame;
logic [3:0] bits_left, tick;
assign tx = frame[0];
logic [31:0] shift;
logic [23:0] flash_id;
logic [5:0] clocks_left;
logic half_tick;
assign cs_n = clocks_left == 0;
assign mosi = shift[31];
always_comb begin
case (addr)
UART_RXDATA: rdata = irq ? fifo[head] : 0;
UART_STATUS: rdata = {29'b0, dma_req, irq, bits_left == 0};
SPI_DATA: rdata = {8'b0, flash_id};
SPI_STATUS: rdata = {31'b0, !cs_n};
default: rdata = 0;
endcase
end
always_ff @(posedge clk) begin
if (!reset_n) begin
used <= 0;
head <= 0;
tail <= 0;
frame <= '1;
bits_left <= 0;
tick <= 0;
clocks_left <= 0;
half_tick <= 0;
sclk <= 0;
shift <= 0;
flash_id <= 0;
end else begin
if (push) begin
fifo[tail] <= rx_data;
tail <= !tail;
end
if (pop) head <= !head;
case ({push,pop})
2'b10: used <= used + 1'b1;
2'b01: used <= used - 1'b1;
default: ;
endcase
if (bits_left != 0) begin
tick <= tick + 1'b1;
if (tick == 15) begin
frame <= {1'b1, frame[9:1]};
bits_left <= bits_left - 1'b1;
end
end else if (access && wr && addr == UART_TXDATA) begin
frame <= {1'b1, wdata[7:0], 1'b0};
bits_left <= 10;
tick <= 0;
end
if (cs_n) begin
if (access && wr && addr == SPI_DATA) begin
shift <= {wdata[7:0], 24'b0};
clocks_left <= 32;
half_tick <= 0;
end
end else begin
half_tick <= !half_tick;
if (half_tick) begin
sclk <= !sclk;
if (!sclk) flash_id <= {flash_id[22:0], miso};
else begin
shift <= shift << 1;
clocks_left <= clocks_left - 1'b1;
end
end
end
end
end
endmodule
// Small board model. DR and IR share the same capture/shift/pause sequencer.
// Only IDCODE and BYPASS have data paths in this fixture.
module board_tap #(parameter logic [31:0] ID = 32'h2a53_10c5) (
input logic tck, tms, tdi, output logic tdo
);
typedef enum {RESET, IDLE, SELECT_DR, SELECT_IR, CAPTURE, SHIFT,
EXIT1, PAUSE_SCAN, EXIT2, UPDATE_SCAN} phase_t;
phase_t phase = RESET;
logic ir_branch = 0;
logic [1:0] opcode = 1, ir_shift;
logic [31:0] data_shift;
always @(posedge tck) begin
case (phase)
RESET: if (!tms) phase <= IDLE;
IDLE: if (tms) phase <= SELECT_DR;
SELECT_DR: if (tms) phase <= SELECT_IR;
else begin phase <= CAPTURE; ir_branch <= 0; end
SELECT_IR: if (tms) phase <= RESET;
else begin phase <= CAPTURE; ir_branch <= 1; end
CAPTURE: begin
if (ir_branch) ir_shift <= 2'b01;
else data_shift <= (opcode == 1) ? ID : 0;
if (tms) phase <= EXIT1; else phase <= SHIFT;
end
SHIFT: begin
if (ir_branch) ir_shift <= {tdi, ir_shift[1]};
else if (opcode == 1) data_shift <= {tdi, data_shift[31:1]};
else data_shift[0] <= tdi;
if (tms) phase <= EXIT1;
end
EXIT1: if (tms) phase <= UPDATE_SCAN; else phase <= PAUSE_SCAN;
PAUSE_SCAN: if (tms) phase <= EXIT2;
EXIT2: if (tms) phase <= UPDATE_SCAN; else phase <= SHIFT;
UPDATE_SCAN: if (tms) phase <= SELECT_DR; else phase <= IDLE;
endcase
end
always @(negedge tck) begin
if (phase == RESET) opcode <= 1;
if (phase == UPDATE_SCAN && ir_branch) opcode <= ir_shift;
if (phase == SHIFT) tdo <= ir_branch ? ir_shift[0] : data_shift[0];
else tdo <= 1'bz;
end
endmodule
Read included file: machine.svh
localparam int LUI = 0, ADDI = 1, ANDI = 2, ORI = 3, SLLI = 4, SRLI = 5, ADD = 6, SUB = 7, AND = 8, OR = 9, LW = 10, SW = 11,
BEQ = 12, BNE = 13, BLT = 14, BGE = 15, JAL = 16, JALR = 17, CSRR = 18, CSRW = 19, CSRS = 20, CSRC = 21, MRET = 22, WORD = 23;
localparam int MSTATUS = 'h300, MIE = 'h304, MTVEC = 'h305, MSCRATCH = 'h340, MEPC = 'h341, MCAUSE = 'h342, MIP = 'h344;
int kind [0:1023], fa [0:1023], fb [0:1023]; // the Boot ROM: one row for each word
logic [31:0] fc [0:1023];
int here = 0; // the address of the next row
task automatic at(input int address); // the rows that follow start at this address
here = address;
endtask
task automatic i(input int k, input int a, input int b, input logic [31:0] c); // add one row
if (here < 4096) begin kind[here >> 2] = k; fa[here >> 2] = a; fb[here >> 2] = b; fc[here >> 2] = c; end
here += 4;
endtask logic clk = 0;
logic [31:0] x [0:31]; // the 32 registers
logic [31:0] pc; // the address of the next instruction
logic [31:0] ram [0:16383]; // SRAM: 64 KiB from 8000_0000. Nothing is in it at power-on
logic [31:0] mstatus, mie, mtvec, mscratch, mepc, mcause; // the machine CSRs of this model
int steps, traps, taken; // instructions, exceptions, interrupts
bit stopped;
localparam int SHOW = 1; // 2: print every instruction. 1: print events only. 0: print nothing
task automatic say(input string text);
if (SHOW != 0) $display("t=%0d | %s", ticks, text);
endtask
// ---- UART0 (test code). TXDATA 00, STATUS 04 (bit 0 ROOM, bit 1 RX_READY), RXDATA 0c ----
string uart_text = ""; // every byte that was sent, as text
int uart_wait = 0; // after a byte: 12 ticks with no room (a lab number)
logic [7:0] rx_queue [0:3]; // received bytes that software has not read yet
int rx_count = 0;
logic [7:0] rx_plan [0:7]; // the bytes the board will send, and at which tick
int rx_tick [0:7], rx_planned = 0;
wire rx_ready = (rx_count != 0); // UART0 asks for an interrupt while a received byte waits
// ---- GPIO (test code). OUT 08, TGL 14 ----
logic [15:0] gpio_out = 0;
int gpio_changes = 0;
// ---- DMA (test code). SRC 00, DST 04, LEN 08, START 0c. It moves one byte of SRAM in each tick. ----
logic [31:0] dma_src = 0, dma_dst = 0, dma_len = 0;
int dma_left = 0;
bit dma_done = 0; // its interrupt request: 1 from the last byte until the next start
int ticks = 0;
function automatic logic [31:0] tc_peek(input logic [31:0] ad);
case (ad)
32'h1000_0004: return {30'b0, rx_ready, (uart_wait == 0)};
32'h1000_000c: return {24'b0, rx_queue[0]};
32'h1000_1008: return {16'b0, gpio_out};
default: return 32'h0;
endcase
endfunction
function automatic bit tc_exists(input bit wr, input logic [31:0] ad); // 1: a register is at this address
case (ad)
32'h1000_0000, 32'h1000_1014, 32'h1000_6000, 32'h1000_6004, 32'h1000_6008, 32'h1000_600c: return wr;
32'h1000_0004, 32'h1000_000c: return !wr;
32'h1000_1008: return 1;
default: return 0;
endcase
endfunction
task automatic tc_read(input logic [31:0] ad);
if (ad == 32'h1000_000c && rx_count != 0) begin // reading RXDATA removes the oldest byte
for (int n = 0; n < 3; n++) rx_queue[n] = rx_queue[n + 1];
rx_count--;
end
endtask
task automatic tc_write(input logic [31:0] ad, input logic [31:0] wd);
case (ad)
32'h1000_0000: if (uart_wait == 0) begin // a byte written with no room is lost
uart_text = {uart_text, $sformatf("%c", wd[7:0])}; uart_wait = 12;
say($sformatf("UART0 sends %02h \"%c\"", wd[7:0], wd[7:0]));
end else say($sformatf("UART0 has no room: %02h is lost", wd[7:0]));
32'h1000_1008: begin gpio_out = wd[15:0]; gpio_changes++; say($sformatf("GPIO OUT = %04h", gpio_out)); end
32'h1000_1014: begin gpio_out = gpio_out ^ wd[15:0]; gpio_changes++; say($sformatf("GPIO OUT = %04h", gpio_out)); end
32'h1000_6000: dma_src = wd;
32'h1000_6004: dma_dst = wd;
32'h1000_6008: dma_len = wd;
32'h1000_600c: if (wd[0]) begin
dma_left = dma_len; dma_done = 0;
say($sformatf("DMA starts: %0d bytes from %08h to %08h", dma_len, dma_src, dma_dst));
end
default: ;
endcase
endtask
task automatic tc_tick();
ticks++;
if (uart_wait != 0) uart_wait--;
for (int n = 0; n < rx_planned; n++) if (rx_tick[n] == ticks && rx_count < 4) begin
rx_queue[rx_count] = rx_plan[n]; rx_count++;
say($sformatf("UART0 receives %02h \"%c\"", rx_plan[n], rx_plan[n]));
end
if (dma_left != 0) begin // one byte: read it from SRAM, write it to SRAM
ram[dma_dst[15:2]][8 * dma_dst[1:0] +: 8] = ram[dma_src[15:2]][8 * dma_src[1:0] +: 8];
dma_src++; dma_dst++; dma_left--;
if (dma_left == 0) begin dma_done = 1; say("DMA done"); end
end
endtask
task automatic board_sends(input int tick, input logic [7:0] value); // plan one received byte
rx_plan[rx_planned] = value; rx_tick[rx_planned] = tick; rx_planned++;
endtask
// Interrupt sources of ap_soc: 1 UART0, 2 GPIO, 3 timer and PWM, 4 SPI, 5 DMA, 6 watchdog, 7 to 16 spare.
wire wdg_warn; // the early warning of the watchdog; tied to 0 where a lab has none
wire [16:1] sources = {10'b0, wdg_warn, dma_done, 3'b0, rx_ready};
// ---- The two chip blocks of ap_soc, unchanged: the interrupt controller and the machine timer ----
logic reset_n = 0, plic_commit = 0, plic_write = 0, cmp_low = 0, cmp_high = 0;
logic [21:0] plic_offset = 0;
logic [31:0] dev_wdata = 0;
wire [31:0] plic_rdata;
wire [63:0] mtime, mtimecmp;
wire irq_external, irq_timer;
ap_plic plic (.clk, .reset_n, .commit(plic_commit), .write_en(plic_write), .offset(plic_offset), .wdata(dev_wdata),
.level_irq(sources), .rdata(plic_rdata), .notify_irq(irq_external));
ap_clint_timer clint (.clk, .reset_n, .write_cmp_low(cmp_low), .write_cmp_high(cmp_high), .wdata(dev_wdata),
.mtime, .mtimecmp, .mtip(irq_timer));
logic wdg_write; // one write to the watchdog commits at the next rising edge
logic [11:0] wdg_offset;
wire wdg_armed, wdg_reset;
wire [3:0] wdg_left; // ticks left before the warning
wire wdg_tick = (mtime[4:0] == 5'd31); // the supervision tick: one in every 32 clock ticks (a lab number)
watchdog_supervisor wdg (.clk(clk), .reset_n(reset_n), .tick(wdg_tick), .debug_halt(1'b0), .dev_mode(1'b0), .privileged(1'b1),
.psel(wdg_write), .penable(wdg_write), .pwrite(wdg_write), .offset(wdg_offset), .pwdata(dev_wdata),
.armed(wdg_armed), .irq(wdg_warn), .reset_req(wdg_reset), .remaining(wdg_left));
bit wdg_was_armed, wdg_was_warned;
wire [31:0] mip = {20'b0, irq_external, 3'b0, irq_timer, 7'b0}; // bit 11: external. bit 7: machine timer
function automatic string cn(input logic [11:0] a); // the name of a CSR
case (a)
MSTATUS: return "mstatus"; MIE: return "mie"; MTVEC: return "mtvec"; MSCRATCH: return "mscratch";
MEPC: return "mepc"; MCAUSE: return "mcause"; MIP: return "mip";
default: return "?";
endcase
endfunction
function automatic logic [31:0] csr_value(input logic [11:0] a);
case (a)
MSTATUS: return mstatus; MIE: return mie; MTVEC: return mtvec; MSCRATCH: return mscratch;
MEPC: return mepc; MCAUSE: return mcause;
default: return mip;
endcase
endfunction
task automatic csr_store(input logic [11:0] a, input logic [31:0] v); // each CSR keeps only its writable bits
case (a)
MSTATUS: begin mstatus[3] = v[3]; mstatus[7] = v[7]; end // MIE and MPIE
MIE: mie = v & 32'h0000_0888; // external, timer and software enables
MTVEC: mtvec = v & 32'hffff_fffd;
MSCRATCH: mscratch = v;
MEPC: mepc = v & 32'hffff_fffc;
MCAUSE: mcause = v;
default: ; // mip is read-only
endcase
endtask
// The entry of a trap, for an exception or an interrupt: what the processor does by itself.
task automatic enter(input logic [31:0] cause, input string text);
mepc = pc & 32'hffff_fffc; mcause = cause;
mstatus[7] = mstatus[3]; mstatus[3] = 1'b0; // MPIE takes MIE, MIE closes
say($sformatf("%s: mcause=%08h mepc=%08h, next is %08h", text, cause, mepc, mtvec & 32'hffff_fffc));
pc = mtvec & 32'hffff_fffc;
endtask
// Start one read or write of a word. The value of a read is in bus_rdata after half a tick.
logic [31:0] bus_rdata;
bit bus_fault;
task automatic bus(input bit wr, input logic [31:0] ad, input logic [31:0] wd);
bus_fault = 0; bus_rdata = 0;
if (ad[31:12] == 20'h0) begin // Boot ROM: data words can be read
if (wr) bus_fault = 1;
else bus_rdata = (kind[ad[11:2]] == WORD) ? fc[ad[11:2]] : 32'h0;
end
else if (ad[31:16] == 16'h8000) begin // SRAM
if (wr) ram[ad[15:2]] = wd;
else bus_rdata = ram[ad[15:2]];
end
else if (ad[31:22] == 10'h030) begin // ap_plic, from 0c00_0000
plic_offset = ad[21:0]; plic_write = wr; dev_wdata = wd; plic_commit = 1;
end
else if (ad == 32'h0200_4000 || ad == 32'h0200_4004) begin // ap_clint: mtimecmp
if (wr) begin dev_wdata = wd; cmp_low = !ad[2]; cmp_high = ad[2]; end
else bus_rdata = ad[2] ? mtimecmp[63:32] : mtimecmp[31:0];
end
else if (ad == 32'h0200_bff8 || ad == 32'h0200_bffc) begin // ap_clint: mtime, read only here
if (wr) bus_fault = 1;
else bus_rdata = ad[2] ? mtime[63:32] : mtime[31:0];
end
else if (tc_exists(wr, ad)) begin // UART0, GPIO, DMA
if (wr) tc_write(ad, wd);
else begin bus_rdata = tc_peek(ad); tc_read(ad); end
end
else if (wr && (ad == 32'h1000_3000 || ad == 32'h1000_3004 || ad == 32'h1000_3008)) begin // the watchdog: writes only
wdg_offset = ad[11:0]; dev_wdata = wd; wdg_write = 1;
if (ad[3:0] == 4'h8) say($sformatf("watchdog kick, %0d ticks were left", wdg_left));
end
else if ((ad == 'h10002000 || ad == 'h10002004 || ad == 'h10004010 ||
ad == 'h10005000 || ad == 'h10005004)) begin
io_addr = ad; io_data = wd; io_wr = wr; io_sel = 1;
#1; bus_rdata = spi_data;
end
else bus_fault = 1; // nothing answers at this address
endtask
// One tick: one instruction, then one rising clock edge.
task automatic step();
int k, a, b;
logic [31:0] c, r1, r2, res, next, ad;
string text, effect;
bit writes, take, done, access;
// An interrupt is taken between two instructions: MIE at 1, and a request that is pending and enabled.
if (mstatus[3] && (mie & mip) != 0) begin
if (mie[11] && mip[11]) enter(32'h8000_000b, "interrupt, external");
else enter(32'h8000_0007, "interrupt, machine timer");
taken++;
end
done = 0; writes = 1; access = 0; res = 0; effect = ""; next = pc + 4; text = "";
if (pc >= 32'h1000) begin enter(1, "exception, no instruction at this address"); traps++; done = 1; k = WORD; a = 0; b = 0; c = 0; end
else begin k = kind[pc >> 2]; a = fa[pc >> 2]; b = fb[pc >> 2]; c = fc[pc >> 2]; end
r1 = x[b[4:0]]; r2 = x[c[4:0]];
// An immediate has 12 bits with a sign (20 bits in lui). A row outside that range is no instruction.
if (!done && ((k == LUI && c[31:20] != 0) || ((k == ADDI || k == ANDI || k == ORI || k == LW || k == SW || k == JALR) && !($signed(c) >= -2048 && $signed(c) <= 2047)))) begin
enter(2, $sformatf("exception, immediate out of range at %08h", pc)); traps++; done = 1;
end
if (!done) case (k)
LUI: begin res = c << 12; text = $sformatf("lui x%0d, 0x%0h", a, c); end
ADDI: begin res = r1 + c; text = $sformatf("addi x%0d, x%0d, %0d", a, b, $signed(c)); end
ANDI: begin res = r1 & c; text = $sformatf("andi x%0d, x%0d, %0d", a, b, $signed(c)); end
ORI: begin res = r1 | c; text = $sformatf("ori x%0d, x%0d, %0d", a, b, $signed(c)); end
SLLI: begin res = r1 << c[4:0]; text = $sformatf("slli x%0d, x%0d, %0d", a, b, c); end
SRLI: begin res = r1 >> c[4:0]; text = $sformatf("srli x%0d, x%0d, %0d", a, b, c); end
ADD: begin res = r1 + r2; text = $sformatf("add x%0d, x%0d, x%0d", a, b, c[4:0]); end
SUB: begin res = r1 - r2; text = $sformatf("sub x%0d, x%0d, x%0d", a, b, c[4:0]); end
AND: begin res = r1 & r2; text = $sformatf("and x%0d, x%0d, x%0d", a, b, c[4:0]); end
OR: begin res = r1 | r2; text = $sformatf("or x%0d, x%0d, x%0d", a, b, c[4:0]); end
LW, SW: begin
ad = r1 + c; access = 1;
text = $sformatf("%s x%0d, %0d(x%0d)", (k == LW) ? "lw" : "sw", a, $signed(c), b);
bus(k == SW, ad, x[a[4:0]]);
if (k == SW) begin writes = 0; effect = $sformatf("mem[%08h] = %08h", ad, x[a[4:0]]); end
end
BEQ, BNE, BLT, BGE: begin
r1 = x[a[4:0]]; r2 = x[b[4:0]]; writes = 0;
case (k)
BEQ: take = (r1 == r2);
BNE: take = (r1 != r2);
BLT: take = ($signed(r1) < $signed(r2));
default: take = ($signed(r1) >= $signed(r2));
endcase
text = $sformatf("%s x%0d, x%0d, 0x%0h", (k == BEQ) ? "beq" : (k == BNE) ? "bne" : (k == BLT) ? "blt" : "bge", a, b, c);
if (take) begin next = c; effect = $sformatf("taken: next is %08h", next); end
else effect = "not taken";
end
JAL, JALR: begin
res = pc + 4;
if (k == JAL) begin next = c; text = $sformatf("jal x%0d, 0x%0h", a, c); end
else begin next = (r1 + c) & ~32'd1; text = $sformatf("jalr x%0d, %0d(x%0d)", a, $signed(c), b); end
if (k == JAL && next == pc && !wdg_armed) begin
if (SHOW == 2) $display("%08h | %s | the program stops here", pc, text);
else say($sformatf("the program stops at %08h", pc));
stopped = 1; done = 1;
end
end
CSRR: begin res = csr_value(c[11:0]); text = $sformatf("csrr x%0d, %s", a, cn(c[11:0])); end
CSRW, CSRS, CSRC: begin
writes = 0;
case (k)
CSRW: csr_store(c[11:0], x[a[4:0]]);
CSRS: csr_store(c[11:0], csr_value(c[11:0]) | x[a[4:0]]);
default: csr_store(c[11:0], csr_value(c[11:0]) & ~x[a[4:0]]);
endcase
text = $sformatf("%s %s, x%0d", (k == CSRW) ? "csrw" : (k == CSRS) ? "csrs" : "csrc", cn(c[11:0]), a);
effect = $sformatf("%s = %08h", cn(c[11:0]), csr_value(c[11:0]));
end
MRET: begin
writes = 0; next = mepc; text = "mret";
mstatus[3] = mstatus[7]; mstatus[7] = 1'b1; // MIE takes MPIE back
effect = $sformatf("next is %08h, MIE=%0d", next, mstatus[3]);
if (SHOW == 1) say($sformatf("mret: back to %08h", next));
end
default: begin enter(2, $sformatf("exception, illegal instruction %08h at %08h", c, pc)); traps++; done = 1; end
endcase
#1; // half a tick: the devices answer
if (access && !done) begin
if (plic_commit && !plic_write) begin
bus_rdata = plic_rdata;
if (plic_offset == 22'h20_0004) say($sformatf("PLIC claim returns %0d", plic_rdata));
end
if (plic_commit && plic_write && plic_offset == 22'h20_0004) say($sformatf("PLIC complete %0d", dev_wdata));
if (bus_fault) begin
enter((k == LW) ? 5 : 7, $sformatf("exception, no memory at %08h for %s at %08h", ad, (k == LW) ? "a load" : "a store", pc));
traps++; done = 1;
end
else if (k == LW) begin res = bus_rdata; effect = $sformatf(" from mem[%08h]", ad); end
end
if (!done) begin
if (writes) begin
if (a[4:0] != 0) x[a[4:0]] = res; // register 0 is never written
effect = {$sformatf("x%0d = %08h", a, x[a[4:0]]), effect};
if (k == JAL || k == JALR) effect = {effect, $sformatf(", next is %08h", next)};
end
if (SHOW == 2) $display("%08h | %s | %s", pc, text, effect);
pc = next; steps++;
end
tc_tick();
clk = 1; #1; clk = 0; // the rising edge: registers of the chip blocks load
plic_commit = 0; plic_write = 0; cmp_low = 0; cmp_high = 0;
wdg_write = 0;
if (wdg_armed && !wdg_was_armed) say($sformatf("watchdog armed, %0d ticks left", wdg_left));
if (wdg_warn && !wdg_was_warned) say("watchdog early warning: source 6 asks ap_plic");
if (wdg_reset) say("watchdog reset request: the chip resets here");
wdg_was_armed = wdg_armed; wdg_was_warned = wdg_warn;
endtask
task automatic power_on();
for (int n = 0; n < 32; n++) x[n] = 0;
for (int n = 0; n < 16384; n++) ram[n] = 'x; // SRAM holds nothing known
mstatus = 32'h0000_1800; mie = 0; mtvec = 0; mscratch = 0; mepc = 0; mcause = 0; // the values after reset
pc = 0; steps = 0; traps = 0; taken = 0; stopped = 0;
uart_text = ""; uart_wait = 0; rx_count = 0; rx_planned = 0; gpio_out = 0; gpio_changes = 0;
dma_left = 0; dma_done = 0; ticks = 0;
reset_n = 0; #1 clk = 1; #1 clk = 0; reset_n = 1; // one clock edge in reset for the chip blocks
wdg_write = 0; wdg_offset = 0; wdg_was_armed = 0; wdg_was_warned = 0;
endtask
task automatic run();
while (!stopped && !wdg_reset && steps + traps + taken < 400) step();
endtask
bit supply, osc_ok, lock_ok, button, serviced, io_sel, io_wr;
logic [31:0] io_addr, io_data;
wire osc, pll, sampled, strap, fabric, core, ready, pending, gated;
wire [31:0] spi_data;
wire pwm, miso, cs_n;
wire [3:0] pads, oe;
ap_crg_boot sequencer(clk,supply,osc_ok,lock_ok,1'b0,1'b1,ready,1'b0,osc,pll,sampled,strap,fabric,core);
boot_rom_port availability(clk,fabric,1'b0,32'b0,ready,,,);
sleep_clock gate(clk,reset_n,button,gpio_out[0],1'b1,serviced,pending,gated);
capture_pwm timer(clk,reset_n,io_sel && io_addr[31:12]=='h10002,io_sel,io_wr,1'b0,io_addr[11:0],io_data,,,pwm,);
serial_slice serial(clk,reset_n,io_sel,io_sel,io_wr,io_addr,io_data,spi_data,1'b0,8'b0,,,,cs_n,,,1'b1);
pad_slice #(.ROUTES(48'h180)) mux(clk,reset_n,io_sel,io_sel,io_wr,1'b0,io_addr,io_data,,4'b0,4'b0,1'b1,pwm,1'b0,pads,,,,,oe);
bit tck,tms;
wire tdo;
board_tap tap(tck,tms,1'b0,tdo);
task automatic shift_edge(input bit mode);
tms=mode; #1; tck=1; #1; tck=0; #1;
endtask
logic [31:0] idcode;
task automatic identify();
shift_edge(0); shift_edge(1); shift_edge(0); shift_edge(0);
for (int i=0;i<32;i++) begin idcode[i]=tdo; shift_edge(i==31); end
endtask
int aon_edges, core_edges, pad_edges;
always @(posedge clk) aon_edges++;
always @(posedge gated) core_edges++;
always @(posedge pads[0]) if (oe[0]) pad_edges++;
task automatic pulse();
#1; clk=1; #1; clk=0; #1;
endtask
task automatic boot();
supply=1;
repeat(12) begin
if (osc) osc_ok=1;
if (pll) lock_ok=1;
pulse();
$display("edge=%0d boot osc=%b pll=%b strap_valid=%b fabric=%b ready=%b core=%b",aon_edges,osc,pll,sampled,fabric,ready,core);
if (core) begin
reset_n=1;
pc=strap ? 32'h80000000 : 0;
if (pc!=0 || kind[0]!=JAL) $fatal(1,"first fetch");
pulse();
$display("edge=%0d fetch pc=%08h jump_target=%08h",aon_edges,pc,fc[0]);
disable boot;
end
end
$fatal(1,"boot timed out");
endtask
Check Yourself
Common Mistakes
Wrong Reset the PC to wake the processor.
A reset discards the context the program intended to resume.
Fix Open the gate and continue at the parked address.
Wrong Clear pending while sleep stays requested.
The gate can close again before the resumed work finishes.
Fix Withdraw the sleep request as part of service.
Remember
- Close the gate only after work has drained.
- Use a running domain to detect wake.
- Check both continuity of execution and continuity of data.