Skip to content

feat(watchdog): real per-platform hardware impls for ALL platforms (#2731 Phase 2) - #2745

Merged
zackees merged 7 commits into
masterfrom
feat/watchdog-phase2-all-platforms
Jun 4, 2026
Merged

zackees merged 7 commits into
masterfrom
feat/watchdog-phase2-all-platforms

Conversation

@zackees

@zackees zackees commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Phase 2 of #2731 — closes the request for all platforms in one squashed PR. Every supported MCU now has its own watchdog_<platform>.impl.hpp wired into the dispatcher; the previous Phase 1 (#2738) landed only host/stub/ESP32.

Per-platform coverage

Platform Implementation Persist Notes
AVR (atmega/attiny) avr/wdt.h + .init3 MCUSR=0 + wdt_disable() boot-loop fix in-RAM (8B) Captures MCUSR pre-clear for cause reporting; without .init3 fix, post-WDT-reset AVRs loop forever on Optiboot-less variants
Teensy 4.x (iMXRT1062) WDT_T4<WDT3> (RTWDOG) — bundled Teensyduino in-RAM (16B) NEVER touches WDOG1/WDOG2 (bootloader chip risk); fixes the AutoResearch bricking documented at AutoResearch.ino:204-214
Teensy 3.x / LC (K20/K66/KL26) Direct WDOG register unlock + config in-RAM (8B) One-shot-after-unlock; LPO-clocked timeout in ms
RP2040 / RP2350 Pico SDK hardware/watchdog.h; reset_usb_boot() for rebootIntoBootloader() watchdog_hw->scratch[0..3] (16B) Never touches reserved scratch[4..7]; pause_on_debug enabled by default
nRF52 NRF_WDT registers; CRV from ms in-RAM (8B) Does NOT touch GPREGRET (reserved for Adafruit bootloader DFU sentinels)
STM32 IWatchdog.h (STM32duino bundled) in-RAM (8B) LSI-clocked IWDG; range up to 32 s
SAMD21 / SAMD51 Adafruit_SleepyDog library in-RAM (8B) Library handles sync-busy waits + power-of-two timeout rounding
Apollo3 am_hal_wdt_* (AmbiqSuite SDK) in-RAM (8B) Reset cause deferred to Phase 3 (SDK type dance)
MGM240 (EFR32MG24) WDOG0 via Gecko SDK em_wdog.h in-RAM (8B) Avoids WDOG1 (Matter/OpenThread may claim it)
ESP32 family (unchanged from #2738) in-RAM (16B) TWDT + real esp_task_wdt_deinit() teardown
Host stub (unchanged from #2738) in-RAM (16B) Thread-backed deadline timer; 15/15 tests pass
WASM routes to noop n/a Phase 3 emscripten timer integration

Tier coverage per platform

Every platform implements full Tier 0 (begin/feed/disable/lastResetCause/persist*/consecutiveCrashCount/markCleanShutdown/isInSafeMode/reboot). Tier 1/2 methods that aren't hardware-verified return false per the documented contract; the capability macros (FL_WATCHDOG_HAS_*) tell user code what's actually supported per platform.

Persist storage strategy

In-RAM on every new platform — explicitly NOT flash/EEPROM in Phase 2. This keeps the user API stable today; Phase 3 will move each platform to its best-fit backing (RP scratch[0..3] already there, Teensy 4 OCRAM2 retained, nRF52 InternalFS, AVR EEPROM with wear awareness, SAMD51 SmartEEPROM, etc.) without changing any user-visible API.

Why some Tier 1/2 are false everywhere

onTimeout() (both overloads), setPauseOnDebug(), writeCrashLog(), setWindow(), crash report — these need per-platform fault-handler integration that has board-specific risks I can't verify without hardware. Returning false is the documented contract for "this platform doesn't support this method"; user code that checks the return value works portably and can opt into platform-specific features via the FL_WATCHDOG_HAS_* macros.

Verification

  • bash test fl_wdt_watchdog --debug → 15/15 host stub tests pass under ASAN/UBSAN
  • bash lint --cpp → clean
  • CI will exercise the host + WASM + ESP32 platform compiles automatically. Per-platform hardware compile / runtime validation depends on the CI matrix for each board.

References

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Watchdog support added across many MCUs (Apollo3, Teensy/Kinetis, nRF52, RP2040, i.MX RT, STM32, SAMD21/51, Silabs MGM240, AVR): start/feed/reboot, reset-cause detection, small persistent bytes, consecutive-crash counters, and configurable safe-mode thresholds.
  • Chores

    • Platform selection now detects optional platform/library availability and falls back gracefully when absent.
  • Notes

    • Advanced features (timeout callbacks, crash logs/reports, window mode, pause-on-debug, bootloader reboot) are stubbed or reported unsupported on several platforms.

Phase 2 of #2731: every supported MCU now has a real hardware watchdog
implementation wired into `fl::Watchdog`. The dispatcher
`platforms/watchdog.impl.cpp.hpp` routes each platform to its own
`watchdog_<platform>.impl.hpp`:

- **AVR (atmega/attiny)** — `avr/wdt.h` + critical `.init3` MCUSR=0 +
  wdt_disable() boot-loop fix that captures MCUSR before clearing for
  cause reporting. Without this `.init3`, post-WDT-reset boards loop
  forever on Optiboot-less AVR variants.
- **Teensy 4.x (iMXRT1062)** — `WDT_T4<WDT3>` (RTWDOG) only; explicitly
  avoids WDOG1/WDOG2 / bootloader-chip risk. Reset cause from `SRC_SRSR`.
  Fixes the AutoResearch bricking documented at `AutoResearch.ino:204-214`.
- **Teensy 3.x / LC (K20/K66/KL26)** — direct `WDOG` register unlock +
  config sequence with the one-shot-after-unlock constraint. Cause from
  `RCM_SRS0`/`SRS1`.
- **RP2040 / RP2350** — Pico SDK `hardware/watchdog.h` + `pause_on_debug`
  enabled by default. Persist storage uses `watchdog_hw->scratch[0..3]`
  (16 bytes, packed 4-per-register). NEVER touches `scratch[4..7]` (SDK
  bootrom reserved). `rebootIntoBootloader()` calls `reset_usb_boot()`
  for the bootrom UF2 entry path.
- **nRF52** — `NRF_WDT` registers; CRV computed from ms with rounding.
  Cause from `NRF_POWER->RESETREAS`, write-1-to-clear on read. Does NOT
  touch GPREGRET/GPREGRET2 (reserved for Adafruit bootloader sentinel
  values 0x57, 0xA8, 0x4e, 0x90, 0xB0).
- **STM32** — IWDG via the bundled STM32duino `IWatchdog.h` wrapper.
  Range up to 32 s.
- **SAMD21 / SAMD51** — `Adafruit_SleepyDog` library; handles register
  sync-busy waits and power-of-two timeout rounding internally.
- **Apollo3** — `am_hal_wdt_*` from AmbiqSuite SDK. Reset cause deferred
  to Phase 3 (SDK signature dance).
- **MGM240 (EFR32MG24)** — `WDOG0` via Gecko SDK `em_wdog.h`. Power
  selection picks smallest period ≥ requested timeout. Avoids `WDOG1`
  (potentially claimed by Matter / OpenThread stack).

Each impl provides the singleton `Watchdog::instance()`, full Tier 0
surface (begin/feed/disable/lastResetCause/persist*/consecutiveCrashCount/
markCleanShutdown/isInSafeMode/reboot), and returns false for Tier 1/2
methods that aren't yet hardware-verified. The capability macros
(`FL_WATCHDOG_HAS_HARDWARE`, `FL_WATCHDOG_PERSIST_BYTES`,
`FL_WATCHDOG_MAX_TIMEOUT_MS`, etc.) are set per platform.

Persist storage is in-RAM on most platforms — Phase 3 will move it to
the appropriate flash/EEPROM/scratch/BURAM backing for each platform.
This keeps the user API stable today.

Host stub regression: 15/15 watchdog tests still pass; lint clean.
Hardware verification per platform deferred to PRs that test on
specific boards via `bash autoresearch <board>`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds platform-specific watchdog driver implementations for Apollo3, Teensy 3.x/4.x, RP2040/2350, nRF52, STM32, SAMD21/51, MGM240, and AVR. Each implementation defines persistent state, wires hardware control (begin/feed/disable), detects reset causes, manages crash counting and safe-mode thresholds, and stubs unsupported advanced features. The platform dispatcher routes to the correct implementation when optional headers are available.

Changes

Watchdog Backend Implementations Across MCU Families

Layer / File(s) Summary
Platform dispatcher and routing
src/platforms/watchdog.impl.cpp.hpp
Platform selection preprocessor updated to route watchdog implementations for Teensy 3.x/4.x, RP2040/RP2350, nRF52, STM32, SAMD, Apollo3, MGM240, and AVR, with FL_HAS_INCLUDE gating and fallback to noop when headers are missing.
Teensy 3.x (K20) watchdog
src/platforms/arm/k20/watchdog_k20.impl.hpp
Kinetis WDOG unlock/configure, interrupt-safe feed, RCM_SRS0/SRS1 reset-cause detection and lazy caching, in-RAM persistence, crash counting/safe-mode threshold, SCB_AIRCR reboot, and stubbed advanced APIs.
MGM240 (EFR32) watchdog
src/platforms/arm/mgm240/watchdog_mgm240.impl.hpp
EFR32 WDOG with timeout→period mapping, EMU_RSTCAUSE translation and clearing, init/feed/disable wiring, in-memory persistence/crash counting, safe-mode helpers, NVIC_SystemReset reboot, and conservative stubs.
nRF52 watchdog
src/platforms/arm/nrf52/watchdog_nrf52.impl.hpp
nRF52 WDT with sticky RESETREAS handling (read/clear), cached reset-cause translation, crash-count increment on watchdog resets, in-RAM persist, safe-mode thresholding, init/feed behavior, and unsupported-feature stubs.
SAMD21/SAMD51 watchdog
src/platforms/arm/samd/watchdog_samd.impl.hpp
Adafruit_SleepyDog integration with timeout clamping, numeric resetCause→ResetCause mapping and caching, bounded crash-count increment, in-RAM persistence, safe-mode threshold helpers, reboot, and stubs for unsupported APIs.
STM32 (IWatchdog) watchdog
src/platforms/arm/stm32/watchdog_stm32.impl.hpp
IWatchdog wrapper with timeout clamping and ms→µs conversion, reload/feed, one-time reset-cause caching via IWatchdog.isReset(), crash counting, bounds-checked in-RAM persistence, reboot, and conservative stubs.
Apollo3 (Ambiq Artemis) watchdog
src/platforms/apollo3/watchdog_apollo3.impl.hpp
Ambiq LFRC watchdog with timeout clamp/normalize, LFRC reset config, init/start/feed/disable wiring, RSTGEN STAT→ResetCause caching (watchdog-priority), in-RAM persist, crash counting/safe-mode threshold, SWPOR reboot, and stubbed advanced APIs.
Teensy 4.x (iMXRT1062) watchdog
src/platforms/arm/mxrt1062/watchdog_mxrt1062.impl.hpp
Wraps Teensyduino RTWDOG: timeout clamping, feed forwarding, SRC_SRSR→ResetCause translation + cached crash-counting, in-RAM persist, SCB_AIRCR reboot, and stubbed features.
RP2040/RP2350 watchdog
src/platforms/arm/rp/watchdog_rp.impl.hpp
Pico SDK watchdog using watchdog_hw->scratch[] for 16-byte packed persistent storage, watchdog_caused_reboot() detection, crash-count tracking, feed/reboot and USB-bootloader reboot, with stubbed callbacks/logging/window APIs.
AVR watchdog with startup hook
src/platforms/avr/watchdog_avr.impl.hpp
AVR watchdog with .init3 startup hook to capture/clear MCUSR, MCUSR→ResetCause mapping, ms→WDTO_* conversion, lazy cached reset-cause with crash-counting, in-RAM persistence, safe-mode logic, reboot path, and stubs for unavailable features.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#2738: Adds the unified Watchdog API and initial platform plumbing; closely related.

Poem

"I am a rabbit, small and spry, 🐇
I nibble bytes where watchdogs lie,
Across each board I hop and peep,
Counting crashes while you sleep,
Hooray — each platform now has eyes!"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 2.64% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly and specifically describes the main change: implementing real per-platform hardware watchdog implementations for all supported MCU platforms as Phase 2 of issue #2731.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/watchdog-phase2-all-platforms

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 and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 16

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/platforms/apollo3/watchdog_apollo3.impl.hpp`:
- Around line 65-76: The implementation currently always returns
ResetCause::UNKNOWN causing Watchdog::lastResetWasWatchdog() to never detect
watchdog resets; update Watchdog::lastResetCause() to read the Apollo3
RSTGEN->STAT register (using the AmbiqSuite API or direct register access), map
the relevant AM_HAL_RESET_* bits to the appropriate ResetCause enum values
(including returning ResetCause::WATCHDOG when the watchdog bit is set), and
preserve FL_NOEXCEPT behavior and existing crash counter logic; ensure the
mapping covers the documented reset bits and falls back to UNKNOWN for
unrecognized values so lastResetWasWatchdog() works correctly.
- Around line 23-29: Apollo3WatchdogState fields (persist, crash_count) are
being zero-initialized on each reset so consecutiveCrashCount() and
isInSafeMode() never grow across resets; stop placing them in normal zeroed RAM
by moving the persistent state to a no-init/retained section. Remove the inline
initializers (e.g. "= {0}" and "= 0") from Apollo3WatchdogState for persist and
crash_count and annotate the struct or those members with the MCU no-init
attribute (e.g. __attribute__((section(".noinit"))) or the platform-equivalent
NOINIT macro) so the data survives resets, keep transient fields used only at
runtime (cached_cause, cause_cached, armed) in normal RAM, and ensure
lastResetCause(), consecutiveCrashCount(), and isInSafeMode() read/update the
retained persist/crash_count region consistently.

In `@src/platforms/arm/k20/watchdog_k20.impl.hpp`:
- Around line 30-36: The watchdog state (K20WatchdogState: crash_count, persist,
armed, cached_cause, cause_cached) is allocated in normal static RAM so it's
cleared on reboot; move the actual instance into non-initialized RAM (e.g.
declare the singleton with attribute((section(".noinit"))) or equivalent
platform NOINIT macro) so its bytes survive a watchdog reset, and guard its use
with a small init/magic/version check so you don't treat random memory as valid.
Update code that reads/writes crash_count and persist (consecutiveCrashCount(),
lastResetCause() and any reset/clear logic) to reference the new noinit instance
and to initialize/reset it only when the magic/version mismatch or on power-on
initializations. Ensure any writes that must be persistent across power loss are
still handled appropriately (i.e. use proper non-volatile storage if required).

In `@src/platforms/arm/mgm240/watchdog_mgm240.impl.hpp`:
- Around line 26-32: The crash_count and persist fields in Mgm240WatchdogState
are in normal RAM and are lost across resets; change storage to a
non-initialized/persistent region and ensure read/write on init/updates:
move/declare Mgm240WatchdogState (or at least crash_count and persist) into a
non-volatile/noinit section (e.g., add __attribute__((section(".noinit"))) or
use the platform's backup RAM API), load them during watchdog init, increment
and immediately persist crash_count after a watchdog-triggered reset, and
clear/persist reset on a successful boot; update any code paths that reference
Mgm240WatchdogState (e.g., where crash_count is updated/checked and where
persist[] is used) to use the persistent-read/write helpers so state survives
reboots.
- Around line 49-65: mgm240PickPeriod() uses wrong WDOG enum identifiers and
incorrect ms thresholds; replace the hardcoded ms buckets with a correct mapping
from requested ms to required LFRCO cycles (cycles = ceil(ms * 32.768)) and then
pick the smallest WDOG_PeriodSel_TypeDef constant whose cycle-count >= cycles
(use the Gecko SDK enum names like wdogPeriod_9, wdogPeriod_17, wdogPeriod_33,
wdogPeriod_65, wdogPeriod_129, wdogPeriod_257, wdogPeriod_513,
wdogPeriod_1k/2k/.../8k as provided by the SDK rather than the current incorrect
names), or implement a small table of (cycle_count, enum) pairs and search it;
also verify Mgm240WatchdogState::persist and ::crash_count live in
retention/no-init memory (or mark them accordingly) if they must survive reset.

In `@src/platforms/arm/mxrt1062/watchdog_mxrt1062.impl.hpp`:
- Around line 23-27: The capability macros FL_WATCHDOG_HAS_PRE_TIMEOUT_IRQ and
FL_WATCHDOG_HAS_WINDOW_MODE advertise features that are actually disabled
(onTimeout(...) and setWindow(...) return false); update the implementation to
be consistent by either (A) removing/undefining those two macros so callers
won't take the supported code paths, or (B) fully implement the features so
onTimeout(...) and setWindow(...) return true and behave correctly; ensure the
macros and the functions onTimeout(...) and setWindow(...) in this watchdog
implementation match (both advertise+implement or both absent/disabled) and
apply the same fix to the other identical block referenced later in the file.
- Around line 32-39: The crash_count field in Mxrt1062WatchdogState is currently
in volatile RAM so it resets to zero after a watchdog reboot; change the
implementation to store and read the crash count from the persistent bytes
(persist[FL_WATCHDOG_PERSIST_BYTES]) so the count survives resets and makes
isInSafeMode()/lastResetCause() cumulative. Update Mxrt1062WatchdogState (remove
or ignore the transient crash_count), add helper accessors that
serialize/deserialize crash_count into persist (and bounds-check), and modify
lastResetCause(), isInSafeMode(), and any code that increments or reads
crash_count to use those new accessor functions so the value is persisted across
reboots. Ensure the persist layout and any endian/size assumptions are
documented in comments near the persist array.

In `@src/platforms/arm/nrf52/watchdog_nrf52.impl.hpp`:
- Around line 27-33: The crash counter and persist buffer are stored in normal
static RAM and get zeroed on reboot, so consecutive watchdog resets never
accumulate; move crash_count and persist out of regular initialized data into
retention/noinit storage (or platform persistent storage) so their values
survive a reset before lastResetCause() runs. Concretely: change
Nrf52WatchdogState so persist and crash_count are placed in a noinit/retention
section (or use the platform persistent API) instead of being zero-initialized,
remove the inline initializers for those fields, and ensure the watchdog
initialization/read path (functions referencing Nrf52WatchdogState, crash_count,
persist, and lastResetCause()) treats uninitialized memory correctly and
increments crash_count toward mSafeModeThreshold across resets. Ensure
cause_cached and cached_cause can still be initialized normally.

In `@src/platforms/arm/rp/watchdog_rp.impl.hpp`:
- Around line 40-45: RpWatchdogState currently stores crash_count, cached_cause
and cause_cached in transient RAM so they are lost across watchdog resets;
change the code to persist these values in the backend scratch registers using
the existing persistRead()/persistWrite() (or the platform scratch read/write
helpers) instead of the in-memory fields so consecutiveCrashCount() and
reset-cause bookkeeping survive reboots; update code paths that read/update
RpWatchdogState (e.g., where crash_count is incremented and where
cached_cause/cause_cached are set/cleared) to read from persistRead() at startup
and write back with persistWrite() whenever the values change, and ensure
consecutiveCrashCount() reads the persisted crash_count rather than the struct
field.
- Around line 80-84: Watchdog::disable currently does nothing; call the Pico SDK
API to actually stop the watchdog counter: invoke watchdog_disable() inside
Watchdog::disable() (and include the appropriate SDK header if not already
included) so that Tier-0 disable has effect on this backend; retain the existing
comment about the enable bit if desired but ensure watchdog_disable() is
executed (handle any necessary noexcept constraints).

In `@src/platforms/arm/samd/watchdog_samd.impl.hpp`:
- Around line 30-36: SamdWatchdogState and the persist*() usage are stored in
regular RAM which is cleared on reset, so change persistence to a retained
storage region (RTC backup RAM or NVM) and update the accessors to read/write
that retained area; specifically modify SamdWatchdogState usage and the
persist*(...) helpers to operate on a retained block so lastResetCause() can
correctly increment crash_count across reboots and consecutiveCrashCount()
becomes sticky. Locate all uses of SamdWatchdogState, persist*(),
lastResetCause(), and consecutiveCrashCount() (including the other referenced
ranges) and replace RAM-backed reads/writes with reads/writes to the MCU
retained/backup storage API (or use a small NVM slot), ensure initialization
only happens when the retained marker is invalid, and update save/commit calls
so crash_count and persist bytes survive resets.

In `@src/platforms/arm/stm32/watchdog_stm32.impl.hpp`:
- Around line 32-38: Stm32WatchdogState’s crash_count and persist live in normal
zero-initialized RAM, so a watchdog reset clears them and
consecutiveCrashCount() cannot accumulate across boots; fix by moving the
persistent state out of .bss (e.g. place the Stm32WatchdogState instance into a
no-init/backup RAM region or use RTC backup registers/backup SRAM) so
crash_count and persist survive resets detected by IWatchdog.isReset(); update
any references to the state (Stm32WatchdogState, crash_count, persist,
consecutiveCrashCount()) to use the new storage location and ensure
initialization logic does not overwrite existing preserved data on boot.
- Around line 68-79: The function Watchdog::lastResetCause() currently treats
any non-IWDG reset as POWER_ON; update it to read the MCU reset status register
(CSR/RSR) via the existing STM32 reset status API or registers referenced in the
file header, map the specific cause bits to the appropriate ResetCause enum
values (e.g., SOFTWARE, EXTERNAL, BROWN_OUT, POR/POWER_ON, etc.), and only use
ResetCause::WATCHDOG when IWatchdog.isReset() is true; keep caching in
platforms::stm32WatchdogState() (s.cause_cached and s.cached_cause), increment
s.crash_count only for watchdog resets as before, and clear or acknowledge the
CSR/RSR flags after reading so subsequent boots behave correctly.

In `@src/platforms/avr/watchdog_avr.impl.hpp`:
- Around line 34-46: sAvrCapturedMcusr and the static AvrWatchdogState s{} are
currently placed in normal data/bss and get zeroed in .init4, clobbering
retained watchdog info when fastled_watchdog_init3() runs; fix by placing
sAvrCapturedMcusr and the persist/crash_count storage for AvrWatchdogState into
a noinit section (remove explicit "= 0" zero-init) so they are not cleared at
startup, add a magic/version guard field in AvrWatchdogState (e.g.,
magic/version) and initialize that only on cold boot in fastled_watchdog_init3()
to detect invalid retained data, and update avrWatchdogState(),
fastled_watchdog_init3(), and lastResetCause() to use the noinit storage and the
magic check to determine whether retained persist/crash_count/MCUSR are valid.
- Around line 80-85: The function fastled_watchdog_init3 is marked
__attribute__((naked)) but contains normal C statements (sAvrCapturedMcusr =
MCUSR; MCUSR = 0; wdt_disable();) which is fragile; remove the naked attribute
and keep the section(".init3") and used/inline attributes so the startup hook
runs normally, i.e. change the declaration to __attribute__((used,
section(".init3"))) inline void fastled_watchdog_init3() { ... } (or
alternatively, if you must keep naked, replace the body with equivalent
assembler that saves MCUSR into sAvrCapturedMcusr, clears MCUSR, and disables
the WDT), referencing fastled_watchdog_init3, sAvrCapturedMcusr, MCUSR and
wdt_disable when applying the change.
- Around line 64-75: The function timeoutToWdtoConstant currently uses incorrect
upper-bound thresholds (15,30,60,120) for selecting watchdog prescaler
constants, causing values like 16/31/61/121 ms to round up incorrectly; update
the comparisons in timeoutToWdtoConstant to use the actual AVR bucket boundaries
(16, 32, 64, 125) for WDTO_15MS, WDTO_30MS, WDTO_60MS, WDTO_120MS respectively
(keeping the remaining thresholds 250,500,1000,2000,4000 as-is) so the function
returns the smallest WDTO_* constant whose documented timeout is >= requested
ms.
🪄 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: 944cc309-f053-4dc6-8ca4-6cdeb196ee49

📥 Commits

Reviewing files that changed from the base of the PR and between a27cbff and a34ab8e.

📒 Files selected for processing (10)
  • src/platforms/apollo3/watchdog_apollo3.impl.hpp
  • src/platforms/arm/k20/watchdog_k20.impl.hpp
  • src/platforms/arm/mgm240/watchdog_mgm240.impl.hpp
  • src/platforms/arm/mxrt1062/watchdog_mxrt1062.impl.hpp
  • src/platforms/arm/nrf52/watchdog_nrf52.impl.hpp
  • src/platforms/arm/rp/watchdog_rp.impl.hpp
  • src/platforms/arm/samd/watchdog_samd.impl.hpp
  • src/platforms/arm/stm32/watchdog_stm32.impl.hpp
  • src/platforms/avr/watchdog_avr.impl.hpp
  • src/platforms/watchdog.impl.cpp.hpp

Comment thread src/platforms/avr/watchdog_avr.impl.hpp Resolved
Comment thread src/platforms/avr/watchdog_avr.impl.hpp Resolved
Comment thread src/platforms/avr/watchdog_avr.impl.hpp Resolved
zackees and others added 2 commits June 3, 2026 22:54
CI on teensy41 failed with `fatal error: Watchdog_t4.h: No such file
or directory` — the WDT_T4 library is bundled with Teensyduino but is
not auto-installed for the PlatformIO build configuration FastLED uses.

Wrap each platform impl that depends on an external Arduino library
(Watchdog_t4, IWatchdog, Adafruit_SleepyDog, am_mcu_apollo, em_wdog,
kinetis.h, hardware/watchdog.h, nrf.h, avr/wdt.h) with
`__has_include(<header>)` in the dispatcher. When the optional library
is missing, the dispatcher falls through to the noop fallback instead
of breaking the compile. User code that calls the watchdog API still
works (as a no-op); installing the matching library opts back into
the hardware behavior.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- apollo3: implement lastResetCause() via RSTGEN->STAT bit decode
  (was hard-returning UNKNOWN); watchdog reset is now detected and
  participates in crash accounting.
- avr: correct timeoutToWdtoConstant() bucket boundaries from
  15/30/60/120 -> 16/32/64/125 to match WDTO_* prescaler ms ceilings;
  prevents 16/31/61/121 ms requests from spilling into the next bucket.
- avr: drop __attribute__((naked)) from .init3 hook — naked is
  toolchain-fragile with C/C++ statements; .init3 already runs after
  BSS zeroing and stack setup so a normal section attribute is correct.
- watchdog dispatcher: replace __has_include with FL_HAS_INCLUDE for
  portability per BannedMacrosChecker.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/platforms/apollo3/watchdog_apollo3.impl.hpp`:
- Around line 65-97: The reset-status sticky bits are not being cleared
correctly in Watchdog::lastResetCause(); update the implementation (function
Watchdog::lastResetCause and state platforms::apollo3WatchdogState usage) to
clear RSTGEN status via the AmbiqSuite mechanism instead of writing back to
RSTGEN->STAT — call RSTGEN->CLRSTAT (or use am_hal_reset_status_clear()) with
the bits you read (const fl::u32 stat) after determining s.cached_cause and
incrementing s.crash_count so the next boot’s cause isn’t misattributed; ensure
you only clear the bits you observed and preserve the cached cause behavior
(s.cause_cached, s.cached_cause, s.crash_count).
🪄 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: d53a7548-a6dc-4400-9e28-f2f4453286f2

📥 Commits

Reviewing files that changed from the base of the PR and between c283325 and 66a3846.

📒 Files selected for processing (3)
  • src/platforms/apollo3/watchdog_apollo3.impl.hpp
  • src/platforms/avr/watchdog_avr.impl.hpp
  • src/platforms/watchdog.impl.cpp.hpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/platforms/watchdog.impl.cpp.hpp
  • src/platforms/avr/watchdog_avr.impl.hpp

zackees and others added 2 commits June 3, 2026 23:30
- avr: move sAvrCapturedMcusr into `.noinit` section. The previous
  `.bss`/`.data` placement was zeroed by avr-libc's `.init4` step,
  which runs AFTER our `.init3` capture hook — clobbering the
  captured MCUSR before lastResetCause() could read it.
- rp: actually call Pico SDK `watchdog_disable()` in `disable()` so
  the Tier-0 disable hook stops the counter (RP is the one platform
  here with a clean SDK teardown).
- mxrt1062: drop `FL_WATCHDOG_HAS_PRE_TIMEOUT_IRQ` /
  `FL_WATCHDOG_HAS_WINDOW_MODE` until the matching Tier-1/2 wrappers
  are implemented. Capability macros must match runtime behavior
  (the wrappers currently return false).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The Gecko SDK defines `WDOG_PeriodSel_TypeDef` values as cycle counts
(wdogPeriod_9, _17, _33, _65, _129, _257, _513, _1k, _2k, _4k, _8k,
_16k, _32k, _64k, _128k, _256k) — not the power-of-two ms ladder the
old code used. The previous `wdogPeriod_16/32/64/128/256/512` names
do not exist in the SDK (compile break on actual EFR32MG24 hardware),
and the existing ms→enum table was off by ~32× because it confused
cycles with milliseconds.

Recompute the table at LFRCO ≈ 32.768 kHz (ms = cycles * 1000 / 32768)
and update FL_WATCHDOG_MAX_TIMEOUT_MS to the actual 8 s ceiling
imposed by wdogPeriod_256k.

Addresses CodeRabbit review on PR #2745.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/platforms/arm/rp/watchdog_rp.impl.hpp (1)

52-57: ⚠️ Potential issue | 🔴 Critical

Fix RP watchdog reset cause detection so Watchdog::reboot() doesn’t increment crash_count
rpDetectResetCause() uses watchdog_caused_reboot(), which the Pico SDK treats as true for any watchdog-initiated reset (including watchdog_reboot()), so lastResetCause() will classify that reboot as ResetCause::WATCHDOG and increment crash_count on the next boot. Use watchdog_enable_caused_reboot() (the “enabled + magic marker” predicate the SDK provides) in rpDetectResetCause() instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/platforms/arm/rp/watchdog_rp.impl.hpp` around lines 52 - 57, Replace the
current watchdog check in rpDetectResetCause() — which calls
watchdog_caused_reboot() — with the SDK predicate
watchdog_enable_caused_reboot() so only watchdog resets that used the “enabled +
magic marker” path are classified as ResetCause::WATCHDOG; update the function
rpDetectResetCause() to call watchdog_enable_caused_reboot() and return
ResetCause::WATCHDOG only when that predicate is true, leaving the default
return ResetCause::POWER_ON unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/platforms/arm/rp/watchdog_rp.impl.hpp`:
- Around line 52-57: Replace the current watchdog check in rpDetectResetCause()
— which calls watchdog_caused_reboot() — with the SDK predicate
watchdog_enable_caused_reboot() so only watchdog resets that used the “enabled +
magic marker” path are classified as ResetCause::WATCHDOG; update the function
rpDetectResetCause() to call watchdog_enable_caused_reboot() and return
ResetCause::WATCHDOG only when that predicate is true, leaving the default
return ResetCause::POWER_ON unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e3226658-b0f4-4c59-a5e4-6a7379bf4fed

📥 Commits

Reviewing files that changed from the base of the PR and between 66a3846 and c9562c6.

📒 Files selected for processing (3)
  • src/platforms/arm/mxrt1062/watchdog_mxrt1062.impl.hpp
  • src/platforms/arm/rp/watchdog_rp.impl.hpp
  • src/platforms/avr/watchdog_avr.impl.hpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/platforms/avr/watchdog_avr.impl.hpp
  • src/platforms/arm/mxrt1062/watchdog_mxrt1062.impl.hpp

zackees and others added 2 commits June 3, 2026 23:36
The Apollo3 RSTGEN->STAT bits are sticky across resets. Without
clearing them, the next boot would read stale bits from prior resets,
misattribute the reset cause, and inflate `crash_count`. Per the
AmbiqSuite HAL convention, write to RSTGEN->CLRSTAT (not back to STAT)
to clear the sticky bits — this is `am_hal_reset_status_clear()` in
the HAL, but we write the register directly to avoid an extra
HAL include.

Addresses CodeRabbit review on PR #2745.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Addresses CodeRabbit comment on PR #2745 — previously every non-IWDG reset
on STM32 was reported as POWER_ON, losing the ability to distinguish
software/external/brownout. Now reads RCC->CSR (RCC->RSR on H7) bit by bit
with proper "specific first" priority and clears RMVF so subsequent boots
don't OR-accumulate stale flags. Each bit name is `#ifdef`-guarded so
families that don't expose a particular flag don't fail to compile.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees merged commit ca09808 into master Jun 4, 2026
9 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 4, 2026
zackees added a commit that referenced this pull request Jun 5, 2026
…s through (Closes #2798) (#2800)

* fix(watchdog/avr): mark .init3 hook __attribute__((naked)) so it falls through

`fastled_watchdog_init3()` (added in #2745) was attributed
`section(".init3"), used` but *not* `naked`. GCC therefore emitted a
standard prologue/epilogue ending in `ret`. But `.init3` is not a function
call site — the linker concatenates it inline into the boot init chain
between `.init2` (BSS clear) and `.init4` (data copy), and there is no
return address on the stack when it runs. The `ret` pops two bytes of
uninitialized SRAM and jumps there, hanging the chip before `setup()` can
run.

Symptom on CI: `uno AVR8JS Test` fails because the emulated firmware
never reaches `Serial.println("Test setup starting")` — the avr8js grep
for `"Test loop"` times out at 30 s on a nearly-empty serial log. Green
at `c2faf92e` (before #2745), red at every commit after.

Fix: add `__attribute__((naked))` (the avr-libc-canonical pattern for
clearing `MCUSR` + `wdt_disable()` in `.init3`) and drop the `inline`
keyword (which combines awkwardly with `naked`). The three statements
the hook performs compile to plain `STS`/inline-asm sequences with no
stack temps, so `naked` is safe — and is in fact the only correct
choice for code placed in `.initN`. The trailing comment is updated to
explain why no explicit `ret` is needed (execution falls through to
`.init4`).

The prior in-source justification for *not* using `naked` ("fragile
across optimization/toolchain versions") was a general concern that
doesn't apply to this specific body — it's the standard recipe for
`.init3` WDT/MCUSR clearing across AVR codebases.

Regression-guarded locally with `bash compile`:

  PASS  uno          (classic-AVR — uses the .init3 hook)
  PASS  attiny85     (classic-AVR — uses the .init3 hook)
  PASS  attiny88     (classic-AVR — uses the .init3 hook)
  PASS  attiny4313   (classic-AVR — uses the .init3 hook)
  PASS  atmega8a     (megaAVR / no classic symbols — noop fallback)
  PASS  nano_every   (megaAVR-0 — noop fallback)
  PASS  ATtiny1604   (tinyAVR-1 — noop fallback)
  PASS  ATtiny1616   (tinyAVR-1 — noop fallback)

`bash lint` clean. Runtime verification (avr8js emulator) is only
available on CI; PR CI is the authoritative check.

Closes #2798

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* review(watchdog/avr): address CodeRabbit on PR #2800

Fix the `.init3` lifecycle comment in `watchdog_avr.impl.hpp`. The previous
wording ("runs after the C runtime has zeroed BSS") contradicted the
`sAvrCapturedMcusr` block 50 lines above it, which (correctly) explains
that `.init4` BSS/data init runs AFTER our `.init3` hook — that being the
whole reason the captured-MCUSR variable lives in `.noinit`.

Reword to state the actual ordering and cross-link the rationale, so a
future reader can't accidentally "fix" the .noinit attribute back to .bss.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees deleted the feat/watchdog-phase2-all-platforms branch August 21, 2026 19:15
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