Gates to Games
A COURSE IN 9 PARTS · RISC-V · FPGA · C · HDMI · DEBUG

From digital logic to games on your own chip

Start with gates and adders. Build a RISC-V processor, its system on chip, its firmware and a graphics chip. Finish by playing games with DVI on HDMI on a chip you designed, on a $25 FPGA board, then follow the same design toward silicon.

85lessons on the path
85ready now, 85 with video
~89 hof guided work
$25Tang Nano 9K board, from Tier 2

Every lesson, four parts

Each lesson is one page with one goal. The same four parts, always in the same order.

1Watch

A short video with chapters and a transcript.

2Explore

A bench you can touch: the same circuit you just saw.

3Try

A small challenge. The page checks your answer.

4Build

The real Verilog or C, and the lab that uses it.

The course

Parts are in the order you take them. The two language tracks come right before they're first needed.

Ready · watch it nowComing soon · listed so you can see the whole path
TIER 0 · BITS · LESSON 1 OF 8

Why build a computer from scratch?

See what you'll build, tier by tier, how every lesson works, and flip your first bits.

video8-bit bench4 auto-checked questionsLab 0A setup
2

Explore

Pick a part of the course to see what you build in it. Then flip the eight bits below and watch the number change.

THE STACK · CLICK A PARTT0 · Bits
BENCH · EIGHT WIRESclick a bit
THE NUMBER0

no bits on

Each wire has a weight. Add the weights of the wires that are on. Lesson 0.2 explains why.

3

Try

Four quick questions about how the course fits together. Pick an answer and the page tells you why.

0 of 4 correct.

4

Build

Lab 0A: install the free tools and run your first simulation. You need them from lesson 0.8 onward, so set them up now.

# 1. Get the open toolchain (one download, all tools)
#    github.com/YosysHQ/oss-cad-suite-build/releases
tar -xzf oss-cad-suite-*.tgz
source oss-cad-suite/environment

# 2. Check it works
yosys -V
iverilog -V

# 3. Your first simulation: hello.v
module hello;
  initial $display("Hello from a simulated chip");
endmodule

iverilog -o hello hello.v && vvp hello
LAB 0A · 20 MINSet up the bench

Install OSS CAD Suite, run hello.v, and paste the output into the lab form.

Show answer

The quickest way is the setup script in the repository: setup/setup.sh on Linux or macOS, setup\setup.bat on Windows. It installs the OSS CAD Suite into tools/. Then:

source env.sh                 # Windows: . .\env.ps1
yosys -V                      # Yosys 0.70+...
iverilog -V                   # Icarus Verilog version 14.0 (devel)
iverilog -o hello hello.v && vvp hello

Expected output, the line to paste into the lab form:

Hello from a simulated chip

If iverilog is not found, the tools are not on your PATH in this terminal: run source env.sh again.

WHAT'S IN THE SUITEYosys, nextpnr, Icarus Verilog, Verilator, GTKWave

The same tools that build NandTier into a bitstream in Tier 5.

HARDWARENot yet

Tier 0 and Tier 1 run in the browser. You need the Tang Nano 9K from Tier 2.

TIER 0 · BITS · LESSON 2 OF 8

Numbers are wires

Read eight wires as a number three ways: unsigned, signed and hex. Then see why adding can overflow.

video8-bit bench with an adder3 graded targets
2

Explore

Click the bits. All three readings change at once. Switch to Add two bytes to see when a sum stops fitting.

BENCH · ONE BYTE
3

Try

Set the bits to hit each target. The page checks as you click.

BENCH · CLICK THE BITS0x00

4

Build

In Verilog, a byte is [7:0]: eight wires. Whether it's signed is a choice you make when you read it.

module readings;
  reg [7:0] x = 8'hC8;        // 1100_1000
  reg [7:0] a = 8'd100, s;
  initial begin
    $display("%d", x);           // 200
    $display("%d", $signed(x));  // -56
    s = a + a;                    // 8 wires: no room for 200 signed
    $display("%d", $signed(s));  // -56: overflow
  end
endmodule
PRACTICE · 10 MINPredict, then run

Change x to 8'h80 and 8'h7F. Write down both readings before you run iverilog.

Show answer

Each reading is the same 8 wires, read two ways. Unsigned, all eight bits count up. Signed (two's complement), the top bit is worth −128.

x = 8'h80  (1000_0000):  %d -> 128    $signed -> -128
x = 8'h7F  (0111_1111):  %d -> 127    $signed -> 127

0x80 is the one pattern where the two readings are furthest apart: it is the most negative 8-bit number. 0x7F is the largest positive one, so both readings agree.

IN NANDTIEROne register, two compares

The core reads the same 32 wires as signed for slt and unsigned for sltu. You'll see it in lesson 1.6.

TIER 0 · BITS · LESSON 3 OF 8

Gates, and why NAND is enough

Learn AND, OR, NOT and XOR by their truth tables, then build every one of them from NAND alone.

videogate bench + NAND-only mode1 mystery circuit
2

Explore

Pick a gate and click its inputs, or click a row of the truth table. Then switch to NAND only and watch the same results come from NAND gates.

AND

3

Try

This box hides one gate, built from NANDs. Flip the inputs to fill its truth table, then name the gate.

BENCH · MYSTERY BOX0 of 4 rows seen

Which gate is inside?

See all four rows first.

4

Build

Verilog has gates built in. Here is XOR from four NANDs, and a check that it matches Verilog's own ^ on every input.

module xor_from_nand (input a, input b, output y);
  wire n1, n2, n3;
  nand g1 (n1, a, b);
  nand g2 (n2, a, n1);    // upper
  nand g3 (n3, n1, b);    // lower
  nand g4 (y,  n2, n3);
endmodule

module tb;
  reg a, b; wire y; integer i;
  xor_from_nand dut (a, b, y);
  initial for (i = 0; i < 4; i = i + 1) begin
    {a, b} = i; #1;
    if (y !== (a ^ b)) $display("FAIL %b%b", a, b);
  end
endmodule
PRACTICE · 15 MINBuild OR from NAND

Copy the module, rewire it as three NANDs (lesson chapter "OR from three NANDs") and check it against |.

Show answer

De Morgan: a OR b = NOT(NOT a AND NOT b). A NAND with both inputs tied together is a NOT, so OR is two inverting NANDs feeding a third:

module or_from_nand (input a, input b, output y);
  wire na, nb;
  nand g1 (na, a, a);     // NOT a
  nand g2 (nb, b, b);     // NOT b
  nand g3 (y, na, nb);    // NOT(NOT a AND NOT b) = a OR b
endmodule

module tb;
  reg a, b; wire y; integer i;
  or_from_nand dut (a, b, y);
  initial begin
    for (i = 0; i < 4; i = i + 1) begin
      {a, b} = i; #1;
      if (y !== (a | b)) $display("FAIL %b%b", a, b);
    end
    $display("done");
  end
endmodule

A correct circuit prints only done.

IN NANDTIERNo NAND gates at all

Your FPGA builds every gate from 4-input lookup tables. Lesson 5.1 opens one up.

TIER 0 · BITS · LESSON 4 OF 8

Adders

Build a 1-bit full adder from five gates, chain four of them, and see why the carry sets the clock speed.

video6-step walkthrough4-bit ripple bench1 graded challenge
2

Explore

Step through the full adder. Each step lights one part and dims the rest. Use the arrow keys, or switch to free play and click the inputs.

BENCH · FULL ADDER
Settledgate delays
STEP 1 OF 6

← → to step
BENCH · 4-BIT RIPPLE CARRY ADDER0 gate delays
A
B
RIPPLE

0 + 0 = 0

Click the bits of A and B. Press Add to watch the carry move from column 0 to column 3, one column every two gate delays.

3

Try

Use the circuit to answer a question the walkthrough didn't. The page checks your answer as you go.

BENCH · CLICK A, B, CINSettled

Find every input that makes S = 0 and Cout = 1

Click the input pins to change them. Each new answer fills a slot.

0 of 3 found.

4

Build

The same five gates as two lines of Verilog, then four of them chained into a ripple adder. In Lab 0B you test the full adder on all eight inputs.

module full_adder (input a, input b, input cin,
                   output s, output cout);
  assign s    = a ^ b ^ cin;                 // two XORs
  assign cout = (a & b) | (cin & (a ^ b));   // G + P·Cin
endmodule

module ripple4 (input [3:0] a, b, output [3:0] s, output cout);
  wire [4:0] c;  assign c[0] = 1'b0;
  full_adder fa0 (a[0], b[0], c[0], s[0], c[1]);
  full_adder fa1 (a[1], b[1], c[1], s[1], c[2]);
  full_adder fa2 (a[2], b[2], c[2], s[2], c[3]);
  full_adder fa3 (a[3], b[3], c[3], s[3], c[4]);
  assign cout = c[4];
endmodule
LAB 0B · 25 MINA full adder, tested exhaustively

Write full_adder.v and a testbench that checks all 8 inputs against Verilog's own +.

Show answer

Three inputs give only 8 cases, so the testbench can try them all and compare with Verilog's own +. {cout, s} is the 2-bit sum:

module full_adder (input a, input b, input cin, output s, output cout);
  assign s    = a ^ b ^ cin;
  assign cout = (a & b) | (cin & (a ^ b));
endmodule

module tb;
  reg a, b, cin; wire s, cout; integer i, errors = 0;
  full_adder dut (a, b, cin, s, cout);
  initial begin
    for (i = 0; i < 8; i = i + 1) begin
      {a, b, cin} = i; #1;
      if ({cout, s} !== a + b + cin) begin
        errors = errors + 1;
        $display("FAIL a=%b b=%b cin=%b -> %b%b", a, b, cin, cout, s);
      end
    end
    $display("%0d errors in 8 cases", errors);
  end
endmodule
iverilog -o fa full_adder.v && vvp fa
0 errors in 8 cases

Break it on purpose, for example cout = a & b, and the testbench names exactly the rows where the carry comes from cin: a b cin = 0 1 1 and 1 0 1.

IN NANDTIEROne 33-bit adder does four jobs

The ALU in hw/core/nt_alu.v uses one adder for ADD, SUB, SLT and SLTU. You'll open it in lesson 1.6.

TIER 0 · BITS · LESSON 5 OF 8

Multiplexers, decoders and a 4-bit ALU

Choose a value with a multiplexer, pick one line with a decoder, and combine an adder and logic into a small ALU.

videomux and decoder bench4-bit ALU bench4 auto-checked questionsLab 0B
2

Explore

First the two choosers: flip the inputs and the select of a 2:1 mux, and the number going into a 2-to-4 decoder. Then drive a 4-bit ALU: every unit computes, and the multiplexer passes the one the operation asks for.

BENCH · 2:1 MUX AND 2-TO-4 DECODERclick the bits
MUX

DECODER
THE CHOOSERS

One picks a value, the other a line

A mux sends one of its inputs to the output. A decoder turns one number into one active line. The bus picks a device the same way: the top address bits go into a decoder.

BENCH · A 4-BIT ALU
A
B
THE RESULT

3

Try

Four questions. Use the ALU bench above if you want to check by hand.

4

Build

The 4-bit ALU as Verilog: every unit is one expression, and a case statement is the multiplexer. Lab 0B tests a full adder the same way, on every input.

module alu4 (input [3:0] a, b, input [2:0] op, output reg [3:0] y);
  wire [3:0] sum  = a + b;
  wire [3:0] diff = a + ~b + 4'd1;   // a - b: invert b, carry in 1
  always @* begin
    case (op)                        // the output multiplexer
      3'd0: y = sum;
      3'd1: y = diff;
      3'd2: y = a & b;
      3'd3: y = a | b;
      default: y = a ^ b;
    endcase
  end
endmodule

// a 2:1 mux and a 2-to-4 decoder
assign m = s ? d1 : d0;
assign line = 4'b0001 << n;
LAB 0B · 25 MINA full adder, tested exhaustively

Write the adder and a testbench that tries every input against Verilog's own +.

Show answer

Three inputs give only 8 cases, so the testbench can try them all and compare with Verilog's own +. {cout, s} is the 2-bit sum:

module full_adder (input a, input b, input cin, output s, output cout);
  assign s    = a ^ b ^ cin;
  assign cout = (a & b) | (cin & (a ^ b));
endmodule

module tb;
  reg a, b, cin; wire s, cout; integer i, errors = 0;
  full_adder dut (a, b, cin, s, cout);
  initial begin
    for (i = 0; i < 8; i = i + 1) begin
      {a, b, cin} = i; #1;
      if ({cout, s} !== a + b + cin) begin
        errors = errors + 1;
        $display("FAIL a=%b b=%b cin=%b -> %b%b", a, b, cin, cout, s);
      end
    end
    $display("%0d errors in 8 cases", errors);
  end
endmodule
iverilog -o fa full_adder.v && vvp fa
0 errors in 8 cases

Break it on purpose, for example cout = a & b, and the testbench names exactly the rows where the carry comes from cin: a b cin = 0 1 1 and 1 0 1.

IN NANDTIERThe same shape, 32 bits wide

The processor's ALU in Tier 1 has an adder, a shifter and logic, with a multiplexer choosing the result.

IN NANDTIERDecoders pick devices

The bus looks at the top bits of every address to decide which memory or peripheral answers.

TIER 0 · BITS · LESSON 6 OF 8

Memory from feedback

Make a circuit remember with feedback: an SR latch, a D latch, and the D flip-flop every register is made of.

videolatch and flip-flop bench4 auto-checked questions
2

Explore

Three circuits, from simple to useful. Drive their inputs and watch Q. For the flip-flop, click CLK twice: once up, once down, to make one clock pulse.

BENCH · SR LATCH · D LATCH · D FLIP-FLOP

3

Try

Four questions about when Q is allowed to change.

4

Build

In Verilog you don't wire NANDs together: you describe the behaviour, and the tools build it. A flip-flop is written with always @(posedge clk).

// a D latch: transparent while en is 1 (usually a mistake in FPGA designs)
always @* if (en) q = d;

// a D flip-flop: changes only at the rising edge of clk
always @(posedge clk) q <= d;

// a 32-bit register with an enable, built from 32 flip-flops
always @(posedge clk)
  if (we) r <= wdata;
WATCH OUTAccidental latches

An always @* block that doesn't assign its output on every path makes a latch. The HDL track shows how to avoid it.

ON AN FPGAReal flip-flops

Every logic cell has flip-flops built in. The synthesis tool maps your always @(posedge clk) onto them.

TIER 0 · BITS · LESSON 7 OF 8

The clock edge, over time

Read a timing diagram: Q follows D only at rising edges, data must be stable around the edge, and the slowest path sets the clock.

videoflip-flop timing bench4 auto-checked questionsLab 0C
2

Explore

The clock runs on its own. Flip D whenever you like, even several times between edges. Q only takes D's value at each rising edge.

BENCH · D FLIP-FLOP TIMING
NOW

Each grey line is a rising edge. Between edges, D can do anything; Q doesn't move.

3

Try

Four questions on timing.

4

Build

Lab 0C: a 4-bit counter, a testbench with a 25 MHz clock, and a waveform to open in GTKWave.

module counter (input clk, input resetn, input en, output reg [3:0] q);
  always @(posedge clk)
    if (!resetn)  q <= 4'd0;
    else if (en)  q <= q + 4'd1;   // one step per rising edge
endmodule

// in the testbench: a 40 ns clock period, like the system clock
always #20 clk = !clk;
LAB 0C · 40 MINA counter and its waveform

Simulate the counter with Icarus Verilog and find, in GTKWave, the edge where it wraps from 15 to 0.

Show answer
module tb;
  reg clk = 0, resetn = 0, en = 1; wire [3:0] q;
  counter dut (clk, resetn, en, q);
  always #20 clk = !clk;
  initial begin
    $dumpfile("counter.vcd"); $dumpvars(0, tb);
    #50 resetn = 1;
    #800 $finish;
  end
endmodule
iverilog -o c counter.v tb.v && vvp c && gtkwave counter.vcd

Add clk and q to the wave view and show q in decimal. q steps 0, 1, 2 … on rising edges only. The wrap is the 16th rising edge after reset is released: q goes from 15 straight to 0, because 15 + 1 = 16 needs a fifth bit that a 4-bit register does not have. With the timing above that edge is at t = 660 ns.

ABOUT 25 MHZOne tick, about 40 ns

Everything between two flip-flops has to settle within one clock period, with a little setup time to spare.

TIER 0 · BITS · LESSON 8 OF 8

State machines, and the same circuits in Verilog

Build a state machine from a state register and next-state logic, then write every Tier 0 circuit in Verilog.

videotraffic-light bench2 auto-checked tasksLabs 0B and 0C
2

Explore

A traffic light as a state machine. Set the timer input, then press Clock: the state changes only at the edge, and only if the timer says so.

BENCH · TRAFFIC LIGHT FSM
EDGE 0

3

Try

First, put a processor's control steps in order for a load instruction. Then match each circuit with its Verilog.

4

Build

A state machine is two blocks: a clocked one for the state register, and a combinational one for the next state. Every Tier 0 circuit fits on one line or two.

localparam GREEN = 2'd0, YELLOW = 2'd1, RED = 2'd2;
reg [1:0] state, next;

always @(posedge clk)                 // the state register
  state <= resetn ? next : GREEN;

always @* begin                       // the next-state logic
  next = state;
  if (timer) case (state)
    GREEN:   next = YELLOW;
    YELLOW:  next = RED;
    default: next = GREEN;
  endcase
end

assign s    = a ^ b ^ cin;            // full adder
assign cout = (a & b) | (cin & (a ^ b));
assign y    = s ? d1 : d0;            // 2:1 mux
always @(posedge clk) q <= d;         // D flip-flop
LABS 0B AND 0CWrite and test them

A full adder checked on all 8 inputs, and a counter you watch in GTKWave.

Show answer

These are labs 0B and 0C again, now together: the exhaustive full-adder testbench from lesson 0.4 (0 errors in 8 cases) and the counter waveform from lesson 0.7 (the wrap from 15 to 0 on the 16th rising edge after reset). The answers there apply unchanged.

IN NANDTIERState machines everywhere

The CPU's control unit, the serial port, the SD card port and the picture unit are all built this way.

NEXTThe HDL track

H.1 picks up from here: Verilog properly, then testbenches, then SystemVerilog.

HDL TRACK · VERILOG → SYSTEMVERILOG · LESSON 1 OF 10

Verilog in one sitting

Read and write a small Verilog module: ports, assign, operators, widths, and a first testbench.

videolive expression bench2 auto-checked expressionsLab H1 with Icarus
2

Explore

Type any expression of a, b and c using & | ^ ~ and brackets. The truth table updates as you type.

BENCH · assign y = …8 rows
assign y = ;
WHAT THE TOOLS BUILD

An OR of an AND

3

Try

Finish the full adder. Write s and cout using only a, b, cin and the four operators. Each one is checked against all 8 rows.

BENCH · FULL ADDER0 of 2
assign s    = ;
assign cout = ;

Write s and cout

Use a, b, cin and & | ^ ~. Rows turn green when your output matches a real full adder.

s8 rows
cout8 rows

4

Build

Lab H1: put the module and the testbench in two files and run them with Icarus Verilog.

module full_adder (
  input  a, b, cin,
  output s, cout
);
  assign s    = a ^ b ^ cin;
  assign cout = (a & b) | (cin & (a ^ b));
endmodule

module tb;
  reg a, b, cin; wire s, cout; integer i;
  full_adder dut (.a(a), .b(b), .cin(cin), .s(s), .cout(cout));
  initial for (i = 0; i < 8; i = i + 1) begin
    {a, b, cin} = i; #1;
    $display("%b %b %b -> %b %b", a, b, cin, s, cout);
  end
endmodule

// iverilog -o sim full_adder.v tb.v && vvp sim
LAB H1 · 20 MINSimulate the full adder

Run the testbench and compare the 8 printed rows with the truth table from lesson 0.4.

Show answer

The 8 rows must match the truth table from lesson 0.4 exactly:

a b cin | cout s
0 0  0  |  0   0
0 0  1  |  0   1
0 1  0  |  0   1
0 1  1  |  1   0
1 0  0  |  0   1
1 0  1  |  1   0
1 1  0  |  1   0
1 1  1  |  1   1

A quick check: s is 1 when an odd number of inputs are 1, cout when two or more are.

WIDTHSAlways write them

8'hC8, 4'b1011, 16'd500. A number without a width is 32 bits wide.

IN NANDTIERNamed ports everywhere

Every module in the SoC is connected with .port(signal), so a swapped wire can't hide.

HDL TRACK · VERILOG → SYSTEMVERILOG · LESSON 2 OF 10

Combinational logic done right

Write always @(*) blocks that never build an accidental latch.

videomux bench that can latch3 latch hunts
2

Explore

This 4-to-1 multiplexer is written with case. Remove a case or the default and choose sel = 3: watch y get stuck on its old value.

BENCH · 4-TO-1 MUX
OUTPUT

y = 0

3

Try

Each snippet below is meant to be combinational. Pick the answer that names the latch, or says there isn't one.

0 of 3 correct.

4

Build

The safe pattern: a default for every output at the top of the block, and a default branch in the case.

module mux4 (
  input      [1:0] sel,
  input            a, b, c, d,
  output reg       y
);
  always @(*) begin
    y = 1'b0;              // default first: no path is undecided
    case (sel)
      2'b00:   y = a;
      2'b01:   y = b;
      2'b10:   y = c;
      default: y = d;
    endcase
  end
endmodule

// verilator --lint-only -Wall mux4.v   (should print nothing)
PRACTICE · 10 MINBreak it on purpose

Delete the default line and the default: branch, then lint it. Read the LATCH warning.

Show answer

Without the default line and the default: branch, some input combination leaves the output unassigned, so the circuit must remember the old value: a latch. The linter says so:

verilator --lint-only -Wall mux.v
%Warning-LATCH: mux.v:...: Latch inferred for signal 'y'
                (not all control paths of combinational always assign a value)

Yosys reports the same thing during synthesis as a $dlatch cell. The fix is the rule from the lesson: assign every output at the top of a combinational block, then override it.

THE RULEEvery output, every path

In always @(*), use = and give every output a value before any if or case.

IN NANDTIERLint before you add it

The repo has no lint step of its own, so make it yours: verilator --lint-only -Wall on a module before you add it to hw/.

HDL TRACK · VERILOG → SYSTEMVERILOG · LESSON 3 OF 10

Sequential logic: registers, counters and reset

Clock registers with always @(posedge clk), and see why <= and = build different hardware.

videoclock-it-yourself shift register2 prediction rounds
2

Explore

Set the input, then press Clock. With <= every value moves one stage per clock. Switch to = and a stage disappears.

BENCH · 3-STAGE SHIFT REGISTER
0 CLOCKS

Each value moves one stage

3

Try

All three registers start at 0. Work out a, b, c after the clocks, set them, and press Check.

ROUND 1

4

Build

A shift register and a counter with a synchronous reset. Non-blocking everywhere inside the clocked blocks.

module shift3 (input clk, rst, in, output reg a, b, c);
  always @(posedge clk)
    if (rst) begin a <= 0; b <= 0; c <= 0; end
    else     begin a <= in; b <= a; c <= b; end  // all read first, then all update
endmodule

module counter8 (input clk, rst, output reg [7:0] count);
  always @(posedge clk)
    if (rst) count <= 8'd0;
    else     count <= count + 8'd1;            // 255 + 1 wraps to 0
endmodule
PRACTICE · 15 MINWatch it in a waveform

Add $dumpfile and $dumpvars to a testbench and open the VCD in GTKWave.

Show answer
initial begin
  $dumpfile("wave.vcd");   // the file GTKWave opens
  $dumpvars(0, tb);         // 0 = everything below tb, all levels
end
iverilog -o sim tb.v dut.v && vvp sim && gtkwave wave.vcd

Put the two lines at the start of the testbench's initial block, before any delay, or the first values are missing. $dumpvars(1, tb) would record only the testbench's own signals.

THE RULE<= in clocked blocks

Non-blocking for always @(posedge clk), blocking for always @(*). Never both in one block.

IN NANDTIERA clean reset

Reset passes through a 16-stage synchronizer, nt_reset_sync, before it reaches the core. Lesson 2.3.

HDL TRACK · VERILOG → SYSTEMVERILOG · LESSON 4 OF 10

State machines in Verilog

Write a state machine in the two-block pattern, and build an overlapping 1011 detector.

videolive 1011 detector1 graded challenge
2

Explore

Press 0 or 1 to feed bits. The highlighted state is how much of 1011 the detector has seen. The matching case branch lights up in the code.

BENCH · 1011 DETECTORstate S0
INPUT SO FAR

·

found = 0

3

Try

Make found go high twice using only seven bits. Overlap is allowed: the end of one match can start the next.

BENCH · 7 BITS MAX0 of 7 bits

Two matches in seven bits

Each press adds a bit. Reset to try again.

0 matches.

4

Build

The detector in the two-block pattern. The clocked block only stores the state; the combinational block decides everything.

module det1011 (input clk, rst, bit_in, output found);
  localparam S0 = 3'd0, S1 = 3'd1, S2 = 3'd2, S3 = 3'd3, S4 = 3'd4;
  reg [2:0] state, next;

  always @(posedge clk)                      // 1: state register
    if (rst) state <= S0; else state <= next;

  always @(*) begin                          // 2: next-state logic
    next = state;                            // default: stay
    case (state)
      S0: next = bit_in ? S1 : S0;           // seen ""
      S1: next = bit_in ? S1 : S2;           // seen "1"
      S2: next = bit_in ? S3 : S0;           // seen "10"
      S3: next = bit_in ? S4 : S2;           // seen "101"
      S4: next = bit_in ? S1 : S2;           // seen "1011"
      default: next = S0;
    endcase
  end

  assign found = (state == S4);              // Moore output
endmodule
LAB H4 · 25 MINTest it with a stream

Write a testbench that feeds 1011011 and checks found is high on exactly two clocks.

Show answer

The detector is a Moore machine, so found is high for the clock after the fourth bit of each 1011. The stream 1011011 contains 1011 twice, overlapping on one bit:

module tb;
  reg clk = 0, rst = 1, bit_in = 0; wire found;
  reg [6:0] stream = 7'b1011011;
  integer i, hits = 0;
  det1011 dut (clk, rst, bit_in, found);
  always #5 clk = !clk;
  always @(posedge clk) if (found) hits = hits + 1;
  initial begin
    @(negedge clk) rst = 0;
    for (i = 6; i >= 0; i = i - 1) begin   // first bit first
      bit_in = stream[i]; @(negedge clk);
    end
    @(negedge clk);
    $display("found was high on %0d clocks", hits);
    $finish;
  end
endmodule
found was high on 2 clocks

The overlap works because state S4 goes back to S2 ("seen 10") on a 0, not to S0.

ENCODINGBinary or one-hot

Five states fit in 3 flip-flops (binary) or 5 (one-hot). Yosys can re-encode state machines for you.

IN NANDTIERThe same pattern everywhere

The core's sequencer nt_control (FETCH, DECODE, EXECUTE, MEM, WB) and the flash cache's line fill are written this way.

HDL TRACK · LESSON 5 OF 10

Parameters, generate and hierarchy

Build a design from module instances, make modules configurable with parameters, and let generate decide the structure.

videoparameter bench4 auto-checked questions
2

Explore

A small module with two parameters and a feature switch. Change them and watch what the elaborated design contains.

BENCH · PARAMETERS AND GENERATE
ELABORATED

3

Try

Four questions on instances and parameters.

4

Build

A bank of two-flop synchronizers, one per bit, its width set by a parameter. The generate block is named so the instance paths read well.

module sync_bank #(parameter WIDTH = 8) (
  input              clk,
  input  [WIDTH-1:0] in,
  output [WIDTH-1:0] out
);
  genvar i;
  generate for (i = 0; i < WIDTH; i = i + 1) begin : g_bit
    reg [1:0] s;
    always @(posedge clk) s <= {s[0], in[i]};
    assign out[i] = s[1];
  end endgenerate
