Skip to content

fix(teensy-flexio): bound every busy-loop + harden ISR/deinit lifecycle - #3411

Merged
zackees merged 1 commit into
masterfrom
flexio/wait-timeout-and-diagnostics
Jun 26, 2026
Merged

zackees merged 1 commit into
masterfrom
flexio/wait-timeout-and-diagnostics

Conversation

@zackees

@zackees zackees commented Jun 26, 2026 •

Copy link
Copy Markdown
Member

#3410 FlexIO bring-up — Round 1: kill the unbounded loops + ISR race

Three distinct unbounded busy-loops + an ISR-vs-deinit race were causing runSingleTest --flex-io to either hang the RPC indefinitely or crash the firmware with IMPRECISERR data-bus faults.

Loops bounded

  1. flexio_wait() — was while (!sDmaComplete) {} forever → bounded 50 ms
  2. flexio_configure_hw SWRST wait → bounded 1 ms
  3. ChannelEngineFlexIO::show() initial poll spin → bounded 100 ms + force-clears stuck channels

Race fixed

  1. flexio_show() now disables DMA + clears complete/interrupt/error before reprogramming TCD (no more mid-transfer TCD writes that triggered IMPRECISERR)
  2. flexio_deinit() reorders teardown: disable → detach ISR → clear NVIC IRQ → null-pointer → delete (no more late IRQ dereferencing a freed channel)
  3. flexio_dma_isr() defensively null-checks sDmaChannel

Status

FlexIO is NOT yet working. Driver still produces class=timeout with crash signature IMPRECISERR @ 0x2BB06 after these fixes. But the lower-level busy-loops and ISR race no longer mask the real bug. Future investigators get clean signals.

Likely remaining issues per #3410:

  • FlexIO2 clock-init race vs DMA arming
  • ObjectFLED's pre-registered TMR4/XBAR/DMA ownership conflicting with FlexIO2 hardware setup
  • Wrong shifter/timer/DMA-trigger wiring

Test plan

  • bash test --unit → 254/254 passed
  • bash lint --cpp → clean
  • bash autoresearch teensy41 --flex-io --tx-pin 8 --rx-pin 22 --timeout 30 --skip-lint → still timeout but no more 120s hangs; firmware crashes with diagnosable IMPRECISERR instead of silent freeze

Refs: #3410, #3359, #3406

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability of FlexIO transfers on Teensy 4.x by preventing rare hangs during wait, reset, and shutdown operations.
    • Added safeguards so interrupted or timed-out transfers recover more cleanly instead of stalling indefinitely.
    • Reduced the chance of crashes during DMA interrupt handling when hardware teardown happens at the same time.

