2. Bytes, words, and the image
Why this layer exists
Every later object in this book, ember the kernel and hearth the type-1 hypervisor, is an image: bytes plus the addresses they must sit at, which the CPU starts executing with no one underneath it. This chapter builds the smallest image that boots, prints where the linker placed everything, and exits. ember is such an image, kept small, and the skill is the one hearth uses in Part VII when it boots as a -kernel with no Linux under it: know where your first byte lies, know how you were entered, own the whole machine from instruction one.
Mechanism
Why a kernel is not a process
A process is a program that a kernel has already made a home for. By the time its main runs, three things have happened that the program never wrote.
A loader read the executable and placed each loadable segment where the program expects to find it. The program’s first byte is wherever the kernel put it, at an address the kernel arranged to exist for that program alone. A kernel has no one to do this for it. Its first byte must already be where the machine’s entry mechanism looks, and the next section derives where that is for this board.
An exit path exists. A process ends by asking the kernel (the exit system call) and the kernel reclaims its memory, closes its files and tells its parent. A kernel has no parent and nothing to ask. Stopping is something it does to the machine, by driving a device the board provides for the purpose; the last Mechanism section describes ember’s.
A stack was set up. On Linux the kernel builds the initial stack, with the arguments and environment on it, and maps .bss as zero-filled memory; the C runtime’s startup code then runs and calls main. In a freestanding image none of that exists. The first instructions must give the CPU a stack before any C function can be entered, and must zero .bss themselves.
Two more services follow from those and matter later. A process that faults is handled or killed by a kernel that was waiting for the fault; a kernel that faults has no one to deliver it to, and the CPU sends it to whatever address its trap-vector register holds, whose reset value the privileged specification leaves unspecified (chapter 3 installs a shim in M-mode, machine mode, the most privileged level, and chapter 5 a handler in S-mode, supervisor mode, where a kernel normally runs; exercise (b) shows what QEMU does with nothing installed). And a process sees addresses that translation (the hardware rewriting the addresses a program names before the bus decodes them; chapter 4 builds it) made up for it, whereas the image sees the board’s own: the numbers the bus decodes, until chapter 4.
A type-1 hypervisor is not a kernel with extra flags. It is entered exactly as this image is, the first thing the CPU runs, so everything above applies to it unchanged. The mistake is to read the rest as a kernel with a feature switched on. The two differ in what they serve. A kernel’s clients are processes, which were written to call it: most services are requests, arriving through one instruction at a system-call table the kernel owns (ecall, the instruction a program executes to ask the kernel for service on purpose; chapter 5). A hypervisor’s client is a kernel that does not know it has a landlord. The guest executes privileged instructions as though it owned the machine, writes its own page tables, and takes its own interrupts. None of those privileged acts is a request, and no code on the hypervisor’s side can turn it into one, because the guest does them itself even if it also makes some requests (a guest ecall is one, and chapter 18 follows it). What the hypervisor needs from the hardware is a way to give the guest private copies of the state it believes it owns and to stop it at the acts that touch what the hypervisor keeps, and a second layer of translation under the guest’s own (chapters 18 and 19, the hardware support the RISC-V H extension adds). That is a different contract with the CPU, not a kernel with options. It is also why hearth has no system-call table: an image with one is a kernel hosting processes, the arrangement wick has from the other side, a Linux process asking its host kernel for a virtual machine.
The reset contract
The board decodes every address that a load, a store or an instruction fetch puts on the bus to one of three kinds of target. ROM (read-only memory) holds a few instructions the board builder wrote and software cannot change. DRAM (dynamic RAM, the board’s main memory) holds everything the image owns. A device exposes its registers at fixed addresses so that an ordinary load or store reads or writes the device; that arrangement is memory-mapped I/O (MMIO), and this chapter’s two devices, the UART (the serial port) and the exit device, are both reached that way. Every address in this chapter is such a bus address. Chapter 4 names the other kind of address, the one a program uses once translation is on.
Power-on is not a blank page. On this board, with -bios none -kernel ember.elf, the hart (RISC-V for hardware thread: one fetch/decode/execute context with its own control registers) comes out of reset in M-mode (chapter 3) at 0x1000, in the ROM. QEMU builds its instructions in riscv_setup_rom_reset_vec (hw/riscv/boot.c):
1: auipc t0, %pcrel_hi(fw_dyn) # t0 -> the data words that follow
addi a2, t0, %pcrel_lo(1b)
csrr a0, mhartid # a0 = the hart's ID
ld a1, 32(t0) # a1 = where the device tree blob was loaded
ld t0, 24(t0) # t0 = start_addr
jr t0 # jump there
Three facts fall out, binding for everything this book builds on this board:
a0= hart ID,a1= device tree. The image does not guess which hart it is; the ROM tells it. The flattened device tree (FDT) is a format the board builder uses to describe the hardware; a file in that format is a device tree blob (DTB), anda1points at one in DRAM. This chapter’s image never parses it, since every address it uses is on this page, but the blob is there, and a guest that wants to discover devices instead of hard-coding them reads it (exercise (f) dumps it).- The jump target is a board constant, not your ELF’s entry point. In
hw/riscv/virt.c, thestart_addrhanded to that ROM ismemmap[VIRT_DRAM].base, the DRAM base0x80000000.jr t0therefore lands on whatever byte is at0x80000000. Your kernel, given as-kernel, is loaded byriscv_load_kernelwith itsPT_LOADsegments copied to their physical addresses (p_paddr); QEMU does not read the ELF’se_entryon this path at all: in QEMU v11.1.1 (a QEMU board behaviour, not a RISC-V one),riscv_load_kernelinhw/riscv/boot.ccalls the ELF loader without an entry pointer, and the kernel entry it hands on is the image’s lowest load address (the function’s own comment says it uses “low address not ELF entry point”). That address goes into the firmware-info block a firmware like OpenSBI would consume, and the-bios noneROM never reads the block. Link the image’s first byte at0x80000000, or be loaded but never entered. - The hart is in M-mode. The privileged specification’s Reset section says that “a hart’s privilege mode is set to M” and that
pc“is set to an implementation-defined reset vector”, which is why the vector at0x1000is QEMU’s choice and not the architecture’s. With-bios nonethere is no firmware to hand off to S-mode. We take the machine bare, with everything ours; chapter 3 is the whole story of what M-mode is and how to leave it.
The figure’s left column is the board’s address ladder; the right is DRAM expanded into the image. The arrow between them is the ROM’s jump: everything in this chapter happens along it.
What -bios none removes
The default boot, -bios default, loads OpenSBI into DRAM at 0x80000000 and starts it in M-mode; OpenSBI later enters your kernel in S-mode at a higher address. OpenSBI owns M-mode: the timer, the platform services, the first trap handlers. That is the comfortable division every real RISC-V system runs. -bios none deletes it: nothing is at 0x80000000 but your image, there is no SBI (the supervisor binary interface, the firmware services an S-mode kernel calls) to call, no one to ask for anything. The price of taking the machine bare is that every M-mode obligation this book eventually names (the traps that stay in M, the timer shim) is yours from reset.
The ELF as a container
The linker emits an ELF with three parts that matter here: sections: .text for code, .rodata for read-only data, .data for initialized writable data, .bss for zero-initialized data; program headers: the loadable segments, each recording a file offset, a size, and the physical address p_paddr where the bytes land; and e_entry, the entry point convention. QEMU’s loader (in hw/core/loader.c) walks the program headers and copies each PT_LOAD segment to its physical address. Each segment is placed by two addresses that the linker records separately: the load address (LMA, where its bytes land) and the run address (VMA, the address its symbols resolve to, where the code expects to execute). In this image they are equal everywhere, because the linker script pins them together and uses no AT(), and that equality is load-bearing. The image runs with no translation (translation, chapter 4’s subject), so the numbers in the image are the numbers on the bus. Chapter 4 can then turn translation on over an identity map, a translation that sends every address to the same number, without moving anything.
Why does the ELF carry two addresses at all? Because in a general system they differ: a kernel linked to run at a high address that only translation makes valid, but loaded low, needs AT() in its link script so the file’s bytes sit at the low load address while symbols resolve to the high run address. That split is the norm for S-mode kernels; this image deliberately does without it.
ENTRY(_start) stays in the link script anyway. It makes the ELF self-describing (objdump -f, gdb, and any loader that does honor entry points read it). QEMU’s -bios default flow does not use it: OpenSBI is given the image’s lowest load address (hw/riscv/virt.c, v11.1.1), so on this board the entry is decorative, and the chapter says so outright: the acceptance test is behavioral. The lab boots and the transcript matches; relink elsewhere and nothing runs (exercise (b) makes you watch it happen).
The linker script as a contract with the CPU
Read ember/link.ld in the walkthrough below; here is what each clause buys.
. = 0x80000000;sets the location counter to the DRAM base. Every section that follows is placed relative to it. Move this line, move the image.KEEP(*(.text.start))pins the entry section first in.text.KEEPdefeats the linker’s garbage collection:_startis referenced by no symbol the linker can see (the reset vector jumps to an address, not to a symbol), so withoutKEEPthe section could be dropped and the image’s first bytes could be anything..bss (NOLOAD)gives.bssno file bytes. The ELF records the section’s address and size, and zero bytes of image; DRAM comes up with arbitrary contents (QEMU happens to zero it; real hardware does not promise to), sostart.Smust zero the range before any C runs. An uninitialized global in C is a promise the image itself keeps.- The symbols the script defines (
__bss_start,__bss_end,stack_top) are addresses, not variables. C sees them asextern char __bss_start[]; the value is the link-time constant. That is why the capture can print them: every number was fixed when the linker ran, before the machine booted.
The stack
la sp, stack_top is the first instruction of the image for a reason: the ABI (application binary interface: the register and stack rules that compiled code and the compiler agree on) requires a valid, 16-byte-aligned sp at every call boundary, and no one else will provide one. stack_top is the top of a 256 KiB region the script reserves after .bss; the stack grows down into it. The region sits inside the image rather than at the top of DRAM to keep every symbol address inside one ±2 GiB band, which is what -mcmodel=medany guarantees for auipc-relative addressing. A 128 MiB DRAM would fit either way; the discipline of keeping the image compact pays the moment it grows.
Freestanding C
-nostdlib -nostartfiles -ffreestanding -fno-builtin strips assumptions you did not know you had. No startup files: nothing sets a stack, clears .bss, or calls main, and start.S does all three. No libc: no memcpy, no printf, no malloc, which is why the chapter’s UART and number printing are hand-rolled. One caveat is worth stating because it bites eventually: GCC documents that even in freestanding mode it may emit calls to memcpy, memmove, memset, and memcmp for operations it chooses to synthesize. This image compiles and links clean, since none were emitted, but the first time one appears, the link fails with an undefined reference, and the fix is to provide the four functions, not to hunt a flag.
The UART as raw MMIO
The ns16550a UART at 0x10000000 is a bank of byte-wide registers spaced one byte apart; the device tree for this board has no reg-shift property. The registers this chapter needs:
| Register | Offset | Meaning |
|---|---|---|
| THR (write), RBR (read) | +0 |
the byte to send; the byte that arrived |
| IER | +1 |
interrupt enables (chapter 5) |
| FCR (write), IIR (read) | +2 |
FIFO control, interrupt identification (chapter 5) |
| LCR | +3 |
line control: divisor latch, data format |
| LSR | +5 |
line status: bit 5 (0x20) transmitter holding register empty, bit 0 (0x01) data ready |
Sending a byte is two steps: wait for LSR bit 5, then store the byte to THR. Receiving is the mirror: LSR bit 0 says RBR holds an unread byte. The volatile on the device pointer is not decoration: it is what tells the compiler the pointed-to state can change between reads, so at -O2 the poll loop cannot be hoisted out or the store to THR sunk past the poll.
One board wart, taught now because the lab shows it: no divisor is ever programmed (the divisor latch lives behind LCR bit 7). Output works anyway, and the lab’s transcript is the proof. QEMU’s 16550 model does not gate the transmitter on the divisor; it drains THR as fast as the guest polls. A physical 16550 without its divisor programmed can drop characters or send garbage framing. The lesson is not “QEMU is lax”; it is that the device decides what a register write means, and the device tree only describes what the board builder wired. The UART’s clock-frequency shows the pitfall of reading a dump: dtc prints its four bytes as the strings "", "8@", because they happen to look like text, and as a 32-bit cell they are 3686400 (labs/ch02/ex/dtb.txt). The property is fine and the reading was wrong. When the description and the behavior disagree, the lab is the arbiter.
The finisher: the only exit the board offers
There is no exit(2) for an image and no parent to return to. The virt board carries a small device for exactly this: the SiFive test finisher at 0x00100000 (hw/misc/sifive_test.c). A write whose bits 15:0 are 0x5555 makes QEMU exit with the code in bits 31:16; low bits 0x3333 exit marking a failure; 0x7777 resets the machine. That write is ember’s halt(). The finisher is a board device, not an ISA feature (a test fiction, named as one), and it is the honest ancestor of the power-off register a real board gives you. hearth will use the same register when it wants QEMU to let go.
Walkthrough
The image in five listings, in link order. The reference code is ember/start.S, link.ld, uart.c, halt.c and main.c; every listing is shown as compiled at chapter 2, and the files carry other chapters’ branches that this chapter does not.
start.S, the no-one-else instructions. la sp, stack_top provides the stack nothing else will. csrr a2, mhartid reads the hart ID from the CSR (control and status register; chapter 3) into the third argument register; the ROM put the same number in a0, and the capture prints both to prove they agree. The loop zeroes .bss eight bytes per store until __bss_end, comparing addresses unsigned with bgeu. Then call main, and, because main returning would be undefined, a wfi loop (wait for interrupt: the hart idles until an interrupt may need service; chapter 6 gives the instruction’s contract) that never yields.
.section .text.start, "ax", @progbits
.globl _start
_start:
la sp, stack_top
csrr a2, mhartid
la t0, __bss_start
la t1, __bss_end
1: bgeu t0, t1, 2f
sd zero, 0(t0)
addi t0, t0, 8
j 1b
2: call main
3: wfi
j 3b
How main receives its arguments: the reset contract left a0 (hart ID) and a1 (FDT) in registers; start.S added a2 = mhartid. The RISC-V calling convention makes a0–a7 the first arguments, so main(hartid, fdt, mhartid) reads them with no stack and no frame. main here is not the hosted main the C runtime calls; it is a plain function the image enters with the machine’s initial registers.
link.ld, the contract. The location counter’s first assignment pins the base; KEEP holds the entry section first in .text; .data absorbs the compiler’s small-data section (.sdata) so every initialized global lands in one place; .bss (NOLOAD) fixes the zero-promise; the reserved stack region defines stack_top, and after it sits chapter 4’s page-table pool: link.ld is one file for every chapter, and the pool is placed after stack_top so that it moves none of the symbols this chapter prints.
. = 0x80000000;
SECTIONS
{
.text : {
KEEP(*(.text.start))
*(.text .text.*)
}
.rodata : {
*(.rodata .rodata.*)
}
.data : {
*(.data .data.*)
*(.sdata .sdata.*)
}
.bss (NOLOAD) : {
__bss_start = .;
*(.sbss .sbss.*)
*(.bss .bss.*)
*(COMMON)
. = ALIGN(8);
__bss_end = .;
}
/* Stack, growing down from the top of the reserved region. */
. = ALIGN(16);
. = . + 0x40000; /* 256 KiB stack region */
. = ALIGN(16);
stack_top = .;
. = ALIGN(4096);
pt_pool_start = .;
. = . + 0x80000; /* 512 KiB page-table pool (ch 4) */
pt_pool_end = .;
}
uart.c, the polling driver. The while on LSR bit 5 is the handshake; the store to THR is the send. uart_getc returns the byte in RBR when LSR bit 0 says one arrived, else -1. The receive side is unused this chapter, and chapter 5’s interrupt path builds on it. The offsets are the byte-spaced table above; a board whose device tree declares reg-shift spaces every register by 4 instead, and exercise (e) makes the difference felt.
#define UART0 0x10000000UL
#define THR 0x0 /* transmit holding register (write) */
#define RBR 0x0 /* receive buffer register (read) */
#define LSR 0x5 /* line status register */
#define LSR_THR 0x20 /* THR empty: the transmitter can take another byte */
#define LSR_DR 0x01 /* data ready: RBR holds an unread byte */
static volatile unsigned char *const uart = (volatile unsigned char *)UART0;
void uart_putc(char c)
{
while ((uart[LSR] & LSR_THR) == 0)
;
uart[THR] = (unsigned char)c;
}
void uart_puts(const char *s)
{
while (*s)
uart_putc(*s++);
}
int uart_getc(void)
{
if ((uart[LSR] & LSR_DR) == 0)
return -1;
return uart[RBR];
}
halt.c, the finisher write. Clean exit: 0x5555. Failure: the code packed into bits 31:16 over 0x3333. The loop after the write exists because halt must not return on any board, and on a board without a finisher it never would.
#define FINISHER 0x00100000UL
#define FINISHER_PASS 0x5555 /* status: shut down, exit code in bits 31:16 */
#define FINISHER_FAIL 0x3333 /* status: panic, exit code in bits 31:16 */
static volatile unsigned int *const finisher = (volatile unsigned int *)FINISHER;
void halt(int code)
{
finisher[0] = code
? ((unsigned int)code << 16) | FINISHER_FAIL
: FINISHER_PASS;
/* Not reached on this board. */
for (;;)
;
}
main.c, the proof transcript. puthex prints a 64-bit value in hex with no library; sym_line prints one linker symbol’s value, which is the symbol’s address and not a dump of memory. The two proofs the lab pins: .data survived the load (data_word == 0x600d: bytes that were in the file), and .bss starts at zero (bss_probe[0] == bss_probe[31] == 0: bytes that were not). If a0 and mhartid disagree, the boot story is wrong; if either proof fails, the machine did not keep the ELF’s promises. Then PASS, halt(0).
/* Linker symbols: their values are addresses, fixed at link time. */
extern char _start[], __bss_start[], __bss_end[], stack_top[];
/* In .data: the image carries both these bytes and their address. */
static volatile unsigned long data_word = 0x600d;
/* In .bss: no file bytes; start.S zeroes the range before main runs. */
static volatile unsigned long bss_probe[32];
static void puthex(unsigned long v)
{
static const char digits[] = "0123456789abcdef";
int started = 0;
uart_puts("0x");
if (v == 0) {
uart_putc('0');
return;
}
for (unsigned long shift = 60;; shift -= 4) {
unsigned long d = (v >> shift) & 0xf;
if (d != 0 || started || shift == 0) {
uart_putc(digits[d]);
started = 1;
}
if (shift == 0)
break;
}
}
static void sym_line(const char *label, unsigned long addr)
{
uart_puts("ember: ");
uart_puts(label);
puthex(addr);
uart_puts("\r\n");
}
static void ch2_report(unsigned long hartid, unsigned long mhartid)
{
if (hartid != 0 || hartid != mhartid)
halt(1);
uart_puts("ember: hart a0=");
puthex(hartid);
uart_puts(" mhartid=");
puthex(mhartid);
uart_puts("\r\n");
/* Link-time addresses belong to chapter 2. Later labs must not
* pin them: a correct mine that differs in size would fail the
* diff before its stub ever ran. */
sym_line("_start ", (unsigned long)_start);
sym_line("__bss_start ", (unsigned long)__bss_start);
sym_line("__bss_end ", (unsigned long)__bss_end);
sym_line("data_word ", (unsigned long)&data_word);
sym_line("stack_top ", (unsigned long)stack_top);
uart_puts("ember: .data survived: data_word = ");
puthex(data_word);
uart_puts("\r\n");
uart_puts("ember: .bss zero: bss_probe[0] = ");
puthex(bss_probe[0]);
uart_puts(", bss_probe[31] = ");
puthex(bss_probe[31]);
uart_puts("\r\n");
}
Exercises
(a) Chapter 4 builds its tables over this image in units of one gibibyte ( bytes) at the top level, and the arithmetic it starts from needs no machinery. Divide 0x80000000 by : what are the quotient and the remainder? Do the same for the UART (0x10000000), the last virtio slot (0x10008000) and the last byte of DRAM (0x87ffffff, the board has 128 MiB).
Answer
0x80000000 is 231, so it divides by 230 as quotient 2, remainder 0: the DRAM base is the first byte of the third gibibyte of the address space. The last byte of DRAM, 0x87ffffff, is 231 + 227 - 1, still below 3 · 230, so its quotient is also 2: all 128 MiB of DRAM lie in that one gibibyte. The UART 0x10000000 is 228 and the last virtio slot 0x10008000 is a little above it, both under 230, so both have quotient 0. The remainders are 0, 0x10000000, 0x10008000 and 0x7ffffff. Every device the figure draws sits in the first gibibyte and every byte of DRAM in the third, so a table of 1 GiB entries covers all of them with two entries (the board has more devices, such as the PCIe windows, which do not sit there). Chapter 4 shows why the top level of a page table is divided at exactly this size, and what the rule is for an address with bits above that range.
(b) Relink ember at 0x80400000: change the one line in link.ld, rebuild, and boot it with the lab’s QEMU command. Describe what happens, and explain it from the reset vector.
Answer
The run is silent (labs/ch02/ex/reloc.txt holds only the line QEMU prints when timeout kills it). QEMU’s loader honors the program headers, so the image is in memory at 0x80400000, and readelf shows e_entry there too. The reset vector does not read e_entry. It jumps to start_addr, the board’s DRAM base 0x80000000, where nothing of the image now lives. QEMU’s own trace (labs/ch02/ex/reloc.trace, from -d int) shows the first thing the hart does: an illegal-instruction exception at epc = 0x80000000 with tval = 0, the fetch of an all-zero word, which is not an instruction. No handler was installed, and QEMU’s reset value for the trap-vector register is 0, so the hart is sent to address 0, where there is no memory; every one of the following exceptions in the trace is an instruction access fault at epc = 0, repeating until the timeout. This is the failure the “Why a kernel is not a process” section predicts for a kernel that faults: nobody catches it. The bytes are at 0x80400000, execution is at 0x80000000, and the two never meet.
(c) Add a 2 MiB uninitialized global array and rebuild. What happens to the ELF’s size on disk, and why? What happens at boot?
Answer
Two builds that differ only by the array: bss-base and bss-grow in labs/ch02/ex/. bss-grow.size compares them. The .bss section goes from 0x100 to 0x200100 bytes and the loadable segment’s MemSiz grows by exactly 0x200000, while its FileSiz is equal in the two images. The file on disk grows by 120 bytes (labs/ch02/ex/size.sh builds both with the Nix shell’s -rpath dropped, so the number does not depend on the directory the shell was started in; it is GCC 16.2.0 on straylight and another toolchain would give another small number), which is the new variable’s records in the symbol table, the string table and the debug sections, and not 2 MiB. No file bytes are added, because .bss (NOLOAD) records an address and a size and nothing else. At boot the image still passes. Each transcript prints the size of the range start.S clears (bss-base.txt: 0x100; bss-grow.txt: 0x200100), so the clear loop now runs 262,176 eight-byte stores where it ran 32, and bss_probe still reads zero. That is the whole point of NOLOAD: memory costs file bytes only when you initialize it, and costs boot time either way, which an emulator hides and hardware does not.
(d) In start.S, point the stack into the UART window: li sp, 0x10000008 in place of la sp, stack_top. Predict what you see, then run it.
Answer
Nothing prints (labs/ch02/ex/stack-uart.txt is only the timeout line), and the reason is not the one the exercise invites you to guess. The stack grows down. main opens with addi sp, sp, -32, which puts sp at 0x0fffffe8, below the UART, and its first store, sd s0, 16(sp) (this host’s GCC 16.2; the order of the prologue’s stores is the compiler’s choice), goes to 0x0ffffff8. QEMU’s trace (labs/ch02/ex/stack-uart.trace) records exactly that: a store access fault (cause = 7) with tval = 0x0ffffff8, at the first store of main’s prologue, because that address is in the hole between the interrupt controller and the UART where the board has nothing. With no handler installed the hart then falls into the same loop of instruction access faults at address 0 that exercise (b) shows. Pointing sp at a device does not turn the device into a stack. Every store has device semantics, so sp must name RAM; and because the stack grows down, naming the bottom of a region puts the first frame outside it.
(e) In a copy of ember/ or your finished mine/, poll LSR at +4 instead of +5. What do you see, and what does the missing reg-shift have to do with it?
Answer
Silence (labs/ch02/ex/lsr-plus4.txt). The trace (labs/ch02/ex/lsr-plus4.trace) lists the distinct blocks of straight-line code (QEMU calls them translation blocks) among the last 2000 lines of QEMU’s execution log: two, both in uart_puts, the three-instruction poll (lbu, andi 0x20, beqz) that the exercise moved. Why it never exits: labs/ch02/ex/uart-regs.txt reads both offsets after a normal boot and finds +5 = 0x60 (LSR with bit 5, transmitter empty, set) and +4 = 0x08. Offset +4 is register 4 on a byte-spaced 16550, the modem control register, and its bit 5 is clear. The DTB for this board has no reg-shift property, so the registers are one byte apart. On a 16550 with reg-shift = 2, four address bytes per register, register 5 would live at +20 and +4 would be register 1, IER. Same chip, different wiring: the stride is a board property the device tree describes, which is why a portable driver treats it as data instead of baking it into the code.
(f) Dump the board’s device tree and locate every node the figure’s left column shows:
qemu-system-riscv64 -machine virt,dumpdtb=virt.dtb -m 128M
dtc -I dtb -O dts -o virt.dts virt.dtb
Answer
labs/ch02/ex/dtb.sh runs those two commands and lists the nodes; labs/ch02/ex/dtb.txt is its output (QEMU 11.1.1 on the build host). memory@80000000 carries the DRAM base and size (reg = <0x00 0x80000000 0x00 0x8000000>, 128 MiB). The finisher is test@100000. The CLINT is clint@2000000 (compatible = "sifive,clint0", "riscv,clint0"). The PLIC is not named plic: it is interrupt-controller@c000000, and its compatible is "sifive,plic-1.0.0", "riscv,plic0". The UART is not named uart either: it is serial@10000000, compatible = "ns16550a". Eight virtio_mmio nodes run from 0x10001000 to 0x10008000. The board lists more than the figure draws: rtc@101000, fw-cfg@10100000, two flash banks at flash@20000000, pci@30000000, platform-bus@4000000 and cpu@0. The one box in the figure with no node is the ROM: the reset vector at 0x1000 is built by QEMU (riscv_setup_rom_reset_vec) and is not described in the DTB, because the DTB is written for the software the ROM is about to launch.
Lab
From the repository root:
make lab CH=02
builds the reference image, boots it under a 30-second timeout, feeds it the lab’s (empty) input.txt on stdin, and diffs the serial transcript against the committed capture.txt:
ember: hart a0=0x0 mhartid=0x0
ember: _start 0x80000000
ember: __bss_start 0x800007a0
ember: __bss_end 0x800008a0
ember: data_word 0x80000660
ember: stack_top 0x800408a0
ember: .data survived: data_word = 0x600d
ember: .bss zero: bss_probe[0] = 0x0, bss_probe[31] = 0x0
PASS
The capture pins the whole chapter. _start at 0x80000000 is the reset contract; the symbol lines are the linker’s contract; .data intact and .bss zero are the ELF’s contract; the two hart IDs agreeing is the register handoff. Every number is a link-time constant, so the transcript is byte-identical on every run, so the diff and not QEMU’s exit status is the acceptance.
Your copy is labs/ch02/mine/: the same tree with uart_putc, uart_getc, and halt stubbed as silent no-ops. Run:
make lab CH=02 IMPL=mine
and it fails loudly: an empty transcript against the capture, then the timeout’s kill message. Bring up the console and the exit: the register table and the finisher encoding are everything you need. When the diff goes quiet, you have written the image’s two device drivers, and chapter 3 can change the privilege mode they run in.
Exercises (b) to (e) are side runs: each is a patch in labs/ch02/ex/ applied to a scratch copy of ember/, so the tree is never edited. Run make ex CH=02 from the repository root, inside nix develop, to rebuild each patched image, boot it under the lab’s QEMU flags and diff its transcript against the committed one. trace.sh writes the .trace files, size.sh --record writes the .size file the answers cite (without --record it prints to stdout) and dtb.sh writes exercise (f)’s dtb.txt; the scripts that write overwrite those files, make ex does not diff them, and none of this is part of make check.
Further reading
- QEMU RISC-V
virtboard: the board every lab in this book boots: its devices, boot options, and the device tree it generates and passes to the guest. - Tool Interface Standard (TIS) Executable and Linking Format (ELF) Specification, Version 1.2 (TIS Committee, May 1995): sections, program headers, and the three fields this chapter separates:
p_vaddr,p_paddr(reserved by the spec for systems where physical addressing is relevant, which is this board) ande_entry. - The RISC-V Instruction Set Manual, Volume II: Privileged Architecture (RISC-V International; the version in the link is 20260120): the Reset section of the machine-level ISA chapter is the architecture’s whole statement about the first instruction; the CSR map is worth a skim now.