Repository navigation
fix(esp32s3,lcd): force full teardown on cross-driver switch (#2270) - #2321
Conversation
The ESP32-S3 LCD_CAM I80 peripheral is shared between the clocked-SPI
driver (APA102/SK9822) and the clockless driver (WS2812/SK6812) via the
`LcdSpiPeripheralEsp` singleton. When the active driver changed at
runtime, the singleton's fast-path skipped teardown whenever the
hardware shape (lanes / clock / transfer size) happened to match the
previous session, leaving the previous owner's ISR callback, completion
semaphore state, panel_io handle, and ring-buffer ownership stale. The
third alternating switch (SPI -> CLOCKLESS -> SPI) silently produced no
DMA output (`passed:false` despite `mismatchedLeds:0`).
Fix:
- Add `LcdSpiOwnerDriver` enum and an `owner` field on `LcdSpiConfig`.
- Track owning driver on the singleton; force slow-path teardown when
the owner changes, even if the hardware shape matches.
- Both channel-driver wrappers tag their config with the correct owner.
- Harden the teardown path: null the ISR callback BEFORE deleting the
panel_io, drain the completion semaphore before deleting it, clear
the owner back to NONE.
- Backward-compatible: callers that leave `owner = NONE` keep the
existing fast-path behavior (used by legacy host tests).
Mock peripheral mirrors the same owner-aware behavior so host tests can
exercise the cross-driver alternation path. Added four regression tests
for the bug's exact failure signature.
Hardware validation pending — ESP32-S3 Blink build confirmed.
Issue: #2270
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
📝 WalkthroughWalkthroughThis change adds explicit ownership tracking to the shared ESP32 LCD_CAM peripheral singleton. A new Changes
Sequence DiagramsequenceDiagram
actor DrvA as LCD_SPI Driver
participant Core as Core Logic
participant Periph as LcdSpiPeripheralEsp
actor DrvB as LCD_CLOCKLESS Driver
DrvA->>Core: beginTransmission()
Core->>Core: config.owner = LCD_SPI
Core->>Periph: initialize(config)
Periph->>Periph: mOwner == NONE?<br/>Yes → fast path
Periph->>Periph: mOwner = LCD_SPI
Periph-->>Core: ✓ initialized
Note over DrvA,DrvB: Later, different driver<br/>attempts transmission
DrvB->>Core: beginTransmission()
Core->>Core: config.owner = LCD_CLOCKLESS
Core->>Periph: initialize(config)
Periph->>Periph: owner changed?<br/>LCD_SPI → LCD_CLOCKLESS
Periph->>Periph: teardownLocked()
Periph->>Periph: clear callbacks<br/>drain semaphore<br/>delete resources
Periph->>Periph: reinitialize
Periph->>Periph: mOwner = LCD_CLOCKLESS
Periph-->>Core: ✓ reinitialized
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.h (1)
83-97: Consider renamingteardownLocked()— the class holds no lock.The
Lockedsuffix typically signals "caller already holds the class mutex" butLcdSpiPeripheralEsphas no synchronization primitives. Since the real serialization here is temporal (singleton accessed from one task plus an ISR whose callback you clear first), a name liketeardownUnsafe(),teardownInternal(), or justteardown()would be less misleading. Optional, and a cross-file rename.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.h` around lines 83 - 97, The method name teardownLocked() on LcdSpiPeripheralEsp is misleading because the class has no mutex; rename it to a clearer name (e.g., teardown(), teardownInternal(), or teardownUnsafe()) and update all callers (initialize(), deinitialize(), and any other places referencing teardownLocked) and the declaration in lcd_spi_peripheral_esp.h to match; ensure the ISR callback-clearing logic and any comments remain correct and adjust any documentation/comments that mention teardownLocked or "locked" semantics.src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hpp (2)
222-257: Teardown ordering looks correct for ISR safety.Clearing
mCallback/mUserCtxbeforeesp_lcd_panel_io_del()is the right sequence: the ISR trampolinelcd_spi_flush_ready()readsself->mCallbackunder anifcheck, so nulling it first means any in-flighton_color_trans_donefrom the previous owner becomes a no-op before the panel_io is torn down. Draining withxSemaphoreTake(..., 0)beforevSemaphoreDelete()also correctly prevents a stale "given" token from carrying into the next owner's firsttransmit().One nit worth a short comment in the body: the ordering (
panel_iodeleted before the semaphore) is load-bearing —esp_lcd_panel_io_delis what guarantees no further ISRs will referencemCompleteSem. A future reorder that deletes the semaphore first would create a UAF window where an in-flight DMA-done ISR could touch a freedSemaphoreHandle_t. Consider adding a one-line comment capturing that invariant near line 240.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hpp` around lines 222 - 257, Add a one-line comment in LcdSpiPeripheralEsp::teardownLocked explaining that esp_lcd_panel_io_del(mPanelIo) must occur before deleting mCompleteSem because esp_lcd_panel_io_del is what ensures no further on_color_trans_done ISRs (which may call lcd_spi_flush_ready and access mCompleteSem) will run; reference the ordering around the esp_lcd_panel_io_del(...) and vSemaphoreDelete(...) calls and mention mCompleteSem and lcd_spi_flush_ready to make the load-bearing invariant explicit.
103-135: Fast/slow path split is correct, with one subtle back-compat behavior worth double-checking.The
sameOwnerpredicate makes a NONE caller always treated as compatible (line 112-113). Combined with theconfig.owner != NONEguard on lines 125-127, this means:
- A legacy NONE caller arriving after
LCD_SPIkeepsmOwner == LCD_SPI, so a followingLCD_CLOCKLESScall still correctly triggers the teardown. Good.- But a legacy NONE caller arriving first (cold init) sets
mOwner = NONEat line 215. If anLCD_SPIcaller then arrives with the same shape,sameOwnerevaluates to(LCD_SPI == NONE) || (LCD_SPI == NONE) == false, so the teardown correctly fires. Good.So the logic is sound. Just worth a short comment on lines 111-113 stating the asymmetric intent — "an incoming NONE is always compatible with whatever is currently stored, but an incoming concrete owner is only compatible with itself or with a NONE-stored owner" — so this doesn't get "fixed" into symmetry later and silently reintroduce
#2270.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hpp` around lines 103 - 135, Add a short clarifying comment in LcdSpiPeripheralEsp::initialize immediately where the sameOwner predicate is computed (the sameOwner expression using config.owner and mOwner) explaining the intentional asymmetry: an incoming NONE owner is considered compatible with whatever is stored, but an incoming concrete owner is only compatible with itself or with a stored NONE, to ensure backward compatibility and avoid silently reintroducing issue `#2270`; place this comment adjacent to the sameOwner logic so future readers don't refactor it into a symmetric check.src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_mock.cpp.hpp (1)
103-115: Owner-aware teardown mirrors the ESP impl correctly.Minor observation: the mock reads
mConfig.owneras the "stored owner" whileLcdSpiPeripheralEspuses a dedicatedmOwnerfield. Semantically equivalent here becausemConfig = configis only written on a successful init anddeinitialize()doesn't resetmConfig, but the divergence is worth a one-line comment so a future refactor that clearsmConfigindeinitialize()doesn't silently flip this to compare against stale state. Non-blocking.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_mock.cpp.hpp` around lines 103 - 115, The mock currently compares the incoming owner against mConfig.owner while the ESP implementation uses a dedicated mOwner; add a one-line clarifying comment above the sameOwner calculation (near the comparison using mConfig.owner) noting that mConfig.owner is treated as the stored owner here and warning that if deinitialize() ever clears mConfig this should be switched to a dedicated mOwner (or kept in sync) to avoid comparing against stale state; reference mConfig.owner, mOwner, sameOwner, and deinitialize() in the comment so future maintainers know the semantic dependency.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hpp`:
- Around line 115-135: The fast-path shape check in the initialization logic
(variables sameShape, mConfig, config in the method that uses
mInitialized/mOwner/teardownLocked) misses GPIO mapping fields so a caller can
change clock_gpio/dc_gpio/data_gpios and still skip teardown; update the
sameShape computation to include comparison of clock_gpio and dc_gpio and a deep
comparison of the data_gpios array (length and per-index values) between mConfig
and config so any GPIO mapping change forces the slow-path teardownLocked() and
rebuild of the I80/DMA state; keep the existing owner handling (config.owner !=
LcdSpiOwnerDriver::NONE -> mOwner = config.owner) unchanged.
---
Nitpick comments:
In `@src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hpp`:
- Around line 222-257: Add a one-line comment in
LcdSpiPeripheralEsp::teardownLocked explaining that
esp_lcd_panel_io_del(mPanelIo) must occur before deleting mCompleteSem because
esp_lcd_panel_io_del is what ensures no further on_color_trans_done ISRs (which
may call lcd_spi_flush_ready and access mCompleteSem) will run; reference the
ordering around the esp_lcd_panel_io_del(...) and vSemaphoreDelete(...) calls
and mention mCompleteSem and lcd_spi_flush_ready to make the load-bearing
invariant explicit.
- Around line 103-135: Add a short clarifying comment in
LcdSpiPeripheralEsp::initialize immediately where the sameOwner predicate is
computed (the sameOwner expression using config.owner and mOwner) explaining the
intentional asymmetry: an incoming NONE owner is considered compatible with
whatever is stored, but an incoming concrete owner is only compatible with
itself or with a stored NONE, to ensure backward compatibility and avoid
silently reintroducing issue `#2270`; place this comment adjacent to the sameOwner
logic so future readers don't refactor it into a symmetric check.
In `@src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.h`:
- Around line 83-97: The method name teardownLocked() on LcdSpiPeripheralEsp is
misleading because the class has no mutex; rename it to a clearer name (e.g.,
teardown(), teardownInternal(), or teardownUnsafe()) and update all callers
(initialize(), deinitialize(), and any other places referencing teardownLocked)
and the declaration in lcd_spi_peripheral_esp.h to match; ensure the ISR
callback-clearing logic and any comments remain correct and adjust any
documentation/comments that mention teardownLocked or "locked" semantics.
In `@src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_mock.cpp.hpp`:
- Around line 103-115: The mock currently compares the incoming owner against
mConfig.owner while the ESP implementation uses a dedicated mOwner; add a
one-line clarifying comment above the sameOwner calculation (near the comparison
using mConfig.owner) noting that mConfig.owner is treated as the stored owner
here and warning that if deinitialize() ever clears mConfig this should be
switched to a dedicated mOwner (or kept in sync) to avoid comparing against
stale state; reference mConfig.owner, mOwner, sameOwner, and deinitialize() in
the comment so future maintainers know the semantic dependency.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: a2879773-f669-4631-8ebb-ab237f7c3e4a
📒 Files selected for processing (7)
src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hppsrc/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.cpp.hppsrc/platforms/esp/32/drivers/lcd_spi/ilcd_spi_peripheral.hsrc/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hppsrc/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.hsrc/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_mock.cpp.hpptests/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_mock.cpp
| if (mInitialized) { | ||
| if (mConfig.num_lanes == config.num_lanes && | ||
| const bool sameShape = | ||
| mConfig.num_lanes == config.num_lanes && | ||
| mConfig.clock_hz == config.clock_hz && | ||
| mConfig.max_transfer_bytes >= config.max_transfer_bytes) { | ||
| mConfig.max_transfer_bytes >= config.max_transfer_bytes; | ||
|
|
||
| if (sameShape && sameOwner) { | ||
| // Fast path - same driver, compatible config. Record the | ||
| // (possibly NONE) owner from the caller in case it now | ||
| // reports a concrete identity that was unset before. | ||
| if (config.owner != LcdSpiOwnerDriver::NONE) { | ||
| mOwner = config.owner; | ||
| } | ||
| return true; | ||
| } | ||
| deinitialize(); | ||
|
|
||
| // Slow path - either the shape changed or the owning driver | ||
| // changed. Both cases require a full tear-down so we don't | ||
| // carry stale callback / semaphore / panel_io state forward. | ||
| teardownLocked(); | ||
| } |
There was a problem hiding this comment.
Pre-existing shape check gap (flagging for awareness, not this PR).
sameShape compares only num_lanes, clock_hz, and max_transfer_bytes. It does not compare clock_gpio, dc_gpio, or data_gpios. If a same-owner caller re-initializes with identical lane count / clock / size but a different data_gpios[] mapping, the fast path returns without rebuilding the I80 bus and DMA goes out on the previous GPIO routing. This is pre-existing behavior and not something #2270 introduces, so no action needed in this PR, but it's worth filing a follow-up since it's an analogous stale-state footgun to the one you just fixed.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hpp` around
lines 115 - 135, The fast-path shape check in the initialization logic
(variables sameShape, mConfig, config in the method that uses
mInitialized/mOwner/teardownLocked) misses GPIO mapping fields so a caller can
change clock_gpio/dc_gpio/data_gpios and still skip teardown; update the
sameShape computation to include comparison of clock_gpio and dc_gpio and a deep
comparison of the data_gpios array (length and per-index values) between mConfig
and config so any GPIO mapping change forces the slow-path teardownLocked() and
rebuild of the I80/DMA state; keep the existing owner handling (config.owner !=
LcdSpiOwnerDriver::NONE -> mOwner = config.owner) unchanged.
CI status
Root cause + fix in #2322. Once #2322 merges, this PR will rebase cleanly on top and CI should go green. WASM check failures ( LCD-specific validation in this PR's own test suite all passes:
Hardware validation on a physical ESP32-S3 ( |
Summary
Fixes #2270. On ESP32-S3 the
LCD_SPIandLCD_CLOCKLESSdrivers share the sameLcdSpiPeripheralEspsingleton. When alternating between the two drivers at runtime, the singleton's fast-path skipped teardown whenever the hardware shape (lanes / clock / transfer size) happened to match, leaving the previous owner's ISR callback, completion-semaphore state, panel_io handle, and ring-buffer ownership stale. The third alternating switch silently produced no DMA output (passed:falsedespitemismatchedLeds:0).Root cause
When the same shape came through a different driver,
initialize()returned early without tearing down the ISR callback or draining the semaphore, so the nexttransmit()could reuse stale state.Fix
LcdSpiOwnerDriverenum (NONE,LCD_SPI,LCD_CLOCKLESS) and anownerfield onLcdSpiConfig.LcdSpiPeripheralEspnow tracks the owning driver on a newmOwnermember.initialize()forces the slow-path (full teardown + recreate) when the incomingownerdiffers from the previously stored one, even if the shape matches.channel_driver_lcd_spi,channel_driver_lcd_clockless) tag theirLcdSpiConfigwith the correct owner.teardownLocked()helper):xSemaphoreTake(..., 0)) beforevSemaphoreDelete().NONE.owner = NONEkeep the existing fast-path behavior.Expected behavior after fix
Reproducing the failing table from the issue:
LCD_SPIpassed:truepassed:trueLCD_CLOCKLESSpassed:truepassed:trueLCD_SPIpassed:falsepassed:trueLCD_CLOCKLESSpassed:falsepassed:trueTests
Added four regression tests in
tests/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_mock.cpp:same owner reuse does not deinit— fast-path still works when the same driver re-initializes.cross-driver switch forces deinit— confirmsdeinitCountincrements by 1 when the owner changes even if shape matches.repeated cross-driver alternation never fails— walks the exact 4-switch sequence from the issue; every switch succeeds.legacy caller without owner field still works— backward-compat guard for callers leavingowner = NONE.All tests pass in both quick and debug (ASAN/LSAN/UBSAN) builds.
ESP32-S3 firmware compiles cleanly with the changes included.
Test plan
bash test --cpp lcd_spi_peripheral_mock(quick + debug)bash test --cpp channel_driver_lcd_spibash test --cpp channel_driver_lcd_clocklessbash compile esp32s3 --examples Blink(ESP-IDF build sanity)bash lintrunSingleTestRPC loop that reproduces the 4-switch pattern from the issue table).Non-goals
ownerfield is an optional config member with a backward-compatibleNONEdefault.LCD_RGBon ESP32-P4 (separate singleton, unaffected).🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
Tests