Module 9 · Lesson 85 of 112

Timers and interrupts on bare metal

Configure a RISC-V machine timer interrupt on QEMU and share state safely between the handler and main code using critical sections and interior mutability.

  • Beginner to advanced
  • 11 min read
  • 35 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM with gcc; for the challenge exercise, the previous lesson's Rust QEMU project and qemu-system-riscv64 (Ubuntu package qemu-system-misc)

Your place in the module
By the end you can 4 objectives
  • Configure the machine timer on QEMU virt: mtvec, mtimecmp, mie.MTIE, and mstatus.MIE
  • Share a counter between main code and an interrupt handler using critical-section and Mutex<RefCell<T>> instead of raw static mut
  • Explain what hardware saves on trap entry (mepc, mcause, mstatus) and what software must save, dispatch, and restore
  • Re-arm mtimecmp inside the handler so the timer interrupt does not storm
Video coming soonTimers and interrupts on bare metal
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The vector table and UART output
  • Cortex-M reads its initial stack pointer and reset handler address from the first two vector words.
  • RISC-V uses a platform-defined reset address and a separate trap vector register.
  • NS16550 accepts a byte when THRE is set, while PL011 accepts a write when TXFF is clear.
01

Sharing state without an OS

4 min read

The last lesson printed over a UART. This lesson answers how to set up a timer interrupt and share static state safely.

An interrupt is a function call you never wrote. The hardware stops your main loop at an arbitrary instruction, runs a handler, and resumes exactly where it stopped. That is the whole problem in one sentence: the handler can land between any two instructions of your main code, including between the two halves of counter += 1. The borrow checker reasons about one flow of control; it cannot see the second flow that the hardware injects. Rust marks that gap honestly: sharing mutable state across it is unsafe, and you must close the gap yourself.

The naive pattern is a :

rust
static mut TICKS: u64 = 0;

// main loop reads TICKS; the handler does:
unsafe { TICKS += 1; }

This compiles, and it is still wrong. On RISC-V, TICKS += 1 is three steps: load the old value into a register, add one, store it back. If the timer interrupt fires after the main loop's load but before its store, the handler increments the memory value, and then the main loop's store overwrites it with a stale result. One tick is silently lost. Making the variable volatile does not help: volatile forces the memory accesses to happen, but it does not make the three steps one indivisible unit. In edition 2024 the language pushes you away from this pattern: creating a reference to a static mut is denied by default (the static_mut_refs lint), so you either use raw pointers (&raw mut TICKS) or, better, stop sharing bare mutable statics at all.

The fix is a . The critical-section crate defines the API, and the riscv crate implements it for a single hart when you enable its critical-section-single-hart feature: entering the section clears the machine interrupt enable bit in mstatus, and leaving restores the previous state. The idiomatic bare-metal pattern, popularised by the bare-metal crate and the Cortex-M ecosystem, wraps the state in Mutex<RefCell<T>>:

rust
use core::cell::RefCell;
use critical_section::Mutex;

static TICKS: Mutex<RefCell<u64>> = Mutex::new(RefCell::new(0));

fn bump_ticks() {
    critical_section::with(|cs| {
        *TICKS.borrow(cs).borrow_mut() += 1;
    });
}

Two layers, two jobs. The Mutex here is not the blocking std::sync::Mutex from the threads lessons: it owns the value and only hands out a reference when you present the cs token, which you can obtain only inside critical_section::with, that is, only with interrupts off. That excludes the handler. But the token gives you a shared reference &RefCell<u64>, and a shared reference cannot mutate: that is where comes in. RefCell::borrow_mut turns &RefCell<u64> into a mutable borrow, checked at run time. Because the critical section already excluded every other context, the check never fails; it costs a counter increment, not a lock. The same wrapper works for a shared peripheral: put the UART writer struct inside Mutex<RefCell<Uart>> and both the main loop and the handler use it through the same token.

This is exactly the discipline Linux documents for signal handlers in signal-safety(7): a signal handler is the hosted-world twin of an interrupt handler, it can land between any two instructions, and shared state must be accessed in a way that cannot tear. Keep the section short: every cycle inside it is a cycle interrupts are blocked, which adds latency to every other event.

One counter, two contexts, no lost updatesMain loopTimer handlerTICKScs: read tickscs: add onecs: read again1. Main loop → TICKScs: read ticks2. Timer handler → TICKScs: add one3. Main loop → TICKScs: read again
Both contexts touch TICKS only inside a critical section, so the load-add-store sequences never interleave
02

Arming the machine timer

5 min read

The RISC-V privileged specification defines the timer facility, and QEMU's virt machine implements it with a CLINT (core-local interruptor) block. Two memory-mapped 64-bit registers matter. mtime at 0x0200_bff8 is a free-running counter clocked at 10 MHz on QEMU virt (the device tree's timebase-frequency property carries this value). mtimecmp for hart 0 at 0x0200_4000 is the compare register: whenever mtime >= mtimecmp, the machine timer interrupt pending bit (mip.MTIP) is set. There is no "acknowledge" write that clears it: the only way to deassert the interrupt is to move mtimecmp into the future. Linux's own timer subsystems (see the timers reference) solve the same re-arm problem for hrtimers; here you do it by hand in three lines.

