From Reset to a Running Application
Stop at the first driver instruction. Work backward from a usable stack and data word to the signals that allowed the first fetch.
You Will Be Able To
- Explain the order of power and reset release.
- Distinguish the first fetch from the first driver instruction.
- Use a breakpoint to verify start-up memory before enabling a device.
- Lesson
- S11.2
- Time
- 24 min
- Runs on
- Your browser
- Check
- 5 questions
The supply is good and the processor has a clock. Why can a fetch from the correct address still be too early?
Before You Start
Recall that the program counter names the next instruction. A reset vector gives its first address.
Read this timeline left to right. S11.6 and S11.7 continue the same execution.
| Question | |
|---|---|
| 1 | What allows the sequencer to start the PLL? |
| 2 | At edge nine, why is the core still in reset? |
| 3 | Which instruction can safely use the stack? |
| 4 | What distinguishes copied data from cleared data at driver entry? |
| 5 | At BREAK_PC equal to hexadecimal 20, what full breakpoint line appears? |
The Idea
At power-up, software cannot ask anything to wait. Hardware must hold the processor until its first instruction can be supplied.
After release, the responsibility changes hands. Instructions must establish every value the application expects to find in writable memory.
New Words
| Word | Meaning |
|---|---|
| Boot strap | A board input sampled once to select the starting memory. |
| Breakpoint | An address where the lab stops before executing the instruction. |
| Initializer | A value kept in the image and copied into writable memory during start-up. |
| Board edge / kit tick | An edge counts a rising reference clock. A kit tick counts one active instruction step. |
One Timeline, Three Zoom Levels
- Cycle 0
Power is good. The sequencer starts the oscillator.
- Cycle 1
The ROM answers the first fetch at zero. Its jump selects the start-up address.
- Cycle 2
The reset jump has landed at address four. The first stack instruction is next.
- Cycle 3
Writable state and the vector now exist. Driver setup can open a delivery path.
- Cycle 4
One incoming byte takes the processor away from its wait loop.
- Cycle 5
Firmware has given the mover two addresses and a length. Four byte copies follow.
- Cycle 6
A completed GPIO store asks the board to stop the core clock.
- Cycle 7
The button has reached the always-on detector. The next core edge will execute the waiting instruction.
Columns mark events in order. Their widths do not measure elapsed time. A tick counts an active kit step; an edge counts the board clock.
Zoom 1 · Power and the First Fetch
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=00000004Zoom 2 · Instruction Boundaries and Service
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 doneZoom 3 · Clock Stop and the Restored Word
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=0000004b
t=60 | GPIO OUT = 0000
t=62 | UART0 sends 4b "K"
t=63 | the program stops at 000000a0
copy=0000004b console=K interrupts=1 exceptions=0The Smallest Example, Worked by Hand
Watch edges eight through ten. At eight, the fabric is released but the ROM still reports zero for ready.
Edge nine supplies the last local warm-up edge. The ROM now reports one. The sequencer reads that result on edge ten.
Count from edge five, where the fabric leaves reset. Four edges buy ROM availability. A fifth buys permission to fetch.
The Rules
Rule 1: Check the receiver.
Follow supply good, a usable clock and a responding memory before allowing the processor to fetch.
Rule 2: Record the selected address.
Observe the saved strap when the core leaves reset.
Rule 3: Stop before side effects.
Inspect startup state at driver entry, before a peripheral can interrupt.
Power-Up: Who Can Wait for Whom?
The board tells the sequencer that its supply is good. The sequencer starts the oscillator and waits for the ready input.
The oscillator can now supply a reference. The sequencer starts the PLL and waits for lock before sampling the strap.
The board model acknowledges each request at the next opportunity. Those gaps describe this fixture. Physical supplies and oscillators have their own settling times.
Once the saved strap is valid, fabric reset can lift. Processor reset stays asserted until both fabric and ROM can respond.
Boot ROM: Where the First Address Goes
Strap zero selects the read-only image at address zero. The ROM availability slice counts four local edges after release.
The S5 one-word ROM supplies the ready signal. The S6 kit supplies the actual program words once release succeeds.
At address zero the image contains a jump. Its target is four, where start-up begins. Address zero names an instruction, not a stack.
- Power
- Control / FSM
- Memory
- Processor
- Start
A good supply lets the oscillator start.
- Release
The fabric and ROM receive their clocks and reset release.
- Ready
The sequencer lets the core request its first word.
Read the diagram as text
- Supply: provides a good indication
- Sequencer: holds the core
- Boot ROM: reports available
- Core: fetches at zero
- Supply → Sequencer: Start
- Sequencer → Boot ROM: Release
- Boot ROM → Core: Ready
Follow the signals before following the address.
Start-Up: Make Unknown Memory Usable
At address four, sp still reads zero and both words show x. A reset processor can start with unknown SRAM.
The first instruction loads 0x80010000 into sp. A descending stack can now allocate its first word inside the top of SRAM.
Next, a load reads the initializer 0x1234 from ROM. A store copies it to 0x80000000. A second store clears the destination.
Start-up installs the handler address in mtvec before driver entry. This tiny image uses one initializer and one zero word.
Now Run It
Run the application through the final console byte. Then set BREAK_PC to hexadecimal 20 and run again.
break pc=00000020 ticks=8 sp=80010000 source=00001234 copy=00000000The stack pointer is one byte above the last SRAM byte. The source and destination have different values. Both observations matter.
The timeline uses the S6 instruction model, actual boot sequencer, ROM availability, interrupt controller, machine timer and sleep gate.
The five-stage core cross-check runs the same assembled image with modeled memory and devices. It checks final state with its clock running.
Why It Is Built This Way
Hardware handles readiness because no instruction can run before the first fetch. Software handles layout because each application can place its data differently.
Saving the strap also frees the board pin for another use. Later pin activity cannot redirect a running program.
The Trap: Stopping One Instruction Too Late
A breakpoint tests state on entry. Stopping after the handler runs hides whether start-up ever copied the initializer.
Move the stop upstream. If the source already differs at driver entry, the UART has not yet had a chance to change it.
At Scale
Common bring-up practice keeps observations on both sides of each release.
First board
Capture the supply-good indication and the first address at core release. Save the image alongside that capture.
Another image
Repeat the driver-entry stop using the new link addresses. Compare symbols before comparing raw PCs.
Try It
Run without a breakpoint. Find the first valid ROM response and the saved return address at interrupt entry.
Set BREAK_PC to 32 decimal. Read the source and destination before driver setup.
Set it to 100 decimal to continue the investigation at the DMA setup in S11.6.
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 edge=78 resume pc=00000094 sp=80010000 source=0000004b copy=0000004b t=60 | GPIO OUT = 0000 t=62 | UART0 sends 4b "K" t=63 | the program stops at 000000a0 copy=0000004b console=K interrupts=1 exceptions=0Read 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 Use the live strap to explain the current PC.
The sequencer captured its choice before release.
Fix Inspect boot_sel at the sampling edge.
Wrong Treat every x in SRAM as a read fault.
An uninitialized SRAM word can be selected successfully.
Fix Inspect the bus response and the start-up stores separately.
Remember
- Read the power-up sequence as a chain of acknowledgments.
- Follow the reset jump into start-up.
- Use driver entry to check the software environment before the first interrupt.