$ cat posts/building-my-own-computer.md
Building my own computer, from the instruction set up
Most of my courses explain one layer of a computer at a time: logic, then processors, then compilers, then operating systems. I wanted to see how the layers fit together, so I decided to design every one of them myself and run the result on real hardware. The project is called Bedrock.
The target board is a Sipeed Tang Nano 20K: a Gowin GW2AR-18 FPGA with 8 MB of SDRAM in the same package. It’s small and cheap, but it’s enough for a complete little computer.
The layers
| Layer | What I built |
|---|---|
| Instruction set | BR32, my own 32-bit RISC instruction set |
| Processors | M1, a multi-cycle CPU, and P5, a 5-stage pipeline, both in Verilog |
| Memory | instruction and data caches, a write-back system cache and an SDRAM controller |
| Toolchain | an assembler, linker and emulator in Python, plus a C compiler (a port of chibicc) |
| Operating system | Flint, a small Unix-like kernel inspired by xv6, with a shell and programs like ls, cat, grep and ps |
I even built an ALU out of 2,991 NAND gates, just to prove to myself that it all really does come down to one kind of gate. It can be dropped into the CPU in place of the normal one.
Testing everything in lockstep
A bug in a CPU can hide for millions of cycles. To catch them early, the Python emulator acts as a golden model. The Verilog design runs in Verilator in lockstep with it, and the moment the two disagree about a single register, the simulation stops and says where.
make test # instruction, compiler and memory tests on both CPUs
make sim CPU=p5 # boot Flint on the pipelined CPU in Verilator
make bitstream # build the FPGA image for the Tang Nano 20K
Every test passes on the emulator, on both CPUs, and on a model of the board’s real memory system.
What a cache is worth
The most satisfying change so far was making the system cache write-back instead of write-through. Here’s the average number of clock cycles per instruction (CPI) on my benchmark:
| CPU | Before | After |
|---|---|---|
| M1 (multi-cycle) | 7.79 | 6.81 |
| P5 (pipelined) | 2.64 | 1.34 |
With the new cache, the pipelined CPU runs as fast as it does with perfect, zero-wait memory.
I also added a czero instruction that zeroes a whole 16-byte cache line at once, to speed up memset and copying. It helped on the pipeline, but it made copying slightly slower on the multi-cycle CPU, where the extra instruction cost as much as the memory traffic it saved. Measure, don’t guess.
Next: the real board
So far all of this runs in simulation. Both designs fit on the FPGA (about 30% and 40% of the logic) and close timing at the board’s 27 MHz clock. The next step is to load the bitstream onto the actual Tang Nano and watch Flint boot over the serial port. That will be its own post.