QEMU virt: timer registers in the address map0x8000_0000DRAMcode, stack, statics0x1000_0000UART0NS16550A(other devices)0x0200_bff8mtimefree-running counter0x0200_4000mtimecmphart 0 compare0x8000_0000DRAMcode, stack, statics0x1000_0000UART0NS16550A(other devices)0x0200_bff8mtimefree-running counter0x0200_4000mtimecmphart 0 compare
The QEMU virt address map: the CLINT counter and compare registers sit below the UART you already use

Setup has four steps, and the order matters: you enable the global interrupt switch last, so nothing fires before the handler address and the compare value are in place.

Step by stepBringing up the machine timer
  1. Point mtvec at your trap entry, in direct mode, so every trap lands at the one entry point from the last lesson's table.

  2. Program mtimecmp with mtime + interval. At 10 MHz, an interval of 10_000_000 is one second.

  3. Set mie.MTIE, the machine timer interrupt enable bit, so this particular source may raise an interrupt.

  4. Set mstatus.MIE, the global machine interrupt enable. From this instruction onward, the handler can fire.

The code in this lesson targets edition 2024 and was built with critical-section = "1.2" and riscv = { version = "0.16", features = ["critical-section-single-hart"] }. The riscv register API changed between releases (older versions have mtvec::write(addr, mode) and mie::set_mtie), so keep to one version. In Rust, with the riscv crate's register API:

rust
use riscv::register::{mie, mstatus, mtvec::{self, Mtvec, TrapMode}};

const MTIME: *const u64 = 0x0200_bff8 as *const u64;
const MTIMECMP: *mut u64 = 0x0200_4000 as *mut u64;
const INTERVAL: u64 = 10_000_000; // 1 s at the 10 MHz timebase

unsafe extern "C" {
    fn trap_entry(); // defined in assembly, next section
}

/// # Safety
/// Call once, on the only hart, after the shared state is ready.
unsafe fn timer_init() {
    // SAFETY: fixed CLINT addresses of the QEMU virt machine, single hart.
    unsafe {
        mtvec::write(Mtvec::new(trap_entry as *const () as usize, TrapMode::Direct));
        let now = MTIME.read_volatile();
        MTIMECMP.write_volatile(now + INTERVAL);
        mie::set_mtimer();
        mstatus::set_mie();
    }
}

The reads and writes are volatile because these addresses are hardware, not memory: the counter changes on its own between two reads. On RV64 each register is one 64-bit store, so the write is indivisible; on RV32 a 64-bit register takes two 32-bit stores, and a half-written compare value can match by accident. The RISC-V privileged specification's recipe is to store all ones to the low word first, then the new high word, then the new low word, so the compare value never passes through a smaller value than intended.

The handler has exactly two jobs: re-arm, and record the event.

rust
#[unsafe(no_mangle)]
extern "C" fn machine_timer() {
    unsafe {
        MTIMECMP.write_volatile(MTIME.read_volatile() + INTERVAL);
    }
    critical_section::with(|cs| {
        *TICKS.borrow(cs).borrow_mut() += 1;
    });
}
The interrupt storm

If the handler returns without writing a future mtimecmp, the condition mtime >= mtimecmp is still true, mip.MTIP is still set, and the interrupt fires again the instant mret re-enables interrupts. The main loop never runs again; the board looks hung while the CPU is actually spinning in the handler at full speed. Re-arm first, before anything else that could take time.

The main loop then consumes the shared counter and does the slow work, printing over the UART writer from the last lesson:

rust
let mut last = 0;
loop {
    let ticks = critical_section::with(|cs| *TICKS.borrow(cs).borrow());
    if ticks != last {
        last = ticks;
        uart_puts("tick\n");
    }
    riscv::asm::wfi();
}

Put together with the UART driver of the last lesson and the startup code, this program printed tick once per second on qemu-system-riscv64 -machine virt -bios none in a real run (five lines in six seconds). wfi (wait for interrupt) halts the hart until an interrupt arrives, so the loop costs no busy cycles. Printing from the main loop keeps the handler tiny. You can print directly inside the handler, but then the UART must live behind the same Mutex<RefCell<...>>, and every character transmits with interrupts effectively blocked: at 115200 baud one character is roughly 87 microseconds of latency added to every other event. On a real board with an LED on a GPIO pin, the handler would write the GPIO set or clear register instead of bumping a counter; the sharing rules are identical.

Other timers, same shape

A Cortex-M part has SysTick in the core itself: a 24-bit down-counter with its own reload register and interrupt, so you program a reload value instead of a compare value. The Raspberry Pi's ARM cores use the architected generic timer with per-core compare registers. The pattern never changes: counter, compare or reload, enable bit, handler that re-arms.

03

Inside the trap: entry, dispatch, return

4 min read

So far trap_entry was a symbol you promised to define. This section opens it up, because the gap between "hardware jumped here" and "your Rust function runs" is where bare-metal interrupt code usually breaks.

Going deeperExplore the mechanism

