From 8a5df68b1f0e8d26e63dc4ce6488800f37e3ae31 Mon Sep 17 00:00:00 2001 From: gdiciocco Date: Sat, 26 Sep 2026 22:49:34 +0200 Subject: [PATCH 1/3] Fix ADC conversion start states and add lifecycle diagnostics Restrict fast ADCv2 and software knock starts to ADC_READY and ADC_ERROR, matching the vendored ChibiOS HAL contract. Use adcIsBufferComplete in ADCv2/ADCv4 callbacks and expose starts, completions, skipped requests and HAL errors through adc_stats. Add production-caller/HAL regression tests for ADCv2 and ADCv4 to CI. Validation: 36 ADCv2 and 21 ADCv4 tests under ASan/UBSan, 720 general tests, and Core8 F4 / Proteus F7 / Proteus H7 builds. Core8 USB sampling smoke completed with original firmware and configuration restored afterward. Refs FOME-Tech/fome-fw#586 and rusefi/rusefi#7710. --- .github/workflows/build-unit-tests.yaml | 4 + firmware/CHANGELOG.md | 2 + .../sensors/impl/software_knock.cpp | 11 +- firmware/hw_layer/adc/adc_diagnostics.cpp | 63 +++ firmware/hw_layer/adc/adc_diagnostics.h | 43 ++ firmware/hw_layer/hw_layer.mk | 1 + .../hw_layer/ports/stm32/stm32_adc_v2.cpp | 32 +- .../hw_layer/ports/stm32/stm32_adc_v4.cpp | 22 +- unit_tests/Makefile | 2 + unit_tests/adc_lifecycle/README.md | 95 ++++ unit_tests/adc_lifecycle/adc_lifecycle.mk | 42 ++ unit_tests/adc_lifecycle/mocks/biquad.h | 10 + unit_tests/adc_lifecycle/mocks/ch.hpp | 2 + unit_tests/adc_lifecycle/mocks/hal.h | 49 +++ .../adc_lifecycle/mocks/hal_v4_config.h | 35 ++ unit_tests/adc_lifecycle/mocks/knock_config.h | 6 + unit_tests/adc_lifecycle/mocks/knock_logic.h | 2 + unit_tests/adc_lifecycle/mocks/mpu_util.h | 22 + unit_tests/adc_lifecycle/mocks/pch.h | 182 ++++++++ .../adc_lifecycle/mocks/thread_controller.h | 2 + .../adc_lifecycle/test_adc_lifecycle.cpp | 406 ++++++++++++++++++ 21 files changed, 1021 insertions(+), 12 deletions(-) create mode 100644 firmware/hw_layer/adc/adc_diagnostics.cpp create mode 100644 firmware/hw_layer/adc/adc_diagnostics.h create mode 100644 unit_tests/adc_lifecycle/README.md create mode 100644 unit_tests/adc_lifecycle/adc_lifecycle.mk create mode 100644 unit_tests/adc_lifecycle/mocks/biquad.h create mode 100644 unit_tests/adc_lifecycle/mocks/ch.hpp create mode 100644 unit_tests/adc_lifecycle/mocks/hal.h create mode 100644 unit_tests/adc_lifecycle/mocks/hal_v4_config.h create mode 100644 unit_tests/adc_lifecycle/mocks/knock_config.h create mode 100644 unit_tests/adc_lifecycle/mocks/knock_logic.h create mode 100644 unit_tests/adc_lifecycle/mocks/mpu_util.h create mode 100644 unit_tests/adc_lifecycle/mocks/pch.h create mode 100644 unit_tests/adc_lifecycle/mocks/thread_controller.h create mode 100644 unit_tests/adc_lifecycle/test_adc_lifecycle.cpp diff --git a/.github/workflows/build-unit-tests.yaml b/.github/workflows/build-unit-tests.yaml index b9c7fb44fa..34e038c076 100644 --- a/.github/workflows/build-unit-tests.yaml +++ b/.github/workflows/build-unit-tests.yaml @@ -40,6 +40,10 @@ jobs: working-directory: ./unit_tests/ run: make -j4 COVERAGE=yes + - name: Run ADC lifecycle tests + working-directory: ./unit_tests/ + run: make -j4 adc-lifecycle-test + - name: Run Tests working-directory: ./unit_tests/ #run: ASAN_OPTIONS=detect_stack_use_after_return=1 build/fome_test diff --git a/firmware/CHANGELOG.md b/firmware/CHANGELOG.md index e684873864..10707a14bd 100644 --- a/firmware/CHANGELOG.md +++ b/firmware/CHANGELOG.md @@ -31,6 +31,7 @@ or ## Unreleased ### Added + - Add `adc_stats` console diagnostics for fast ADC and software knock: conversion starts, completed buffers, skipped starts by reason, and ADC errors. - Fahrenheit temperature support: pick "Fahrenheit" under Settings > Temperature Units in TunerStudio and all temperature gauges, datalogs, sensor adjustments, and thermistor calibration points display in °F. The stored tune is unchanged (always Celsius internally), so switching units never resets your configuration and works on every supported board. - Add mode for "true" wasted spark on odd fire engines (Viper V10) where companion cylinders are not exactly 360 degrees apart. Requires cam sync. - New `CPU usage` output channel showing approximate firmware CPU load @@ -52,6 +53,7 @@ or - Instant RPM is now used automatically on triggers with 24 or more teeth per engine cycle (a 12 tooth crank wheel or better), instead of only when "Always use instant RPM" was enabled. RPM, and everything derived from it, now responds within a fraction of an engine cycle instead of once per cycle. The setting remains, and now forces instant RPM on triggers with fewer teeth than that. ### Fixed + - Prevent an ADC panic when fast ADC or software knock sampling overlaps the previous conversion's completion callback. - Changing or clearing the MAP 2, MAF, MAF 2 or fuel level sensor input no longer leaves the sensor reading its old pin (and the pin claimed) until the ECU is rebooted. MAF and fuel level input changes now take effect immediately, like other analog sensors - STM32F7 dual-bank ECUs no longer stall (potentially stopping the engine) when burning configuration with the engine running - configuration is now committed to flash when the engine is stopped #776 - SD card log field names now include their category prefix (e.g. `Boost: Target` instead of just `Target`), matching the names shown in TunerStudio diff --git a/firmware/controllers/sensors/impl/software_knock.cpp b/firmware/controllers/sensors/impl/software_knock.cpp index 8d78d0ae9e..270eb9f598 100644 --- a/firmware/controllers/sensors/impl/software_knock.cpp +++ b/firmware/controllers/sensors/impl/software_knock.cpp @@ -7,6 +7,8 @@ #if EFI_SOFTWARE_KNOCK +#include "adc_diagnostics.h" + #include "knock_config.h" #include "ch.hpp" @@ -35,16 +37,19 @@ void onKnockSamplingComplete() { void onStartKnockSampling(uint8_t cylinderNumber, float samplingSeconds, uint8_t channelIdx) { if (!engineConfiguration->enableSoftwareKnock) { + knockAdcDiagnostics.skippedDisabled++; return; } - // Cancel if ADC isn't ready - if (!((KNOCK_ADC.state == ADC_READY) || (KNOCK_ADC.state == ADC_COMPLETE) || (KNOCK_ADC.state == ADC_ERROR))) { + // ADC_COMPLETE belongs to the completion callback; the HAL is not ready yet. + if (!((KNOCK_ADC.state == ADC_READY) || (KNOCK_ADC.state == ADC_ERROR))) { + recordAdcSkippedState(knockAdcDiagnostics, KNOCK_ADC.state); return; } // If there's pending processing, skip this event if (knockNeedsProcess) { + knockAdcDiagnostics.skippedPending++; return; } @@ -61,6 +66,7 @@ void onStartKnockSampling(uint8_t cylinderNumber, float samplingSeconds, uint8_t currentChannelIdx = channelIdx; adcStartConversionI(&KNOCK_ADC, conversionGroup, knockSampleBuffer, sampleCount); + knockAdcDiagnostics.started++; lastKnockSampleTime = getTimeNowNt(); knockSnifferPin.setHigh(); } @@ -159,6 +165,7 @@ static void processLastKnockEvent() { engine->module()->onKnockSenseCompleted( currentCylinderNumber, currentChannelIdx, db, lastKnockTime); + knockAdcDiagnostics.processed++; } void KnockThread::ThreadTask() { diff --git a/firmware/hw_layer/adc/adc_diagnostics.cpp b/firmware/hw_layer/adc/adc_diagnostics.cpp new file mode 100644 index 0000000000..657e86371d --- /dev/null +++ b/firmware/hw_layer/adc/adc_diagnostics.cpp @@ -0,0 +1,63 @@ +#include "pch.h" + +#if HAL_USE_ADC +#include "adc_diagnostics.h" + +AdcDiagnostics fastAdcDiagnostics; +AdcDiagnostics knockAdcDiagnostics; +static bool fastIsCircular; + +AdcDiagnosticsSnapshot getAdcDiagnostics() { + // Timer/scheduler updates are already locked. ADC/DMA callbacks use + // EFI_IRQ_ADC_PRIORITY, which this system lock masks; it also prevents + // the knock processing thread from running during the copy. + chibios_rt::CriticalSectionLocker lock; + return {fastAdcDiagnostics, knockAdcDiagnostics}; +} + +static void printCounters(const char* name, const AdcDiagnostics& counters) { + efiPrintf( + "adc %s started=%lu completed=%lu errors=%lu last_error=%lu processed=%lu", + name, + static_cast(counters.started), + static_cast(counters.completed), + static_cast(counters.errors), + static_cast(counters.lastError), + static_cast(counters.processed)); + efiPrintf( + "adc %s skip_active=%lu skip_complete=%lu skip_not_ready=%lu", + name, + static_cast(counters.skippedActive), + static_cast(counters.skippedComplete), + static_cast(counters.skippedNotReady)); + efiPrintf( + "adc %s skip_no_channels=%lu skip_invalid_channels=%lu skip_disabled=%lu skip_pending=%lu", + name, + static_cast(counters.skippedNoChannels), + static_cast(counters.skippedInvalidChannels), + static_cast(counters.skippedDisabled), + static_cast(counters.skippedPending)); +} + +static void printAdcDiagnostics() { + const auto snapshot = getAdcDiagnostics(); + // Formatting and console I/O must stay outside the critical section. + efiPrintf( + "adc mode=%s started_unit=%s completed_unit=buffer counters=uint32_since_boot knock_compiled=%d", + fastIsCircular ? "circular" : "timer", + fastIsCircular ? "stream" : "conversion", +#if EFI_SOFTWARE_KNOCK + 1 +#else + 0 +#endif + ); + printCounters("fast", snapshot.fast); + printCounters("knock", snapshot.knock); +} + +void initAdcDiagnostics(bool circular) { + fastIsCircular = circular; + addConsoleAction("adc_stats", printAdcDiagnostics); +} +#endif // HAL_USE_ADC diff --git a/firmware/hw_layer/adc/adc_diagnostics.h b/firmware/hw_layer/adc/adc_diagnostics.h new file mode 100644 index 0000000000..ae049cf816 --- /dev/null +++ b/firmware/hw_layer/adc/adc_diagnostics.h @@ -0,0 +1,43 @@ +#pragma once + +#include +#include "hal.h" + +// Counts since boot, wrapping modulo 2^32 (about 5 days at 10 kHz). No runtime reset: +// each field has one serialized writer, and console readers use a locked snapshot. +struct AdcDiagnostics { + uint32_t started = 0; + uint32_t completed = 0; + uint32_t errors = 0; + uint32_t lastError = 0; + uint32_t skippedActive = 0; + uint32_t skippedComplete = 0; + uint32_t skippedNotReady = 0; + uint32_t skippedNoChannels = 0; + uint32_t skippedInvalidChannels = 0; + uint32_t skippedDisabled = 0; + uint32_t skippedPending = 0; + uint32_t processed = 0; +}; + +extern AdcDiagnostics fastAdcDiagnostics; +extern AdcDiagnostics knockAdcDiagnostics; + +// Called only after the caller's existing readiness guard has rejected a start. +inline void recordAdcSkippedState(AdcDiagnostics& counters, adcstate_t state) { + if (state == ADC_ACTIVE) { + counters.skippedActive++; + } else if (state == ADC_COMPLETE) { + counters.skippedComplete++; + } else { + counters.skippedNotReady++; + } +} + +struct AdcDiagnosticsSnapshot { + AdcDiagnostics fast; + AdcDiagnostics knock; +}; + +AdcDiagnosticsSnapshot getAdcDiagnostics(); +void initAdcDiagnostics(bool fastIsCircular); diff --git a/firmware/hw_layer/hw_layer.mk b/firmware/hw_layer/hw_layer.mk index cc665d48d4..4ad0c417d9 100644 --- a/firmware/hw_layer/hw_layer.mk +++ b/firmware/hw_layer/hw_layer.mk @@ -22,6 +22,7 @@ HW_LAYER_EMS_CPP = \ $(PROJECT_DIR)/hw_layer/mmc_card_attach.cpp \ $(PROJECT_DIR)/hw_layer/mmc_card_mount.cpp \ $(PROJECT_DIR)/hw_layer/adc/adc_inputs.cpp \ + $(PROJECT_DIR)/hw_layer/adc/adc_diagnostics.cpp \ $(PROJECT_DIR)/hw_layer/adc/adc_provider.cpp \ $(PROJECT_DIR)/hw_layer/adc/adc_subscription.cpp \ $(PROJECT_DIR)/hw_layer/adc/ads1015.cpp \ diff --git a/firmware/hw_layer/ports/stm32/stm32_adc_v2.cpp b/firmware/hw_layer/ports/stm32/stm32_adc_v2.cpp index 5ca2bad42d..78da9b519d 100644 --- a/firmware/hw_layer/ports/stm32/stm32_adc_v2.cpp +++ b/firmware/hw_layer/ports/stm32/stm32_adc_v2.cpp @@ -10,6 +10,8 @@ #if HAL_USE_ADC +#include "adc_diagnostics.h" + /* Depth of the conversion buffer, channels are sampled X times each.*/ #define SLOW_ADC_OVERSAMPLE 8 @@ -23,6 +25,7 @@ static const GPTConfig fast_adc_timer_config = {GPT_FREQ_FAST, fast_adc_timer_ca #endif void portInitAdc() { + initAdcDiagnostics(false); // Init slow ADC adcStart(&ADCD1, NULL); @@ -234,18 +237,24 @@ static Stm32AdcV2Provider provider; static void adc_callback_fast(ADCDriver* adcp) { // State may not be complete if we get a callback for "half done" - if (adcp->state == ADC_COMPLETE) { + if (adcIsBufferComplete(adcp)) { + fastAdcDiagnostics.completed++; onFastAdcComplete(adcp->samples); } assertInterruptPriority(__func__, EFI_IRQ_ADC_PRIORITY); } +static void fastAdcErrorCallback(ADCDriver*, adcerror_t error) { + fastAdcDiagnostics.errors++; + fastAdcDiagnostics.lastError = error; +} + ADCConversionGroup adcgrpcfgFast = { .circular = FALSE, .num_channels = 0, .end_cb = adc_callback_fast, - .error_cb = nullptr, + .error_cb = fastAdcErrorCallback, /* HW dependent part.*/ .cr1 = 0, .cr2 = ADC_CR2_SWSTART, @@ -320,18 +329,25 @@ auto& ADC_FAST_DEVICE = ADCD2; static void fast_adc_timer_callback(GPTDriver*) { chibios_rt::CriticalSectionLocker csl; - if (ADC_FAST_DEVICE.state != ADC_READY && ADC_FAST_DEVICE.state != ADC_COMPLETE && - ADC_FAST_DEVICE.state != ADC_ERROR) { + // ADC_COMPLETE belongs to the completion callback; the HAL is not ready yet. + if (ADC_FAST_DEVICE.state != ADC_READY && ADC_FAST_DEVICE.state != ADC_ERROR) { + recordAdcSkippedState(fastAdcDiagnostics, ADC_FAST_DEVICE.state); return; } if (adcgrpcfgFast.num_channels == 0 || adcgrpcfgFast.num_channels > maxFastChannels) { // No channels configured (yet), don't attempt to sample // with an invalid configuration + if (adcgrpcfgFast.num_channels == 0) { + fastAdcDiagnostics.skippedNoChannels++; + } else { + fastAdcDiagnostics.skippedInvalidChannels++; + } return; } adcStartConversionI(&ADC_FAST_DEVICE, &adcgrpcfgFast, fastAdcSampleBuf, ADC_BUF_DEPTH_FAST); + fastAdcDiagnostics.started++; assertInterruptPriority(__func__, EFI_IRQ_ADC_PRIORITY); } @@ -342,14 +358,18 @@ static void fast_adc_timer_callback(GPTDriver*) { #include "knock_config.h" static void knockCompletionCallback(ADCDriver* adcp) { - if (adcp->state == ADC_COMPLETE) { + if (adcIsBufferComplete(adcp)) { + knockAdcDiagnostics.completed++; onKnockSamplingComplete(); } assertInterruptPriority(__func__, EFI_IRQ_ADC_PRIORITY); } -static void knockErrorCallback(ADCDriver*, adcerror_t) {} +static void knockErrorCallback(ADCDriver*, adcerror_t error) { + knockAdcDiagnostics.errors++; + knockAdcDiagnostics.lastError = error; +} static const uint32_t smpr1 = ADC_SMPR1_SMP_AN10(KNOCK_SAMPLE_TIME) | ADC_SMPR1_SMP_AN11(KNOCK_SAMPLE_TIME) | ADC_SMPR1_SMP_AN12(KNOCK_SAMPLE_TIME) | ADC_SMPR1_SMP_AN13(KNOCK_SAMPLE_TIME) | diff --git a/firmware/hw_layer/ports/stm32/stm32_adc_v4.cpp b/firmware/hw_layer/ports/stm32/stm32_adc_v4.cpp index f50b4010ac..10e349e6ef 100644 --- a/firmware/hw_layer/ports/stm32/stm32_adc_v4.cpp +++ b/firmware/hw_layer/ports/stm32/stm32_adc_v4.cpp @@ -10,6 +10,8 @@ #if HAL_USE_ADC +#include "adc_diagnostics.h" + #include "mpu_util.h" // All ADCs should be running at 40MHz @@ -50,6 +52,7 @@ static constexpr int H7_ADC_SHIFT_BITS = log2_int(H7_ADC_OVERSAMPLE); __attribute__((section(".ram4"))) __attribute__((aligned(8192))) adcsample_t knockSampleBuffer[2048]; void portInitAdc() { + initAdcDiagnostics(true); { void* base = &knockSampleBuffer; static_assert(sizeof(knockSampleBuffer) == 8192); @@ -84,13 +87,19 @@ float getMcuTemperature() { static void adc_callback(ADCDriver* adcp) { // State may not be complete if we get a callback for "half done" - if (adcp->state == ADC_COMPLETE) { + if (adcIsBufferComplete(adcp)) { + fastAdcDiagnostics.completed++; onFastAdcComplete(adcp->samples); } assertInterruptPriority(__func__, EFI_IRQ_ADC_PRIORITY); } +static void fastAdcErrorCallback(ADCDriver*, adcerror_t error) { + fastAdcDiagnostics.errors++; + fastAdcDiagnostics.lastError = error; +} + // ADC Clock is 25MHz // 16.5 sampling + 7.5 conversion = 24 cycles per sample total // 16 channels * 4x oversample = 64 samples per batch @@ -107,7 +116,7 @@ static constexpr ADCConversionGroup convGroupSlow = { .circular = true, // Continuous mode means we will auto re-trigger on every timer event .num_channels = slowChannelCount, .end_cb = adc_callback, - .error_cb = nullptr, + .error_cb = fastAdcErrorCallback, .cfgr = ADC_CFGR_EXTEN_0 | (4 << ADC_CFGR_EXTSEL_Pos) | // External trigger ch4, rising edge: TIM3 TRGO ADC_CFGR_OVRMOD, // OVRMOD=1 is required by H7 errata: ES0392 section 2.9.6. If OVRMOD is not set, it is // possible for the secondary ADC's data to be shifted from where it was supposed to @@ -214,6 +223,7 @@ bool readSlowAnalogInputs() { // Oversampling and right-shift happen in hardware, so we can sample directly to the output buffer // Pass the 32-bit view to the HAL - it will receive slowChannelCount/2 32-bit samples in dual mode adcStartConversionI(&ADCD1, &convGroupSlow, sampleBuffer.samples32, 1); + fastAdcDiagnostics.started++; } constexpr uint32_t samplingRate = H7_ADC_SPEED; @@ -295,14 +305,18 @@ static_assert((H7_KNOCK_OVERSAMPLE & (H7_KNOCK_OVERSAMPLE - 1)) == 0, "H7_KNOCK_ static constexpr int H7_KNOCK_ADC_SHIFT_BITS = log2_int(H7_KNOCK_OVERSAMPLE); static void knockCompletionCallback(ADCDriver* adcp) { - if (adcp->state == ADC_COMPLETE) { + if (adcIsBufferComplete(adcp)) { + knockAdcDiagnostics.completed++; onKnockSamplingComplete(); } assertInterruptPriority(__func__, EFI_IRQ_ADC_PRIORITY); } -static void knockErrorCallback(ADCDriver*, adcerror_t) {} +static void knockErrorCallback(ADCDriver*, adcerror_t error) { + knockAdcDiagnostics.errors++; + knockAdcDiagnostics.lastError = error; +} static const uint32_t smpr1 = ADC_SMPR1_SMP_AN0(KNOCK_SAMPLE_TIME) | ADC_SMPR1_SMP_AN1(KNOCK_SAMPLE_TIME) | ADC_SMPR1_SMP_AN2(KNOCK_SAMPLE_TIME) | ADC_SMPR1_SMP_AN3(KNOCK_SAMPLE_TIME) | diff --git a/unit_tests/Makefile b/unit_tests/Makefile index 915c0970e2..0a530586ee 100644 --- a/unit_tests/Makefile +++ b/unit_tests/Makefile @@ -68,3 +68,5 @@ INCDIR += \ include $(UNIT_TESTS_DIR)/unit_test_rules.mk + +include $(UNIT_TESTS_DIR)/adc_lifecycle/adc_lifecycle.mk diff --git a/unit_tests/adc_lifecycle/README.md b/unit_tests/adc_lifecycle/README.md new file mode 100644 index 0000000000..19757f75da --- /dev/null +++ b/unit_tests/adc_lifecycle/README.md @@ -0,0 +1,95 @@ +# ADC lifecycle regression and diagnostics + +Run from `unit_tests`: `make -j12 adc-lifecycle-test`. +The unit-test CI workflow runs this target on Linux and macOS. The target builds +separate ADCv2 (F4/F7) and ADCv4 (H7) host binaries with ASan/UBSan by default. + +## Real callers and HAL + +Both binaries include the complete production ADC port and `software_knock.cpp`, +the vendored ChibiOS `hal_adc.c`, and the matching low-level driver headers. +The static fast timer callback on ADCv2 is reached through the GPT configuration +registered by `portInitAdc`; knock is reached through `onStartKnockSampling`, with +the scheduler's system lock represented by the fixture. ADCv4 starts its circular +stream through `readSlowAnalogInputs`. No production test hooks are needed. + +Mocks replace MCU registers/MPU, RTOS services and unrelated engine services. The +HAL's assertions, conversion state transitions and half/full/error ISR macros are +real. Tests cover all initial states, configuration guards, completion preemption, +pending knock processing, one result per full buffer, distinct rejection reasons, +HAL errors (including ADCv2 DMA error code zero), recovery, counter wrap, and console +snapshots. Console output is checked for length and for formatting outside the lock. +ADCv4 tests distinguish circular stream starts from completed buffers and preserve +the existing policy: the stream is not automatically restarted after an error. + +With the phase-1 guards reverted, either command aborts in `hal_adc.c` with `not ready`: + +``` +./build/adc_lifecycle_test --gtest_filter=AllStates/AdcStartState.FastTimer/4 +./build/adc_lifecycle_test --gtest_filter=AllStates/AdcStartState.KnockScheduler/4 +``` + +The fixtures test software ordering, not physical ADC inputs, DMA timing, interrupt +priorities, RTOS scheduling or filter quality. They cannot establish sample-loss +rates, latency distributions or stability under real IRQ load. + +## Using `adc_stats` on an ECU + +The console command prints one snapshot in seven lines: a header, then three lines +for each of `fast` and `knock`. It does not clear counters or change configuration. +Example header and fast counters: + +``` +adc mode=timer started_unit=conversion completed_unit=buffer counters=uint32_since_boot knock_compiled=0 +adc fast started=100 completed=100 errors=0 last_error=0 processed=0 +adc fast skip_active=0 skip_complete=0 skip_not_ready=0 +adc fast skip_no_channels=42 skip_invalid_channels=0 skip_disabled=0 skip_pending=0 +``` + +H7 reports `mode=circular started_unit=stream`: one start can produce many completed +buffers. Its fast counters describe the shared continuous ADC stream, which also +feeds slow sensors. `knock_compiled=0` distinguishes unavailable software knock from +an idle knock ADC. Fast `processed` is unused; knock `processed` counts results +delivered after filtering. Unsupported reasons for either path remain zero. + +`started` counts accepted HAL starts, and `completed` counts full-buffer callbacks +only. An error callback increments `errors` and stores the raw architecture-specific +code in `last_error`; it does not publish a completed buffer or change recovery +policy. A raw error value of zero is valid on ADCv2. Starting from `ADC_ERROR` is +allowed by the HAL and does not itself increment `errors`. + +Each rejected start increments exactly its first rejection reason, preserving the +original guard order: + +- `skip_active`, `skip_complete`: the ADC is still converting or completing. +- `skip_not_ready`: any other state rejected by the existing readiness guard. +- `skip_no_channels`, `skip_invalid_channels`: ADCv2 has zero or too many fast channels. +- `skip_disabled`: software knock is disabled in the active configuration. +- `skip_pending`: the knock processing thread still owns the previous sample buffer. + +Skip counters cover only requests that reached the caller and were rejected. They +do not count GPT ticks lost or coalesced while interrupts are masked, or analog +errors. Matching start/completion counts with no errors does not prove that no +samples were lost. + +Counters wrap modulo 2^32 (about 4.97 days at 10 kHz). Compute differences modulo +2^32 between snapshots taken less than one wrap apart, and detect reboots separately. +There is no reset command. No calibration or TunerStudio output layout changes. + +## Concurrency and cost + +The two counter records occupy 96 bytes. Each counter has one serialized writer: +fast timer and knock scheduler starts already hold the system lock; ADC/DMA callbacks +run at `EFI_IRQ_ADC_PRIORITY`; only the knock thread writes `processed`. The F4/F7 +configuration uses the same ADC and DMA IRQ priority, and the H7 HAL allocates its +DMA/BDMA handlers at its configured ADC IRQ priority. These IRQs are masked by the +system lock. Taking the 96-byte snapshot also prevents a thread switch, so the +console sees a consistent pair of records. + +A successful single conversion adds one increment at start and one at full-buffer +completion. A rejection adds one increment, and an error callback updates a count +and its last code. There are no additional locks, allocations or console writes in +the ADC/scheduler callbacks. The console briefly locks for the copy, then formats +and queues all lines after unlocking. Existing console buffering can still drop +lines under heavy logging; discard incomplete snapshots instead of treating missing +fields as zero. diff --git a/unit_tests/adc_lifecycle/adc_lifecycle.mk b/unit_tests/adc_lifecycle/adc_lifecycle.mk new file mode 100644 index 0000000000..af48f96bdb --- /dev/null +++ b/unit_tests/adc_lifecycle/adc_lifecycle.mk @@ -0,0 +1,42 @@ +# Real MCU callers and portable ChibiOS HAL with host peripheral mocks. +# Separate binaries/PCH from the engine tests, for the two HAL register layouts. +ADC_LIFECYCLE_DIR := adc_lifecycle +ADC_LIFECYCLE_BINS := build/adc_lifecycle_test build/adc_lifecycle_v4_test +ifeq ($(SANITIZE),yes) +ADC_LIFECYCLE_SANITIZE := -fsanitize=address,undefined +endif +ADC_LIFECYCLE_INC := -I$(ADC_LIFECYCLE_DIR)/mocks \ + -I$(PROJECT_DIR)/ext/ChibiOS/os/hal/include \ + -I$(PROJECT_DIR)/hw_layer/adc \ + -I$(UNIT_TESTS_DIR)/googletest/googletest/include \ + -I$(UNIT_TESTS_DIR)/googletest/googletest + +.PHONY: adc-lifecycle-test +adc-lifecycle-test: $(ADC_LIFECYCLE_BINS) + ./build/adc_lifecycle_test + ./build/adc_lifecycle_v4_test + +build/adc_lifecycle_test: ADC_LIFECYCLE_PORT := ADCv2 +build/adc_lifecycle_v4_test: ADC_LIFECYCLE_PORT := ADCv4 +build/adc_lifecycle_v4_test: ADC_LIFECYCLE_DEFINES := -DADC_TEST_V4=1 + +$(ADC_LIFECYCLE_BINS): $(ADC_LIFECYCLE_DIR)/test_adc_lifecycle.cpp \ + $(ADC_LIFECYCLE_DIR)/adc_lifecycle.mk \ + $(PROJECT_DIR)/controllers/sensors/impl/software_knock.h \ + $(PROJECT_DIR)/config/boards/f407-discovery/knock_config.h \ + $(PROJECT_DIR)/config/boards/proteus/knock_config.h \ + $(wildcard $(ADC_LIFECYCLE_DIR)/mocks/*) \ + $(PROJECT_DIR)/hw_layer/ports/stm32/stm32_adc_v2.cpp \ + $(PROJECT_DIR)/hw_layer/ports/stm32/stm32_adc_v4.cpp \ + $(PROJECT_DIR)/hw_layer/adc/adc_diagnostics.cpp \ + $(PROJECT_DIR)/hw_layer/adc/adc_diagnostics.h \ + $(PROJECT_DIR)/controllers/sensors/impl/software_knock.cpp \ + $(PROJECT_DIR)/ext/ChibiOS/os/hal/src/hal_adc.c \ + $(PROJECT_DIR)/ext/ChibiOS/os/hal/include/hal_adc.h \ + $(PROJECT_DIR)/ext/ChibiOS/os/hal/ports/STM32/LLD/ADCv2/hal_adc_lld.h \ + $(PROJECT_DIR)/ext/ChibiOS/os/hal/ports/STM32/LLD/ADCv4/hal_adc_lld.h | $(BUILDDIR) + $(CPPC) -std=c++20 -g -O0 -Wall -Wextra -Wno-unused-parameter \ + $(ADC_LIFECYCLE_SANITIZE) $(ADC_LIFECYCLE_INC) $(ADC_LIFECYCLE_DEFINES) \ + -I$(PROJECT_DIR)/ext/ChibiOS/os/hal/ports/STM32/LLD/$(ADC_LIFECYCLE_PORT) $< \ + $(UNIT_TESTS_DIR)/googletest/googletest/src/gtest-all.cc \ + $(UNIT_TESTS_DIR)/googletest/googletest/src/gtest_main.cc -pthread -o $@ diff --git a/unit_tests/adc_lifecycle/mocks/biquad.h b/unit_tests/adc_lifecycle/mocks/biquad.h new file mode 100644 index 0000000000..b0fe750f1a --- /dev/null +++ b/unit_tests/adc_lifecycle/mocks/biquad.h @@ -0,0 +1,10 @@ +#pragma once + +// Filtering is covered by test_biquad.cpp; this fixture observes buffer ownership. +struct Biquad { + void configureBandpass(float, float, float) {} + void cookSteadyState(float) {} + float filter(float value) { + return value; + } +}; diff --git a/unit_tests/adc_lifecycle/mocks/ch.hpp b/unit_tests/adc_lifecycle/mocks/ch.hpp new file mode 100644 index 0000000000..7975ab275c --- /dev/null +++ b/unit_tests/adc_lifecycle/mocks/ch.hpp @@ -0,0 +1,2 @@ +#pragma once +#include "pch.h" diff --git a/unit_tests/adc_lifecycle/mocks/hal.h b/unit_tests/adc_lifecycle/mocks/hal.h new file mode 100644 index 0000000000..a9c1e12685 --- /dev/null +++ b/unit_tests/adc_lifecycle/mocks/hal.h @@ -0,0 +1,49 @@ +#pragma once + +#include +#include +#include + +#define TRUE 1 +#define FALSE 0 +#define HAL_USE_ADC TRUE +#define ADC_USE_WAIT FALSE +#define ADC_USE_MUTUAL_EXCLUSION FALSE +#ifdef ADC_TEST_V4 +#include "hal_v4_config.h" +#else +#define STM32F4XX +#define STM32_ADC_USE_ADC1 TRUE +#define STM32_ADC_USE_ADC2 TRUE +#define STM32_ADC_USE_ADC3 TRUE +#define STM32_HAS_ADC1 TRUE +#define STM32_HAS_ADC2 TRUE +#define STM32_HAS_ADC3 TRUE +#define STM32_DMA_IS_VALID_ID(stream, mask) TRUE +#define STM32_PCLK2 84000000 +#define STM32_ADC_ADCPRE 1 +#define ADC_CR2_SWSTART (1U << 30) +#endif +struct ADC_TypeDef; +struct stm32_dma_stream_t; + +// Use the vendored HAL's state machine, structures and port-specific register macros. +#include "hal_adc.h" + +inline int lockDepth = 0; +inline void osalSysLock() { + ++lockDepth; +} +inline void osalSysUnlock() { + assert(lockDepth > 0); + --lockDepth; +} +#define osalDbgCheckClassI() assert(lockDepth > 0) +#define osalDbgCheck(condition) assert(condition) +#define osalDbgAssert(condition, message) assert((condition) && message) + +using msg_t = int; +constexpr msg_t MSG_OK = 0; +inline msg_t adcConvert(ADCDriver*, const ADCConversionGroup*, adcsample_t*, size_t) { + return MSG_OK; +} diff --git a/unit_tests/adc_lifecycle/mocks/hal_v4_config.h b/unit_tests/adc_lifecycle/mocks/hal_v4_config.h new file mode 100644 index 0000000000..7499900346 --- /dev/null +++ b/unit_tests/adc_lifecycle/mocks/hal_v4_config.h @@ -0,0 +1,35 @@ +#pragma once + +// Host stand-ins for the device registry/CMSIS register constants used by ADCv4. +// Driver structures, error codes and sequence macros come from the real HAL. +#define STM32H7XX +#define STM32_ADC_USE_ADC12 TRUE +#define STM32_ADC_USE_ADC3 TRUE +#define STM32_HAS_ADC1 TRUE +#define STM32_HAS_ADC2 TRUE +#define STM32_HAS_ADC3 TRUE +#define STM32_ADC12_HANDLER testAdc12Handler +#define STM32_ADC3_HANDLER testAdc3Handler +#define STM32_ADC12_NUMBER 18 +#define STM32_ADC3_NUMBER 127 +#define STM32_ADC_ADC12_DMA_STREAM 0 +#define STM32_ADC_ADC3_BDMA_STREAM 0 +#define STM32_DMA_IS_VALID_STREAM(stream) TRUE +#define STM32_BDMA_IS_VALID_STREAM(stream) TRUE +#define STM32_DMA_IS_VALID_PRIORITY(priority) TRUE +#define OSAL_IRQ_IS_VALID_PRIORITY(priority) TRUE +#define STM32_ADC_DUAL_MODE TRUE +#define STM32_ADC_SAMPLES_SIZE 32 +#define STM32_HCLK 160000000 +#define STM32_ADCCLK 40000000 +#define STM32_ADCCLK_MAX 50000000 +#define ADC_CFGR_EXTEN_0 (1U << 10) +#define ADC_CFGR_EXTSEL_Pos 5 +#define ADC_CFGR_OVRMOD (1U << 12) +#define ADC_CFGR_CONT (1U << 13) +#define ADC_CFGR2_OVSR_Pos 16 +#define ADC_CFGR2_OVSS_Pos 5 +#define ADC_CFGR2_ROVSE 1U +#define TIM_CR2_MMS_1 (1U << 5) +struct ADC_Common_TypeDef; +struct stm32_bdma_stream_t; diff --git a/unit_tests/adc_lifecycle/mocks/knock_config.h b/unit_tests/adc_lifecycle/mocks/knock_config.h new file mode 100644 index 0000000000..c5e6a0e320 --- /dev/null +++ b/unit_tests/adc_lifecycle/mocks/knock_config.h @@ -0,0 +1,6 @@ +#pragma once +#ifdef ADC_TEST_V4 +#include "../../../../firmware/config/boards/proteus/knock_config.h" +#else +#include "../../../../firmware/config/boards/f407-discovery/knock_config.h" +#endif diff --git a/unit_tests/adc_lifecycle/mocks/knock_logic.h b/unit_tests/adc_lifecycle/mocks/knock_logic.h new file mode 100644 index 0000000000..7975ab275c --- /dev/null +++ b/unit_tests/adc_lifecycle/mocks/knock_logic.h @@ -0,0 +1,2 @@ +#pragma once +#include "pch.h" diff --git a/unit_tests/adc_lifecycle/mocks/mpu_util.h b/unit_tests/adc_lifecycle/mocks/mpu_util.h new file mode 100644 index 0000000000..f68e504bca --- /dev/null +++ b/unit_tests/adc_lifecycle/mocks/mpu_util.h @@ -0,0 +1,22 @@ +#pragma once + +// Memory protection/register access is outside the host lifecycle fixture. +constexpr int MPU_RASR_SIZE_8K = 0; +constexpr int MPU_REGION_3 = 0; +constexpr int MPU_RASR_ATTR_AP_RW_RW = 0; +constexpr int MPU_RASR_ATTR_NON_CACHEABLE = 0; +constexpr int MPU_RASR_ATTR_S = 0; +constexpr int MPU_RASR_ENABLE = 0; +constexpr int MPU_CTRL_PRIVDEFENA = 0; +inline void mpuConfigureRegion(int, void*, uint32_t) {} +inline void mpuEnable(int) {} +inline void SCB_CleanInvalidateDCache() {} +constexpr uint32_t SYSCFG_PMCR_PA0SO = 1; +constexpr uint32_t SYSCFG_PMCR_PA1SO = 2; +constexpr uint32_t SYSCFG_PMCR_PC2SO = 4; +constexpr uint32_t SYSCFG_PMCR_PC3SO = 8; +struct MockSyscfg { + uint32_t PMCR = 0; +}; +inline MockSyscfg syscfg; +inline auto* SYSCFG = &syscfg; diff --git a/unit_tests/adc_lifecycle/mocks/pch.h b/unit_tests/adc_lifecycle/mocks/pch.h new file mode 100644 index 0000000000..5e0c08f5e0 --- /dev/null +++ b/unit_tests/adc_lifecycle/mocks/pch.h @@ -0,0 +1,182 @@ +#pragma once + +#include "hal.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef ADC_TEST_V4 +#define EFI_USE_FAST_ADC 0 +#else +#define EFI_USE_FAST_ADC 1 +#endif +#define EFI_SOFTWARE_KNOCK 1 +#define NO_CACHE +#define CCM_OPTIONAL +#define ADC_MAX_VALUE 4095 +#define ADC_BUF_DEPTH_FAST 4 +#define GPT_FREQ_FAST 1000000 +#define GPT_PERIOD_FAST 100 +#define EFI_IRQ_ADC_PRIORITY 5 +#define PRIO_KNOCK_PROCESS 1 +#define PAL_MODE_INPUT_ANALOG 0 + +using efitick_t = int64_t; +using FastAdcToken = size_t; +using adc_channel_e = int; +constexpr adc_channel_e EFI_ADC_0 = 0; +namespace efi { +using std::size; +} +inline float clampF(float lo, float value, float hi) { + return std::clamp(value, lo, hi); +} +inline efitick_t getTimeNowNt() { + return 1234; +} +inline bool isAdcChannelValid(adc_channel_e ch) { + return ch >= 0 && ch < 16; +} +inline void assertInterruptPriority(const char*, int) {} +inline void firmwareError(const char*, ...) { + assert(false); +} +inline std::vector consoleLines; +inline std::function afterConsolePrint; +inline void efiPrintf(const char* format, ...) { + assert(lockDepth == 0); + char text[256]; + va_list args; + va_start(args, format); + int count = vsnprintf(text, sizeof(text), format, args); + va_end(args); + assert(count >= 0 && count < 250); // Allow room for the production msg delimiters. + consoleLines.emplace_back(text); + if (afterConsolePrint) { + afterConsolePrint(); + } +} +inline void (*adcStatsCommand)() = nullptr; +inline void addConsoleAction(const char* name, void (*action)()) { + assert(std::string(name) == "adc_stats"); + adcStatsCommand = action; +} + +enum class Gpio { + A3, + F4, + F5 +}; +inline void efiSetPadMode(const char*, Gpio, int) {} +struct NamedOutputPin { + NamedOutputPin(const char*, const char*) {} + bool high = false; + void setHigh() { + high = true; + } + void setLow() { + high = false; + } +}; +struct EngineConfiguration { + bool enableSoftwareKnock = true; + float adcVcc = 3.3f; + float knockBandCustom = 0; + float cylinderBore = 86; +}; +inline EngineConfiguration configuration; +inline auto* engineConfiguration = &configuration; +struct KnockController { + int results = 0; + void onKnockSenseCompleted(uint8_t, uint8_t, float, efitick_t) { + ++results; + } +}; +inline KnockController knockController; +struct Engine { + template + T* module() { + return &knockController; + } +}; +inline Engine engineInstance; +inline auto* engine = &engineInstance; + +struct Stm32AdcProviderBase { + virtual const char* name() const = 0; + virtual float get(size_t) const = 0; +}; +inline void registerAdcProvider(Stm32AdcProviderBase&, int, int) {} + +struct GPTDriver {}; +struct GPTConfig { + int frequency; + void (*callback)(GPTDriver*); + int cr2; + int dier; +}; +inline GPTDriver timer; +inline GPTDriver GPTD3; +#define EFI_INTERNAL_FAST_ADC_GPT (&timer) +inline const GPTConfig* timerConfig = nullptr; +inline void gptStart(GPTDriver*, const GPTConfig* config) { + timerConfig = config; +} +inline void gptStartContinuous(GPTDriver*, int) {} + +inline int fastResults = 0; +inline adcsample_t* lastFastSamples = nullptr; +inline void onFastAdcComplete(adcsample_t* samples) { + ++fastResults; + lastFastSamples = samples; +} +void onKnockSamplingComplete(); + +namespace chibios_rt { +struct CriticalSectionLocker { + CriticalSectionLocker() { + osalSysLock(); + } + ~CriticalSectionLocker() { + osalSysUnlock(); + } +}; +struct BinarySemaphore { + explicit BinarySemaphore(bool) {} + int signals = 0; + void signalI() { + assert(lockDepth > 0); + ++signals; + } + void wait() {} +}; +} // namespace chibios_rt +inline void chSysLockFromISR() { + osalSysLock(); +} +inline void chSysUnlockFromISR() { + osalSysUnlock(); +} + +template +struct ThreadController { + ThreadController(const char*, int) {} + virtual void ThreadTask() = 0; + void startThread() {} +}; +enum class PE { + SoftwareKnockProcess +}; +struct ScopePerf { + explicit ScopePerf(PE) {} +}; + +template +void setArrayValues(T (&values)[N], V value) { + std::fill(std::begin(values), std::end(values), value); +} diff --git a/unit_tests/adc_lifecycle/mocks/thread_controller.h b/unit_tests/adc_lifecycle/mocks/thread_controller.h new file mode 100644 index 0000000000..7975ab275c --- /dev/null +++ b/unit_tests/adc_lifecycle/mocks/thread_controller.h @@ -0,0 +1,2 @@ +#pragma once +#include "pch.h" diff --git a/unit_tests/adc_lifecycle/test_adc_lifecycle.cpp b/unit_tests/adc_lifecycle/test_adc_lifecycle.cpp new file mode 100644 index 0000000000..b32c1bc820 --- /dev/null +++ b/unit_tests/adc_lifecycle/test_adc_lifecycle.cpp @@ -0,0 +1,406 @@ +#include "pch.h" +#include "gtest/gtest.h" + +// Keep the production callers (including static timer/callback functions) intact. +// Only their surrounding hardware/services are mocked, not ADC state transitions. +#include "../../firmware/ext/ChibiOS/os/hal/src/hal_adc.c" +#include "../../firmware/hw_layer/adc/adc_diagnostics.cpp" +#ifdef ADC_TEST_V4 +#include "../../firmware/hw_layer/ports/stm32/stm32_adc_v4.cpp" +#else +#include "../../firmware/hw_layer/ports/stm32/stm32_adc_v2.cpp" +#endif +#include "../../firmware/controllers/sensors/impl/software_knock.cpp" + +ADCDriver ADCD1{}; +ADCDriver ADCD2{}; +ADCDriver ADCD3{}; +static int starts; +static int stops; +void adc_lld_init() {} +void adc_lld_start(ADCDriver*) {} +void adc_lld_stop(ADCDriver*) {} +void adc_lld_start_conversion(ADCDriver*) { + ++starts; +} +void adc_lld_stop_conversion(ADCDriver*) { + ++stops; +} +void adcSTM32EnableTSVREFE() {} + +class AdcLifecycle : public testing::Test { +protected: + void SetUp() override { + lockDepth = starts = stops = fastResults = knockController.results = 0; + configuration = {}; + fastAdcDiagnostics = {}; + knockAdcDiagnostics = {}; + consoleLines.clear(); + afterConsolePrint = {}; + adcObjectInit(&ADCD1); + adcObjectInit(&ADCD2); + adcObjectInit(&ADCD3); + portInitAdc(); +#ifdef ADC_TEST_V4 + didStart = false; +#else + adcgrpcfgFast.num_channels = 1; +#endif + knockNeedsProcess = false; + knockSem.signals = 0; + knockSnifferPin.setLow(); + lastFastSamples = nullptr; + } + + void startKnock() { + // The scheduler invokes the knock callback with the system locked. + chibios_rt::CriticalSectionLocker lock; + onStartKnockSampling(2, 0.002f, 0); + } + + void tickFast() { +#ifdef ADC_TEST_V4 + readSlowAnalogInputs(); +#else + timerConfig->callback(&timer); +#endif + } +}; + +class AdcStartState : public AdcLifecycle, public testing::WithParamInterface {}; + +#ifndef ADC_TEST_V4 +TEST_P(AdcStartState, FastTimer) { + ADCD2.state = GetParam(); + tickFast(); + bool allowed = GetParam() == ADC_READY || GetParam() == ADC_ERROR; + EXPECT_EQ(allowed ? 1 : 0, starts); + EXPECT_EQ(allowed ? ADC_ACTIVE : GetParam(), ADCD2.state); + EXPECT_EQ(0, lockDepth); + if (allowed) { + EXPECT_EQ(&adcgrpcfgFast, ADCD2.grpp); + EXPECT_EQ(fastAdcSampleBuf, ADCD2.samples); + EXPECT_EQ(size_t{ADC_BUF_DEPTH_FAST}, ADCD2.depth); + } +} + +#endif + +TEST_P(AdcStartState, KnockScheduler) { + KNOCK_ADC.state = GetParam(); + startKnock(); + bool allowed = GetParam() == ADC_READY || GetParam() == ADC_ERROR; + EXPECT_EQ(allowed ? 1 : 0, starts); + EXPECT_EQ(allowed ? ADC_ACTIVE : GetParam(), KNOCK_ADC.state); + EXPECT_EQ(allowed, knockSnifferPin.high); + EXPECT_EQ(0, lockDepth); + if (allowed) { + EXPECT_EQ(getKnockConversionGroup(0), KNOCK_ADC.grpp); + EXPECT_EQ(knockSampleBuffer, KNOCK_ADC.samples); + EXPECT_GE(KNOCK_ADC.depth, 100U); + EXPECT_EQ(0U, KNOCK_ADC.depth % 2); + } +} + +INSTANTIATE_TEST_SUITE_P( + AllStates, + AdcStartState, + testing::Values(ADC_UNINIT, ADC_STOP, ADC_READY, ADC_ACTIVE, ADC_COMPLETE, ADC_ERROR)); + +#ifndef ADC_TEST_V4 +TEST_F(AdcLifecycle, FastRejectsInvalidChannelCounts) { + for (auto count : {0U, 9U}) { + adcgrpcfgFast.num_channels = count; + tickFast(); + EXPECT_EQ(0, starts); + EXPECT_EQ(ADC_READY, ADCD2.state); + } +} + +#endif + +TEST_F(AdcLifecycle, DisabledKnockDoesNotStart) { + engineConfiguration->enableSoftwareKnock = false; + startKnock(); + EXPECT_EQ(0, starts); + EXPECT_EQ(ADC_READY, KNOCK_ADC.state); +} + +#ifndef ADC_TEST_V4 +TEST_F(AdcLifecycle, FastHalfAndFullBufferThenNextConversion) { + tickFast(); + _adc_isr_half_code(&ADCD2); + EXPECT_EQ(0, fastResults); + EXPECT_EQ(0U, getAdcDiagnostics().fast.completed); + EXPECT_EQ(ADC_ACTIVE, ADCD2.state); + _adc_isr_full_code(&ADCD2); + EXPECT_EQ(1, fastResults); + EXPECT_EQ(fastAdcSampleBuf, lastFastSamples); + EXPECT_EQ(1U, getAdcDiagnostics().fast.completed); + EXPECT_EQ(ADC_READY, ADCD2.state); + EXPECT_EQ(1, stops); + tickFast(); + EXPECT_EQ(2, starts); + EXPECT_EQ(ADC_ACTIVE, ADCD2.state); +} + +#endif + +TEST_F(AdcLifecycle, KnockHalfAndFullBufferThenProcessingAndNextConversion) { + startKnock(); + _adc_isr_half_code(&KNOCK_ADC); + EXPECT_EQ(0, knockSem.signals); + EXPECT_FALSE(knockNeedsProcess); + EXPECT_TRUE(knockSnifferPin.high); + _adc_isr_full_code(&KNOCK_ADC); + EXPECT_EQ(1, knockSem.signals); + EXPECT_TRUE(knockNeedsProcess); + EXPECT_FALSE(knockSnifferPin.high); + EXPECT_EQ(ADC_READY, KNOCK_ADC.state); + // HAL is ready, but the knock thread still owns the previous sample buffer. + startKnock(); + EXPECT_EQ(1, starts); + processLastKnockEvent(); + EXPECT_EQ(1, knockController.results); + processLastKnockEvent(); + EXPECT_EQ(1, knockController.results); + startKnock(); + EXPECT_EQ(2, starts); + EXPECT_EQ(ADC_ACTIVE, KNOCK_ADC.state); +} + +#ifndef ADC_TEST_V4 +TEST_F(AdcLifecycle, FastTickDuringCompletionSkipsAndRecovers) { + tickFast(); + // Reproduce timer preemption inside the real HAL's ADC_COMPLETE interval. + ADCConversionGroup group = adcgrpcfgFast; + group.end_cb = [](ADCDriver* adc) { + EXPECT_EQ(ADC_COMPLETE, adc->state); + timerConfig->callback(&timer); + EXPECT_EQ(1, starts); + EXPECT_EQ(1U, getAdcDiagnostics().fast.skippedComplete); + EXPECT_EQ(0U, getAdcDiagnostics().fast.errors); + adc_callback_fast(adc); + }; + ADCD2.grpp = &group; + _adc_isr_full_code(&ADCD2); + EXPECT_EQ(1, fastResults); + EXPECT_EQ(ADC_READY, ADCD2.state); + tickFast(); + EXPECT_EQ(2, starts); +} + +#endif + +TEST_F(AdcLifecycle, KnockWindowDuringCompletionSkipsAndRecovers) { + startKnock(); + ADCConversionGroup group = *KNOCK_ADC.grpp; + group.end_cb = [](ADCDriver* adc) { + EXPECT_EQ(ADC_COMPLETE, adc->state); + { + chibios_rt::CriticalSectionLocker lock; + onStartKnockSampling(3, 0.002f, 0); + } + EXPECT_EQ(1, starts); + EXPECT_EQ(2, currentCylinderNumber); + EXPECT_EQ(1U, getAdcDiagnostics().knock.skippedComplete); + EXPECT_EQ(0U, getAdcDiagnostics().knock.errors); + knockCompletionCallback(adc); + }; + KNOCK_ADC.grpp = &group; + _adc_isr_full_code(&KNOCK_ADC); + EXPECT_EQ(1, knockSem.signals); + EXPECT_EQ(ADC_READY, KNOCK_ADC.state); + processLastKnockEvent(); + EXPECT_EQ(1, knockController.results); + startKnock(); + EXPECT_EQ(2, starts); +} + +static uint32_t skipped(const AdcDiagnostics& counters) { + return counters.skippedActive + counters.skippedComplete + counters.skippedNotReady + counters.skippedNoChannels + + counters.skippedInvalidChannels + counters.skippedDisabled + counters.skippedPending; +} + +TEST_P(AdcStartState, KnockStateCounters) { + KNOCK_ADC.state = GetParam(); + startKnock(); + const auto counters = getAdcDiagnostics().knock; + const bool allowed = GetParam() == ADC_READY || GetParam() == ADC_ERROR; + EXPECT_EQ(allowed ? 1U : 0U, counters.started); + EXPECT_EQ(allowed ? 0U : 1U, skipped(counters)); + EXPECT_EQ(GetParam() == ADC_ACTIVE ? 1U : 0U, counters.skippedActive); + EXPECT_EQ(GetParam() == ADC_COMPLETE ? 1U : 0U, counters.skippedComplete); + EXPECT_EQ(GetParam() == ADC_UNINIT || GetParam() == ADC_STOP ? 1U : 0U, counters.skippedNotReady); + EXPECT_EQ(0U, counters.errors); // Starting in ADC_ERROR is not a new HAL error. + EXPECT_EQ(0U, counters.completed); +} + +#ifndef ADC_TEST_V4 +TEST_P(AdcStartState, FastStateCounters) { + ADCD2.state = GetParam(); + tickFast(); + const auto counters = getAdcDiagnostics().fast; + const bool allowed = GetParam() == ADC_READY || GetParam() == ADC_ERROR; + EXPECT_EQ(allowed ? 1U : 0U, counters.started); + EXPECT_EQ(allowed ? 0U : 1U, skipped(counters)); + EXPECT_EQ(GetParam() == ADC_ACTIVE ? 1U : 0U, counters.skippedActive); + EXPECT_EQ(GetParam() == ADC_COMPLETE ? 1U : 0U, counters.skippedComplete); + EXPECT_EQ(GetParam() == ADC_UNINIT || GetParam() == ADC_STOP ? 1U : 0U, counters.skippedNotReady); + EXPECT_EQ(0U, counters.errors); +} + +TEST_F(AdcLifecycle, FastConfigurationSkipReasons) { + adcgrpcfgFast.num_channels = 0; + tickFast(); + adcgrpcfgFast.num_channels = 9; + tickFast(); + auto counters = getAdcDiagnostics().fast; + EXPECT_EQ(1U, counters.skippedNoChannels); + EXPECT_EQ(1U, counters.skippedInvalidChannels); + EXPECT_EQ(2U, skipped(counters)); + EXPECT_EQ(0U, counters.errors); + EXPECT_EQ(0U, counters.started); +} +#endif + +TEST_F(AdcLifecycle, KnockPendingDisabledAndFullBufferCounts) { + engineConfiguration->enableSoftwareKnock = false; + KNOCK_ADC.state = ADC_COMPLETE; + startKnock(); // The first rejection reason wins, preserving the guard order. + EXPECT_EQ(1U, getAdcDiagnostics().knock.skippedDisabled); + EXPECT_EQ(0U, getAdcDiagnostics().knock.skippedComplete); + engineConfiguration->enableSoftwareKnock = true; + KNOCK_ADC.state = ADC_READY; + startKnock(); + _adc_isr_half_code(&KNOCK_ADC); + EXPECT_EQ(0U, getAdcDiagnostics().knock.completed); + _adc_isr_full_code(&KNOCK_ADC); + startKnock(); + auto counters = getAdcDiagnostics().knock; + EXPECT_EQ(1U, counters.started); + EXPECT_EQ(1U, counters.completed); + EXPECT_EQ(1U, counters.skippedPending); + EXPECT_EQ(0U, counters.errors); + EXPECT_EQ(0U, counters.processed); + processLastKnockEvent(); + processLastKnockEvent(); + EXPECT_EQ(1U, getAdcDiagnostics().knock.processed); + startKnock(); + EXPECT_EQ(2U, getAdcDiagnostics().knock.started); +} + +TEST_F(AdcLifecycle, KnockErrorIsObservedAndHalRecovers) { + startKnock(); + _adc_isr_error_code(&KNOCK_ADC, ADC_ERR_DMAFAILURE); + auto counters = getAdcDiagnostics().knock; + EXPECT_EQ(1U, counters.started); + EXPECT_EQ(1U, counters.errors); + EXPECT_EQ(uint32_t{ADC_ERR_DMAFAILURE}, counters.lastError); + EXPECT_EQ(0U, counters.completed); + EXPECT_EQ(0U, counters.processed); + EXPECT_EQ(0, knockSem.signals); + EXPECT_EQ(ADC_READY, KNOCK_ADC.state); + EXPECT_EQ(nullptr, KNOCK_ADC.grpp); + startKnock(); + _adc_isr_error_code(&KNOCK_ADC, ADC_ERR_OVERFLOW); + EXPECT_EQ(2U, getAdcDiagnostics().knock.errors); + EXPECT_EQ(uint32_t{ADC_ERR_OVERFLOW}, getAdcDiagnostics().knock.lastError); + startKnock(); + _adc_isr_full_code(&KNOCK_ADC); + processLastKnockEvent(); + EXPECT_EQ(3U, getAdcDiagnostics().knock.started); + EXPECT_EQ(1U, getAdcDiagnostics().knock.completed); + EXPECT_EQ(1U, getAdcDiagnostics().knock.processed); +} + +TEST_F(AdcLifecycle, FastErrorIsObservedWithoutPublishingSamples) { + tickFast(); +#ifdef ADC_TEST_V4 + auto* driver = &ADCD1; +#else + auto* driver = &ADCD2; +#endif + _adc_isr_error_code(driver, ADC_ERR_DMAFAILURE); + const auto counters = getAdcDiagnostics().fast; + EXPECT_EQ(1U, counters.started); + EXPECT_EQ(1U, counters.errors); + EXPECT_EQ(uint32_t{ADC_ERR_DMAFAILURE}, counters.lastError); + EXPECT_EQ(0U, counters.completed); + EXPECT_EQ(0, fastResults); + EXPECT_EQ(ADC_READY, driver->state); + EXPECT_EQ(nullptr, driver->grpp); +#ifndef ADC_TEST_V4 + tickFast(); + _adc_isr_full_code(driver); + EXPECT_EQ(2U, getAdcDiagnostics().fast.started); + EXPECT_EQ(1U, getAdcDiagnostics().fast.completed); +#else + // Preserve the existing H7 behavior: didStart stays true after an error. + // Diagnostics report the stopped stream; they must not silently restart it. + tickFast(); + EXPECT_EQ(1U, getAdcDiagnostics().fast.started); + EXPECT_EQ(ADC_READY, driver->state); +#endif +} + +#ifdef ADC_TEST_V4 +TEST_F(AdcLifecycle, CircularFastCountsBuffersNotStreamStarts) { + tickFast(); + for (int i = 0; i < 3; i++) { + _adc_isr_half_code(&ADCD1); + EXPECT_EQ(static_cast(i), getAdcDiagnostics().fast.completed); + _adc_isr_full_code(&ADCD1); + EXPECT_EQ(ADC_ACTIVE, ADCD1.state); + tickFast(); + } + EXPECT_EQ(1U, getAdcDiagnostics().fast.started); + EXPECT_EQ(3U, getAdcDiagnostics().fast.completed); + EXPECT_EQ(3, fastResults); + EXPECT_EQ(0, stops); +} +#endif + +TEST_F(AdcLifecycle, ConsoleUsesOneSnapshotOutsideTheLock) { + startKnock(); + _adc_isr_full_code(&KNOCK_ADC); + // Simulate new data arriving after the snapshot, during slow console output. + afterConsolePrint = [] { knockAdcDiagnostics.completed = 100; }; + ASSERT_NE(nullptr, adcStatsCommand); + adcStatsCommand(); + ASSERT_EQ(7U, consoleLines.size()); + EXPECT_NE(std::string::npos, consoleLines[0].find("knock_compiled=1")); +#ifdef ADC_TEST_V4 + EXPECT_NE(std::string::npos, consoleLines[0].find("started_unit=stream")); +#else + EXPECT_NE(std::string::npos, consoleLines[0].find("started_unit=conversion")); +#endif + EXPECT_EQ("adc knock started=1 completed=1 errors=0 last_error=0 processed=0", consoleLines[4]); + EXPECT_EQ(100U, getAdcDiagnostics().knock.completed); + EXPECT_EQ(0, lockDepth); +} + +TEST_F(AdcLifecycle, CountersWrapAndConsoleFitsMaximumValues) { + knockAdcDiagnostics.started = UINT32_MAX; + startKnock(); + EXPECT_EQ(0U, getAdcDiagnostics().knock.started); + knockAdcDiagnostics.completed = UINT32_MAX; + _adc_isr_full_code(&KNOCK_ADC); + EXPECT_EQ(0U, getAdcDiagnostics().knock.completed); + AdcDiagnostics maximum{ + UINT32_MAX, + UINT32_MAX, + UINT32_MAX, + UINT32_MAX, + UINT32_MAX, + UINT32_MAX, + UINT32_MAX, + UINT32_MAX, + UINT32_MAX, + UINT32_MAX, + UINT32_MAX, + UINT32_MAX}; + fastAdcDiagnostics = knockAdcDiagnostics = maximum; + adcStatsCommand(); // The mock checks formatting fits the actual 256-byte line buffer. + EXPECT_EQ(7U, consoleLines.size()); +} From fbbc52ddf5a4576824c570162498c62fb332803e Mon Sep 17 00:00:00 2001 From: gdiciocco Date: Sat, 26 Sep 2026 23:28:24 +0200 Subject: [PATCH 2/3] Run ADC lifecycle suites through the common test target Build all three host test binaries by default and run them through make test from the existing CI Run Tests step. Keep the ADC-only target available and update the local test instructions. Validation: clean coverage build; 720 engine, 36 ADCv2 and 21 ADCv4 tests pass. --- .github/workflows/build-unit-tests.yaml | 8 ++------ CLAUDE.md | 4 ++-- unit_tests/Makefile | 8 ++++++++ unit_tests/adc_lifecycle/README.md | 10 +++++++--- 4 files changed, 19 insertions(+), 11 deletions(-) diff --git a/.github/workflows/build-unit-tests.yaml b/.github/workflows/build-unit-tests.yaml index 34e038c076..d842eacbb9 100644 --- a/.github/workflows/build-unit-tests.yaml +++ b/.github/workflows/build-unit-tests.yaml @@ -40,14 +40,10 @@ jobs: working-directory: ./unit_tests/ run: make -j4 COVERAGE=yes - - name: Run ADC lifecycle tests - working-directory: ./unit_tests/ - run: make -j4 adc-lifecycle-test - - name: Run Tests working-directory: ./unit_tests/ - #run: ASAN_OPTIONS=detect_stack_use_after_return=1 build/fome_test - run: build/fome_test + #run: ASAN_OPTIONS=detect_stack_use_after_return=1 make -j4 test COVERAGE=yes + run: make -j4 test COVERAGE=yes - name: Set FTP variables env: diff --git a/CLAUDE.md b/CLAUDE.md index 944a7f0796..69b660cf68 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,13 +53,13 @@ Outputs are placed in `firmware/deliver/`: ```bash cd unit_tests -make -j12 -./build/fome_test +make -j12 test # Run a specific test ./build/fome_test --gtest_filter=TestName ``` +The `test` target builds and runs the engine suite and both ADC lifecycle suites. Unit tests use Google Test and run on amd64/aarch64, not on the ECU. ### Code Generation diff --git a/unit_tests/Makefile b/unit_tests/Makefile index 0a530586ee..2f668f9103 100644 --- a/unit_tests/Makefile +++ b/unit_tests/Makefile @@ -70,3 +70,11 @@ INCDIR += \ include $(UNIT_TESTS_DIR)/unit_test_rules.mk include $(UNIT_TESTS_DIR)/adc_lifecycle/adc_lifecycle.mk + +all: $(ADC_LIFECYCLE_BINS) + +.PHONY: test +test: all + ./$(BINARY_OUTPUT) + ./build/adc_lifecycle_test + ./build/adc_lifecycle_v4_test diff --git a/unit_tests/adc_lifecycle/README.md b/unit_tests/adc_lifecycle/README.md index 19757f75da..39560f6f09 100644 --- a/unit_tests/adc_lifecycle/README.md +++ b/unit_tests/adc_lifecycle/README.md @@ -1,8 +1,12 @@ # ADC lifecycle regression and diagnostics -Run from `unit_tests`: `make -j12 adc-lifecycle-test`. -The unit-test CI workflow runs this target on Linux and macOS. The target builds -separate ADCv2 (F4/F7) and ADCv4 (H7) host binaries with ASan/UBSan by default. +Run all engine and ADC lifecycle tests from `unit_tests`: `make -j12 test`. +The default build includes separate ADCv2 (F4/F7) and ADCv4 (H7) host binaries +with ASan/UBSan by default. The unit-test CI workflow builds all three binaries +in `Build Tests` and runs them through the common `test` target in `Run Tests` +on Linux and macOS. + +To build and run only the ADC suites: `make -j12 adc-lifecycle-test`. ## Real callers and HAL From 5a83b5f326abddf46455e320d0026e141b3e13ff Mon Sep 17 00:00:00 2001 From: gdiciocco Date: Sat, 26 Sep 2026 23:39:32 +0200 Subject: [PATCH 3/3] Keep STM32 SRAM placement out of ADC host tests Apply the H7 .ram4 section attribute only in production builds and mark the host fixture explicitly as non-production. Keep the 8192-byte buffer alignment on both targets. This fixes the ADCv4 build on macOS, where Mach-O requires segment,section syntax. --- firmware/hw_layer/ports/stm32/stm32_adc_v4.cpp | 5 ++++- unit_tests/adc_lifecycle/mocks/pch.h | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/firmware/hw_layer/ports/stm32/stm32_adc_v4.cpp b/firmware/hw_layer/ports/stm32/stm32_adc_v4.cpp index 10e349e6ef..d2dc8c166e 100644 --- a/firmware/hw_layer/ports/stm32/stm32_adc_v4.cpp +++ b/firmware/hw_layer/ports/stm32/stm32_adc_v4.cpp @@ -49,7 +49,10 @@ static constexpr int H7_ADC_SHIFT_BITS = log2_int(H7_ADC_OVERSAMPLE); // ADC3 is in the AHB4 domain, which is only accessible by the BDMA controller // BDMA can only access AHB4, which means we have to put the buffers in SRAM4 -__attribute__((section(".ram4"))) __attribute__((aligned(8192))) adcsample_t knockSampleBuffer[2048]; +#if EFI_PROD_CODE +__attribute__((section(".ram4"))) +#endif +__attribute__((aligned(8192))) adcsample_t knockSampleBuffer[2048]; void portInitAdc() { initAdcDiagnostics(true); diff --git a/unit_tests/adc_lifecycle/mocks/pch.h b/unit_tests/adc_lifecycle/mocks/pch.h index 5e0c08f5e0..0d20bb6200 100644 --- a/unit_tests/adc_lifecycle/mocks/pch.h +++ b/unit_tests/adc_lifecycle/mocks/pch.h @@ -10,6 +10,8 @@ #include #include +#define EFI_PROD_CODE 0 + #ifdef ADC_TEST_V4 #define EFI_USE_FAST_ADC 0 #else