endmodule

// use it, overriding the default
sync_bank #(.WIDTH(4)) u_keys (.clk(clk), .in(buttons), .out(keys));
// paths: u_keys.g_bit[0].s ... u_keys.g_bit[3].s
IN NANDTIEROne source, several boards

The top level takes parameters for board differences, and a generate block adds a debug block only where the FPGA supports it.

HABITConnect ports by name

.clk(clk) keeps working when someone reorders the port list.

HDL TRACK · LESSON 6 OF 10

Testbenches and simulation

Write a self-checking testbench, and see how an event-driven simulator orders blocking and non-blocking assignments.

videoevent-queue bench4 auto-checked questionsLab 0B pattern
2

Explore

The same three-stage shift register, written twice. Press Clock edge and compare: with <= each value moves one stage per edge; with = the input races straight through.

BENCH · ONE CLOCK EDGE
always @(posedge clk) begin
  b <= a;
  c <= b;
end

always @(posedge clk) begin
  b = a;
  c = b;
end

THE EVENT QUEUE

edge 0

Within one time step, all blocking work happens first; every non-blocking update is applied at the end, together.

3

Try

Four questions on testbenches and simulators.

4

Build

A complete, self-checking testbench for an 8-bit adder: clock, reset, corner cases, random values, a reference, and a PASS/FAIL line.

