From the First Interrupt to the First DMA Copy
Follow one byte through three owners. The UART holds it, the handler publishes it, and DMA moves the resulting word.
You Will Be Able To
- Open the interrupt path in a safe order.
- Connect trap entry, claim, service, completion and return.
- Prove a DMA transfer from the programmed addresses and the destination word.
- Lesson
- S11.6
- Time
- 23 min
- Runs on
- Your browser
- Check
- 5 questions
The source word held hexadecimal 1234 at driver entry. It holds 4b before the copy starts. Which instruction changed it?
Before You Start
Continue the S11.2 image at program address 0x20. The stack, source word, cleared destination and trap vector already exist.
| Question | |
|---|---|
| 1 | Which enable should firmware open last here? |
| 2 | Which value identifies UART0 specifically? |
| 3 | What makes a second receive claim unnecessary? |
| 4 | What proves that DMA finished? |
| 5 | At the wake breakpoint 0x94, what full line describes the two SRAM words? |
The Idea
A driver arranges for an event to reach software. A handler removes the cause and leaves a result the interrupted program can use.
A separate engine then moves the result. Work backward from the copied word to distinguish these two writers.
New Words
| Word | Meaning |
|---|---|
| Claim ID | The source number returned by reading the controller claim register. |
| Resume address | The interrupted instruction address saved in mepc. |
| Descriptor | The source address, destination address and length supplied to the mover. |
One Picture: Ownership of the Sample
- Peripheral
- Processor
- Memory
- Bus
- Pop
Reading receive data consumes the oldest byte.
- Publish
The handler stores the zero-extended byte in SRAM.
- Move
After return, the main program submits a four-byte copy.
Read the diagram as text
- UART queue: holds incoming K
- Handler: pops and stores
- Source word: holds 0000004b
- DMA: copies to the next word
- UART queue → Handler: Pop
- Handler → Source word: Publish
- Source word → DMA: Move
Follow the value through each change of owner.
The Smallest Example, Worked by Hand
UART0 is source one. Setting enable bit one needs the mask two. Setting the priority register needs offset four times one.
DMA is source five. Its pending mask is one shifted left five places, or 32. The program polls that bit.
Only source one is enabled for delivery. DMA completion can be pending while the processor takes exactly one interrupt.
The Rules
Rule 1: Prepare the handler first.
Initialize addresses and storage before opening the global enable.
Rule 2: Consume the device cause.
For this UART, pop the byte before completing its controller ID.
Rule 3: Start last.
Write both endpoints and the byte count before launching DMA.
Driver Initialization: Build the Delivery Path
The program gives UART0 priority one. The controller threshold is still zero, so a pending enabled source can win.
It writes two into the enable word. Next it prepares the claim and UART base registers used by the handler.
Bit eleven of mie opens machine external delivery. Bit three of mstatus opens delivery globally. Firmware sets that last.
The main loop tests a software flag in x30. A quiet input leaves that flag zero even though all enables are open.
First Interrupt: Why There Are Two Addresses
At tick 36 the board delivers K. The queue requests source one. The external request enters the core between instructions.
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 00000060The core saves 0x60 in mepc and enters the vector at 0x180. The cause word identifies a machine external interrupt.
The first handler load reads the claim register. The returned one names UART0. The next load pops the byte at UART offset twelve.
The handler stores 0x4b over the initializer, completes ID one, and sets x30. A machine return restores the interrupted PC.
Returning to 0x60 can revisit a branch using an older test value. The next loop test observes x30 and exits.
First DMA Transfer: Distinguish Launch from Completion
At address 0x64 the source already holds the byte. The still-zero destination proves the handler did not write both locations.
edge=56 copy pc=00000064 sp=80010000 source=0000004b copy=00000000
t=51 | DMA starts: 4 bytes from 80000000 to 80000004
t=55 | DMA doneFirmware programs 0x80000000, 0x80000004 and length four. The final write starts the engine. The kit moves one SRAM byte per tick.
The first byte carries 4b. The next three carry zero. Done rises after the fourth byte and sets the controller pending bit.
The foreground loop masks with 32 and waits for that evidence. It leaves the disabled DMA source pending.
Now Run It
Stop at 0x64. Check both words, then move the breakpoint to 0x94 in the same image.
The later stop follows DMA and the board wake. If the source is correct at both stops, investigate transfer length and destination first.
The claim controller is RTL. The S6 kit supplies UART bytes and the DMA mover. Its byte rate is a teaching choice.
Why It Is Built This Way
Separate acceptance from completion and software can issue work without copying every byte itself.
A pending bit can also support polling. This program needs no second handler merely to observe that the first copy finished.
The Trap: Confusing Claim with Consumption
A claim removes a pending controller entry. The receive queue still holds the byte until software reads it.
Completing early can admit another request from the same level. Repeated claims would then exaggerate the number of samples.
At Scale
On a board with several interrupt sources, a shared handler must dispatch on the returned ID.
Name the device
Capture cause, claim and the first device read together. Only the claim identifies this external source.
Check the boundary
Use distinct bytes and inspect the last destination byte. A short copy can still produce a plausible first word.
Try It
Run to 0x64. Compare its source against the initializer recorded at driver entry.
Set BREAK_PC to -1 to see launch, done and the console result.
Change SAMPLE to 0x52 and repeat both observations.
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 break pc=00000064 ticks=45 sp=80010000 source=0000004b copy=00000000Read 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 Add one to the trap PC before returning.
An interrupt interrupted a legal instruction boundary.
Fix Use the saved resume address.
Wrong Pass a word count to LEN.
The mover counts bytes.
Fix Multiply the number of whole words by four.
Remember
- Enable the global interrupt after preparing its target.
- Claim the ID, consume the cause and complete that ID.
- Observe the DMA destination after completion.