Skip to content

Resync the SPI link after a framing slip - #13

Merged
twells46 merged 3 commits into
masterfrom
oscar/spi-resync
Oct 19, 2026
Merged

twells46 merged 3 commits into
masterfrom
oscar/spi-resync

Conversation

@objorkman

@objorkman objorkman commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #11 (item 2). Stacked on #12. This PR targets oscar/dma-write-bounds, so the diff shows only this change. I'll retarget it to master once #12 merges.

What and why

SPI2 is a slave feeding circular DMA of a fixed 89 bytes, and nothing realigns the DMA with the host's frames. One transfer of the wrong length, or a glitch on SCK or chip select, offsets every later frame. After that:

  • The firmware drops every host write.
  • libwallaby logs DMA de-synchronized on every transfer.
  • This continues until the STM32 is reset.

kipr/botui#60 reports this is "common enough that it is a hassle to explain to customers over the phone how to … reflash." Reflashing fixes it only because it resets the STM32.

Changes

Detection. The main loop calls spi2_dma_check_sync() once per pass. It treats the link as slipped if any of these is true:

  • Between transfers, the RX stream's remaining count isn't a full frame (89). This catches a wrong-length transfer right after it ends. Just after chip select rises, the last byte can still be in transit to memory, so a mismatch is confirmed 2 µs later.
  • handle_dma() saw a bad start ('J') or end ('S') byte and set spi_resync. This catches slips the count can't see, like an extra SCK edge that shifts bits without changing the byte count. A wrong version byte alone doesn't count as a slip, because a reset can't fix a protocol mismatch.
  • SPI2 has overrun, which stops reception.

Recovery.

  1. If a transfer is in progress, wait up to 60 µs for chip select to go high, rather than retrying a whole 922 µs pass later. That wait is what keeps recovery short under continuous traffic.
  2. With interrupts off, re-check chip select, stop both DMA streams (bounded wait), reset SPI2 through RCC (which drops any partial byte), and reinitialize and restart the link.
  3. Check chip select again. If the host started a transfer during the reset, SPI2 caught only its tail, so spi_resync stays set and the next pass resets again.

Shared boot code. SPI_DMA_Config() is split so boot and resync use the same code:

  • spi2_dma_init() holds the SPI2 and DMA stream setup. It doesn't reconfigure pins, because GPIO_DeInit(GPIOB) at runtime would reset digital ports 4, 5, 13, 14, 15 and analog 0.
  • spi2_dma_start() holds the enable sequence that init() ran inline.

Boot runs the same steps, except that DMA interrupts and streams are now enabled after the NVIC setup rather than just before it.

Docs. AGENTS.md describes the resync.

Not handled: a slip in the TX direction alone, which neither the RX count nor the received bytes can show. Nothing suggests it happens; wrong-length transfers and SCK/chip-select glitches shift both directions together.

Expected recovery

I simulated the link with libwallaby's timing (89 bytes at 16 MHz, usleep(50) between transfers), one check per 922 µs pass, and 20,000 random slip lengths. The table shows transfers lost after the slip transfer itself.

Continuous traffic: mean / p95 / worst Light traffic (5–20 ms between calls)
Today lost until the STM32 resets lost until the STM32 resets
This PR's first version (main loop only) 5.7 / 16 / 54 0.45 / 1
This PR 3.0 / 7 / 20 0 / 0

Writes sent in lost transfers are dropped; libwallaby doesn't retry.