On a trap taken into machine mode, the hardware does five things atomically: it writes the interrupted instruction's address to mepc; it writes the reason to mcause (the top bit, bit 63 on RV64, marks an interrupt, and the low bits carry the code: 7 is the machine timer interrupt, 3 machine software, 11 machine external); it copies mstatus.MIE into mstatus.MPIE and then clears MIE, so handlers run with interrupts off by default; it records the previous privilege mode in mstatus.MPP; and it jumps to the address in mtvec. In direct mode every trap goes to the single BASE address. In vectored mode, interrupts go to BASE + 4 * cause (a table of jump instructions, so the machine timer would land at BASE + 28), while exceptions still go to BASE.

mret reverses the hardware part: it copies MPIE back into MIE, sets MPIE to 1, and jumps to mepc. For an asynchronous interrupt, mepc already points at the instruction to resume, so you must not touch it. The famous mepc += 4 trick belongs to synchronous traps like ecall, where returning to the same instruction would loop forever; applying it to a timer interrupt silently skips one instruction of your main loop.

What hardware does not do is save your registers. A normal Rust function may clobber the caller-saved registers (ra, t0-t6, a0-a7: sixteen registers, 128 bytes on RV64) because the calling convention says the caller saved them. But the interrupted main loop is not a caller: it never agreed to this call. So the entry must be a small assembly trampoline that pushes those registers on the stack, calls a Rust dispatcher, pops them, and executes mret:

rust
core::arch::global_asm!(
    ".section .text.trap",
    ".globl trap_entry",
    "trap_entry:",
    "addi sp, sp, -128",
    "sd ra, 0(sp)",
    // ... sd t0..t6, a0..a7 at 8..120(sp) ...
    "call trap_dispatch",
    "ld ra, 0(sp)",
    // ... ld t0..t6, a0..a7 ...
    "addi sp, sp, 128",
    "mret",
);

The dispatcher is plain Rust and reads the cause the hardware left behind:

rust
#[unsafe(no_mangle)]
extern "C" fn trap_dispatch() {
    const MACHINE_TIMER: usize = (1usize << 63) | 7; // RV64
    if riscv::register::mcause::read().bits() == MACHINE_TIMER {
        machine_timer();
    } else {
        loop {} // unexpected trap: park here for the debugger
    }
}
The path of one timer interruptmtime >=mtimecmptimerinterruptpendingHardwaresaves statemepc,mcause, MIEoffJump tomtvecSaveregisterscaller-saved, on stackDispatchand re-armRestoreregistersmretMIE back onmtime >=mtimecmptimerinterruptpendingHardwaresaves statemepc,mcause, MIEoffJump tomtvecSaveregisterscaller-saved, on stackDispatchand re-armRestoreregistersmretMIE back on
The full path of one timer tick: hardware state save, software register save, dispatch and re-arm, restore, mret
Going deeperExplore the mechanism

Two refinements are worth knowing. First, you rarely write the trampoline by hand: the riscv-rt runtime crate provides an #[interrupt] attribute macro that generates the save/restore frame and wires the named handler (for example MachineTimer) into the vector, which is the RISC-V counterpart of the Cortex-M convention where hardware itself stacks eight registers on exception entry. Second, the critical-section-single-hart implementation is only sound because there is one hart: disabling interrupts on this hart excludes every other context. Start QEMU with -smp 2 and a second hart can touch your statics while this hart's interrupts are off; you then need a real spinlock-based critical-section implementation, and static sharing must be reasoned about like the multi-threaded case from the threads lessons.

This dispatch shape (read a cause, look up a handler, run it, acknowledge the source) is the same one Linux formalises in its generic IRQ layer, where flow handlers acknowledge and mask the interrupt controller before calling device handlers; you are writing the smallest possible version of that architecture. Notice the division of labour one more time: hardware saves mepc, mcause, and the interrupt enable state; software saves the working registers, re-arms the source, and updates shared state inside a critical section; mret undoes the hardware part. Get any one of those three wrong and the symptom is distinctive: a skipped instruction (touched mepc), a corrupted main loop (missing register save), or a storm (missing re-arm).

The next lesson, Building, loading, and debugging, answers how to turn this code into an image QEMU actually loads, and how to stop at trap_dispatch in a debugger to read mcause and mepc when the ticks do not arrive.

Key takeaways

  • A static mut increment is a load-add-store sequence; an interrupt landing in the middle loses an update, which is why access is unsafe and belongs inside a critical section.
  • On QEMU virt the CLINT mtime counter runs at 10 MHz; the machine timer interrupt is pending whenever mtime >= mtimecmp and stays pending until the handler writes a future compare value.
  • On trap entry hardware writes mepc and mcause and clears mstatus.MIE; software saves the caller-saved registers, dispatches on mcause, restores, and returns with mret.
  • Mutex<RefCell<T>> splits the job: the critical-section token excludes the interrupt, and RefCell provides interior mutability behind a shared reference.
Reflect
  1. Explain to a colleague, in two sentences: configure the machine timer on QEMU virt: mtvec, mtimecmp, mie.MTIE, and mstatus.MIE
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close