`timescale 1 ns / 1 ps
module tb_adder;
  reg  clk = 0, resetn = 0;
  reg  [7:0] a, b;  wire [8:0] y;
  integer i, errors = 0, checks = 0;
  adder8 dut (.a(a), .b(b), .y(y));
  always #20 clk = !clk;                       // 25 MHz

  task check; begin
    #1 checks = checks + 1;
    if (y !== a + b) begin errors = errors + 1;
      $display("FAIL: %h + %h = %h", a, b, y); end
  end endtask

  initial begin
    $dumpfile("tb_adder.vcd"); $dumpvars(0, tb_adder);
    repeat (3) @(posedge clk); resetn = 1;
    a = 0;    b = 0;    check;                 // corner cases
    a = 8'hFF; b = 8'h01; check;
    for (i = 0; i < 1000; i = i + 1) begin   // then random
      a = $random; b = $random; check;
    end
    if (errors == 0) $display("PASS: adder8 (%0d checks)", checks);
    $finish;
  end
endmodule
TWO SIMULATORSIcarus and Verilator

Run the same testbench in both; a design that passes in two is less likely to hide a simulator-dependent bug.

IN NANDTIERDrive, reference, compare

The unit testbenches in the repository follow this pattern and print one PASS line each.

HDL TRACK · LESSON 7 OF 10

cocotb: testbenches in Python

Drive a design from Python with cocotb, let simulated time pass with await, and check against a Python model.

videococotb step-through4 auto-checked questions
2

Explore

Step through a cocotb test. Each step highlights one line and shows what happens to the design and to simulated time.

BENCH · A COCOTB TEST
SIMULATOR

3

Try

Four questions on cocotb.

4

Build

A random test against a Python model, and the Makefile that runs it with Icarus. Change SIM to run it on Verilator.

# test_alu.py
import cocotb, random
from cocotb.triggers import Timer

M = (1 << 32) - 1
def model(a, b): return (a + b) & M

@cocotb.test()
async def add_random(dut):
    dut.op.value = 0                       # ADD
    for _ in range(20000):
        a, b = random.getrandbits(32), random.getrandbits(32)
        dut.a.value = a; dut.b.value = b
        await Timer(1, "ns")
        assert dut.y.value == model(a, b), f"{a:#x} + {b:#x}"

# Makefile
SIM ?= icarus
TOPLEVEL_LANG = verilog
VERILOG_SOURCES = nt_alu.v
TOPLEVEL = nt_alu
MODULE = test_alu
include $(shell cocotb-config --makefiles)/Makefile.sim
INSTALLpip install cocotb

It drives Icarus, Verilator and commercial simulators the same way.

IN THE LABcocotb on the ALU

The lab runs thousands of random operations on the processor's ALU against a Python model.

HDL TRACK · LESSON 8 OF 10

What synthesis does with your code

Predict the hardware a piece of Verilog becomes, know what synthesis ignores, and read its warnings.

videoVerilog-to-hardware bench4 auto-checked questions
2

Explore

Pick a piece of Verilog to see what synthesis builds from it, and what to watch for.

BENCH · VERILOG → HARDWARE
BECOMES

3

Try

Four questions on synthesis.

4

Build

Synthesise a design with Yosys, read the statistics, and check the log for latches.

# synthesise for the Gowin FPGA and print a cell count
yosys -p "read_verilog counter.v; synth_gowin -top counter; stat"

# a quick look at the generic logic, before FPGA mapping
yosys -p "read_verilog counter.v; proc; opt; stat"

# find accidental latches
yosys -p "read_verilog design.v; proc" | grep -i latch

# draw the result
yosys -p "read_verilog full_adder.v; synth_gowin; write_json fa.json"
netlistsvg fa.json -o fa.svg
READ THE LOGWarnings are bugs

A latch warning, a width warning or a signal driven twice usually means the hardware isn't what you meant.

IN NANDTIEROne open tool

Yosys synthesises the whole SoC; Tier 5 reads its reports.

HDL TRACK · LESSON 9 OF 10

SystemVerilog for design

Use logic, always_ff, always_comb, enums, structs, interfaces and packages to say exactly what you mean.

videoVerilog-to-SV bench4 auto-checked questions
2

Explore

Turn a small Verilog block into SystemVerilog, one feature at a time.

BENCH · VERILOG → SYSTEMVERILOG
THIS STEP

3

Try

Four questions on SystemVerilog for design.

4

Build

The traffic light from lesson 0.8, written in SystemVerilog.

typedef enum logic [1:0] {GREEN, YELLOW, RED} light_t;

module traffic (input logic clk, resetn, timer, output light_t state);
  light_t next;

  always_ff @(posedge clk)
    if (!resetn) state <= GREEN;
    else         state <= next;

  always_comb begin
    next = state;
    if (timer) unique case (state)
      GREEN:  next = YELLOW;
      YELLOW: next = RED;
      RED:    next = GREEN;
    endcase
  end
endmodule
TOOLSWhere it works

Commercial tools support the design subset fully; the free tool chain reads much of it, or after conversion to Verilog.

IN NANDTIERPlain Verilog

NandTier is written in Verilog so every free tool builds it, but it follows the same habits.

HDL TRACK · LESSON 10 OF 10

SystemVerilog for verification

Write assertions and cover properties, and see how formal tools, constrained random and coverage build trust.

videohandshake assertion bench4 auto-checked questions
2

Explore

A valid/ready handshake, checked every clock by the property valid && !ready |=> valid. Choose how the sender behaves and when the receiver is ready.

BENCH · VALID / READY
ASSERTION

3

Try

Four questions on verification.

4

Build

Properties for a valid/ready bus: two assertions and a cover. Simulators check them while tests run; formal tools try to break them for every input.

module bus_props (input logic clk, resetn, valid, ready,
                  input logic [31:0] addr);
  default clocking @(posedge clk); endclocking
  default disable iff (!resetn);

  // once valid, hold it until the transfer happens
  a_hold: assert property (valid && !ready |=> valid);

  // and keep the address stable meanwhile
  a_addr: assert property (valid && !ready |=> $stable(addr));

  // show that a transfer happens at all
  c_xfer: cover property (valid && ready);
endmodule

// attach it to a design without touching the design
bind my_bus bus_props u_props (.*);
FORMALSymbiYosys

Runs the same assertions through a solver: a counterexample waveform, or a proof.

NEXTTier 1

You can now read and test Verilog. Tier 1 builds a processor with it.

TIER 1 · CORE · LESSON 1 OF 11

What a CPU actually does

Follow one instruction through fetch, decode, execute and write back, and meet RV32IM.

video4-stage stepper4 quick questions
2

Explore

Five instructions, one stage at a time. Each press of Next stage moves the current instruction through fetch, decode, execute or write back.

BENCH · ONE INSTRUCTION, FOUR STAGESaddi, addi, add, sub, add
WHAT HAPPENS

Ready

3

Try

Four questions about the loop every CPU runs.

0 of 4 correct.

4

Build

The five-line program from the bench, as you would write it in a file. GCC's assembler turns it into the five words you saw fetched.

# five.S : the bench program
    addi a0, x0, 5      # a0 = 5
    addi a1, x0, 7      # a1 = 7
    add  a2, a0, a1     # a2 = 12
    sub  a3, a2, a0     # a3 = 7
    add  a4, a3, a3     # a4 = 14

# riscv-none-elf-as -march=rv32im five.S -o five.o     (the toolchain fw/common.mk uses)
# riscv-none-elf-objdump -d five.o
PRACTICE · 10 MINRead the machine code

Run objdump -d and match each word with the Fetch step on the bench.

Show answer
riscv-none-elf-as -march=rv32im five.S -o five.o
riscv-none-elf-objdump -d five.o

   0:  00500513    li   a0,5
   4:  00700593    li   a1,7
   8:  00b50633    add  a2,a0,a1
   c:  40a606b3    sub  a3,a2,a0
  10:  00d68733    add  a4,a3,a3

objdump shows addi a0, x0, 5 as its alias li a0,5. The words are what the bench's Fetch step shows, one per step, at addresses 0, 4, 8, 12 and 16. sub differs from add only in bit 30 (0x40000000).

RV32IMWhat the letters mean

32-bit registers, the base Integer set, and the M extension for multiply and divide.

IN NANDTIERThe real core

The core in hw/core/ runs these exact words. Lesson 1.9 traces one through the real datapath.

TIER 1 · CORE · LESSON 2 OF 11

Assembly language

Write RISC-V assembly with registers, immediates, loads, stores and branches.

videoRV32IM simulatorgraded challenge on 3 data sets
2

Explore

This is a real RV32IM simulator. Edit the program, press Reset, then Step through it. Changed registers light up.

3

Try

a0 points at five 32-bit words. Leave the largest in a0. The checker runs your code on three data sets, one of them all negative.

4

Build

The sum loop from the video, ready to assemble with the RISC-V GCC toolchain.

# sum.S : a0 = 1 + 2 + ... + 10
    .globl sum10
sum10:
    li   a0, 0          # sum
    li   t0, 1          # i
    li   t1, 10
loop:
    add  a0, a0, t0
    addi t0, t0, 1
    bge  t1, t0, loop   # while i <= 10
    ret                 # a0 = 55
LAB 1A · YOUR FIRST PROGRAMSThree small programs

Sum a range, find a maximum, count the 1 bits in a word. Run each one on the bench first.

Show answer

Measured on the repository's instruction-set simulator (test/core/rv32i_iss.py):

sum_range:              # a0 = a0 + (a0+1) + ... + a1
    mv   t0, a0
    li   a0, 0
1:  bgt  t0, a1, 2f
    add  a0, a0, t0
    addi t0, t0, 1
    j    1b
2:  ret                    # 1..10 -> 55

max_array:              # a0 = largest of a1 signed words at a0
    lw   t0, 0(a0)
    li   t1, 1
1:  bge  t1, a1, 2f
    slli t2, t1, 2         # byte offset = index * 4
    add  t2, t2, a0
    lw   t3, 0(t2)
    ble  t3, t0, 3f
    mv   t0, t3
3:  addi t1, t1, 1
    j    1b
2:  mv   a0, t0
    ret                    # {7, -3, 42, 19, 0, 41} -> 42

popcount:               # a0 = number of 1 bits in a0
    li   t0, 0
1:  beqz a0, 2f
    andi t1, a0, 1
    add  t0, t0, t1
    srli a0, a0, 1         # logical shift: zeros come in
    j    1b
2:  mv   a0, t0
    ret                    # 0xF0F00001 -> 9

Use srli, not srai, in popcount: with an arithmetic shift a negative word never reaches 0 and the loop never ends.

PSEUDO-INSTRUCTIONSli, mv, j, ret

Names the assembler turns into real instructions: mv a, b is addi a, b, 0.

NEXTWatch it in hardware

In lesson 1.9 the same loop runs on the Verilog core, one clock at a time.

TIER 1 · CORE · LESSON 3 OF 11

Branches, loops and functions

Call and return with jal and ret, keep the calling convention, and use the stack.

videorecursive factorial with live stackgraded function
2

Explore

Step through fact(4). Watch sp move down as frames are pushed, and back up as each call returns.

3

Try

Write max2: return the larger of a0 and a1 in a0. The checker calls it four times, each time with a fresh return address.

4

Build

Recursive factorial, keeping the calling convention: ra and the argument saved on the stack, result in a0.

# fact.S : a0 = a0!
fact:
    li   t0, 1
    ble  a0, t0, base       # 0! = 1! = 1
    addi sp, sp, -8         # make a frame
    sw   ra, 4(sp)          # save return address
    sw   a0, 0(sp)          # save n
    addi a0, a0, -1
    call fact               # a0 = (n-1)!
    lw   t1, 0(sp)
    mul  a0, a0, t1         # n * (n-1)!
    lw   ra, 4(sp)
    addi sp, sp, 8          # drop the frame
    ret
base:
    li   a0, 1
    ret
THE CONVENTIONWho saves what

Arguments in a0–a7, result in a0. A function that uses an s register or makes a call saves it first.

PRACTICE · 15 MINIterative vs recursive

Write factorial with a loop instead. Count the instructions each version runs on the bench.

Show answer
fact_loop:              # a0 = a0!, no stack, no calls
    li   t0, 1
1:  li   t1, 1
    ble  a0, t1, 2f
    mul  t0, t0, a0
    addi a0, a0, -1
    j    1b
2:  mv   a0, t0
    ret

Measured for 5! (both return 120): the recursive version runs 52 instructions, the loop 25. The recursive one pays for a stack frame on every call: 5 stores and loads of ra and n, the call and ret. It also needs 8 bytes of stack per level, so a large n can run out of the 8 KiB SRAM; the loop needs none.

IN NANDTIERThe firmware stack

The boot ROM sets sp before calling C code. Tier 3 shows where.

TIER 1 · CORE · LESSON 4 OF 11

Machine code

Split any 32-bit word into its fields, and encode instructions by hand.

videolive decoder3 hand encodings
2

Explore

Type any 32-bit word in hex. The bench picks the format from the opcode and splits the word into its fields.

BENCH · DECODERR-type
0x
DISASSEMBLY

Register fields always sit in the same bits: rd in 11:7, rs1 in 19:15, rs2 in 24:20. Only the immediate moves around.

3

Try

Encode each instruction by hand and type the word in hex. A wrong answer shows what your word really means.

Encodehex, 8 digits
0x

Three instructions

a0 = x10, a1 = x11, a2 = x12, sp = x2. Opcodes: OP-IMM 0010011, OP 0110011, STORE 0100011 (funct3 010 for sw).

4

Build

In Verilog, decoding the register fields is just wiring: each field is a slice of the instruction.

// field slices: no logic, just wires
wire [6:0] opcode = instr[6:0];
wire [4:0] rd     = instr[11:7];
wire [2:0] funct3 = instr[14:12];
wire [4:0] rs1    = instr[19:15];
wire [4:0] rs2    = instr[24:20];
wire [6:0] funct7 = instr[31:25];

wire is_op     = (opcode == 7'b0110011);   // R-type
wire is_sub    = is_op && funct7[5];       // bit 30: add vs sub
PRACTICE · 10 MINDecode a branch

Paste FE0598E3 and work out its offset by hand from the scrambled immediate bits. Lesson 1.7 explains why they are scrambled.

Show answer
FE0598E3 = 1111111 00000 01011 001 10001 1100011
           imm[12|10:5] rs2  rs1  f3  imm[4:1|11] opcode

opcode 1100011 -> branch     funct3 001 -> BNE
rs1 = 01011 = x11 (a1)       rs2 = 00000 = x0 (zero)
imm[12] = 1, imm[11] = 1, imm[10:5] = 111111, imm[4:1] = 1000
imm = 1 1 111111 1000 0 = 0x1FF0 (13 bits) = -16
bne a1, zero, -16      # jump back 4 instructions while a1 != 0

A negative offset with this shape is the bottom of a loop. The bits are scrambled so that imm bit 10:5 and the register fields stay in the same places in every format (lesson 1.7).

FORMATSR I S B U J

Six layouts. Register fields never move, so the register file can be read before the format is known.

IN NANDTIERThe decoder bench

The website's Tier 1 decoder bench does the same split on the real core's instructions.

TIER 1 · CORE · LESSON 5 OF 11

The register file

Thirty-two registers with two read ports and one write port: reads follow the address at once, writes land on the clock edge, and x0 is always zero.

videoregister file bench4 auto-checked questionsdeep dive lab
2

Explore

Pick a register and a value and press Write (clock edge). Then choose what the two read ports look at. Try writing to x0.

BENCH · REGISTER FILE
READ PORTS

3

Try

Four questions on ports and timing.

4

Build

The general shape of a RISC-V register file: an array for x1 to x31, one clocked write, and two reads that are just multiplexers.

module regfile (
  input             clk,
  input      [ 4:0] raddr1, raddr2,
  output     [31:0] rdata1, rdata2,
  input             we,
  input      [ 4:0] waddr,
  input      [31:0] wdata
);
  reg [31:0] regs [1:31];                 // x0 needs no storage

  always @(posedge clk)                   // the write port
    if (we && waddr != 5'd0)
      regs[waddr] <= wdata;

  // two read ports: combinational, and x0 reads as zero
  assign rdata1 = (raddr1 == 5'd0) ? 32'd0 : regs[raddr1];
  assign rdata2 = (raddr2 == 5'd0) ? 32'd0 : regs[raddr2];
endmodule
DEEP DIVEThe register file lab

The full lab, with its RTL, testbench and waveforms: the Register file deep dive.

IN NANDTIERA debug write port

Next to the CPU write port there is one for the debugger, used only while the core is halted.

TIER 1 · CORE · LESSON 6 OF 11

The ALU inside the core

Ten operations from one adder, one shifter and some logic, with a multiplexer choosing the result.

video32-bit ALU bench4 auto-checked questionsdeep dive lab
2

Explore

Set a and b (decimal, or hex with 0x) and pick an operation. Every unit computes all the time; the highlighted one is what the multiplexer passes to y.

BENCH · 32-BIT ALU
THE RESULT

3

Try

Four questions about the ALU.

4

Build

The general shape: subtract and compare share the adder, a case statement is the output multiplexer. The operation code is taken straight from the instruction.

module alu (input [3:0] op, input [31:0] a, b, output reg [31:0] y);
  wire        alt  = op[3];                 // bit 30 of the instruction
  wire [ 2:0] f3   = op[2:0];               // funct3
  wire        sub  = alt || f3 == 3'b010 || f3 == 3'b011;
  wire [32:0] sum  = {1'b0, a} + {1'b0, sub ? ~b : b} + sub;   // a - b = a + ~b + 1
  wire        ltu  = !sum[32];
  wire        lt   = (a[31] != b[31]) ? a[31] : sum[31];

  always @* case (f3)
    3'b000:  y = sum[31:0];                               // add / sub
    3'b001:  y = a << b[4:0];                             // sll
    3'b010:  y = {31'b0, lt};                             // slt
    3'b011:  y = {31'b0, ltu};                            // sltu
    3'b100:  y = a ^ b;
    3'b101:  y = alt ? $signed(a) >>> b[4:0] : a >> b[4:0];   // sra / srl
    3'b110:  y = a | b;
    default: y = a & b;
  endcase
endmodule
DEEP DIVEThe ALU lab

Build and test it yourself: the ALU deep dive.

IN NANDTIEROne shifter for both directions

A left shift is done by reversing the bits, shifting right, and reversing back.

IN NANDTIERBranches use their own comparator

The ALU only serves register and immediate arithmetic. Branch decisions and targets have their own hardware.

TIER 1 · CORE · LESSON 7 OF 11

Immediates

Find the constant inside an instruction, sign-extend it, and build any 32-bit value with lui and addi.

videoimmediate extractor4 auto-checked questionsdeep dive lab
2

Explore

Type an instruction word in hex, or pick one. The bench finds its format from the opcode, collects the immediate bits and sign-extends them.

BENCH · IMMEDIATE EXTRACTOR
THE IMMEDIATE

3

Try

Four questions about immediates.

4

Build

The immediate generator is five ways to arrange bits, chosen by the opcode. Bit 31 is the sign in every format.

wire [31:0] imm_i = {{21{ir[31]}}, ir[30:20]};
wire [31:0] imm_s = {{21{ir[31]}}, ir[30:25], ir[11:7]};
wire [31:0] imm_b = {{20{ir[31]}}, ir[7], ir[30:25], ir[11:8], 1'b0};
wire [31:0] imm_u = {ir[31:12], 12'b0};
wire [31:0] imm_j = {{12{ir[31]}}, ir[19:12], ir[20], ir[30:21], 1'b0};

// and a multiplexer chosen by the opcode
always @* case (1'b1)
  is_lui, is_auipc: imm = imm_u;
  is_jal:           imm = imm_j;
  is_branch:        imm = imm_b;
  is_store:         imm = imm_s;
  default:          imm = imm_i;
endcase

// building a constant: li a0, 0x12345FFF
//   lui  a0, 0x12346      (one bigger, because...)
//   addi a0, a0, -1       (0xFFF sign-extends to -1)
DEEP DIVEDecoder and control

The immediate generator lives in the decoder: the Decoder and control deep dive.

WATCH OUTlui + addi

If bit 11 of the low part is set, addi subtracts, so the upper part has to be one bigger. The assembler handles this for li.

TIER 1 · CORE · LESSON 8 OF 11

The load/store unit

Turn a byte address into a word access with write strobes, pick out and extend the loaded bytes, and catch misaligned accesses.

videolanes and strobes bench4 auto-checked questionsdeep dive lab
2

Explore

Memory holds one word. Pick load or store, a size and an offset. Watch the strobes for a store, and the shifting and extension for a load.

BENCH · LOAD/STORE UNIT
RESULT

3

Try

Four questions about loads and stores.

4

Build

The general shape: a word-aligned bus address, data copied into every lane, a strobe mask, and a shift plus extension for loads.

wire [1:0] size = funct3[1:0];             // 00 byte, 01 half, 10 word
wire [1:0] ofs  = addr[1:0];
assign misaligned = (size == 2'b01 && ofs[0]) || (size == 2'b10 && ofs != 2'b00);
assign bus_addr   = {addr[31:2], 2'b00};

always @* case (size)                      // stores
  2'b00:   begin wdata = {4{store_data[7:0]}};  mask = 4'b0001 << ofs; end
  2'b01:   begin wdata = {2{store_data[15:0]}}; mask = ofs[1] ? 4'b1100 : 4'b0011; end
  default: begin wdata = store_data;            mask = 4'b1111; end
endcase

wire [31:0] shifted = rdata >> {ofs, 3'b000};   // loads
wire        sext    = !funct3[2];               // lb/lh sign-extend, lbu/lhu don't
always @* case (size)
  2'b00:   load = {{24{sext && shifted[7]}},  shifted[7:0]};
  2'b01:   load = {{16{sext && shifted[15]}}, shifted[15:0]};
  default: load = rdata;
endcase
DEEP DIVEThe whole core

The load/store unit inside the core: the Core deep dive.

IN NANDTIERMisaligned means trap

The core doesn't split an access in two. A misaligned load or store stops the core, as lesson 1.11 shows.

TIER 1 · CORE · LESSON 9 OF 11

The whole datapath

Put every part together, and follow instructions through fetch, decode, execute, memory and write back.

videodatapath stepper4 auto-checked questionsModules M3 and M4
2

Explore

Pick an instruction and press Next state. The parts it uses in each state light up.

BENCH · DATAPATH STEPPER
STATE

3

Try

Four questions about the datapath.

4

Build

The control unit is a state machine. Most instructions take fetch, decode and execute; loads and stores add memory and write back.

localparam FETCH = 0, DECODE = 1, EXECUTE = 2, MEM = 3, WB = 4, TRAP = 5;

always @(posedge clk)
  if (!resetn) state <= FETCH;
  else case (state)
    FETCH:   if (bus_done) state <= DECODE;
    DECODE:  state <= EXECUTE;
    EXECUTE: if (exception)    state <= TRAP;
             else if (is_mem)  state <= MEM;
             else if (!md_wait) state <= FETCH;   // commit: write rd and PC
    MEM:     if (bus_done) state <= WB;
    WB:      state <= FETCH;                      // commit a load or store
    TRAP:    state <= TRAP;                       // until reset
  endcase
DEEP DIVEControl, then the core

the Decoder and control deep dive and the Core deep dive.

DESIGN CHOICEMulti-cycle, not pipelined

One instruction at a time is slower, but there are no hazards to handle, and every state can be checked on its own.

TIER 1 · CORE · LESSON 10 OF 11

Multiply and divide

The M extension: a product wide enough for every multiply, division one bit per cycle, and the corner cases RISC-V defines.

videodivider stepper4 auto-checked questions
2

Explore

Choose a dividend and a divisor (8 bits, to keep it short) and press Step. Each step shifts in one bit and tries to subtract.

BENCH · RESTORING DIVISION · 8 BITS
QUOTIENT, REMAINDER

3

Try

Four questions on multiply and divide.

4

Build

One step of restoring division: shift the next dividend bit into the remainder, and keep the subtraction only if it fits.

// each cycle, while count != 0
wire [32:0] rem_sh = {rem, quot[31]};          // shift in the next bit
wire [32:0] diff   = rem_sh - {1'b0, divisor};
wire        fits   = !diff[32];                // no borrow: it fits

always @(posedge clk) if (running) begin
  rem   <= fits ? diff[31:0] : rem_sh[31:0];
  quot  <= {quot[30:0], fits};                 // one quotient bit per cycle
  count <= count - 1;
end

// divide by zero:   quotient = all ones, remainder = dividend
// -2^31 / -1:       quotient = -2^31,    remainder = 0
IN NANDTIERMultiplier blocks

All four multiplies use one product from the FPGA's multiplier blocks. Divides take about 32 cycles.

LATERIs it worth the area?

Tier 3 measures what the M extension costs, and what it saves the firmware.

TIER 1 · CORE · LESSON 11 OF 11

Traps, and trusting the core

What happens when an instruction can't complete, how the core counts cycles, and how it is tested at every level.

videotrap bench4 auto-checked questionsdeep dive lab
2

Explore

Pick an instruction (a0 = 0x1000). The bench says whether it completes, or which cause stops the core.

BENCH · WHAT TRAPS?
RESULT

3

Try

Four questions on traps and testing.

4

Build

Every cause is checked in execute and ORed into one signal. If it is set, the instruction doesn't commit, and the control unit goes to its trap state.

wire exception = illegal_instruction
               || ecall_or_ebreak
               || jump_misaligned
               || (is_load_or_store && mem_misaligned)
               || (csr_access && !csr_allowed);

// in the control unit, at the end of EXECUTE
if (exception) state <= TRAP;          // no commit: rd and PC unchanged

// performance counters
always @(posedge clk) begin
  cycle <= cycle + 1;
  if (commit) instret <= instret + 1;
end
DEEP DIVECSRs and traps

The full lab: the CSRs and traps deep dive.

IN NANDTIERTested at every level

A testbench per core module, assembly and C programs, and random programs checked against an instruction set simulator.

NEXTTier 2: the SoC

The core is done. Next, the bus, memories and peripherals around it.

TIER 2 · SoC · LESSON 1 OF 11

The SoC at a glance

Meet the seven blocks around the core, and read NandTier's memory map.

videolive memory map3 address hunts
2

Explore

Type any 32-bit address, or click a row. The top byte picks the device and the low bits pick a register inside it.

BENCH · NANDTIER MEMORY MAPclick a row
0x
WHO ANSWERS

3

Try

Type the address for each target. The page tells you who answers as you type.

0 of 3.

4

Build

The firmware names every base address once, in a header, so C code never contains a magic number.

// fw/include/nandtier.h (excerpt)
#define NT_FLASH_BASE   0x00000000u     // SPI flash, execute in place
#define NT_SRAM_BASE    0x40000000u     // 8 KiB
#define NT_BOOT_BASE    0x80000000u     // boot RAM, 8 KiB, reset vector
#define NT_GPIO_BASE    0x82000000u
#define NT_UART_BASE    0x83000000u
#define NT_REG(addr)    (*(volatile uint32_t *)(addr))
#define GPIO_OUT        NT_REG(NT_GPIO_BASE + 0x0)
#define GPIO_OE         NT_REG(NT_GPIO_BASE + 0x8)
#define UART_DATA       NT_REG(NT_UART_BASE + 0x0)    // read: byte or 0xFFFFFFFF if none

void led_on(void) { GPIO_OE = 0x3F; GPIO_OUT = ~1u; }   // outputs on; LEDs are active low
MEMORY-MAPPED I/ODevices are addresses

Lighting an LED is a store to 0x8200_0000. No special instructions, just sw.

PRACTICE · 10 MINDraw the map

Sketch the address space from 0 to 0xFFFF_FFFF to scale, then mark where each device sits. Notice how empty it is.

Show answer
0x0000_0000  SPI flash, execute in place (4 MiB on the 9K)
0x4000_0000  SRAM, 8 KiB
0x8000_0000  boot RAM, 8 KiB  <- reset vector
0x8200_0000  GPIO
0x8300_0000  UART
0xC000_0000  SD card (SPI)
0xC100_0000  PPU
0xC200_0000  ILA (64 bytes)

From fw/include/nandtier.h. Drawn to scale, almost everything is empty: about 4 MiB of a 4 GiB space is used, roughly 0.1%. The decoder only looks at the top bits of the address, which is why each device sits on such a round number.

NEXTVolatile

The volatile keyword above is explained in lesson C.4. Two more blocks sit on this bus: the flash config register at 0x8100_0000, and the on-chip logic analyzer at 0xC200_0000 (lesson 6.1).

TIER 2 · SoC · LESSON 2 OF 11

Meet the board

Get to know the Tang Nano 9K, load a bitstream, and blink an LED.

videoblink-rate bench2 auto-checked choicesLab 2A: program the board
2

Explore

The LED is driven by one bit of a counter that adds 1 on every tick of the 27 MHz crystal. Pick the bit and see how fast it blinks.

BENCH · COUNTER → LEDcount[24]
HOW FAST

3

Try

Two choices to get a one-second blink on the real board.

1 · PICK THE BITcount[20]

Choose the bit that gives a full on-and-off blink between 0.8 and 1.6 seconds.

full blink: 0.08 s

2 · The LEDs are active low. Which line lights the LED when the bit is 1?

A one-second blink

bit0.8–1.6 s
polarityactive low

4

Build

Lab 2A: the blink design and its constraints, built with the open tools and loaded over USB.

// blink.v
module blink (input clk, output [5:0] led);
  reg [24:0] count = 0;
  always @(posedge clk) count <= count + 1;   // 27 MHz
  assign led = ~{6{count[24]}};               // active low
endmodule

// tangnano9k.cst
IO_LOC "clk" 52;
IO_LOC "led[0]" 10;  IO_LOC "led[1]" 11;  IO_LOC "led[2]" 13;
IO_LOC "led[3]" 14;  IO_LOC "led[4]" 15;  IO_LOC "led[5]" 16;

# yosys -p "synth_gowin -top blink -json blink.json" blink.v
# nextpnr-himbaechel --json blink.json --write pnr.json \
#   --device GW1NR-LV9QN88PC6/I5 --vopt family=GW1N-9C --vopt cst=tangnano9k.cst
# gowin_pack -d GW1N-9C -o blink.fs pnr.json
# openFPGALoader -b tangnano9k blink.fs
LAB 2A · PROGRAM THE BOARDYour first bitstream

Build blink.fs, load it, then write it to flash with -f and power-cycle the board.

Show answer
openFPGALoader -b tangnano9k blink.fs      # into the FPGA's RAM: lost at power-off
openFPGALoader -b tangnano9k -f blink.fs   # into the configuration flash: survives

Loaded the first way, the LEDs blink until you unplug the board, then the old design comes back. With -f, they blink again after a power cycle. Bit 24 of a 27 MHz counter flips every 2^24 / 27 MHz ≈ 0.62 s, so each LED is on for 0.62 s and off for 0.62 s.

If openFPGALoader cannot find the board on Linux, install the USB rules: setup/setup.sh --udev.

PINSThe constraints file

Port names in Verilog mean nothing to the chip until IO_LOC ties them to pins.

IN NANDTIERSame board folder

NandTier's boards/tangnano9k/ holds the real pin file for HDMI, SD, UART and LEDs.

TIER 2 · SoC · LESSON 3 OF 11

Clocks and reset

Turn 27 MHz into the system clock with a PLL, and release reset cleanly.

videoreset synchronizer benchPLL calculator3 numeric checks
2

Explore

Press reset and every bit clears at once. Release it and clock: a 1 walks in per edge, and the SoC starts only when it reaches bit 15.

BENCH · nt_reset_sync (16 BITS)
PLL · 27 MHz × ÷

WHAT'S HAPPENING

3

Try

NandTier's whole clock plan in three numbers.

0 of 3.

4

Build

The reset synchronizer: assert asynchronously, release synchronously.

// hw/periph/nt_reset_sync.v
module nt_reset_sync #(parameter HOLD_CYCLES = 16) (
    input  clk,
    input  ext_resetn,
    output resetn
);
    reg [HOLD_CYCLES-1:0] hold = {HOLD_CYCLES{1'b0}};
    always @(posedge clk or negedge ext_resetn)
        if (!ext_resetn) hold <= {HOLD_CYCLES{1'b0}};          // clear at once
        else             hold <= {hold[HOLD_CYCLES-2:0], 1'b1}; // a 1 walks in each clock
    assign resetn = hold[HOLD_CYCLES-1];                     // released 16 clocks later
endmodule

// clocks: 27 MHz × 37 ÷ 8 = 124.875 MHz (clk_5x, HDMI)
// 124.875 ÷ 5 = 24.975 MHz (clk_sys: CPU, bus, PPU)
DEEP DIVEClocks and reset

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

ONE DOMAINOne system clock

The CPU, bus and picture unit share clk_sys. Only the HDMI serialisers use clk_5x, from the same PLL and in phase. The one true crossing is the ULX3S's JTAG debug bridge, made safe by a handshake (lesson 6.3).

PRACTICE · 10 MINSimulate the release

Testbench: pulse ext_resetn low between clock edges and check rst falls exactly 16 edges later.

Show answer
module tb;
  reg clk = 0, ext_resetn = 1; wire resetn; integer edges;
  nt_reset_sync dut (.clk(clk), .ext_resetn(ext_resetn), .resetn(resetn));
  always #20 clk = !clk;
  initial begin
    #30 ext_resetn = 0;            // between two edges: asynchronous assert
    #1  if (resetn !== 0) $display("FAIL: reset not immediate");
    #25 ext_resetn = 1;            // release
    edges = 0;
    while (resetn !== 1) begin @(posedge clk); edges = edges + 1; #1; end
    $display("released after %0d rising edges", edges);
    $finish;
  end
endmodule
released after 16 rising edges

hold is a 16-bit shift register (HOLD_CYCLES = 16). Reset goes active at once, without waiting for a clock, but it is only released after sixteen 1s have shifted in, always on a clock edge.

IN NANDTIERTiming budget

40 ns per tick is why the carry chain from lesson 0.4 matters. Lesson 5.7 reads the real timing report.

TIER 2 · SoC · LESSON 4 OF 11

The bus: handshake

Read a bus waveform: valid, ready, wait states and write strobes.

videowaveform bench3 strobe patterns
2

Explore

Pick a device and a transfer. The highlighted column is the edge where valid and ready are both 1: the transfer is done.

THIS TRANSFER

3

Try

Set wstrb[3:0] for each store. Bit n enables byte lane n of the word.

0 of 3.

4

Build

The bus is a handful of wires and one rule. Here is what a simple device looks like from the bus side.

// a device on the bus, cut down from hw/periph/nt_gpio.v (the real one has OUT, IN and OE for 7 pins)
module leds (
    input             clk, resetn,
    input             valid,
    input      [31:0] addr, wdata,
    input      [ 3:0] wstrb,
    output reg        ready,
    output     [31:0] rdata,
    output reg  [5:0] led
);
    always @(posedge clk) begin
        ready <= 1'b0;
        if (!resetn) led <= 6'b111111;                 // LEDs off (active low)
        else if (valid && !ready) begin               // answer one cycle after valid,
            ready <= 1'b1;                                 // like nt_gpio and the RAMs
            if (wstrb[0]) led <= wdata[5:0];
        end
    end
    assign rdata = {26'd0, led};
endmodule
// the UART, the PPU and the SD port answer in the same cycle instead: assign ready = valid;
DEEP DIVEBus and address map

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

THE RULEvalid and ready

A transfer completes on the clock edge where both are 1. Everything else is held steady until then.

DECODERhit & ~(hit − 1)

Keeps only the lowest matching device. No match: ready at once, rdata = 0.

LAB 2B · PERIPHERAL TESTBENCHESTest a device alone

Drive valid/addr/wstrb from a testbench and check ready and rdata, before connecting it to the CPU.

Show answer
module tb;
  reg clk = 0, resetn = 0, valid = 0; reg [31:0] addr = 0, wdata = 0; reg [3:0] wstrb = 0;
  wire ready; wire [31:0] rdata; wire [5:0] led;
  leds dut (clk, resetn, valid, addr, wdata, wstrb, ready, rdata, led);
  always #20 clk = !clk;
  task write(input [31:0] d); begin
    @(negedge clk) begin valid = 1; wdata = d; wstrb = 4'b0001; end
    @(posedge clk); #1 while (!ready) begin @(posedge clk); #1; end
    @(negedge clk) begin valid = 0; wstrb = 0; end
  end endtask
  initial begin
    #100 resetn = 1;
    if (led !== 6'b111111) $display("FAIL: LEDs not off after reset");
    write(32'h15);
    if (led !== 6'h15) $display("FAIL: led = %b", led);
    $display("done"); $finish;
  end
endmodule

Check three things: the reset value, that ready comes one cycle after valid and lasts one cycle, and that a write without wstrb[0] changes nothing. The real tests for every peripheral are in test/periph/ (make -C test periph).

TIER 2 · SoC · LESSON 5 OF 11

The address decoder and memory map

How one bus reaches the right device: regions, base and mask, two levels of decoding, and what happens at an address nobody owns.

videoaddress decoder bench4 auto-checked questionsdeep dive lab
2

Explore

Type any 32-bit address in hex, or pick one. The bench runs the same two-level decode as the SoC: the top two bits pick a region, then the next bits pick the device.

BENCH · ADDRESS DECODER
WHO ANSWERS

3

Try

Four questions about decoding.

4

Build

The general shape of a four-slot decoder: compare under a mask, keep the lowest hit, steer valid, and answer unmapped accesses at once.

module bus_decode4 #(
  parameter [31:0] BASE0 = 32'h0000_0000, MASK0 = 32'hC000_0000,
  parameter [31:0] BASE1 = 32'h4000_0000, MASK1 = 32'hC000_0000,
  parameter [31:0] BASE2 = 32'h8000_0000, MASK2 = 32'hC000_0000,
  parameter [31:0] BASE3 = 32'hC000_0000, MASK3 = 32'hC000_0000
) (
  input         m_valid,  input [31:0] m_addr,
  output        m_ready,  output [31:0] m_rdata,
  output  [3:0] s_valid,  input  [3:0] s_ready,
  input  [31:0] s0_rdata, s1_rdata, s2_rdata, s3_rdata
);
  wire [3:0] hit = {(m_addr & MASK3) == (BASE3 & MASK3),
                    (m_addr & MASK2) == (BASE2 & MASK2),
                    (m_addr & MASK1) == (BASE1 & MASK1),
                    (m_addr & MASK0) == (BASE0 & MASK0)};
  wire [3:0] sel = hit & ~(hit - 4'd1);         // keep the lowest hit: one hot

  assign s_valid = {4{m_valid}} & sel;           // only valid is steered
  assign m_ready = (sel == 4'd0) ? m_valid       // unmapped: answer at once...
                                 : |(s_ready & sel);
  assign m_rdata = ({32{sel[0]}} & s0_rdata) | ({32{sel[1]}} & s1_rdata)
                 | ({32{sel[2]}} & s2_rdata) | ({32{sel[3]}} & s3_rdata);   // ...with 0
endmodule
DEEP DIVEThe bus lab

Build and test the bus yourself: the Bus deep dive.

IN NANDTIERTwo levels

One decoder on bits 31:30, then one inside 0x8… and one inside 0xC…, each on bits 27:24 or 31:24.

WATCH OUTAliases are real

Bits the decoder ignores make copies of a device elsewhere in the map. A wrong pointer can still reach real hardware.

TIER 2 · SoC · LESSON 6 OF 11

SRAM and boot RAM

Block RAMs in four byte lanes, one-cycle reads, and a boot program that lives in the bitstream.

videobench4 auto-checked questions
2

Explore

Pick a store size and an offset. The four lanes show which ones are written, and the word you would read back.

BENCH · BYTE LANES
WORD

3

Try

Four quick questions.

4

Build

The general shape: four 8-bit RAMs side by side, each with its own write enable from the bus strobes.

reg [7:0] lane0 [0:DEPTH-1], lane1 [0:DEPTH-1], lane2 [0:DEPTH-1], lane3 [0:DEPTH-1];

always @(posedge clk) begin
  if (valid && wstrb[0]) lane0[addr] <= wdata[ 7: 0];
  if (valid && wstrb[1]) lane1[addr] <= wdata[15: 8];
  if (valid && wstrb[2]) lane2[addr] <= wdata[23:16];
  if (valid && wstrb[3]) lane3[addr] <= wdata[31:24];
  rdata <= {lane3[addr], lane2[addr], lane1[addr], lane0[addr]};   // ready next cycle
  ready <= valid;
end

// boot RAM: the same, plus initial contents from the build
initial $readmemh("brom_lane0.hex", lane0);
DEEP DIVEMemories

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

IN NANDTIERBoot RAM is in the bitstream

Rebuilding the boot ROM updates the RAM contents, so the bitstream must be rebuilt too.

LABThe bus lab

the Bus deep dive covers how memories hang off the bus.

Show answer

This card points to the deep dive for lessons 2.4 and 2.5. Open it and check yourself against its exercises: which address bits the decoder looks at, and what a read from an unused address returns.

TIER 2 · SoC · LESSON 7 OF 11

The UART

Start bit, eight data bits, stop bit: serial bytes, a baud divider, and a receive FIFO.

videobench4 auto-checked questions
2

Explore

Type a character. The bench draws the frame the transmitter sends: idle high, a start bit, eight data bits lowest first, and a stop bit.

BENCH · UART FRAME
BITS

3

Try

Four quick questions.

4

Build

The general shape of a transmitter: a divider counts out each bit time, and a shift register sends ten bits.

reg [15:0] cnt;  reg [3:0] bitn;  reg [9:0] sh;  reg busy;
assign tx = busy ? sh[0] : 1'b1;               // idle high

always @(posedge clk)
  if (!busy && start) begin
    sh <= {1'b1, data, 1'b0};                  // stop, data (LSB first), start
    busy <= 1; bitn <= 0; cnt <= div - 1;
  end else if (busy) begin
    if (cnt == 0) begin
      cnt <= div - 1; sh <= {1'b1, sh[9:1]}; bitn <= bitn + 1;
      if (bitn == 9) busy <= 0;
    end else cnt <= cnt - 1;
  end
DEEP DIVEUART

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

IN NANDTIERTwo places at once

Every byte written to the UART is also drawn as text on the HDMI screen.

WATCH OUTEmpty reads

Reading the data register with nothing in the FIFO returns all ones, not zero.

TIER 2 · SoC · LESSON 8 OF 11

GPIO

Output, input and direction registers, high impedance, and why inputs need a synchronizer.

videobench4 auto-checked questions
2

Explore

Toggle the OUT and OE bits, and press the button on pin 5. IN shows the level on each pin: driven pins read back what you drive.

BENCH · GPIO PINS
REGISTERS

3

Try

Four quick questions.

4

Build

The general shape: three registers, tri-state pins, and a two-flop synchronizer on the inputs.

reg  [N-1:0] out, oe;
wire [N-1:0] pin_in;
reg  [N-1:0] s1, s2;                         // synchronizer

genvar i;
generate for (i = 0; i < N; i = i + 1) begin : g
  assign pin[i] = oe[i] ? (out[i] ^ INVERT[i]) : 1'bz;   // drive, or let go
end endgenerate

always @(posedge clk) begin
  s1 <= pin;  s2 <= s1;                        // two flops: metastability settles
end
// register reads: 0x0 OUT, 0x4 IN (= s2), 0x8 OE
DEEP DIVEGPIO

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

IN NANDTIERActive-low LEDs

An INVERT parameter flips pins in hardware, so firmware always writes 1 for on.

WATCH OUTRead-modify-write

Change one bit with |= or &= ~ so the other pins keep their values.

TIER 2 · SoC · LESSON 9 OF 11

The SD card port

SPI on four wires, a one-byte engine, and the start-up script that wakes a card.

videobench4 auto-checked questions
2

Explore

Press Next to send each step of the start-up script. The bytes on MOSI and the card's answers on MISO appear below.

BENCH · SD START-UP
STEP

3

Try

Four quick questions.

4

Build

Every command is six bytes, then the card answers with a status byte (R1). This is plain C on top of the byte engine.

static uint8_t spi(uint8_t b) {
    SD_DATA = b;                         // start an 8-bit swap
    while (SD_CTRL & SD_BUSY) ;
    return SD_DATA;                      // the byte that came back
}

static uint8_t sd_cmd(uint8_t cmd, uint32_t arg, uint8_t crc) {
    spi(0x40 | cmd);
    spi(arg >> 24); spi(arg >> 16); spi(arg >> 8); spi(arg);
    spi(crc);
    for (int i = 0; i < 8; i++) {        // wait for the R1 status byte
        uint8_t r = spi(0xFF);
        if (!(r & 0x80)) return r;
    }
    return 0xFF;
}
DEEP DIVESD card over SPI

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

IN NANDTIERHardware moves bytes

The commands, retries and checks are all software, in fw/common.

WATCH OUTStart slowly

A card must start below 400 kHz; only then is the clock divider lowered.

TIER 2 · SoC · LESSON 10 OF 11

Running code from flash

Execute in place, and the prefetch and cache that make it fast.

videobench4 auto-checked questions
2

Explore

Pick a loop and press Run. Each fetch is a hit (1 cycle) or a miss (a line read from flash). The first pass misses; later passes hit.

BENCH · FLASH CACHE
CYCLES

3

Try

Four quick questions.

4

Build

The general shape of a direct-mapped lookup: split the address, compare one tag, and fill the line on a miss.

wire [TAG_W-1:0]  tag  = addr[31 -: TAG_W];
wire [LINE_W-1:0] line = addr[OFS_W +: LINE_W];
wire [OFS_W-1:0]  ofs  = addr[OFS_W-1:0];

wire hit = valid_bits[line] && tags[line] == tag;

always @(posedge clk)
  if (req && hit)  rdata <= data[{line, ofs[OFS_W-1:2]}];   // one cycle
  else if (req)    start_fill(line, tag);                   // read the line from flash

// after the flash is programmed: forget everything
always @(posedge clk) if (invalidate) valid_bits <= 0;
DEEP DIVESPI flash and read cache

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

IN NANDTIERPrefetch and dual I/O

The flash reader keeps going after each word and uses two data lines, so even misses are cheaper.

WATCH OUTStale code

After programming the flash, the cache must be emptied or the CPU runs old instructions.

TIER 2 · SoC · LESSON 11 OF 11

Power-on to a game

Every Tier 2 block in order, from the bitstream to a game on the screen.

videobench4 auto-checked questions
2

Explore

Press Next to step from power-on to a running game. Each step lights the block that is busy.

BENCH · POWER-ON
STEP

3

Try

Four quick questions.

4

Build

The boot ROM's main decision, in the general shape: listen briefly for a programmer, otherwise jump to flash.

int main(void) {
    uart_init(NT_UART_BAUD);
    if (programmer_says_hello(TIMEOUT_CYCLES))   // someone on the UART?
        isp_receive_and_write();                 // load new code
    void (*launcher)(void) = (void (*)(void))0x00000000;
    launcher();                                  // flash, through the cache
}
NEXTTier 3

Each program in this chain gets its own lesson: boot ROM, launcher and games.

IN NANDTIERTwo screens at once

The launcher's menu goes to the UART, and the UART is mirrored on HDMI.

C TRACK · C FOR HARDWARE · LESSON 1 OF 10

C for hardware people

Use exact-width types, and know what a value looks like in memory.

videotype explorer3 numeric checks
2

Explore

Pick a type and type any whole number. The bench shows what the variable really holds, its range, and its bytes in memory.

value

WHAT'S STORED

3

Try

Work these out before you check them on the bench.

4

Build

Hello, world on NandTier: no printf, no terminal, just bytes to the UART data register.

#include <stdint.h>
#define UART_DATA (*(volatile uint32_t *)0x83000000u)

static void uart_putc(char c) { UART_DATA = (uint8_t)c; }
static void uart_puts(const char *s) { while (*s) uart_putc(*s++); }

int main(void) {
    uart_puts("Hello from NandTier\r\n");
    for (;;) ;          // no OS to return to
}

// laptop:  gcc -Wall -O2 test.c && ./a.out
// board:   riscv-none-elf-gcc -march=rv32i -mabi=ilp32 -O2 ...   (fw/common.mk)
LAB C1 · 20 MINHello over UART

Build the program above for the board and watch it in a serial terminal at 115,200 baud.

Show answer

Give the program its own folder, fw/hello/, with the code as main.c and this Makefile. It reuses the launcher's start-up code and linker script, so it runs from the flash like the launcher:

NAME     = hello
SRCS     = start.S main.c
LDSCRIPT = ../fw-flash/flash.ld
OPT      = -O2
vpath %.S ../common
include ../common.mk
.DEFAULT_GOAL := all
all: $(BUILD)/$(NAME).elf $(BUILD)/$(NAME).v
make -C fw/hello
python3 sw/nandtier-programmer.py fw/hello/build/hello.v /dev/ttyUSB1   # then press reset
picocom -b 115200 /dev/ttyUSB1     # Windows: COM5, in PuTTY at 115200 8N1
Hello from NandTier

If you see garbage instead, the baud rates differ: the UART starts at 217 cycles per bit (24.975 MHz / 115,200), so set the terminal to 115,200. On the Tang Nano the UART is the second USB serial port, usually /dev/ttyUSB1. This replaces the launcher in the flash; make program puts it back.

SIZES ON NANDTIERILP32

int, long and pointers are 32 bits. Use uint32_t when the size matters.

IN NANDTIERThe launcher does this

The launcher's console.c builds print, print_hex and print_dec on exactly this store. The firmware is compiled for RV32I (-march=rv32i), so it also runs on bitstreams without the M extension; the core itself is RV32IM. Lesson 3.8 weighs that choice.

C TRACK · C FOR HARDWARE · LESSON 2 OF 10

Bits in C

Set, clear, toggle and test bits, and read or write a field with shifts and masks.

videobit-operation bench3 field extractions
2

Explore

Click a bit to choose n, pick an operation, then press Apply. The C line shows exactly what runs.

THE REGISTER

3

Try

Decode 0x40D60733 in your head, or on paper, with shift and mask.

4

Build

Small inline helpers keep the masks in one place. Field access is shift then mask, or clear then OR.

#include <stdint.h>
static inline void     bit_set(volatile uint32_t *r, unsigned n)   { *r |=  (1u << n); }
static inline void     bit_clear(volatile uint32_t *r, unsigned n) { *r &= ~(1u << n); }
static inline void     bit_toggle(volatile uint32_t *r, unsigned n){ *r ^=  (1u << n); }
static inline unsigned bit_test(uint32_t r, unsigned n)            { return (r >> n) & 1u; }

// fields: read = shift then mask, write = clear then OR
static inline uint32_t field_get(uint32_t r, unsigned lo, unsigned w) { return (r >> lo) & ((1u << w) - 1); }
static inline uint32_t field_set(uint32_t r, unsigned lo, unsigned w, uint32_t v) {
    uint32_t m = ((1u << w) - 1) << lo;
    return (r & ~m) | ((v << lo) & m);
}
// rd of an instruction: field_get(instr, 7, 5)
PRACTICE · 15 MINA tiny disassembler

Use field_get to print rd, rs1, rs2 and funct3 for the words from lesson 1.4.

Show answer
#include <stdio.h>
#include <stdint.h>
/* bit_set ... field_get from the lesson */

int main(void) {
    const uint32_t words[] = { 0x00500513, 0x00700593, 0x00b50633, 0x40a606b3, 0x00d68733 };
    for (unsigned i = 0; i < 5; i++) {
        uint32_t w = words[i];
        printf("%08x  rd=%2u rs1=%2u rs2=%2u funct3=%u\n", w,
               field_get(w, 7, 5), field_get(w, 15, 5),
               field_get(w, 20, 5), field_get(w, 12, 3));
    }
}
00500513  rd=10 rs1= 0 rs2= 5 funct3=0
00700593  rd=11 rs1= 0 rs2= 7 funct3=0
00b50633  rd=12 rs1=10 rs2=11 funct3=0
40a606b3  rd=13 rs1=12 rs2=10 funct3=0
00d68733  rd=14 rs1=13 rs2=13 funct3=0

For the first two (addi), "rs2" is really the low bits of the immediate: the field exists only in R-type instructions. That is why a disassembler decodes the opcode first.

UNSIGNEDAlways for bits

Right-shifting a negative int copies the sign bit. Use uint32_t and the u suffix.

IN NANDTIERSame masks as Verilog

instr[11:7] in the core is (instr >> 7) & 0x1F in C.

C TRACK · C FOR HARDWARE · LESSON 3 OF 10

Pointers, arrays and structs

Follow pointers to bytes, and predict how the compiler lays out a struct.

videostruct layout benchgraded reorder
2

Explore

Add fields and watch the layout. Each square is one byte; dashed squares are padding the compiler inserts to keep fields aligned.

LAYOUT

3

Try

Reorder these four fields so the struct takes only 8 bytes.

BENCH · REORDER↑ ↓ to move

Shrink it to 8 bytes

Same four fields, no packing tricks. Only the order changes.

4

Build

A struct laid over the UART's registers, with a static assert so a layout change can never slip through.

#include <stdint.h>
typedef struct {
    uint32_t data;      // +0  UART_DATA: write a byte, read a byte or 0xFFFFFFFF
    uint32_t div;       // +4  UART_DIV:  217 for 115,200 baud
} uart_regs;
_Static_assert(sizeof(uart_regs) == 8, "UART register layout");

#define UART ((volatile uart_regs *)0x83000000u)

void uart_init(void) { UART->div = 217; }   // 24.975 MHz / 115,200 ≈ 217
PRACTICE · 10 MINPrint the offsets

Use offsetof from <stddef.h> to print each field's offset, and check them against the bench.

Show answer
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
typedef struct { uint32_t data; uint32_t div; } uart_regs;

int main(void) {
    printf("data at +%zu, div at +%zu, size %zu\n",
           offsetof(uart_regs, data), offsetof(uart_regs, div), sizeof(uart_regs));
}
data at +0, div at +4, size 8

These match the bench: UART_DATA at 0x8300_0000 and UART_DIV at 0x8300_0004. If you put a uint8_t field between them, div moves to +4 anyway, because the compiler pads to keep a uint32_t aligned. The _Static_assert in the lesson catches a change like that at compile time.

ALIGNMENTWhy the gaps

NandTier's load/store unit only does aligned word accesses. Misaligned structs would need two.

IN NANDTIEROffsets work too

nandtier.h names the PPU's registers by offset instead, PPU_REG(PPU_SCROLL_X). Both styles compile to the same single store. Tier 4.

C TRACK · C FOR HARDWARE · LESSON 4 OF 10

Memory-mapped registers and volatile

Drive hardware from C, and see exactly what volatile changes in the compiled code.

videovolatile on/off benchLED register bench2 checks
2

Explore

Turn volatile on or off, then send a byte to the UART. Without it, the optimized loop never sees the byte.

gcc -O2

GPIO_OUT (active low)
0x
3

Try

Two checks: one value to write, one keyword to place.

1 · LIGHT LED0 AND LED2 ONLY
GPIO_OUT = 0x ;

2 · Which of these needs volatile?

Two checks

LEDs0 and 2
volatilewhere

4

Build

Every hardware register is declared volatile, once, in the header.

#include <stdint.h>
typedef struct { uint32_t out, in, oe; } gpio_regs;      // +0, +4, +8
#define GPIO ((volatile gpio_regs *)0x82000000u)
#define UART_DATA (*(volatile uint32_t *)0x83000000u)

int uart_getc(void) {                  // wait for one byte
    int c;
    while ((c = (int)UART_DATA) == -1) ;
    return c;
}

int main(void) {
    GPIO->oe = 0x3F;                    // six LEDs are outputs
    for (;;) GPIO->out = ~(uint32_t)uart_getc() & 0x3F;   // show each byte on the LEDs
}
LAB C3 · 25 MINBytes on the LEDs

Type characters in the serial terminal and watch their low six bits light up on the board.

Show answer

Build and program it like lab C1. Each key lights the low six bits of its ASCII code (the LEDs are active low, which is why the code inverts):

key  ASCII      low 6 bits  LEDs (5..0)
'A'  0x41      00 0001     .....#
'a'  0x61      10 0001     #....#
'0'  0x30      11 0000     ##....
' '  0x20      10 0000     #.....
'?'  0x3F      11 1111     ######

Upper and lower case letters differ only in bit 5 (0x20), which you can see as one LED.

CHECK THE ASSEMBLYobjdump -d

Build with and without volatile at -O2. Find the lw inside the loop, or its absence.

IN NANDTIERnandtier.h

fw/include/nandtier.h defines every register once, through NT_REG(): a cast to volatile uint32_t *. All three programs include it.

C TRACK · LESSON 5 OF 10

From C to bytes

Preprocessor, compiler, assembler and linker, the sections, and the calling convention.

videobench4 auto-checked questions
2

Explore

Press Next to send a tiny function through each tool and see what comes out.

BENCH · TOOLCHAIN
STEP

3

Try

Four quick questions.

4

Build

The same steps the Makefiles run, one tool at a time.

riscv64-unknown-elf-gcc -E main.c -o main.i              # preprocess
riscv64-unknown-elf-gcc -S -O2 -march=rv32i -mabi=ilp32 main.i   # compile: main.s
riscv64-unknown-elf-as main.s -o main.o                     # assemble
riscv64-unknown-elf-ld -T link.ld start.o main.o -o prog.elf   # link
riscv64-unknown-elf-objcopy -O binary prog.elf prog.bin     # bytes
riscv64-unknown-elf-objdump -d prog.elf                     # read it back
LABFirmware builds

Run make in fw/ and open the .map and .lst files next to each ELF.

Show answer

Each program's build/ folder has a .map and a .lst next to its ELF. In the .map, find where each section landed and how big it is; in the .lst, find a C function and the instructions it became. For example fw/fw-flash/build/fw-flash.map shows main at 0x00000188 (in the flash) and .bss at 0x4000000c (in the SRAM) when built with GCC 14.2. Your addresses may differ slightly with another compiler version.

CONVENTIONRegisters

a0–a7 arguments, a0 result, ra return address, sp stack, s0–s11 saved.

C TRACK · LESSON 6 OF 10

The linker script and startup code

Memory regions, load and run addresses, and everything that happens before main.

videobench4 auto-checked questions
2

Explore

Toggle where .data runs. Its initial values always live in flash; the startup code copies them to RAM before main.

BENCH · SECTIONS
STARTUP

3

Try

Four quick questions.

4

Build

The general shape of a bare-metal start.S: stack, gp, copy .data, clear .bss, call main.

    .section .text.start
    .globl _start
_start:
    la   sp, _stack_top
    la   gp, __global_pointer$
    la   a0, _data_load          # copy .data: flash -> RAM
    la   a1, _data_start
    la   a2, _data_end
1:  bge  a1, a2, 2f
    lw   t0, 0(a0);  sw t0, 0(a1)
    addi a0, a0, 4;  addi a1, a1, 4;  j 1b
2:  la   a0, _bss_start          # clear .bss
    la   a1, _bss_end
3:  bge  a0, a1, 4f
    sw   zero, 0(a0);  addi a0, a0, 4;  j 3b
4:  call main
5:  j    5b
IN NANDTIERKEEP(.text.start)

The startup section is placed first and kept, so the entry point is where the jump lands.

CASE STUDY5.8 The black screen

What happens when this goes wrong.

C TRACK · LESSON 7 OF 10

Writing a driver

A UART driver in layers: registers, init, putc, getc, blocking, non-blocking and timeouts.

videobench4 auto-checked questions
2

Explore

Call the driver functions. Each call shows the register reads and writes it turns into.

BENCH · UART DRIVER
BUS

3

Try

Four quick questions.

4

Build

A complete little driver, in the general shape.

void uart_init(uint32_t baud) { UART_DIV = (NT_CLK_HZ + baud / 2) / baud; }
void uart_putc(int c)          { UART_DATA = (uint8_t)c; }       // the bus waits if busy
int  uart_getc(void) {
    uint32_t v = UART_DATA;
    return v == 0xFFFFFFFFu ? -1 : (int)(v & 0xFF);
}
void uart_puts(const char *s)  { while (*s) uart_putc(*s++); }
void uart_hex(uint32_t v) {
    for (int i = 28; i >= 0; i -= 4) uart_putc("0123456789ABCDEF"[(v >> i) & 15]);
}
PATTERNOne header per device

Register addresses live in nandtier.h; only drivers include the details.

NEXTFixed point

The next lesson does maths without an FPU.

C TRACK · LESSON 8 OF 10

Fixed-point math

Fractions without an FPU: formats, multiply and shift, rounding and lookup tables.

videobench4 auto-checked questions
2

Explore

Enter two decimal numbers and pick a format. The bench shows the stored integers and the results of add, multiply and divide.

BENCH · FIXED POINT
Q FORMAT

3

Try

Four quick questions.

4

Build

Small helpers for 16.16, using a 64-bit product so nothing overflows.

typedef int32_t fx;                            // 16.16
#define FX(x)      ((fx)((x) * 65536))
#define FX_INT(a)  ((a) >> 16)
static inline fx fx_mul(fx a, fx b) { return (fx)(((int64_t)a * b + 0x8000) >> 16); }
static inline fx fx_div(fx a, fx b) { return (fx)(((int64_t)a << 16) / b); }
COSTWithout M

Every multiply is a call to __mulsi3; lesson 3.8 measures the difference.

TIPSub-pixels

Keep positions with a few fraction bits; draw at pos >> 4.

C TRACK · LESSON 9 OF 10

Speed and size

Measure first, then optimise: cycles, the cache, data size, dead code and the stack.

videobench4 auto-checked questions
2

Explore

Pick versions of the same loop. The bench compares their cycles and code size.

BENCH · CYCLES AND BYTES
MEASURED

3

Try

Four quick questions.

4

Build

Measuring a piece of code with the cycle counter.

uint32_t t0 = nt_cycles();
for (int i = 0; i < N; i++) sum += table[i];
uint32_t cycles = nt_cycles() - t0;
uart_puts("cycles: "); uart_hex(cycles);

// build flags that matter
// -O2 or -Os, -ffunction-sections -fdata-sections, -Wl,--gc-sections,--print-memory-usage
RULEMeasure first

Change one thing, measure again, keep it only if it helped.

WATCH OUTThe stack

Paint it at startup and check how much was used.

C TRACK · LESSON 10 OF 10

Debugging bare metal

UART prints, LEDs, simulation, classic bugs, the PC and bisecting.

videobench4 auto-checked questions
2

Explore

A firmware stops after "install slot 2". Press Next to follow the investigation, one experiment at a time.

BENCH · INVESTIGATION
STEP

3

Try

Four quick questions.

4

Build

Two small helpers worth keeping in every project.

#define TRACE(s)   do { uart_puts(s); uart_putc('\n'); } while (0)
#define STAGE(n)   (GPIO_OUT = (1u << (n)))      // breadcrumbs on the LEDs

void paint_stack(void) {                          // check stack use later
    extern uint32_t _stack_bottom[], _stack_top[];
    for (uint32_t *p = _stack_bottom; p < _stack_top - 64; p++) *p = 0xDEADBEEF;
}
NEXTTier 6

A logic analyser on the bus, and halting the CPU over JTAG.

HABITOne change at a time

If you do not know why it is fixed, it probably is not.

TIER 3 · FIRMWARE · LESSON 1 OF 9

Three programs, one chip

Know where the boot ROM, the launcher and a cartridge live, and how control passes between them.

videomemory-layout benchgraded hand-off order
2

Explore

Pick a program to see where its code, data and stack sit in NandTier's three memories.

LINKER SCRIPT

3

Try

Click the programs in the order they run after power-on.

4

Build

The three linker scripts, cut down to the lines that decide where each program lives.

/* fw/fw-brom/brom.ld : everything in boot RAM */
MEMORY { BOOT (rwx) : ORIGIN = 0x80000000, LENGTH = 8K }

/* fw/fw-flash/flash.ld : code in flash (XIP), data in SRAM (RAM) */
MEMORY { FLASH (rx)  : ORIGIN = 0x00000000, LENGTH = 1M
         RAM   (rwx) : ORIGIN = 0x40000000, LENGTH = 8K }

/* fw/sdk/cart.ld : code in the cartridge slot */
MEMORY { FLASH (rx)  : ORIGIN = 0x00100000, LENGTH = 1M
         RAM   (rwx) : ORIGIN = 0x40000000, LENGTH = 8K }
LAB 3A · BUILD AND INSPECTRead the map files

Build all three programs and find main, .bss and __stack_top in each .map file.

Show answer

Measured with GCC 14.2 (another compiler version moves things a few bytes):

program          main         .bss                 __stack_top
boot ROM         0x80000220   0x80000910 (260 B)   0x80002000  top of boot RAM
launcher         0x00000188   0x4000000c (4.2 KiB) 0x40001ff0  top of SRAM - 16
Snake (a game)   0x00101824   0x40000008 (3.3 KiB) 0x40001ff0  top of SRAM - 16

The boot ROM runs entirely from boot RAM. The launcher and the games run from flash but keep their variables and stack in the SRAM, and leave its last 16 bytes for the handoff message. That is why they cannot both be running: they use the same SRAM.

HAND-OFFThe last 16 bytes

A game leaves a message at 0x4000_1FF0 for the launcher when it quits.

IN NANDTIERTier 5's bug

A cartridge whose _start isn't first gives a black screen. Lesson 5.8.

TIER 3 · FIRMWARE · LESSON 2 OF 9

The boot ROM

Follow the first code after reset: start-up, the UART window, and flash rescue.

videoboot ROM stepper3 checks
2

Explore

Step through the boot ROM. Tick programmer attached to send 0x55 during the half-second window.

WHAT IT DOES

LOG

3

Try

Three numbers the boot ROM depends on.

4

Build

The first instructions the CPU ever runs: fw/fw-brom/start.S.

_start:
    j    reset
    .org 0x54
flash_io_entry:                # 0x8000_0054: called by the launcher too
    j    flash_io
reset:
    la   sp, __stack_top       # top of the boot RAM
    la   t0, __bss_start
    la   t1, __bss_end
1:  bgeu t0, t1, 2f            # clear .bss, one word at a time
    sw   zero, 0(t0)
    addi t0, t0, 4
    j    1b
2:  call main                  # isp.c: listen 500 ms for 0x55
DEEP DIVEBoot ROM

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

LAB 3B · 20 MINWatch it boot

Open a serial terminal, press reset, and send U (0x55) within half a second. The board answers V (0x56).

Show answer

Press reset, then send the byte 0x55 (the letter U) within half a second. The boot ROM's programming mode (fw/fw-brom/isp.c) answers 0x56 (V) and waits for commands; this is how sw/nandtier-programmer.py takes over the board. Send nothing and the boot ROM starts the launcher from flash after the timeout, and its menu appears.

picocom -b 115200 /dev/ttyUSB1      # press reset, then type U
V
THE SLOTNever move 0x54

The launcher jumps to 0x8000_0054 to write flash. Moving it breaks every launcher in the field.

WHAT IT SERVESSeven commands, no read

55 ping, 10 fill the page buffer, 30 erase a 4 KiB sector, 40 program a page, 60 start the SD card, 62 write an SD block, F0 restart (fw/fw-brom/isp.c). There is no flash read: the page buffer echoes a checksum, and the launcher's CRC-32 checks the rest. The video says "read flash"; the code is the reference.

RESCUEYou can't brick it

The boot ROM comes with the bitstream, so whatever is in flash, you can always reprogram it.

TIER 3 · FIRMWARE · LESSON 3 OF 9

The launcher

Drive the launcher's menu and follow the loader as it installs a game.

videolauncher terminalgraded install order
2

Explore

This is a model of the launcher's serial menu, with its real keys. Click the keys, or click the terminal and type. Press p for the game menu, then a game number.

BENCH · LAUNCHER (MODEL)
WHAT'S REAL

The menu keys, the eight games and their sizes, the SD directory at block 8192 with its word checksum, the CRC-32 that decides whether a game is already installed and verifies the copy, 4 KiB erases and 256-byte pages all match fw/fw-flash/ and the SD pack. The timings are not modelled.

3

Try

Put the loader's steps in order.

4

Build

The heart of the loader: check the slot's CRC-32, erase it, copy each 512-byte SD block into two 256-byte flash pages, and check the CRC-32 again.

// fw/fw-flash/loader.c (excerpt)
if (loader_installed(c))                       // CRC-32 of the slot == the directory's: nothing to do
    return 1;
uint32_t slot = loader_flash_base() + NT_CART_SLOT;
for (uint32_t s = 0; s < sectors; s++)
    flash_erase_sector(slot + s * SECTOR);          // 4 KiB each
for (uint32_t b = 0; b < blocks; b++) {
    if (sd_read_block(NT_CART_SD_BLOCK + c->block + b, block_buf))
        return LOADER_READ_ERROR;
    uint32_t addr = slot + b * SD_BLOCK_SIZE;
    flash_program_page(addr, block_buf);            // 256 B (skipped if all 0xFF)
    flash_program_page(addr + PAGE, block_buf + PAGE);
}
return loader_installed(c) ? 0 : LOADER_VERIFY_ERROR;   // read back through XIP, CRC-32 again

// then loader_start(): leave a handoff message, jump to _start
nt_handoff_set(NT_HANDOFF_PLAY, index);
((void (*)(void))NT_CART_SLOT)();
DEEP DIVELauncher and game loader

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

LAB 3C · 20 MINAdd a command

Add case 'H' to the launcher's menu that prints the seconds since boot (nt_cycles() / NT_CLK_HZ, with print_dec). Rebuild with make flash, then make program.

Show answer
/* fw/fw-flash/main.c, in the menu's switch(key) */
case 'H': case 'h':
    print("Up for ");
    print_dec(nt_cycles() / NT_CLK_HZ);
    print(" s\n");
    break;
make flash
make program COMx=/dev/ttyUSB1

H is free in the menu (the used keys are 1–6, A, B, C, D, F, G, I, M, P, R, S, T, W). One catch: nt_cycles() is a 32-bit count of 24.975 MHz cycles, so it wraps every 2^32 / 24,975,000 ≈ 172 s. After about three minutes your command starts again from 0. A fix is to remember the last value and count the wraps.

WHY COMPAREFlash wears out

Each sector survives about 100,000 erases. Skipping identical installs saves them.

IN NANDTIERconsole.c

Every character to the UART is also mirrored by hardware to the HDMI text terminal.

TIER 3 · FIRMWARE · LESSON 4 OF 9

Installing a game

Follow one install from SD block to flash page to the final jump, and why flash must be erased.

videoinstall trace with flash bytes3 hex checks
2

Explore

Step through one install. Watch the flash bytes: erase turns them all to 0xFF, programming clears some bits to 0.

BENCH · ONE INSTALL
FLASH @ 0x0010_0000

3

Try

Flash only lets you clear bits. Work out what each byte reads as.

4

Build

A cartridge is linked for the slot, with _start placed first.

/* fw/sdk/cart.ld (cut down) */
MEMORY { FLASH (rx)  : ORIGIN = 0x00100000, LENGTH = 1M
         RAM   (rwx) : ORIGIN = 0x40000000, LENGTH = 8K }
SECTIONS {
  .text : { KEEP(*(.text.start)) *(.text .text.*) } > FLASH   /* _start FIRST */
  .data : { *(.data .data.*) *(.sdata .sdata.*) } > RAM AT > FLASH
  .bss  : { *(.sbss .sbss.* .bss .bss.* COMMON) } > RAM
  __stack_top = ORIGIN(RAM) + LENGTH(RAM) - 16;            /* below the handoff message */
  ASSERT(_start == ORIGIN(FLASH), "_start is not first in the cartridge")
}

    .section .text.start          # fw/common/start.S, shared with the launcher
_start:
    la   sp, __stack_top
    la   gp, __global_pointer$
    # copy .data from flash to SRAM, clear .bss (two word loops)
    call main                     # fw/sdk/cart_main.c: game_main(); ng_exit();
LAB 3D · 20 MINWatch an install from the inside

Log every SD command and flash command during one install, and count the pages.

Show answer

For Snake (10,672 bytes in the pack): 3 flash sectors erased (4 KiB each), 21 SD blocks read (512 bytes each), and up to 42 flash pages programmed (two 256-byte pages per block). A few pages that are all 0xFF are skipped, so your count can be a little lower. Add a print with the address in flash_erase_sector, sd_read_block and flash_program_page and count the lines.

python3 sw/mkcarts.py --list fw/games/build/carts.img
 2  SNAKE   block 52   10672 bytes   at 00100000

Install the same game twice and the second time you see no flash commands at all: the CRC-32 check finds it already in the slot.

FLASH RULESErase to 1, program to 0

Programming ANDs new data into the old. That's why every install erases first.

IN NANDTIERThree builds

The same C builds for the board and for your PC (test/host, with a C model of the PPU). The course emulator runs the board's own binary from the SD pack.

TIER 3 · FIRMWARE · LESSON 5 OF 9

The game SDK

ngame, the HAL, the art tool and the game loop that every cartridge uses.

videobench4 auto-checked questions
2

Explore

Change the speed and press the arrow buttons. The sprite moves once per frame, exactly as the loop says.

BENCH · GAME LOOP
FRAME

3

Try

Four quick questions.

4

Build

The smallest complete cartridge, in the general shape.

#include "ngame.h"
#include "art.h"

void game_main(void) {
    int x = 120;
    ng_begin(art_chr, ART_TILES, art_palette);
    for (;;) {
        uint8_t b = ng_buttons();
        if (b & BTN_LEFT)  x -= 2;
        if (b & BTN_RIGHT) x += 2;
        ng_sprite(x, 112, S_PLAYER, 0, NG_BIG);
        ng_frame();                      // wait, then show this frame's sprites
        if (ng_quit()) break;
    }
}
DEEP DIVEGame SDK

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

LABThe games

Read fw/games/flappy/flappy.c: it is the smallest complete example.

Show answer

Read fw/games/flappy/flappy.c with three questions: where are the tiles and palette loaded (ng_begin), what changes every frame (the main loop with ng_frame()), and how does it end (cart_exit()). Every other game has the same three parts.

TOOLmkart.py

Turns drawings into tile data and a palette.

TIER 3 · FIRMWARE · LESSON 6 OF 9

How the firmware waits

Polling instead of interrupts, hardware waits, buffers and timeouts.

videobench4 auto-checked questions
2

Explore

Set how much work a frame needs. The rest of the frame is spent polling the frame counter.

BENCH · ONE FRAME
BUDGET

3

Try

Four quick questions.

4

Build

Three kinds of wait, in the general shape.

// 1. until something happens
uint32_t f = PPU_STATUS >> 16;
while ((PPU_STATUS >> 16) == f) ;

// 2. for an exact time
static void wait_cycles(uint32_t n) { uint32_t t = nt_cycles(); while (nt_cycles() - t < n) ; }

// 3. with a way out
uint32_t t0 = nt_cycles();
while (!(SD_CTRL & READY))
    if (nt_cycles() - t0 > LIMIT) return ERR_TIMEOUT;
IN NANDTIERNo interrupts

Every wait is a poll. Adding interrupts is one of the capstones in 5.10.

SAFETY NETFIFOs

The UART keeps sixteen received bytes while the program is busy.

TIER 3 · FIRMWARE · LESSON 7 OF 9

Hardware/software co-design

What NandTier put in hardware, what it left in software, and how to decide.

videobench4 auto-checked questions
2

Explore

Move each feature to hardware or software. The bench estimates the frame time and the chip area (illustrative numbers).

BENCH · HW OR SW
ESTIMATE

3

Try

Four quick questions.

4

Build

How the SDK measures the busiest frame, in the general shape.

void ng_frame(void) {
    uint32_t busy = nt_cycles() - frame_start;     // the work this frame took
    if (busy > slowest) slowest = busy;
    wait_for_next_frame();
    frame_start = nt_cycles();
    ...
}
uint32_t ng_slowest_frame(void) { return slowest; }
METHODMeasure, find, decide

Measure where time goes; only then consider new hardware.

NEXT3.8

The method applied to the multiply instruction.

TIER 3 · FIRMWARE · LESSON 8 OF 9

The M extension: hardware for the hot loop

Build with and without multiply instructions, measure, and count the cost.

videobench4 auto-checked questions
2

Explore

Pick how often the loop multiplies. The bench compares a software multiply with the hardware instruction (illustrative cycle counts).

BENCH · RV32I vs RV32IM
CYCLES

3

Try

Four quick questions.

4

Build

The one line that decides it, in the firmware build.

# fw/common.mk
ARCH = -march=rv32i  -mabi=ilp32      # runs on any RV32I core
# ARCH = -march=rv32im -mabi=ilp32    # one instruction per multiply

# compare: build both, play the same level, read ng_slowest_frame()
IN NANDTIERThe hardware is there

The core implements M on the FPGA multiplier blocks.

WATCH OUTPortability

An M build stops with an illegal instruction on a core without M.

TIER 3 · FIRMWARE · LESSON 9 OF 9

One firmware, four places to run it

The board, the PC, the browser and simulation, all from one source through the HAL.

videobench4 auto-checked questions
2

Explore

Pick a place to run the game, and see what it is good at.

BENCH · FOUR PLACES
PLACE

3

Try

Four quick questions.

4

Build

One header, two meanings.

#ifdef GAME_HOST                       // the PC build
void hal_ppu_write(uint32_t off, uint32_t v);   // -> the C model of the PPU
#else                                  // the board
static inline void hal_ppu_write(uint32_t off, uint32_t v) { PPU_REG(off) = v; }
#endif
LABtest/host

The PC build runs every game and compares screenshots with saved ones.

Show answer
make -C test games      # builds every game for the PC, plays it with scripted keys, compares screenshots

A changed screenshot is either a bug or an intended change. If you changed the game on purpose, look at the new picture, then save it as the new reference.

LABsim/

tb_soc runs the firmware on the simulated chip and saves frames to compare.

Show answer
make -C sim carts       # boot ROM -> launcher -> install Pong from the SD model -> first frame

It needs the Gowin primitive models (GOWIN_HOME) and takes tens of minutes. Pass means the simulated chip's first Pong frame matches the PC build's picture pixel for pixel.

TIER 4 · PIXELS · LESSON 1 OF 8

How a picture reaches a screen

Know how a 640 × 480 picture is scanned out: pixels, lines, blanking, sync, and the numbers that time it.

videoslow-motion frame bench4 number checks
2

Explore

One frame of the 640 × 480 mode, drawn to scale and slowed down. Green is picture, grey is blanking, teal is the h sync pulse, copper is v sync.

BENCH · ONE FRAME
THE BEAM

Each line is 800 pixel clocks: 640 picture, 16 front porch, 96 sync, 48 back porch. Each frame is 525 lines: 480 picture, 10, 2 of v sync, 33.

3

Try

Work the frame out in numbers.

4

Build

The whole 640 × 480 mode is a handful of constants.

// horizontal, in pixel clocks
localparam H_ACTIVE = 640, H_FRONT = 16, H_SYNC = 96, H_BACK = 48;
localparam H_TOTAL  = H_ACTIVE + H_FRONT + H_SYNC + H_BACK;   // 800
// vertical, in lines
localparam V_ACTIVE = 480, V_FRONT = 10, V_SYNC = 2,  V_BACK = 33;
localparam V_TOTAL  = V_ACTIVE + V_FRONT + V_SYNC + V_BACK;   // 525
// 800 x 525 = 420,000 clocks per frame
// 24.975 MHz / 420,000 = 59.46 frames per second
DEEP DIVEText terminal and font

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

LAB 4A · 15 MINCount a frame

In simulation, count clocks between two v sync pulses. You should get exactly 420,000.

Show answer

640 visible + 16 front porch + 96 sync + 48 back porch = 800 clocks per line; 480 + 10 + 2 + 33 = 525 lines per frame (the parameters of hw/video/nt_video_timing.v).

800 × 525 = 420,000 clocks between two v sync pulses
24,975,000 / 420,000 = 59.46 frames per second

In the testbench, count posedge clk between two falling edges of vsync (the sync is active low).

PICTURE SIZE256 × 240, doubled

NandTier's own picture fills columns 64–575 at 2× size: every pixel is drawn as 2 × 2.

IN NANDTIER12-bit colour

Four bits each of red, green and blue: 4,096 colours.

TIER 4 · PIXELS · LESSON 2 OF 8

Racing the beam

See why there is no frame buffer, and how two counters and a few comparisons time the whole display.

videocounter benchgraded region checks
2

Explore

Set the two counters, or press Run. The bench evaluates the same comparisons as the Verilog below.

BENCH · TIMING GENERATOR
OUTPUTS

3

Try

For each pair of counter values, pick where the beam is.

4

Build

The timing generator: two counters and a few comparisons.

always @(posedge clk) begin
  if (h == 799) begin
    h <= 0;
    v <= (v == 524) ? 0 : v + 1;
  end else
    h <= h + 1;
end
assign active = (h < 640) && (v < 480);
assign hsync  = ~(h >= 656 && h < 752);   // active low
assign vsync  = ~(v >= 490 && v < 492);
DEEP DIVEVideo timing

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

LAB 4B · 20 MINSimulate it

Run the generator in Icarus Verilog for two frames and open the waveform. Find one h sync pulse and one v sync pulse.

Show answer
iverilog -o vt tb_vt.v hw/video/nt_video_timing.v && vvp vt && gtkwave vt.vcd

Two frames are 840,000 clocks, so run the testbench for at least that long. The h sync pulse starts at x = 656 (640 + 16) and lasts 96 clocks. The v sync pulse starts at line 490 (480 + 10) and lasts 2 lines, that is 1,600 clocks. Both are low while active.

WHY NO FRAME BUFFER90 KB vs 8 KB

256 × 240 × 12 bits is 92,160 bytes. The SoC has 8 KB of SRAM.

THE LINE BUFFER1,600 clocks

The PPU draws one line ahead. Each picture line is shown twice, so it has 2 × 800 clocks to draw it.

TIER 4 · PIXELS · LESSON 3 OF 8

Bits on the HDMI cable

Encode a byte with TMDS: stage 1 for fewer transitions, stage 2 for DC balance, and the control symbols.

videoTMDS encoder bench4 encoding checks
2

Explore

Pick a byte. Watch stage 1 chain the bits, then stage 2 balance them. Press Send to send the same byte again and see the running disparity change the symbol.

BENCH · TMDS ENCODER (DVI)
WHAT HAPPENED

SENT SO FAR

3

Try

Stage 1 picks XNOR when the byte has more than four 1s, or exactly four 1s and bit 0 is 0. Otherwise XOR.

4

Build

Stage 1 of a TMDS encoder in Verilog, following the DVI specification.

wire [3:0] n1 = d[0]+d[1]+d[2]+d[3]+d[4]+d[5]+d[6]+d[7];
wire use_xnor = (n1 > 4) || (n1 == 4 && d[0] == 0);
wire [8:0] qm;
assign qm[0] = d[0];
genvar i;
generate for (i = 1; i < 8; i = i + 1) begin : chain
  assign qm[i] = use_xnor ? ~(qm[i-1] ^ d[i]) : (qm[i-1] ^ d[i]);
end endgenerate
assign qm[8] = ~use_xnor;   // 1 = XOR, 0 = XNOR
// stage 2: compare the 1s and 0s in qm[7:0] with the running
// disparity, invert qm[7:0] if needed, and record it in bit 9
DEEP DIVETMDS: DVI on HDMI

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

LAB 4C · 20 MINCheck against the spec

Feed every byte 0–255 through your encoder in simulation and compare with a Python model. All 256 must match.

Show answer

The model has to keep the same running disparity as the hardware, so feed the bytes in order, 0 to 255, and compare one symbol per clock. This model matches hw/video/nt_tmds_encoder.v on all 256 (checked):

def tmds(byte, cnt):
    """One TMDS data symbol (DVI 1.0, 3.2.2). Returns (symbol, new disparity)."""
    d = [(byte >> i) & 1 for i in range(8)]
    n1 = sum(d)
    xnor = n1 > 4 or (n1 == 4 and d[0] == 0)
    q = [d[0]]
    for i in range(1, 8):
        q.append(1 - (q[i-1] ^ d[i]) if xnor else q[i-1] ^ d[i])
    q.append(0 if xnor else 1)                     # q_m[8]
    ones = sum(q[:8]); zeros = 8 - ones
    if cnt == 0 or ones == zeros:
        out = (q[:8] if q[8] else [1 - b for b in q[:8]]) + [q[8], 1 - q[8]]
        cnt += (ones - zeros) if q[8] else (zeros - ones)
    elif (cnt > 0 and ones > zeros) or (cnt < 0 and zeros > ones):
        out = [1 - b for b in q[:8]] + [q[8], 1]
        cnt += 2 * q[8] + (zeros - ones)
    else:
        out = q[:8] + [q[8], 0]
        cnt += -2 * (1 - q[8]) + (ones - zeros)
    return sum(b << i for i, b in enumerate(out)), cnt
# testbench: data = i at each clock, $display("%0d %0d", i, symbol) one clock later
# then: python3 model.py rtl.txt
all 256 match
CONTROL SYMBOLSSync in blanking

During blanking, the blue channel sends one of four 10-bit control symbols, carrying h sync and v sync.

IN NANDTIERSerializer

clk_5x = 124.875 MHz, double data rate: 10 bits per pixel clock on each lane.

TIER 4 · PIXELS · LESSON 4 OF 8

The PPU in 3D: from a store to a pixel

Follow one pixel through the name table, a CHR tile and a palette, to its final 12-bit colour.

videopixel-trace bench4 lookup checks
2

Explore

A small background built from real-format data: 8 × 8 tiles at 4 bits per pixel, a name table and palettes. Click any pixel to trace its colour. Change the scroll to move the map.

BENCH · PIXEL TRACE
THE LOOKUPS
3

Try

Do the lookups by hand. Scroll is 0 unless the question says so.

4

Build

Filling the video memories from C: one tile, one palette, one map entry. (Simplified: the real SDK wraps this in ng_* calls.)

#define PPU_PALETTE ((volatile uint32_t *)0xC1000400)
#define PPU_NAMETAB ((volatile uint32_t *)0xC1002000)
#define PPU_CHR     ((volatile uint32_t *)0xC1004000)

// tile 1: one 32-bit word per row, leftmost pixel in the lowest nibble
static const uint32_t ball[8] = { 0x00111100, 0x01222210, 0x12233221, 0x12333321,
                                  0x12333321, 0x12233221, 0x01222210, 0x00111100 };
for (int r = 0; r < 8; r++) PPU_CHR[1 * 8 + r] = ball[r];

PPU_PALETTE[1 * 16 + 3] = 0xFD6;              // palette 1, colour 3: 12-bit RGB
PPU_NAMETAB[5 * 64 + 10] = NT_ENTRY(1, 1, 0, 0); // map row 5, column 10: tile 1, palette 1, no flips
DEEP DIVEPPU: tiles, sprites, scrolling

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

LAB 4D · 20 MINPut a tile on screen

From a cartridge, write a tile, a palette and one map entry. Then change only the palette, and watch the colour change.

Show answer

The lesson's code is the whole answer. Then change only the palette entry:

PPU_PALETTE[1 * 16 + 3] = 0x0F0;   // palette 1, colour 3: green instead of 0xFD6

The ball's centre turns green and nothing else changes: the tile and the map entry still say "tile 1, palette 1", and colour 3 of palette 1 is now another colour. Change NT_ENTRY(1, 1, 0, 0) to palette 2 instead and the same tile is drawn with palette 2's colours.

PRIORITYWho wins a pixel

Sprite, unless marked behind an opaque background; then background; then the backdrop.

SEE IT IN 3DThe PPU model

The course's 3D PPU view replays real video-memory writes from NandTier Hopper.

TIER 4 · GRAPHICS · LESSON 5 OF 8

Tiles and palettes

Eight-by-eight tiles, a name table, palettes, scrolling and the split line.

videobench4 auto-checked questions
2

Explore

Click cells to paint the tile with the selected colour index. The map below uses the tile six times: change the palette and every copy changes.

BENCH · TILE PAINTER
TILE

3

Try

Four quick questions.

4

Build

Writing tile rows, a map entry and a palette colour, in the general shape.

// one tile row: 8 pixels x 4 bits, pixel 0 in the low nibble
hal_ppu_write(PPU_CHR + (tile * 8 + row) * 4, row_bits);
// one map entry: tile, palette, flips
hal_ppu_write(PPU_NAMETAB + (r * 64 + c) * 4, tile | (pal << 8) | (hflip << 10));
// one colour: 12-bit 0xRGB
hal_ppu_write(PPU_PALETTE + (pal * 16 + idx) * 4, 0xF80);
IN NANDTIERThe font is tiles

The first 64 tiles are the text font.

TRICKPalette effects

Change one colour and every pixel that uses it changes.

TIER 4 · GRAPHICS · LESSON 6 OF 8

Sprites, layers and priority

Sixty-four sprites, their flags, who wins each pixel, and sixteen per line.

videobench4 auto-checked questions
2

Explore

Pick what is at one pixel: is the sprite pixel opaque, is it marked behind, is the background pixel opaque? The bench says what is shown.

BENCH · PRIORITY
SHOWN

3

Try

Four quick questions.

4

Build

Building an OAM word, in the general shape.

uint32_t oam = (y & 0xFF)
             | ((x & 0x1FF) << 8)       // 9-bit, can be negative
             | (tile << 17)
             | (pal << 25)
             | (hflip << 27) | (vflip << 28)
             | (big << 29)              // 16 x 16
             | (behind << 30);
hal_ppu_write(PPU_OAM + i * 4, oam);    // lower i = in front
LIMIT16 per line

The line buffer has time for sixteen sprites on each line.

IN NANDTIERLower index wins

Sprite 0 is drawn in front of sprite 1.

TIER 4 · GRAPHICS · LESSON 7 OF 8

The game loop

Input, update, draw and wait, inside a frame budget.

videobench4 auto-checked questions
2

Explore

Press Next to run one frame at a time. The bar shows how much of the frame budget each part used.

BENCH · FRAME BY FRAME
FRAME

3

Try

Four quick questions.

4

Build

A game as a state machine, in the general shape.

enum { TITLE, PLAY, OVER } state = TITLE;
for (;;) {
    uint8_t p = ng_pressed();
    switch (state) {
    case TITLE: if (p & BTN_START) { ng_seed(ng_frame_count()); reset_world(); state = PLAY; } break;
    case PLAY:  update_world(ng_buttons()); draw_world(); if (dead()) state = OVER; break;
    case OVER:  if (p & BTN_START) state = TITLE; break;
    }
    ng_frame();
}
BUDGETOne frame

About 420 000 CPU cycles at 60 frames a second.

TIPBoxes

Rectangle overlap is enough collision for most games.

TIER 4 · GRAPHICS · LESSON 8 OF 8

Making a game: Flappy, Hopper and Invaders

Flappy Chip, Hopper and Alien Raid: one SDK, three designs.

videobench4 auto-checked questions
2

Explore

Pick a game and switch layers off to see what each is made of.

BENCH · LAYERS
MADE OF

3

Try

Four quick questions.

4

Build

Drawing the next column just before it scrolls into view, as Flappy and Hopper do.

void scroll_step(void) {
    scroll_x = (scroll_x + speed) & 511;            // the map is 512 pixels wide
    int col = ((scroll_x >> 3) + 33) & 63;          // just off the right edge
    if (col != last_col) { draw_column(col); last_col = col; }
    ng_scroll(scroll_x, 0);
}
LABfw/games

flappy, hopper and invaders: read them in that order.

Show answer

Read them in order of size. Flappy has one moving sprite and gravity. Hopper adds a scrolling world. Invaders adds many sprites and collisions. Each one adds one idea to the previous one.

YOUR TURNMake one

Copy the smallest, change the rules, draw new art.

Show answer
cp -r fw/games/flappy fw/games/mygame
# rename in its Makefile and source, add mygame to fw/games/Makefile
make games
python3 sw/mkcarts.py --list fw/games/build/carts.img   # your game is in the pack
make program COMx=/dev/ttyUSB1

Start with one rule change (gravity, speed, gap size) before drawing new art. The PC build (make -C test games) lets you play it without the board.

TIER 5 · SILICON · LESSON 1 OF 10

What a LUT really is

Read and write a LUT4's 16-bit INIT value for any function of four inputs.

videoLUT4 builder4 INIT checks
2

Explore

Toggle the inputs to address the LUT, pick a preset, or click the stored bits to make your own function. The INIT value updates as you go.

THE LUT
3

Try

Write the INIT value for each function of a (bit 0 of the address), b, c and d. Hex, like 0x8000.

4

Build

A LUT4 is just a 16:1 multiplexer over a constant. This behaves exactly like the cell synthesis places.

module lut4 #(parameter [15:0] INIT = 16'h6996) (
    input  wire a, b, c, d,
    output wire f
);
    assign f = INIT[{d, c, b, a}];   // the inputs are the address
endmodule

// Gowin's own primitive, as Yosys writes it in the netlist:
// LUT4 #(.INIT(16'h6996)) u (.I0(a), .I1(b), .I2(c), .I3(d), .F(f));
LAB TB · 20 MINSynthesise with Yosys yourself

Run synth_gowin on the Tier 0 full adder and read off each LUT's INIT.

Show answer

Generic cells first, then Gowin cells; measured with Yosys 0.70:

yosys -p "read_verilog full_adder.v; synth_gowin -top full_adder; write_verilog -noattr out.v"
LUT3 #(.INIT(8'h96))  -> s     (a ^ b ^ cin)
LUT3 #(.INIT(8'hE8))  -> cout  (majority of a, b, cin)

Read INIT as a truth table, bit i = the output for inputs i. 0x96 = 1001_0110: 1 for 1, 2, 4 and 7 inputs high, an odd count. 0xE8 = 1110_1000: 1 for 3, 5, 6 and 7, two or more high. The whole full adder is two LUTs.

WIDERMUX2_LUT5 and up

Two LUT4s and a MUX2_LUT5 make any 5-input function; MUX2_LUT6/7 go further.

IN NANDTIER3,833 LUTs

Gowin's count for the 9K before the logic analyzer was added (the video's number). The current RTL, ILA included, maps to 4,418 LUTs plus 567 ALUs.

TIER 5 · SILICON · LESSON 2 OF 10

NandTier on the chip, in 3D

See NandTier placed on the chip, then read a critical path: logic plus routing, Fmax, slack, and what would shorten it.

videotiming calculator4 checks
2

Explore

The real numbers from nextpnr, as a calculator. Pick a board, or change the logic and routing delays, or cut the path in half with a pipeline register.

TIMING
3

Try

Questions from the real report.

4

Build

Lab 5C: read nextpnr's placement and timing report yourself.

# count placed cells by kind
python3 -c "import json,collections,re; c=json.load(open('oss/build/tangnano20k/nandtier_pnr.json'))['modules']['top']['cells']; print(collections.Counter(re.sub(r'\d+$','',v['attributes'].get('NEXTPNR_BEL','/?').split('/')[1]) for v in c.values()).most_common(8))"
# Tang Nano 20K, current RTL: LUT 5250, DFF 1928, ALU 1228, MUX 714, RAM16SDP 36, BSRAM 24, ...

# the critical path: steps, total delay, Fmax
python3 -c "import json; r=json.load(open('oss/build/tangnano20k/report.json')); p=r['critical_paths'][0]['path']; print(len(p), round(sum(s['delay'] for s in p),3), r['fmax'])"
# 29 steps, 12.167 ns, achieved 82.19 MHz against 24.975
# (make fpga BOARD=tangnano20k first; the same works for the 9K)
DEEP DIVEThe full SoC

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

LAB 5C · 25 MINRead the placement yourself

Count the cells nextpnr placed by kind, and read the critical path from report.json.

Show answer

Run the two commands in the lesson after make fpga. The counts tell you what the design is made of: mostly LUT4 and DFF, with ALU cells for adders and counters and BSRAM for the memories. The critical path's steps alternate between logic and routing; on these chips routing is usually more than half of the delay. Compare achieved with constraint (24.975 MHz): the difference is your timing margin.

PLACER VS ROUTER87.9 MHz → 96.1 MHz

On the 20K, placement estimated 87.9 MHz from wire distances; routing, which knows every switch, reported 96.1. The estimate can miss either way.

THE 3D VIEWPlaced before the ILA

The video and the 3D view show the 9K placement from before the logic analyzer was added. Today the design fills 65% of the 9K's LUTs in the open flow (lesson 6.1 tells how it went to 90% and back).

TIER 5 · SILICON · LESSON 3 OF 10

The open-source toolbox

Know which free tool does which step, and follow NandTier's three tool chains.

videotool-chain explorergraded bitstream order
2

Explore

NandTier's three chains of tools. Click a tool for what it reads, what it writes, and the command this repo uses.

BENCH · TOOLS IN THIS REPO
PICK A TOOL

3

Try

Click the open bitstream flow's tools in the order a design meets them.

4

Build

The make targets that run each chain (Lab 5A).

make fpga BOARD=tangnano20k         # Yosys synth_gowin → nextpnr-himbaechel → gowin_pack
                                     # result: oss/build/tangnano20k/nandtier.fs
make fpga-load BOARD=tangnano20k    # openFPGALoader: into SRAM, until power-off
make fpga-flash BOARD=tangnano20k   # or into the configuration flash

make fpga BOARD=tangnano9k          # the same for the 9K: 65% of its LUTs, timing met (see below)
cat oss/build/tangnano9k/stat.txt   # Yosys's cell counts, to compare with Gowin
LAB 5A · 30 MINOpen-source bitstream

Build with Yosys, nextpnr and Apicula, load it, and compare stat.txt with Gowin's numbers.

Show answer
make fpga                          # Yosys -> nextpnr-himbaechel -> gowin_pack
make fpga-load                     # into the FPGA
grep -A25 'Device utilisation' oss/build/tangnano9k/nextpnr.log

Measured on the Tang Nano 9K: 5,914 of 8,640 LUT4 (68%), 2,232 flip-flops, 24 of 26 block RAMs, timing met with room to spare. Gowin's IDE reports its own numbers, which don't compare one-to-one: it counts LUTs, ALUs and ROM16 cells together, and fills spare block RAMs with small memories.

ONE DOWNLOADOSS CAD Suite

Yosys, nextpnr, Apicula, Trellis, IceStorm, SymbiYosys, Icarus, Verilator, cocotb, GTKWave and more.

OTHER BOARDS20K and ULX3S

The open flow also targets the Tang Nano 20K and the ULX3S (ECP5), with pins and clocks in boards/.

THE 9K TODAYIt fits, with room to spare

Yosys maps the 9K design to 5,621 of 8,640 LUT4s (65%) and nextpnr meets timing at 42.9 MHz against the 24.975 MHz needed. For a while it did not fit: the logic analyzer's flags took 7,833 LUT4s and nextpnr stopped with "Unable to find legal placement". Lesson 6.1 shows the cause and the fix.

TIER 5 · SILICON · LESSON 4 OF 10

Yosys and netlistsvg: from Verilog to cells

Follow synthesis from generic cells to Gowin cells, and work out a mapped LUT's INIT.

videosynthesis stepper4 checks
2

Explore

Pick a circuit and step through the passes. The cell counts are the real Yosys results for these circuits.

WHAT THIS PASS DID

3

Try

Cells and INITs.

4

Build

Lab TB: the same steps on your machine.

# generic cells first
yosys -p "read_verilog full_adder.v; proc; opt; stat"
# → 3 $xor, 2 $and, 1 $or

# then Gowin cells, and a JSON netlist
yosys -p "read_verilog full_adder.v; synth_gowin -top full_adder; stat; write_json fa.json"
# → 2 LUT3, 3 IBUF, 2 OBUF

# draw it
netlistsvg fa.json -o fa.svg
LAB TB · 20 MINSynthesise with Yosys yourself

Generic cells first, then Gowin cells; then the whole SoC's stat.txt.

Show answer

Generic cells first, then Gowin cells; measured with Yosys 0.70:

yosys -p "read_verilog full_adder.v; synth_gowin -top full_adder; write_verilog -noattr out.v"
LUT3 #(.INIT(8'h96))  -> s     (a ^ b ^ cin)
LUT3 #(.INIT(8'hE8))  -> cout  (majority of a, b, cin)

Read INIT as a truth table, bit i = the output for inputs i. 0x96 = 1001_0110: 1 for 1, 2, 4 and 7 inputs high, an odd count. 0xE8 = 1110_1000: 1 for 3, 5, 6 and 7, two or more high. The whole full adder is two LUTs.

For the whole SoC, make fpga writes oss/build/tangnano9k/stat.txt. Measured on the 9K: 5,914 LUT4 after packing, 2,232 flip-flops, 24 of 26 block RAMs.

NANDTIER11,470 cells

The current 9K synthesis (Yosys 0.69): 3,204 LUT4, 2,238 LUT3, 1,041 ALU, 2,944 flip-flops, 1,076 wide-function muxes, 36 distributed RAMs, 24 block RAMs, 1 multiplier. The video's 7,782 is from before the logic analyzer.

SEE ITnetlistsvg

Real gate symbols for AND, OR, XOR and muxes; the quickest check of what synthesis made.

TIER 5 · FPGA FLOW · LESSON 5 OF 10

nextpnr: placing and routing

Packing, placement, routing round by round, and the timing and fullness reports.

videobench4 auto-checked questions
2

Explore

Place the cells, then route round by round. Red tiles are wires wanted by more than one net; each round raises their price, and nets move away.

BENCH · PLACE AND ROUTE
ROUND

3

Try

Four quick questions.

4

Build

The open flow for the Tang Nano 9K, in the general shape a Makefile runs it.

yosys -p "read_verilog top.v; synth_gowin -top top -json top.json"
nextpnr-himbaechel --json top.json --write pnr.json \
    --device GW1NR-LV9QN88PC6/I6 --vopt family=GW1N-9C \
    --vopt cst=tangnano9k.cst --freq 25 --seed 1
gowin_pack -d GW1N-9C -o top.fs pnr.json
openFPGALoader -b tangnano9k top.fs
TRY ITChange the seed

Run with a few seeds and compare the Fmax lines: the spread is normal.

Show answer
cd oss/build/tangnano9k
for s in 1 2 3; do
  nextpnr-himbaechel --json nandtier.json --write /tmp/pnr$s.json --seed $s \
    --device GW1NR-LV9QN88PC6/I5 --vopt family=GW1N-9C \
    --vopt cst=../../../boards/tangnano9k/tangnano9k.cst \
    --sdc ../../../boards/tangnano9k/tangnano9k.sdc -q -l seed$s.log
  grep 'Max frequency' seed$s.log | tail -1
done

The placer starts from a random placement, so each seed gives a slightly different result. A spread of a few MHz in Max frequency is normal. What matters is that every seed passes at 24.975 MHz; a design that passes only with a lucky seed is too close to the limit.

WATCH OUTNear full

Above about 90% of LUTs, routing gets slow and timing gets worse.

TIER 5 · FPGA FLOW · LESSON 6 OF 10

Two roads to a bitstream

The open tools and the Gowin IDE: one core, a thin board layer for each.

videobench4 auto-checked questions
2

Explore

Step through both roads side by side. Same Verilog in, a bitstream for the same board out.

BENCH · TWO ROADS
STEP

3

Try

Four quick questions.

4

Build

A RAM written so that both Yosys and the Gowin tools map it onto block RAM, with no vendor IP.

module ram #(parameter AW = 11) (
  input clk, input we, input [AW-1:0] addr,
  input [31:0] wdata, output reg [31:0] rdata);
  reg [31:0] mem [0:(1<<AW)-1];
  always @(posedge clk) begin
    if (we) mem[addr] <= wdata;
    rdata <= mem[addr];          // registered read: block RAM
  end
endmodule
IN NANDTIERThin board layers

Each road has its own top level for clocks, RAMs and pins. The core is shared.

HABITSecond opinion

When a tool reports something odd, build with the other road and compare.

TIER 5 · FPGA FLOW · LESSON 7 OF 10

Reading the reports

Utilisation, timing, the critical path, and the warnings that matter.

videobench4 auto-checked questions
2

Explore

A build report. Pick what to look for, and the lines that answer it light up.

BENCH · BUILD REPORT
FOUND

3

Try

Four quick questions.

4

Build

A tiny script that compares this build with the last one, so a jump stands out.

# keep last build's numbers next to the build
grep -E "LUT4|DFF|BSRAM|Max frequency" build.log > now.txt
diff -u last.txt now.txt && echo "no change"
mv now.txt last.txt
WATCH OUTLatches

An inferred latch in combinational logic is almost always a missing else or default.

HABITCompare

A sudden jump in size, or a drop in speed, points at the last change.

TIER 5 · FPGA FLOW · LESSON 8 OF 10

Case study: the black screen

Split the problem in half, prove each half, and find a linker bug.

videobench4 auto-checked questions
2

Explore

Follow the investigation. Each step proves one half, so the bug has fewer places to hide.

BENCH · INVESTIGATION
EVIDENCE

3

Try

Four quick questions.

4

Build

The fix, and the check that stops it coming back.

/* link.ld */
.text : {
  KEEP(*(.text.start))      /* _start first, always */
  *(.text*)
} > SLOT

# build check
nm -n cart.elf | head -1 | grep -q " _start$" || { echo "slot must start with _start"; exit 1; }
METHODHalve it

Hardware alive? Bytes arrived? Then it must be the file.

LABLogic analyser

Tier 6 shows how the capture in this story was taken.

Show answer

The capture in this story was taken with the on-chip logic analyzer from lesson 6.1: armed on the address that went wrong, it recorded the bus around it. Lab 6A shows you how to take one yourself.

TIER 5 · FPGA FLOW · LESSON 9 OF 10

One design, three FPGA families, and a real chip

The same Verilog on three boards, and what a real chip would need.

videobench4 auto-checked questions
2

Explore

Pick a board. Shared files stay the same; only the thin board layer changes.

BENCH · BOARDS
CHANGES

3

Try

Four quick questions.

4

Build

The general shape of a board top level: make the clocks, instance the shared SoC, map the pins.

module top_tangnano9k (input clk27, input btn_n, output [5:0] led_n, ...);
  wire clk_sys, clk_hdmi;
  board_pll pll (.clkin(clk27), .clk_sys(clk_sys), .clk_hdmi(clk_hdmi));
  wire [5:0] led;
  nandtier_soc soc (.clk(clk_sys), .clk_hdmi(clk_hdmi), .led(led), ...);
  assign led_n = ~led;             // LEDs light on low on this board
endmodule
IN NANDTIERThree boards

Tang Nano 9K, Tang Nano 20K and ULX3S share every core file.

NEXT STEPReal silicon

Open PDKs and shared wafers make a real chip possible from the same Verilog.

TIER 5 · FPGA FLOW · LESSON 10 OF 10

Capstone projects

Eight ways to extend NandTier, and the method to do it well.

videobench4 auto-checked questions
2

Explore

Pick a capstone to see what it touches, how to test it, and what to measure.

BENCH · CAPSTONES
CAPSTONE

3

Try

Four quick questions.

4

Build

A short write-up template: what changed, what it cost, what you measured.

## Capstone: <name>
Done means:   <one sentence you can test>
Changed:      <files and modules>
Cost:         LUTs  before → after   ·  Fmax  before → after
Measured:     <frame time, code size, cycles ...>
Still works:  all games boot and play
METHODDone first

Write down what done means before you start.

RULEKeep it working

A capstone that breaks the games is not finished.

TIER 6 · DEBUG · LESSON 1 OF 8

The on-chip logic analyzer

Record the CPU bus inside the running chip: arm, trigger on an address, and read back 128 clocks.

videoreading, 10 minILA bench on a real bus trace4 checks
1

Read

A simulation can't see the real flash chip, the real SD card or a board that only fails when it's warm. When the board shows a black screen, you need to look inside the running FPGA. An integrated logic analyzer (ILA) is a small recorder built into the design: it samples signals every clock and keeps the last few hundred, so you can read them out afterwards.

NandTier's ILA is hw/periph/nt_ila.v, at 0xC200_0000. On every rising edge of clk_sys it samples the CPU bus:

  • SAMPLE0, the address, and SAMPLE1, the data: the write data for a store, the read data otherwise.
  • SAMPLE2, eight flags: bit 0 ready, bit 1 valid, bits 5:2 the write strobes, bit 6 instruction fetch, bit 7 trap.

A ring buffer. Samples go into 128 slots and the write pointer wraps around, so once it's full the buffer always holds the latest 128 clocks. Reading back starts at the oldest: write READ_INDEX (0 = oldest), then read the three sample registers. A sample read takes one extra bus cycle, because the block RAM has to be read first.

A trigger. Writing CTRL bit 0 arms the ILA; bit 1 also enables the address trigger. A clock matches when a transfer completes (valid and ready) and (address ^ TRIGGER_ADDR) & TRIGGER_MASK is zero. After the match the ILA records POST_COUNT more clocks and stops. The rest of the buffer still holds what happened before the event. Without the trigger, it stops as soon as the buffer is full.

128 clocks is short. An instruction takes 4 clocks, a load or store 7, so the buffer holds about 25 instructions. A store to the UART while the transmitter is still busy waits thousands of clocks, and fills the whole buffer with one transfer. That's what the trigger is for: stop at the event, not at an arbitrary moment.

Two ways in. The CPU reaches the ILA's registers at 0xC200_0000 on every board. On the ULX3S, JTAG reaches the same registers (lesson 6.2), so you can read a trace even when the CPU is stuck in a trap.

What it costs. The 128 × 64-bit address and data samples live in block RAM. The 128 × 8 flag bits used to sit in 1,024 flip-flops, and reading one flag byte back out of them was a 128-to-1 multiplexer. That pushed the Tang Nano 9K past its size in the open flow (lesson 5.3) and put the multiplexer at the top of the timing report (lesson 6.8). Now each sample is one 72-bit block RAM word: address, data and the 8 flags, in the same two block RAMs, which had 8 bits spare. The 9K places again, at 65% of its LUTs.

2

Explore

The bus traffic below is the real launcher, run in the course emulator up to the first menu line it prints. The clock-by-clock valid/ready pattern follows the core's state machine: 4 clocks per instruction, 7 for a load or store to memory, 6 to the UART (which answers in the same cycle), plus the emulator's wait cycles for flash-cache misses and a busy UART. The ILA itself is modelled register for register from nt_ila.v.

BENCH · nt_ila ON THE LAUNCHER'S BUS
WHAT THE ILA HOLDS

Flags: R ready, V valid, the four write strobes, I instruction fetch, T trap. The data column means something only on a ready clock.

3

Try

Four numbers about the ILA. Hex or decimal; the page checks as you type.

4

Build

Arm the ILA from C, let the event happen, then dump the samples. Every name is from fw/include/nandtier.h; print_hex is the launcher's.

// capture the 40 clocks after the first store to the UART, and what led up to it
#include "nandtier.h"

void ila_arm_uart(void)
{
    ILA_TRIGGER_ADDR = NT_UART_BASE;          // 0x8300_0000: UART_DATA
    ILA_TRIGGER_MASK = 0xFFFFFFFFu;           // every address bit must match
    ILA_POST_COUNT   = 40;                    // clocks to keep after the match
    ILA_CTRL = ILA_CTRL_ARM | ILA_CTRL_TRIGGER_ADDR;
}

void ila_dump(void)
{
    while (!(ILA_CTRL & ILA_STATUS_DONE))
        ;
    uint32_t n = (ILA_CTRL & ILA_STATUS_COUNT_MASK) >> ILA_STATUS_COUNT_SHIFT;
    for (uint32_t i = 0; i < n; i++) {
        ILA_READ_INDEX = i;                   // 0 = the oldest sample
        print_hex(ILA_SAMPLE0, 8); print(" ");
        print_hex(ILA_SAMPLE1, 8); print(" ");
        print_hex(ILA_SAMPLE2, 2); print("\n");
    }
}
DEEP DIVEBus logic analyzer

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

LAB 6A · 30 MINCatch the first UART byte

Add ila_arm_uart() at the top of the launcher's main() and ila_dump() behind a new menu key. Find the store to 0x8300_0000 in your dump.

Show answer
/* fw/fw-flash/main.c */
int main(void) {
    ila_arm_uart();                 /* before the first print */
    ...
    case 'L': case 'l': ila_dump(); break;    /* L is free in the menu */

Press L. In the dump, find the line whose address is 83000000 with a write strobe in its flags: the data column holds the first character the launcher printed. Above it you see the instructions that led there: fetches from the flash, with the fetch bit (6) set in the flags.

WATCH YOURSELFReading is bus traffic too

The CPU's own accesses to the ILA are on the bus it records. Arm first, run the code you want to see, and only then read. The dump after DONE is safe: capture has stopped.

TESTEDtest/periph/tb_ila.v

Arming, the address trigger, the post count and read-back are checked by make -C test periph.

TIER 6 · DEBUG · LESSON 2 OF 8

JTAG: the TAP and the user chain

Walk the JTAG state machine with TMS, then build the 64-bit frames that reach NandTier's ILA through the ECP5 user chain.

videoreading, 12 minTAP stepper + frame builder4 checks
1

Read

JTAG (IEEE 1149.1) is the test port on almost every chip. Your cable already uses it to load bitstreams. It has four wires: TCK the clock, TMS mode select, TDI data in and TDO data out.

The TAP. Inside the chip, a 16-state machine called the TAP controller moves on every rising edge of TCK, steered only by TMS. It has two paths of the same shape: one for the instruction register (IR) and one for a data register (DR). Five clocks with TMS = 1 reach Test-Logic-Reset from any state, so a lost cable can always resynchronise.

  • An IR scan shifts in an instruction. The instruction picks which data register sits between TDI and TDO.
  • A DR scan shifts bits through that register, least significant bit first. At the same time the old contents come out on TDO. Update-DR latches the new value.

The user chain. The ECP5 lets a design own two data registers, selected by the instructions ER1 (0x32) and ER2 (0x38). Its JTAGG primitive brings the JTAG signals into the fabric (JTCK, JTDI, JSHIFT, JUPDATE, and JCE1 while ER1 is selected). NandTier's nt_ecp5_jtag_ila (in hw/periph/nt_jtag_ila.v) hangs a 64-bit shift register on ER1.

The frame. A request is 64 bits: OP in 63:60 (1 write, 2 read, 0 no-op), ADDR in 59:52 (the register offset), SEQ in 51:44 (a sequence number), zero in 43:32, DATA in 31:0. The response that comes back out has the status in 63:60 (0 ok, 2 invalid), SEQ echoed in 59:52, and the read data in 31:0. Offsets 0x00–0x1C reach the ILA, 0x80–0x90 reach the CPU debug registers (lesson 6.3). Anything else, or an address that isn't word aligned, gets status 2.

Two scans per access. Scan the request in; Update-DR hands it to the SoC. Run a few idle clocks, then scan a no-op: what comes out on TDO is the response. The helper sw/ila_jtag.tcl repeats the no-op until the SEQ in the response matches.

Which boards. Only the ULX3S build turns this on (ENABLE_ECP5_JTAG). On the Tang Nanos, the Gowin JTAG has no user-chain bridge in this repo yet, so there the CPU reads the ILA itself.

2

Explore

Clock TCK with TMS = 0 or 1 and watch the TAP move. The shift states are outlined. Then build a frame: the bench shows the 64 bits, and the Tcl call that sends them.

BENCH · THE TAP CONTROLLER
FRAME BUILDER
3

Try

Two TMS questions and two frames. Type TMS bits in the order you clock them, like 110, and frames as 16 hex digits.

4

Build

The two procedures every access goes through, from sw/ila_jtag.tcl. OpenOCD runs them after you create the tap.

# OpenOCD, after the adapter config:  jtag newtap ecp5 tap -irlen 8
set nt_ila_tap "ecp5.tap"
set nt_ila_ir 0x32                          ;# ER1, the user chain

proc nt_ila_scan {frame} {
	global nt_ila_tap nt_ila_ir
	irscan $nt_ila_tap $nt_ila_ir            ;# IR scan: select ER1
	set result [drscan $nt_ila_tap 64 $frame] ;# DR scan: 64 bits in, 64 out
	return [expr {$result}]
}

proc nt_ila_xfer {op addr data} {
	...
	set frame [expr {(($op & 0xF) << 60) | (($addr & 0xFF) << 52) |
	                 (($nt_ila_seq & 0xFF) << 44) | ($data & 0xFFFFFFFF)}]
	nt_ila_scan $frame                       ;# the request
	for {set attempt 0} {$attempt < 8} {incr attempt} {
		runtest 64                           ;# idle clocks: the SoC answers
		set response [nt_ila_scan 0]         ;# a no-op brings the response out
		if {(($response >> 52) & 0xFF) == $nt_ila_seq} { ... return [expr {$response & 0xFFFFFFFF}] }
	}
}

# then:  source sw/ila_jtag.tcl ; nt_ila_dump
DEEP DIVEJTAG analyzer and CPU debug

The real module from the repository, with its diagram, a code walkthrough and exercises: open the deep dive.

LAB 6B · 30 MIN · ULX3SDump the ILA over JTAG

Build make fpga BOARD=ulx3s, load it, start OpenOCD with your probe, create the tap, source sw/ila_jtag.tcl, arm with nt_ila_write 0 1, then nt_ila_dump.

Show answer
make fpga BOARD=ulx3s && make fpga-load BOARD=ulx3s
openocd -f your_probe.cfg -c "jtag newtap ecp5 tap -irlen 8; init"
# in the OpenOCD telnet console (telnet localhost 4444):
source sw/ila_jtag.tcl
nt_ila_write 0 1      ;# CTRL = ARM
nt_ila_dump

You get the same table as lab 6A, but without any firmware's help: JTAG reaches the analyzer even while the CPU is stuck. The probe's own config file depends on your adapter.

TDOLeast significant bit first

The shift register moves right: {tdi, shift_reg[63:1]}, and TDO is shift_reg[0].

TESTEDtest/periph/tb_jtag_ila.v

Drives the bridge's JTAG side bit by bit and checks reads, writes, bad addresses and SEQ echo.

TIER 6 · DEBUG · LESSON 3 OF 8

Halting the CPU over JTAG

Halt, step and inspect the core through JTAG, and see how one request crosses safely from the JTAG clock into clk_sys.

videoreading, 12 mindebug console + clock-crossing stepper4 checks
1

Read

The same JTAG bridge reaches a second set of registers, hw/periph/nt_cpu_debug.v:

offsetregistermeaning
0x80CONTROL / STATUSwrite 1 halt, 2 resume, 4 step one instruction; read bit 0 halted, bit 1 trap, bit 2 halt requested
0x84PCread or write the program counter while halted (word aligned)
0x88GPR_SELECTregister index 0–31
0x8CGPR_DATAread or write that register while halted; x0 stays zero
0x90SYSTEM_RESETbit 0 holds the SoC in reset; the bridge keeps working

Where it halts. Built with ENABLE_DEBUG, the core's state machine nt_control gets a HALTED state. A halt request is taken when an instruction commits (at the end of EXECUTE, or of WB for a load or store), or when a fetch completes. It never interrupts a bus transfer halfway. A step resumes with step_active set, runs one instruction, and halts again. A trapped core can be read, but leaving a trap takes a reset.

Not a RISC-V Debug Module. This is project-specific: OpenOCD runs the Tcl commands, but its RISC-V target and GDB don't apply.

Two clocks. TCK comes from the cable: any speed, and it stops between scans. clk_sys runs at 24.975 MHz. A 64-bit command can't be passed across bit by bit, because the bits could land on different edges of the other clock. So nt_jtag_ila_bridge sends one bit across and keeps the data still:

  • On Update-DR, the JTAG side copies the frame into command_mailbox and flips request_toggle.
  • The clk_sys side passes that toggle through two flip-flops (request_sync). Once the synchronised bit differs from request_seen, it reads the mailbox, which has been stable for at least two of its clocks, and starts the access.
  • The answer goes back the same way: response_mailbox, then a flip of acknowledge_toggle, synchronised into the TCK domain. The next scan's Capture-DR loads the response into the shift register.

The ULX3S constraints file says BLOCK ASYNCPATHS, so the timing analyser doesn't try to time these crossings. They are safe by design, not by timing.

2

Explore

A model of the core running the sum loop from lesson 1.2. Each button is one Tcl command; the bench shows the frames it sends. Below, step one request across the clock boundary.

BENCH · CPU DEBUG OVER JTAG
ONE REQUEST, TWO CLOCKS
3

Try

Four questions about halting and crossing clocks.

4

Build

The heart of the crossing in nt_jtag_ila.v, cut down: only the toggle crosses, the mailbox waits.

// JTAG side (jtag_clk): hand a frame over
if (jtag_chain1 && jtag_update && command_op_valid &&
    request_toggle == acknowledge_sync[1]) begin   // the last one was answered
    command_mailbox <= shift_reg;
    request_toggle  <= !request_toggle;                 // the only bit that crosses
end

// clk_sys side: two flip-flops, then use the mailbox
request_sync <= {request_sync[0], request_toggle};
if (!command_active && request_sync[1] != request_seen) begin
    request_seen <= request_sync[1];
    ila_addr     <= command_mailbox[59:52];             // stable for 2+ clocks by now
    ...
end

# OpenOCD session (ULX3S)
source sw/ila_jtag.tcl
nt_cpu_halt
nt_cpu_pc
nt_cpu_gpr_read 10        ;# a0
nt_cpu_step
nt_cpu_resume
LAB 6C · 25 MIN · ULX3SStop a game mid-frame

Start Snake, nt_cpu_halt, read the PC and find it in fw/games/snake/build/snake.asm. Step ten times, then resume.

Show answer
nt_cpu_halt
nt_cpu_pc            ;# e.g. 0x001018xx, somewhere in the game
# find that address in fw/games/snake/build/snake.asm
nt_cpu_step          ;# x10, watching the PC
nt_cpu_resume

Snake does little work per frame, so most halts land in ng_frame(), in the loop that waits for the PPU's frame counter to change. Stepping there, the same few instructions repeat: a load from the PPU's STATUS register, a compare and a branch back.

WHY TOGGLESOne bit can't be half-seen

A single bit through two flip-flops arrives on one edge or the next, never split. A 64-bit bus could arrive mixed. That is the whole rule of a clock-domain crossing.

TESTEDtest/periph/tb_cpu_debug.v

Runs the real core with the debug bridge: halt, PC and register access, step and resume.

TIER 6 · DEBUG · LESSON 4 OF 8

From the schematic to the constraints

Follow every top-level port from the board schematic to a package pin, and read what each line of the constraints file sets.

videoreading, 10 minpin map of the QN88 package4 checks
1

Read

Your Verilog talks about ports: clk, ser_tx, tmds_d_p[0]. The chip only has numbered pins, and the board's schematic says which pin each part is soldered to. A constraints file joins the two, and also sets how each pin behaves.

  • Read the schematic like this: find the part (the crystal, an LED, the HDMI connector), follow its net name to the FPGA symbol, and read the pin number there. On the Tang Nano 9K, the 27 MHz crystal lands on pin 52, the six LEDs on pins 10, 11, 13, 14, 15 and 16, and the USB chip's serial port (a BL702) on pins 17 and 18.
  • IO_LOC "port" pin; places a port on a pin. That's the whole join.
  • IO_PORT "port" ...; sets the pin's electrical behaviour. IO_TYPE=LVCMOS33 is a 3.3 V single-ended signal. PULL_MODE=UP holds an unconnected input high (the reset button pulls it low). DRIVE=8 is the output current in mA.
  • HDMI pairs. TMDS needs differential pairs. On the 9K they are emulated (ELVDS_OBUF: two ordinary pins driven opposite), so the schematic pairs 68/69, 70/71, 72/73 and 74/75. The 20K's file uses true LVDS25 buffers instead.
  • The flash pins 59–62 are normally used to configure the FPGA. --mspi_as_gpio (in boards/tangnano9k/board.mk) gives them to the design after configuration, so the CPU can execute from the flash.

Timing is a constraint too. The pins file says where; the .sdc file says how fast: three create_clock lines, the 27 MHz crystal, clk_5x at 124.875 MHz and clk_sys at 24.975 MHz. Without them the timing analyser has nothing to check against (lesson 6.5). The ULX3S keeps both kinds in one .lpf: LOCATE COMP for pins, FREQUENCY PORT for the clock.

Gowin's IDE reads its own copies, project/nandtier.cst and project/nandtier.sdc. Keep them in step with boards/tangnano9k/.

2

Explore

The Tang Nano 9K's GW1NR-9 in its QN88 package, pins counted anticlockwise from pin 1. Copper pins are used by NandTier; click one, or pick a port, to see its line in boards/tangnano9k/tangnano9k.cst.

BENCH · GW1NR-LV9QN88 · 88 PINS
THIS PIN
3

Try

Read the answers off the bench.

4

Build

The three kinds of constraint NandTier uses, from boards/.

// boards/tangnano9k/tangnano9k.cst  (pins, for nextpnr and gowin_pack)
IO_LOC  "clk" 52;                                        // 27 MHz crystal
IO_PORT "clk" IO_TYPE=LVCMOS33 PULL_MODE=UP;
IO_LOC  "resetn" 4;                                      // S1 button, active low
IO_LOC  "tmds_d_p[0]" 71;  IO_LOC "tmds_d_n[0]" 70;     // HDMI, emulated LVDS
IO_LOC  "ser_tx" 17;
IO_PORT "ser_tx" IO_TYPE=LVCMOS33 PULL_MODE=UP DRIVE=8;

# boards/tangnano9k/tangnano9k.sdc  (clocks, for nextpnr)
create_clock -name clk     -period 37.037 [get_ports {clk}]    ;# 27 MHz crystal
create_clock -name clk_5x  -period 8.008  [get_nets {clk_5x}]  ;# rPLL, 124.875 MHz
create_clock -name clk_sys -period 40.040 [get_nets {clk_sys}] ;# CLKDIV /5, 24.975 MHz

# boards/ulx3s/ulx3s.lpf  (pins and clocks together, for nextpnr-ecp5)
LOCATE COMP "clk_25mhz" SITE "G2";
IOBUF  PORT "clk_25mhz" PULLMODE=NONE IO_TYPE=LVCMOS33;
FREQUENCY PORT "clk_25mhz" 25 MHZ;
LAB 6D · 20 MINMove a LED

Swap gpio[0] and gpio[5] in the .cst, rebuild, and press 1 in the launcher. Which LED toggles now? Undo it after.

Show answer
# boards/tangnano9k/tangnano9k.cst: swap the two pin numbers
IO_LOC "gpio[0]" 16;   # was 10
IO_LOC "gpio[5]" 10;   # was 16

Key 1 toggles gpio[0] in software (GPIO_OUT ^= 1 << 0). After the swap, gpio[0] is wired to pin 16, so the LED at the other end of the row (LED 5) toggles instead of LED 0. Nothing in the firmware changed: the constraint file decides which physical pin a signal reaches.

A WRONG PINFails quietly

A port on the wrong pin still builds. The tools only check the pin exists and fits the bank, so a swapped wire shows up on the board, not in the log.

PULL-UPSInputs that float

The UART receive line and the reset button have PULL_MODE=UP: unplugged, they read as idle and not pressed.

TIER 6 · DEBUG · LESSON 5 OF 8

Reading a schematic

Frames, sheets, symbols, references, nets, labels, power and pins: a method for any board.

videobench4 auto-checked questions
2

Explore

This is the real Tang Nano 9K schematic. Pick a part, and the bench follows its net to the FPGA pin.

BENCH · FOLLOW A NET
NET

3

Try

Four quick questions.

4

Build

A schematic tool can export what you just traced by eye: every net, and every pin on it. This is the shape of a KiCad netlist entry.

(net (code "12") (name "/GW1NR 9K/PIN52_XTAL_IN")
  (node (ref "R26") (pin "1"))       ; the oscillator's series resistor
  (node (ref "U5")  (pin "52")       ; the FPGA: IOR17A / GCLKT_3
        (pinfunction "IOR17A/GCLKT_3")))
METHODFour steps

Pick a part, follow its wire, read the label, find the pin.

SOURCEThe real board

Tang Nano 9K schematic, 5 sheets, drawn in KiCad.

TIER 6 · DEBUG · LESSON 6 OF 8

The Tang Nano 9K, net by net

Every line of NandTier's constraints file, checked against the real schematic.

videobench4 auto-checked questions
2

Explore

Pick a group of lines from tangnano9k.cst. The bench shows the wire on the schematic it describes, and whether they match.

BENCH · CST ↔ SCHEMATIC
MATCH

3

Try

Four quick questions.

4

Build

NandTier's Tang Nano 9K constraints for the clock and the LEDs, with each line's source on the schematic. The LED lines spell out the bank's I/O standard.

// 27 MHz oscillator U16 → R26 → pin 52 (IOR17A / GCLKT_3, bank 1, 3.3 V)
IO_LOC  "clk" 52;
IO_PORT "clk" IO_TYPE=LVCMOS33 PULL_MODE=UP;

// LED1..LED6: anode to VCCO3 (1.8 V), cathode to the pin → active low
IO_LOC  "gpio[0]" 10;          // PIN10_IOL15A_LED1
IO_PORT "gpio[0]" IO_TYPE=LVCMOS18 PULL_MODE=UP DRIVE=8;
// … gpio[1..5] on 11, 13, 14, 15, 16
WATCH OUTS1 and S2

The net names and the switch labels disagree. Trust the wire and the pin number.

WATCH OUTShared pins

Pins 68 to 75 go to HDMI and to the RGB screen connector: use one or the other.

TIER 6 · DEBUG · LESSON 7 OF 8

Drawing your own schematic

Plan, sheets, symbols, labels, power, rules check, and the constraints file from the drawing.

videobench4 auto-checked questions
2

Explore

Add an LED or a button to a Tang Nano 9K pin. The bench names the net, picks the I/O standard from the bank voltage, and writes the constraint lines. It also warns about pins the board already uses.

BENCH · NET → CONSTRAINT
RESULT

3

Try

Four quick questions.

4

Build

A small script that turns exported FPGA nets named PINnn_JOB into constraint lines, with the I/O standard taken from each pin's bank.

import re
BANK_V = lambda pin: 1.8 if pin <= 16 or pin >= 79 else 3.3     # Tang Nano 9K banks
for net in open("fpga_nets.txt"):                               # e.g. PIN10_IOL15A_LED1
    m = re.match(r"PIN(\d+)_\w*?_(\w+)$", net.strip())
    if not m: continue
    pin, job = int(m[1]), m[2].lower()
    std = "LVCMOS18" if BANK_V(pin) == 1.8 else "LVCMOS33"
    print(f'IO_LOC  "{job}" {pin};')
    print(f'IO_PORT "{job}" IO_TYPE={std};')
TOOLKiCad

Free and open source: schematic, rules check, and netlist export.

HABITCheck every line

After writing the constraints, check each pin against the drawing.

TIER 6 · DEBUG · LESSON 8 OF 8

Static timing analysis

Check every path between two flip-flops against the clock without simulating: arrival, required time, slack, and the real worst path of NandTier.

videoreading, 12 mintwo real critical paths, step by step4 checks
1

Read

Simulation checks what the design does. Static timing analysis (STA) checks whether it does it in time, for every path at once, without any test vectors. It adds up delays along each path from one flip-flop to the next and compares the total with the clock period from the .sdc file.

  • Arrival time. The clock reaches the launching flip-flop, its output changes (clock-to-Q), and the signal crosses logic (LUTs, carry chains) and routing (wires and switches) to the next flip-flop's D input.
  • Required time. The next clock edge, one period later, minus the flip-flop's setup time, plus any difference in when the clock reaches the two flip-flops (skew).
  • Slack = required − arrival. Positive: the path is in time. Negative: the chip may latch a wrong value. Fmax is the clock at which the worst slack would reach zero.
  • Hold is the opposite check: the new value must not arrive too soon, before the receiving flip-flop has safely captured the old one. In one clock domain on an FPGA, the tools fix hold by routing; you rarely see it fail.

NandTier's worst path, before and after. Both toolchains used to agree on where it was: in the logic analyzer. From sample_count, through oldest_ptr + read_index (which slot is the oldest), then a 128-to-1 multiplexer over 1,024 flag flip-flops, into sample_flags_q. On the 9K, Gowin reported 12 logic levels, Fmax 33.7 MHz against the 24.975 MHz needed: slack 10.4 ns. On the 20K the open flow reported 96.1 MHz. The bench below shows those two reports.

How it was shortened. The flags moved into block RAM next to the data, so the multiplexer is gone. The worst path moved: on the 20K it now runs from the text terminal's screen memory to its text_on flip-flop, 29 steps, 12.2 ns, 82.2 MHz. Fixing one path always reveals the next one. Timing reports tell you which path to fix; the design decides how.

Multiple clocks. Paths between clk_5x and clk_sys are timed too, because both come from one PLL and are related. The JTAG crossing on the ULX3S is declared asynchronous and isn't timed; the toggle handshake makes it safe instead (lesson 6.3).

2

Explore

The worst path from each report, as it was before the flags fix, step by step. Hover a segment, or pick a step, to see the cell it reaches. Grey is the clock and the flip-flop, amber is logic, teal is routing.

BENCH · THE CRITICAL PATH
THE CHECK
3

Try

The arithmetic of a timing report. Numbers in ns or MHz; two decimals is enough.

4

Build

Where the numbers come from: nextpnr writes a JSON report, Gowin writes impl/pnr/nandtier.tr.html and a .timing_paths file.

# open flow: the critical path from nextpnr's report (Tang Nano 20K)
make fpga BOARD=tangnano20k
python3 - <<'EOF'
import json
r = json.load(open('oss/build/tangnano20k/report.json'))
p = r['critical_paths'][0]['path']
for t in ('clk-to-q', 'logic', 'routing', 'setup'):
    print(t, round(sum(s['delay'] for s in p if s['type'] == t), 3))
print('fmax', r['fmax'])
EOF
# clk-to-q 2.259  logic 4.676  routing 5.197  setup 0.035
# fmax {'clk_sys': {'achieved': 82.19, 'constraint': 24.975}}

# Gowin IDE flow (Tang Nano 9K, before the flags fix): impl/pnr/nandtier.tr.html
#   Max Frequency Summary: clk_sys  24.975 MHz  33.713 MHz  12 levels
#   path 1: arrival 29.834  required 40.212  slack 10.378
LAB 6E · 30 MINFind the new worst path

Build the 20K with the open flow and read the critical path from report.json. Name the flip-flop or memory it starts at, the flip-flop it ends at, and the module they belong to.

Show answer
make fpga BOARD=tangnano20k
python3 - <<'EOF'
import json
r = json.load(open('oss/build/tangnano20k/report.json'))
p = r['critical_paths'][0]['path']
print(p[0]['from']['cell'], '->', p[-1]['to']['cell'])
print(len(p), 'steps', round(sum(x['delay'] for x in p), 3), 'ns', r['fmax'])
EOF
u_soc.u_video.u_term.screen.0.0 -> u_soc.u_video.u_term.text_on_DFF_Q
29 steps 12.167 ns {'clk_sys': {'achieved': 82.19, 'constraint': 24.975}}

Measured on the current code. The path starts at a block RAM output (the text terminal's screen memory, port DOB1) and ends at the terminal's text_on flip-flop, all inside nt_text_term. That is why clock-to-Q is large here (2.26 ns): a block RAM output is slower than a flip-flop's. With 82 MHz against the 25 MHz needed there is no reason to fix it, and that is the other half of sign-off: you stop when every path has positive slack.

SLACK, NOT FMAXWhat sign-off means

A design passes when every path's slack is ≥ 0 at the clock you actually run, for every clock. Fmax is a summary of one number.

PLACED VS ROUTEDRead the final report

nextpnr prints an Fmax after placement and again after routing. Only the routed one counts.