Verification

  • Docker build passes. A clean full build gives the same 17 warnings as Bounds-check host register writes in handle_dma #12, none in code this PR touches.
  • Disassembly of spi2_dma_check_sync() checked:
    • It reads GPIOB IDR bit 12 and Stream3's count, and confirms a mismatch after delay_us(2).
    • It checks SPI2's overrun flag (0x40).
    • The chip-select wait is bounded by usCount at 60 µs.
    • The reset runs between cpsid i and cpsie i, with a 100-try bound on stopping the streams.
    • spi_resync is set from the inverted chip-select bit after the restart.
  • Line endings preserved: CRLF files are still all CRLF, and main.c is still LF.
  • Not yet tested on hardware. To test on a Wombat, using the spidev setup from Bounds-check host register writes in handle_dma #12:
    1. Send one short transfer with s.xfer2([0] * n), then run a program that reads analog(0) in a loop for a few seconds. Try n = 1, 10, 50, 88, 90 and 200.
      • Expected on current firmware: DMA de-synchronized continues until wallaby_reset_coproc.
      • Expected with this PR: a few such lines at most, then clean reads. If the program pauses between calls (for example msleep(10)), there should be none.
    2. Run wallaby_reset_coproc a few times while botui is running. The link should come back each time.
    3. Rerun Bounds-check host register writes in handle_dma #12's frame test, a motor/servo/digital/analog check, and wallaby_flash.
    4. Run botui and a program together for 30+ minutes. There should be no stray DMA de-synchronized lines.

@objorkman objorkman self-assigned this Oct 1, 2026
SPI2 runs as a slave feeding circular DMA of a fixed 89 bytes, and
nothing realigned the DMA with the host's frames. One transfer of the
wrong length, or a glitch on SCK or chip select, offset every later
frame: the firmware dropped every host write and libwallaby logged "DMA
de-synchronized" on every transfer until the STM32 was reset. botui#60
reports this is common in the field, where reflashing (which resets the
STM32) is the current fix.

handle_dma() now sets spi_resync when a frame's start or end byte is
wrong. A wrong version byte alone doesn't, since a reset can't fix a
protocol mismatch. The main loop then calls spi2_dma_resync(), which
waits for chip select to be high, stops both DMA streams, resets SPI2
through RCC (dropping any partial byte), and reinitializes and restarts
the link with interrupts briefly disabled.

To share that sequence with boot, SPI_DMA_Config() is split: the SPI2
and DMA stream setup moves to spi2_dma_init(), which leaves GPIO alone
because GPIO_DeInit(GPIOB) would reset digital and analog pins on port B
at runtime, and the enable sequence that init() ran inline moves to
spi2_dma_start(). Boot runs the same steps in the same order, except
that DMA interrupts and streams are now enabled after the NVIC setup
instead of before it.

Part of #11.
Review of the first version found that recovery was slower than
documented. The resync was only attempted once per 922 us main-loop
pass and skipped whenever chip select was low, which is about 30% of the
time under continuous traffic. A simulation with libwallaby's timing (89
bytes at 16 MHz, usleep(50) between transfers) lost 5.7 transfers per
slip on average, 16 at p95 and up to 54. The main loop now calls
spi2_dma_check_sync() every pass, which:

- Treats the link as slipped if, between transfers, the RX stream's
  count isn't a full frame. A wrong-length transfer shows up right
  after it ends, instead of one misaligned frame later. The last byte
  can still be in flight just after chip select rises, so a mismatch is
  confirmed 2 us later. The start/end byte check in handle_dma() stays
  for slips the count can't see, like an extra SCK edge.
- Treats an SPI2 overrun as a slip, since it stops reception.
- Waits up to 60 us for chip select to go high instead of retrying a
  pass later. In the same simulation this gives 3.0 lost transfers on
  average, 7 at p95 and 20 at most, and none when the host pauses
  between calls.
- Re-checks chip select with interrupts off before resetting, and again
  after restarting. If the host started a transfer during the reset,
  SPI2 caught only its tail, so spi_resync stays set.
- Bounds the wait for the DMA streams to stop and retries on the next
  pass if it runs out.

Also computes the framing result once in handle_dma(), drops the
comments in spi2_dma_start() that restated each call, and corrects the
recovery-time wording in AGENTS.md.

Part of #11.
@objorkman
objorkman marked this pull request as ready for review October 4, 2026 02:31
@twells46

Copy link
Copy Markdown
Contributor

I tested this on a Wombat. The recovery works for most slips and a healthy link is unaffected, but on hardware I found that a reset can occasionally leave the link stuck in a state the firmware doesn't leave by itself. I'm working on tracking that down and will follow up here.

Setup

Master now has #8 and #12, so I tested 78637f2 merged onto master 2776fb2 (no conflicts) against master itself. I did not flash the branch head as it stands. The traffic was raw spidev frames shaped like libwallaby's: 89 bytes at 16 MHz with 50 µs between transfers, botui stopped. A third image added counters for each resync cause and a cycle-counter timing of the interrupts-off window.

What works

Test master this PR
20,000-frame soak; 100 Hz for 30 s; 0.5/1/4 MHz clocks 0 desync 0 desync, no resync attempted
Wrong-length transfer (1, 10, 50, 87, 90, 200, 4096 bytes, 20 each), continuous traffic never recovers 2–3.5 transfers lost on average, 10 at worst
The same, with a 10 ms pause after the slip never recovers 0 lost
A write just before the slip — applied exactly once, 30 of 30
89-byte frame with version 3 ignored ignored, no reset
Slip every 50 frames for 15 s — interrupts off 5.5 µs at most, no pass over 700 µs, loop rate 1077/s against 1086/s quiet
#12's frame tests pass pass

Those numbers are better than the description's simulation (3.0 / 7 / 20).

What doesn't

1. A transfer one byte short of a frame is never recovered. After an 88- or 177-byte transfer the link stays desynchronized, 6 of 6 times; n = 88 is in your test list. The main loop is also starved: of 40 replies read 20 ms apart only 5–9 are distinct, against 40 on a healthy link, so sensors, back-EMF and PID are barely running. Master starves the same way after such a transfer, so that part isn't new.

My current reading, not yet proven: the TX stream runs one byte ahead of RX, so after 89k + 88 bytes TX has completed a frame and RX hasn't. handle_dma() only clears the transfer-complete flags when both are set, so DMA1_Stream4_IRQHandler re-enters until the next transfer's first byte arrives. The main loop then only runs while chip select is low, and spi2_dma_check_sync() needs it high.

2. About 0.3% of resets leave the link stuck. This is the one that's new with this PR. Sending one disturbance at a time under continuous traffic and checking the link after each (a write and a read-back), on the image with counters:

Disturbance master this PR
3,000 frames with no 'J' 0 stuck 10 stuck, in each of two runs
3,000 wrong-length transfers (1–87 bytes) — 7 and 9 stuck
  • Every stuck link had the starved main loop from point 1, and only an STM32 reset (or, once, a 1-byte transfer) brought it back.
  • 31 of the 36 were plainly desynchronized.
  • 5 were silent: every reply started with 'J' and carried the right version, so libwallaby would log nothing, but every write was dropped and sensor values barely updated.
  • On master a frame without 'J' is simply ignored, so a single corrupted start or end byte goes from one dropped write to, occasionally, a dead link.
  • The rate varies. On the image without counters one 3,000-frame run had none, but that image did end up stuck part-way through a 120-frame test of unframed frames.

The plainly desynchronized case looks like a reset racing the start of the next host transfer and landing in the state from point 1. I don't have a mechanism for the silent case yet.

Smaller notes

  • libwallaby uses bad replies. r8/r16/r32 return the reply even when byte 0 isn't 'J', and the read-modify-write callers (set_motor_mode, set_servo_enabled, digital OUT/OE) write it back. Emulating that with raw frames on a servo position register, with a slip every 40 rounds, the register was corrupted about 150 times in 640 slips. On master the write-back can't land because the link never recovers. That's a libwallaby fix, not a firmware one.
  • Split frames. One frame sent as two transfers with chip select released in between trips the count check about 1 time in 200. Nothing in libwallaby, botui or wombat-os does that.
  • wallaby_reset_coproc hangs on the current image: with libgpiod 2.2.1, gpioset without -t holds the line until killed. Step 2 of the test plan can't be run as written. I used gpioset -c 0 -t 100ms,100ms,0 23=1, which is what wallaby_flash does.

Not tested: motors and servos through libkipr on this build, and real glitches on SCK or chip select.

A transfer one byte short of a frame (88, 177, ... bytes) hung the
firmware. The TX stream runs ahead of RX because the next reply byte is
preloaded, so after such a transfer TX had completed a frame and RX had
not. handle_dma() only cleared the transfer-complete flags when both
were set, so the TX stream's interrupt re-entered until the host's next
transfer. The main loop, SysTick and the motor and servo timer
interrupts all stopped while the host was idle, and the main loop only
ran while chip select was low, so spi2_dma_check_sync() never saw chip
select high and could not resync.

The same lone TX flag is set for about two byte times in every healthy
frame, so the handler also spun for about 1 us per frame at 16 MHz.

handle_dma() now treats the RX stream's flag as the frame boundary and
the TX stream's interrupt is no longer enabled. Frames are processed at
the same moment as before, since the RX flag was always the later one.

Tested on a Wombat with this change merged onto master:
- 88-, 177- and 266-byte transfers recover with no transfer lost after
  a 1 s pause, and the main loop keeps its rate through the pause.
  Before, none recovered.
- 18,000 unframed or wrong-length transfers left the link stuck 0
  times. Before, about 0.3% of resyncs left it stuck with the main loop
  starved.
- Healthy-link soak, slow clocks, boot while polling and the PR 12 test
  set are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@twells46

Copy link
Copy Markdown
Contributor

Follow-up to my earlier comment: both failures have the same root and one small change fixes them. I pushed it to this branch as 4a731ea.

Cause

  • Point 1 (one byte short). Confirmed as described. The TX stream completes a frame about two bytes before RX does. handle_dma() cleared the transfer-complete flags only when both were set, so after an 88-byte transfer the TX stream's interrupt re-entered until the host's next transfer. With counters in the handler: about 1.05 million lone-TX entries per idle second, and no main-loop passes.
  • Point 2 (0.3% of resets stuck). The reset races the start of the next host frame. If SPI2 is enabled inside byte 0 or byte 1 of a frame, TX ends that frame ahead of RX and the link is in the state from point 1. That window is about 1 µs wide at 16 MHz.
  • The silent case is the same race. Enabled inside byte 0, the slave sometimes starts its reply at once, which leaves TX two bytes ahead of RX: the reply lines up with the host's frames while the firmware sees every frame rotated by one byte. Otherwise the reply is rotated and the link looks dead.

I measured point 2 with an image that holds the reset at a chosen step until chip select falls, waits a set delay, and records both DMA counts afterwards. About 5,700 injected races on this PR without the fix: the link stuck only when the enable landed in bytes 0–1, always in one of three count states, and the 46 stuck links from random traffic on the same image showed the same three.

The change

4a731ea makes handle_dma() treat the RX stream's flag alone as the frame boundary and no longer enables the TX stream's interrupt. Frames are processed at the same moment as before, since the RX flag was always the later one (the handler never saw RX set without TX in about 8,000 healthy frames).

Results with the change

Tested as before: this branch merged onto master 2776fb2, raw spidev frames, botui stopped.

Test Before With 4a731ea
88-, 177-, 266-byte transfer, then 1 s idle never recovers, main loop starved first frame after the pause is good, loop rate unchanged through the pause
Injected reset races (all reset steps; 0.6, 4 and 16 MHz) stuck whenever the enable lands in bytes 0–1 5,609 of 5,609 healthy on the next frame, one extra reset each
Unframed frames and wrong-length transfers, health check after each 46 stuck in 12,000 0 stuck in 78,000
Boot while the host polls 1 of 5 failed 35 of 35 pass
Motors running, 88-byte transfer, then ao() not run motors stop, 9 of 9
Healthy soak, slow clocks, #12's frame tests pass pass

The 78,000 includes back-to-back frames and gaps of 50 µs, 200 µs and random 0–1 ms, at 16 and 4 MHz.

@twells46
twells46 changed the base branch from oscar/dma-write-bounds to master October 19, 2026 14:34
@twells46
twells46 merged commit b2ff45e into master Oct 19, 2026
2 checks passed
twells46 added a commit that referenced this pull request Oct 28, 2026
Resolve the main.c conflict with PR #13: call update_servo_power() after
spi2_dma_check_sync().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants