Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

You have control: one owner for the loop

29 November 2026

Actual firmware

Right. Here we go. Now we’re writing some actual firmware.

Until now the loop blinked an LED and timed itself. #202 gives the loop’s state one owner, and it’s the first change where I read the machine code to check the Rust did what I meant. The work is in #210.

I’m interested in this part of the firmware because everything after it copies its shape. #5’s attitude estimate will be written by TIM3, the hardware timer whose interrupt runs the loop every millisecond, and read by #6’s MAVLink task, like the timing counters today. Whatever pattern the counters use, the attitude inherits.

That pattern had two faults. LoopTiming::record took &self on a shared static, so a second writer would compile and quietly lose counts. And every tick borrowed a RefCell inside a critical section, which kept a panic in a path with a 1 ms deadline. The stack drill in #198 died through that panic.

Taking it apart

Check this out. I take apart the release build, because that’s the image Renode flies. A debug build keeps overflow checks and skips link-time optimisation, so its listing would show code the board never runs.

(cd firmware && cargo build --release)

llvm-objdump comes with the toolchain, because rust-toolchain.toml adds llvm-tools-preview. It isn’t on PATH, so this puts the toolchain’s tools there for the shell:

PATH="$(rustc --print sysroot)/lib/rustlib/$(rustc -vV | sed -n 's/^host: //p')/bin:$PATH"

Then I ask it for the interrupt handler and nothing else:

llvm-objdump -d --no-show-raw-insn -C --disassemble-symbols=TIM3 \
  firmware/target/thumbv7em-none-eabihf/release/firmware

--disassemble-symbols=TIM3 keeps the listing to one function and -C demangles Rust’s names, so a call reads core::cell::panic_already_borrowed. --no-show-raw-insn drops the bytes. llvm-objdump also prints an @ imm tail on branches, which I’ve trimmed. This is the top of TIM3 on main, before the change:

 80001e8:  movw   r1, #0x48
 80001ec:  mrs    lr, primask
 80001f0:  cpsid  i
 80001f2:  movt   r1, #0x2000
 80001f6:  ldr    r0, [r1, #0x4]
 80001f8:  cmp    r0, #0x0
 80001fa:  bne    0x80002e8 <TIM3+0x108>

cpsid i masks every interrupt, which is the critical section. movw and movt build the address of the RefCell’s borrow flag, ldr loads it, and a non-zero flag branches to core::cell::panic_already_borrowed. That runs 1,000 times a second, before the tick does any work.

TIM3 is 98 instructions on main, so I don’t start by reading it top to bottom. I grep for the two things that cost a deadline. cpsid masks interrupts, and bl is a call, which is how a panic or drop code shows up:

llvm-objdump -d --no-show-raw-insn -C --disassemble-symbols=TIM3 \
  firmware/target/thumbv7em-none-eabihf/release/firmware | grep -E 'cpsid|bl\s'
 80001f0:  cpsid  i
 80002e8:  bl     0x8000c2a <core::cell::panic_already_borrowed>

Then I read back from each hit to the branch that guards it. A hit behind a branch the steady tick never takes costs nothing. A hit on the straight path runs every millisecond. The source can’t settle this, because the compiler adds and folds code after it.

The comparison with main now runs the same way every time. I build the commit before #210 in a second worktree, so both images sit side by side and neither build overwrites the other:

git worktree add --detach /tmp/baseline 40d4cf0^
(cd /tmp/baseline/firmware && cargo build --release)

Then the same Renode script flies each image. blackbox.resc takes another ELF through $bin, set before the include:

renode --console --disable-xwt -e '$bin = @/tmp/baseline/firmware/target/thumbv7em-none-eabihf/release/firmware;
  include @renode/blackbox.resc; pause;
  emulation RunFor "00:00:03"; runMacro $timing;
  emulation RunFor "00:00:03"; runMacro $timing; quit'

Renode runs for a moment before pause takes hold, and that moment varies, so the first reading differs between runs. I take the difference between two readings. Each 3 s RunFor adds exactly 3,000 ticks, and a one-count move in jitter is layout noise.

What it showed

The first version took the state from the main function on the first tick. Renode then showed a worst jitter of 187 ns at 3 s against 125 ns on main, three runs each. One count is usually layout noise, but this one was there by tick 55 every time, and a throwaway build that skipped the first tick’s comparison gave 125 ns again. Tick 1 was doing the hand-off before it read the timer.

So the hand-off moved out of the ticks altogether. Since 8518442, the main function leaves TIM3 stopped, unmasks its interrupt and pends it once, which marks the interrupt pending as if the timer had fired. I call that first entry the priming entry. It’s a run of TIM3 that isn’t a tick. It takes the loop from main, starts the timer and returns, so control passes once and is accepted before a single tick counts. Every entry after it should be a tick. No tick can enter before the pend. The timer isn’t counting yet, and embassy’s generate_update_event sets the timer’s update request source bit, URS, for the reload it forces, so that reload raises no update flag.

With the RefCell gone, the grep still found a call to panic_already_borrowed. Link-time optimisation had folded two identical panic stubs into one, and the other was the divide-by-zero check on the timer period. The name on the call was the one thing in the listing that wasn’t true. Making the period a NonZeroU32 removed the check, because the compiler knows it can’t divide by zero.

This is the same spot on the branch:

 80001ea:  movw   r9, #0x48
 80001ee:  movt   r9, #0x2000
 80001f2:  ldr.w  r0, [r9, #0x40]
 80001f6:  cbz    r0, 0x8000250 <TIM3+0x70>
 80001f8:  movw   r2, #0x410
 80001fc:  movt   r2, #0x4000
 8000200:  ldr    r0, [r2]
 8000202:  lsls   r0, r0, #0x1f
 8000204:  beq.w  0x80002fa <TIM3+0x11a>

The cbz skips to the priming entry while the loop is still empty, and every cpsid left in TIM3 sits behind it. The steady tick goes straight to 0x40000410, TIM3’s status register, and leaves unless the update flag is set. On the branch the grep finds four cpsid and one bl, all behind the cbz. They’re the take from HANDOFF and the drop code for whatever CONTROL held before, which the compiler can’t prove was empty.

Reviewing the PR turned up a gap that was already on main, which counted every entry to TIM3 as a tick. A pend with no update behind it, from a stray pend() or a debugger, counted too. The priming entry made the gap plain, because it’s one on purpose. This pends TIM3 by hand halfway through a run:

renode --console --disable-xwt -e 'include @renode/blackbox.resc; pause;
  emulation RunFor "00:00:03"; runMacro $timing;
  sysbus WriteDoubleWord 0xE000E200 0x20000000;
  emulation RunFor "00:00:03"; runMacro $timing; quit'

0xE000E200 is the NVIC’s ISPR0, the first of the Cortex-M4’s interrupt set-pending registers. Writing a 1 to a bit marks that interrupt pending, so the core takes it as soon as its priority allows, as if the peripheral had raised it. A 0 leaves a bit alone. TIM3 is interrupt 29 on the F407, so 0x20000000 pends TIM3 and nothing else. TIM3’s own update flag stays clear, which is what a stray pend() looks like to the handler. On main:

ticks 3057, overruns 0, missed 0, max jitter 125 ns
ticks 6058, overruns 0, missed 0, max jitter 186000 ns

On the branch:

ticks 3001, overruns 0, missed 0, max jitter 125 ns
ticks 6001, overruns 0, missed 0, max jitter 125 ns

One stray pend added a tick the timer never fired and put 186 µs of jitter in the record for good. Where the pend lands sets that figure, and it can reach a full period. The tick now checks the update flag before it reads either timer’s count, then clears it with a single write. Status flags on this timer clear when written 0 and ignore a 1, so writing !1 clears that flag and no other.

I got one figure wrong along the way. The PR first said jitter halved, 62 ns against 125 ns. That’s one count of the 16 MHz timer, and in Renode, which runs a flat 100 MIPS with no bus timing, one count moves with code layout. The PR now says jitter stays within a count.

Why it’s this way

A RefCell keeps a run-time borrow check and interrupt::free has to mask interrupts. A static mut inside a cortex-m-rt #[interrupt] handler needs neither.

static gives the loop storage for the whole run, at a fixed address in RAM. A plain local would live on the stack and be gone when the tick returns. Declaring it inside the handler scopes its name to that function, so nothing else in the firmware can name it. A static at module level would keep the loop just as well, but any code in the crate could reach it. llvm-nm shows where it landed:

llvm-nm -C firmware/target/thumbv7em-none-eabihf/release/firmware | grep CONTROL
20000088 b firmware::__cortex_m_rt_TIM3_trampoline::CONTROL

The lower-case b marks a local symbol in .bss, RAM that start-up zeroes. The branch’s listing sets r9 to 0x20000048, so 0x20000088 is r9 plus 0x40, the word it checks first. The macro hands the handler’s body a &mut to it. The compiler makes sure nothing else can name it, and a Cortex-M interrupt can’t preempt itself, so that &mut never needs a lock. There’s nothing left to check while the loop runs.

What it means for the firmware

State that a handler owns lives in that handler, where the compiler checks it. Shared state gets one writer, handed out once in the way Peripherals::take() works, and readers get plain loads. A value that can’t be zero goes in a type that says so, which drops the check. Any change that touches the tick gets the grep and read-back before it merges.

What’s next

#6 is the first reader. A lower-priority task will frame LOOP_TIMING as MAVLink and send it over the UART with DMA. snapshot() reads the four counters one at a time, and TIM3 can land between those loads, so one frame could carry two ticks’ figures. Every tick bumps ticks, and the task can’t interrupt TIM3, so ticks works as a sequence number. The task can read ticks, then the rest, then ticks again, with a compiler_fence between each so the compiler keeps that order. If ticks moved, it reads again. On one core the fence emits no instruction, so the check costs a load and a compare and can’t hold TIM3 up.

The other half is priority. Every NVIC priority resets to 0, which is P0, the highest and the loop’s own level. DMA already sits a level down, and the USART’s interrupt has to join it. #213 adds a start-up check that nothing else runs at P0. The biggest risk is the UART budget, four messages at 100 Hz against the baud rate, and I’ll write that sum down before any framing code.