FlexIO TX bring-up (#3410). Three distinct unbounded busy-loops in
the FlexIO path caused runSingleTest to ACK then never respond
within the 120 s RPC deadline. Plus an ISR race against deinit
caused IMPRECISERR data-bus faults that compounded the hang.

Changes:

1. `flexio_wait()` (flexio_driver.cpp.hpp): was `while (!sDmaComplete) {}`
   forever. Now bounded to 50 ms.

2. `flexio_configure_hw` SWRST wait: was `while (FLEXIO2_CTRL & (1<<1)) {}`
   forever. Now bounded to 1 ms (SWRST should take a few hundred ns).

3. `ChannelEngineFlexIO::show()` initial poll spin: was
   `while (poll() != READY) {}` forever. Now bounded to 100 ms on
   Teensy and force-clears stuck mTransmittingChannels so subsequent
   shows can proceed.

4. `flexio_show()` now disables DMA + clears complete/interrupt/error
   flags before reprogramming the TCD. Previously, if a previous
   show's DMA was still in flight (because flexio_wait timed out),
   reprogramming the TCD mid-transfer is undefined behaviour on
   i.MX RT eDMA -- triggered an IMPRECISERR bus fault.

5. `flexio_deinit()` now detaches the ISR + clears pending NVIC
   IRQ BEFORE deleting the DMAChannel pointer. The previous order
   left a window where a pending IRQ would fire after delete and
   dereference a freed channel.

6. `flexio_dma_isr()` defensively null-checks `sDmaChannel` so a
   late IRQ vectored to a torn-down channel cannot crash.

Hardware result (bash autoresearch teensy41 --flex-io --tx-pin 8
--rx-pin 22 --timeout 30 --skip-lint):
- Driver still does not produce capture (`class=timeout`,
  CrashReport: IMPRECISERR at ~0x2BB06 in subsequent runs), so the
  bring-up is NOT complete. These changes do remove the lower-level
  busy-loops and ISR race so future investigators get clean
  signals instead of unrecoverable hangs.

Driver state: bench bring-up not yet complete. Follow-up work
needed -- likely FlexIO clock-init race vs DMA arming, or
ObjectFLED's pre-registered TMR4/XBAR ownership conflicting with
FlexIO's FLEXIO2 hardware setup. Tracked in #3410.

Refs: #3410, #3359, #3406
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@fastled-project-sync fastled-project-sync Bot moved this to Triage in FastLED Tracker Jun 26, 2026
@zackees
zackees merged commit 51e9adb into master Jun 26, 2026
5 of 8 checks passed
@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0a125013-bb1e-4de9-8103-5709be1403db

📥 Commits

Reviewing files that changed from the base of the PR and between e420987 and 706fc72.

📒 Files selected for processing (2)
  • src/platforms/arm/teensy/teensy4_common/drivers/flexio/channel_engine_flexio.cpp.hpp
  • src/platforms/arm/teensy/teensy4_common/drivers/flexio/flexio_driver.cpp.hpp

📝 Walkthrough

Walkthrough

Teensy FlexIO code now uses bounded waits in transmission startup, software reset, and completion/deinit paths. The DMA ISR checks for a live channel before clearing interrupts, and teardown clears pending state before deleting the channel.

Changes

Teensy FlexIO safety updates

Layer / File(s) Summary
Channel wait gating
src/platforms/arm/teensy/teensy4_common/drivers/flexio/channel_engine_flexio.cpp.hpp
show() now waits up to 100 ms on Teensy 4.x before clearing transmitting channels and continuing; other builds keep the original spin loop.
DMA ISR guard
src/platforms/arm/teensy/teensy4_common/drivers/flexio/flexio_driver.cpp.hpp
Adds Arduino.h timing support and clears the DMA interrupt only when sDmaChannel is still valid.
Reset and DMA quiesce
src/platforms/arm/teensy/teensy4_common/drivers/flexio/flexio_driver.cpp.hpp
Bounds the FlexIO2 software reset wait and disables/clears DMA state before reprogramming transfer descriptors in flexio_show().
Wait and teardown ordering
src/platforms/arm/teensy/teensy4_common/drivers/flexio/flexio_driver.cpp.hpp
flexio_wait() now returns after 50 ms, and flexio_deinit() detaches interrupts, clears pending IRQs, deletes the DMA channel, and resets driver state.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

  • FastLED/FastLED issue 3410: It targets the same Teensy FlexIO hang, timeout, and teardown paths updated here.

Possibly related PRs

  • FastLED/FastLED#3068: It touches the same Teensy 4 FlexIO wait/timeout flow and DMA teardown paths.

Poem

I hopped through FlexIO under moonlit glow,
Bound the waits so the carrots could flow.
DMA thumped, then settled with care,
And tidy teardown floated through air.
Hoppy code! 🐇

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch flexio/wait-timeout-and-diagnostics

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@zackees
zackees deleted the flexio/wait-timeout-and-diagnostics branch June 26, 2026 05:27
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 26, 2026
zackees added a commit that referenced this pull request Jun 26, 2026
…ot cause of IMPRECISERR (#3412)

#3410 Round 2: addr2line decode of the IMPRECISERR crash addresses
(0x2BB06, 0x2BB0E, 0x2BADE) pointed at `FlexIOPeripheralReal::init()`,
which calls `flexio_configure_hw()` which writes to FLEXIO2 registers.

Inspection of the driver's manually-defined register pointers vs
imxrt.h's authoritative offsets revealed FLEXIO2_CTRL was declared at
base+0x000. But offset 0x000 is FLEXIO2_VERID -- a READ-ONLY version
ID register per i.MX RT1062 FlexIO chapter. FLEXIO2_CTRL is actually
at offset 0x008.

Every `FLEXIO2_CTRL = ...` write in the driver (SWRST, FLEXEN, FASTACC,
deinit's clear-to-0) was silently failing because it was hitting VERID
instead. The FlexIO module never actually enabled, and subsequent
writes to its other registers (which require the module to be clocked
AND enabled) triggered the IMPRECISERR bus fault.

Other register offsets in the driver were spot-checked against imxrt.h
and are correct:
  SHIFTSTAT  0x010 ✓
  SHIFTERR   0x014 ✓
  TIMSTAT    0x018 ✓
  SHIFTSDEN  0x030 ✓
  SHIFTCTL[] 0x080 ✓ (array base, +4 per register)
  SHIFTCFG[] 0x100 ✓
  SHIFTBUF[] 0x200 ✓
  SHIFTBUFBIS[] 0x380 ✓
  TIMCTL[]   0x400 ✓
  TIMCFG[]   0x480 ✓
  TIMCMP[]   0x500 ✓

Only CTRL was wrong. Also: the audit's earlier defensive fixes
(clock-gate-off-before-reconfig, CSCMR2-before-CS1CDR per Teensy
FlexIO_t4 reference, FLEXIO-enable-before-DMA-enable) are kept --
they're correct sequencing per NXP guidance even though the primary
cause was the CTRL offset.

Hardware result:
  bash autoresearch teensy41 --flex-io --tx-pin 8 --rx-pin 22 \
      --timeout 30 --skip-lint
  TEST FLEX_IO lanes=1 leds=100 FAIL 460 ms class=zero_capture
  Captured bytes: 0/300 (x4 patterns)

The test now COMPLETES (was previously timeout + IMPRECISERR crash).
`zero_capture` is the same starting state ObjectFLED was at before its
own bring-up cycle. Driver does not yet produce visible TX output --
next round needs to verify FlexIO actually drives the pad (FlexIO2 pin
muxing, shifter/timer config audit, scope-via-RX-pin diagnostics).

Refs: #3410, #3411

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 26, 2026
…M RX diag (#3413)

#3410 Round 3, two related changes:

1. FlexIO Timer 1 and Timer 3 had TRGSEL=0 -- which encodes
   "Pin 0 input" per i.MX RT1062 RM 47.4.10 -- when the intent
   was "Timer 0 output". The correct encoding is
   TRGSEL = 4*M + pattern; for "Timer M output" pattern is 3,
   so for Timer 0 output the value is 3, not 0. With TRGSEL=0
   Timer 1 was waiting for an external rising edge on pin 0
   that never came, so the WS2812 low-bit PWM never fired and
   no signal appeared on the TX pad.

2. The flexPwmRxDiagnostics JSON block was only emitted when
   `is_object_fled_driver`, but the FlexPWM RX path is useful
   for ANY Teensy driver using a FlexPWM-capable pin as RX --
   e.g. FlexIO TX on pin 8 -> FlexPWM RX on pin 22 during this
   round's bring-up. Now emits on every Teensy 4.x test and
   context.py renders it unconditionally.

Hardware result:
  bash autoresearch teensy41 --flex-io --tx-pin 8 --rx-pin 22 \
      --timeout 30 --skip-lint
  TEST FLEX_IO lanes=1 leds=100 FAIL 460 ms class=zero_capture
  flexPwmRxDiagnostics:
    activeMuxValueLive: 17    (pin 22 ALT1 + SION) OK
    activeSelectValueLive: 1  (#3404 fix) OK
    mctrl: 3840  captctrla: 25  dmaen: 96  dmaErq: 24  -- RX armed
    cval2..5: 0  citer: 4096  biter: 4096  -- ZERO edges captured

So FlexIO TX is still NOT producing edges on pin 8 even after the
TRGSEL fix. The shifter+timer architecture needs deeper auditing
against a known-working WS2812-via-FlexIO reference (cross-check
with NXP AN12491 or similar). At minimum:
 - Timer 2 enable condition (currently TRGSEL=1 = shifter status
   flag; needs to fire only on data=1 bits)
 - Shifter 0 SHIFTCTL pin output routing (SMOD=2 TX, PINCFG=3)
 - Whether the design even works with the current 4-timer
   architecture or needs an alternative

Driver state after this PR:
- No crashes, no hangs, no IMPRECISERR (#3411 + #3412 stable)
- Test classifies cleanly as zero_capture (~460 ms per run)
- RX diagnostic confirms TX is silent on the wire
- Next round = make TX actually drive the pad

Refs: #3410, #3411, #3412

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 26, 2026
…12 + SION + primed shifter (#3414)

#3410 Round 5. Substantive rewrite per the whatnick FRDM-K82F WS2812
reference. The previous 4-timer + 1-shifter design with OR-gated
outputs could not work because FlexIO TRGSEL doesn't expose "shifter
data output" as a per-bit gating source -- only pin-input, shifter-
status-flag, and timer-trigger-output. Timer 2 could not be modulated
by the actual shifter bit value.

This rewrite drops Timers 1/2/3 and uses ONE timer + ONE shifter:
- Each WS2812 bit is pre-encoded as 4 FlexIO bits in the DMA buffer
  (`1000` for 0-bit, `1110` for 1-bit) at ~3.16 MHz baud
- Shifter 0 routes its output directly to the pin via PINCFG=3
- Timer 0 generates the shift clock; no PWM gating needed
- 0-bit gets ~317 ns HIGH + ~950 ns LOW (within WS2812 spec)
- 1-bit gets ~950 ns HIGH + ~317 ns LOW (within WS2812 spec)
- DMA writes pre-encoded u32s to SHIFTBUF (not SHIFTBUFBIS so the
  MSB-first shifter naturally matches MSB-first encoding)

Additional fixes inline with the rewrite:
1. Pin mux now ALT4 + SION (0x14) per Teensyduino FlexIO_t4 reference.
   Without SION the IOMUXC input path is gated and FlexIO cannot drive
   the alt-mode pad output -- root cause of all prior `zero_capture`
   results in Rounds 1-4. All other register settings had been correct.
2. Timer 0 TIMENA = trigger rising edge (was trigger high level) so the
   timer re-arms on each SSF transition instead of latching once.
3. SHIFTBUF[0] primed with first encoded word before DMA enable, so
   SSF transitions happen and the initial Timer 0 trigger fires.

Hardware result on this branch:
  bash autoresearch teensy41 --flex-io --tx-pin 8 --rx-pin 22 \
      --timeout 30 --skip-lint
  TEST FLEX_IO lanes=1 leds=100 FAIL 459 ms class=zero_capture
  cval2..5: 0  citer: 4096  -- still no edges on the wire

The architectural rewrite is in place but TX is STILL silent. Without
a logic analyzer or scope to confirm whether FlexIO is driving the pad
at all, further blind register-tweaking is unproductive. The next
investigator should either (a) attach a scope to pin 8 during the test,
or (b) port a verified-working FlexIO WS2812 codebase line-by-line
(e.g. Finomnis/ws2812-flexio Rust impl, or MCUXpresso SDK FlexIO LED
driver) rather than continue iterating against the i.MX RT1062 RM in
isolation. The base infrastructure (no hangs, no crashes, register
offsets correct, clock init correct per Teensyduino, ALT4+SION,
bounded waits, post-test diagnostic visibility) is now solid enough
for that focused effort.

Refs: #3410, #3411, #3412, #3413

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 26, 2026
CodeRabbit flagged that flexio_read_diagnostics() read FLEXIO2_*
registers unconditionally, but the new autoresearch RPC path now
calls it for every Teensy 4.x test -- including runs that never
bring FlexIO up. Without the CCM clock gate on and FLEXEN set at
least once, those reads hit the same IMPRECISERR class fault we
chased during bring-up (#3411, #3412).

Zero-fill the snapshot, populate the always-safe CCM/state fields,
and bail before touching the FLEXIO2_* block when !sInitialized.
zackees added a commit that referenced this pull request Jun 26, 2026
…4.x (#3415)

* fix(flexio): pin mux offsets, timing, encoding -- TX now alive

Six rounds of FlexIO bring-up against #3410 failed with zero_capture
because of a 0x10 offset error in every entry of kFlexIOPins. The
table values were 16 bytes higher than the real IOMUXC mux/pad
register addresses (cross-checked against Teensyduino's
IOMUXC_SW_MUX_CTL_PAD_GPIO_B*_** macros). The requested TX pin was
never actually switched to ALT4 (FlexIO2); FlexIO shifter and DMA ran
correctly but drove an unrouted internal signal.

Round 7 also fixes four real timing/encoding bugs that would have
masked the mux fix:

1. TIMCMP bit-count was 31 (16 bits per word); per RM 47.4.18 the
   formula is (CMP[15:8]+1)/2, so 32 bits requires 63. The old value
   emitted only half the pre-encoded bits.
2. TIMCTL was missing TRGPOL bit 23 -- trigger needs to be active-low
   so it asserts when SSF is LOW (shifter loaded). Without it the
   timer-enable polarity was inverted.
3. TIMENA was 6 (rising-edge) instead of 2 (level-high), matching the
   verified-working Teensyduino FlexSerial UART driver.
4. CTRL had FASTACC set (bit 2). FASTACC requires FlexIO clock >= 2x
   bus clock; we run FlexIO 120 MHz vs 600 MHz bus, so FASTACC=1
   would corrupt register reads/writes.

Also added flexio_read_diagnostics() and wired it into the
autoresearch RPC harness so future investigation can see real
register state (CTRL, SHIFTSTAT, TIMSTAT, SHIFTSDEN, TCD,
IOMUXC mux/pad) without a logic analyzer -- this is what surfaced
the mux bug.

State after this change: wire is alive, RX captures 300/300 bytes
on every frame, decoder produces non-empty results. Residual byte
corruption (~75%) is now a bit-phase alignment issue at frame start
rather than total silence, and is tractable to follow up.

Refs #3410

* fix(flexio): park pin LOW before each frame to avoid eaten leading bit

After Round 7's mux + timing fixes, the FlexIO TX wire was alive and
the receiver captured 300/300 bytes per frame, but ~75% of bytes
decoded incorrectly. The pattern was a consistent 1-bit left-shift
across each frame: byte_1 = 0xFE for expected 0xFF, byte_n's bits
shifted into byte_n+1's MSB, etc.

Root cause: between flexio_show() calls the FlexIO peripheral leaves
the line in an indeterminate state -- the receiver consistently
captured a long HIGH (~85 us) before the first valid edge of every
frame. The shared WS2812 edge decoder
(fl::channels::rx::decodeWs2812Edges) treats that long HIGH as an
invalid edge-pair (high_ns way out of T0H/T1H range, low_ns below
reset threshold) and silently advances past it -- consuming the
FIRST WS2812 bit of the new frame in the process. Every subsequent
byte then appears bit-shifted by one position.

Fix: before re-asserting FLEXEN at the top of flexio_show(), switch
the pad mux to ALT5 (GPIO), drive the pin LOW via the Teensyduino
fast-GPIO path, wait 60 us so the receiver settles on a clean LOW
idle, then restore ALT4 | SION. The first FlexIO-driven edge after
that is now an unambiguous rising edge that decodes cleanly as the
first data bit.

Aggregate byte corruption dropped from 77.8% to 0.8% (10/1200 bytes
across 4 patterns). Residual errors are scattered single-bit issues
at random LED positions (LED[0], LED[7], LED[36], LED[51], LED[58]
etc) -- the raw_sample diagnostic shows clear receiver-side capture
glitches like double-H edges with no intervening LOW and ~200 us
mid-frame HIGH gaps. Comparable noise floor to ObjectFLED's residual
~0.5% rate on the same RX path.

Refs #3410

* fix(flexio): expose pad DSE/SPEED as build-time defines

Add FL_FLEXIO_TX_DSE and FL_FLEXIO_TX_SPEED defines so hardware-
specific drive strength tuning can be done without editing the
driver. The default DSE=3 was empirically the best on the bench
loopback rig (Teensy 4.1 pin 8 -> pin 22, short jumper) at 0.8%
residual byte corruption; sweeping DSE=1/3/6 converged to the same
RX-side noise floor (the residual errors are FlexPWM capture
dropout visible as ~200 us mid-frame HIGH gaps in raw_sample, not
edge ringing). The override is still useful on different boards or
longer wires where edge integrity does become the limit.

* fix(flexio): guard diagnostic register reads behind sInitialized

CodeRabbit flagged that flexio_read_diagnostics() read FLEXIO2_*
registers unconditionally, but the new autoresearch RPC path now
calls it for every Teensy 4.x test -- including runs that never
bring FlexIO up. Without the CCM clock gate on and FLEXEN set at
least once, those reads hit the same IMPRECISERR class fault we
chased during bring-up (#3411, #3412).

Zero-fill the snapshot, populate the always-safe CCM/state fields,
and bail before touching the FLEXIO2_* block when !sInitialized.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant