Skip to content

20a · The RISC-V Assembly Bridge

Released Thu Oct 1, in class

This is the README OSlings gives every student for 20a_asm_bridge (oslings lesson shows it). The starter code is not published here: it reaches you through OSlings, in class on the class network. Back to All Exercises.

Learn → Understand → Implement. Three small routines in RISC-V assembly, called from Rust, running on the bare machine. The last of them is exercise 35k in miniature — and the moment the rest of the course starts to make sense.

Learn

Every operating system has a floor below which the language cannot reach. There is no way to write "save every register and switch to another stack" in Rust, because Rust has no way to say it — the whole point of a register allocator is that you do not choose which registers get used. So kernels have a small amount of assembly, and it is always in the same three or four places.

This exercise is where you meet that floor. It is deliberately not part of the kernel: it is a tiny standalone program in asmlab/, so you can concentrate on the assembly without also worrying about page tables. But it runs on exactly the same emulated machine, boots the same way, and prints the same way as every kernel exercise from here on. Consider it a dress rehearsal for the boot sequence you write next week.

The register file

RV64 has 32 general-purpose registers, each 64 bits. They have numbers (x0–x31) and, much more usefully, ABI names that say what each is conventionally for:

Register ABI name Role
x0 zero Always zero. Writes to it are discarded.
x1 ra Return address — where ret jumps to.
x2 sp Stack pointer.
x5–x7, x28–x31 t0–t6 Temporaries. Caller-saved.
x10–x17 a0–a7 Arguments, and a0 is also the return value.
x8–x9, x18–x27 s0–s11 Saved registers. Callee-saved.

The last two rows carry the entire calling convention, so they are worth stating plainly:

  • Caller-saved (t0–t6, a0–a7) — a function you call may destroy these. If you need one afterwards, save it before the call.
  • Callee-saved (s0–s11, sp) — a function you call must give these back unchanged. If it wants to use s0, it has to save and restore it.

That distinction is the reason a context switch only has to save twelve or so registers rather than all thirty-one: the caller-saved ones were already spilled to the stack by whoever called swtch, so they are not the switch's problem.

Calling assembly from Rust

Two pieces connect them.

global_asm! drops raw assembly into your crate at module level. Whatever you .globl in there becomes a real symbol the linker can find:

core::arch::global_asm!(r#"
.globl add3
add3:
    add a0, a0, a1
    ret
"#);

The r#"..."# is a raw string — Rust does not process backslashes inside it, which matters because assembly is full of them.

extern "C" declares that symbol on the Rust side, with a signature:

extern "C" {
    pub fn add3(a: u64, b: u64, c: u64) -> u64;
}

"C" names the calling convention: arguments in a0, a1, a2, return value in a0. Rust cannot check this declaration against your assembly — it has no way to — so calling it is unsafe. The signature is a promise you are making, and if you get it wrong the failure is silent and strange.

The instructions you need

Instruction Meaning
add rd, rs1, rs2 rd = rs1 + rs2
addi rd, rs1, imm rd = rs1 + constant
li rd, imm Load a constant into rd
la rd, symbol Load the address of a symbol
lb rd, off(rs) Load one byte from memory at rs + off
sb rs2, off(rs1) Store one byte to memory at rs1 + off
ld rd, off(rs) Load a 64-bit doubleword
sd rs2, off(rs1) Store a 64-bit doubleword
beqz rs, label Branch if rs == 0
bnez rs, label Branch if rs != 0
j label Jump
call symbol Call a function (sets ra)
ret Return — jumps to the address in ra

Local labels. 1: and 2: are numeric labels you can reuse anywhere. Refer to them with a direction: 1b means "the nearest 1: backward" (loops), 2f means "the nearest 2: forward" (skipping ahead). This is how assembly avoids inventing a unique name for every loop.

A note on overflow. RISC-V's add wraps silently — there is no overflow trap. That is different from Rust's +, which panics in debug builds. The hardware simply has no opinion, and one of the checks below relies on that.

Understand

Open asmlab/src/ and read, in order:

  • main.rs — the given harness. It boots, calls each of your three routines, checks the results, and prints OSLINGS:PASS or a specific [fail] line. Read the checks: they tell you exactly what "correct" means, including the edge cases.
  • entry.rs — the boot trampoline. It sets sp and calls kmain. You will write this yourself in exercise 31k.
  • uart.rs — printing, which is a volatile byte store to 0x1000_0000.
  • asm.rs — the only file you edit.

Control flow:

QEMU loads asmlab at 0x8000_0000 → _entry (sets sp) → kmain
    → check_add3 → check_bytecopy → check_baby_swtch → PASS/FAIL → poweroff

Pay particular attention to check_baby_swtch. It sets up a second stack and a second "thread" of execution called co_entry, switches into it, and switches back. If you follow what it is doing, exercise 35k will hold no surprises at all.

Implement

In asmlab/src/asm.rs, fill in the three IMPLEMENT markers:

  1. add3 — add the three arguments, return the sum. Four lines including ret. This is the "does the calling convention work the way I think it does" check.

  2. bytecopy — copy n bytes from src to dst. Watch the n == 0 case: test before you copy, not after. The harness checks that copying zero bytes copies zero bytes, and that copying n bytes does not touch byte n + 1.

  3. baby_swtch — save ra, sp, s0, s1 into *old; load them from *new; ret. Save all four before loading any.

    This one is worth pausing on. The ret at the end jumps to the ra you just loaded, so this function does not return to its caller — it returns into whatever the other context was doing. That is a context switch. You are writing, in eight instructions, the mechanism that lets one CPU run many processes.

Check your work:

oslings run 20a_asm_bridge

This builds for riscv64gc-unknown-none-elf and boots the result in QEMU — the same harness every kernel exercise uses. It passes when the serial console prints OSLINGS:PASS. If a specific check fails, the harness names it; read that line, it points straight at the bug.

If QEMU hangs instead of printing anything, your baby_swtch probably stored the registers but never loaded them, so ret jumped somewhere meaningless.

Stuck? oslings hint.