1. Firmware Bootloader, OTP Security, HAL, Fault/Health Supervision & Factory Toolchain
Repository:
Converters (planovi-converter)• Rule Prefix:BR-BOOT• Documented Rules: 9 • Open[TEAM_WHY_NEEDED]Questions: 4
1. Business Purpose & Actors
Guarantees that every RP2350 Planovi Edge Converter boots only cryptographically signed Planovi firmware, binds each physical unit to an immutable hardware identity (serial number, AES-256 master key, ECDSA P-256 OTA public key, mTLS client certificate/key, and unique setup password stored in RP2350 OTP), automatically recovers from faulty firmware updates or stalled FreeRTOS tasks via one-shot A/B rollback and hardware watchdog supervision, and survives sudden AC power loss with Last-Gasp alerting.
- Actors: Manufacturing/Factory Operator (
tools/provision_device.py,tools/provision_otp.py,tools/make_factory_uf2.py), Field Service Technician (tools/service_update_usb.py, physical reset button onGPIO 22), RP2350 Bootloader & FreeRTOS Health Supervisor (autonomous), Build/Release Pipeline (build.sh,tools/build_firmware_docker.sh,tools/sign_firmware.py).
2. All Features & End-to-End Flows
- Factory Provisioning & UF2 Release Pipeline:
- Trigger: Operator runs
tools/provision_device.pyor manualtools/generate_keys.py+tools/provision_otp.py+build.sh(planovi_release). - Validation:
sign_firmware.pyvalidates payload bounds (8..0x1DFF00B), RP2350 SRAM MSP alignment, Thumb reset vector bounds, prepends 256 Bfirmware_image_header_twith SHA-256 + ECDSA P-256 signature + CRC-32, and emits JSON manifest.make_factory_uf2.pypacks Bootloader (64 KiB) + Slot A (1,920 KiB) +0xFF-erased Slot B (1,920 KiB) +0xFF-erased NVS (192 KiB) into a single 4 MiB RP2350 UF2 (family_id = 0xE48BFF59).provision_otp.pyvalidates X.509 leaf/CA chain, EKUCLIENT_AUTH, P-256 private key match, password complexity, and PEM length limits before interactive"PROVISION"confirmation. - State Change:
picotool otp set -eburns OTP rows0x0082..0x0487, applies--permissions-file(unless--allow-unlocked-otp), then burnsOTP_ROW_MAGIC(0x0500..0x0501) last so a failed lock leaves the chip unprovisioned. - Failure: Any readback verification mismatch or invalid cert aborts exit code non-zero before magic burn.
- Trigger: Operator runs
- Signed A/B Boot & One-Shot Trial Failover (
src/bootloader/bootloader_main.c,bootloader.c,boot_state.c):- Trigger: Power-on, watchdog, or software reset enters bootloader at
0x10000000. - Validation:
bootloader_init()initializes OTP;bootloader_select_slot()runsbootloader_verify_slot()on Slot A (0x10010000) and Slot B (0x101F0000): checks magic (ASLF/PLNV), header CRC-32,header_version == 2, allowed flags (IMAGE_FLAG_ENCRYPTEDforbidden),board_id == "PICO2W-RP2350", vector table MSP & Thumb entry point, payload SHA-256, and ECDSA P-256 signature against OTP OTA pubkey. - State Change: If
boot_state.phase == BOOT_STATE_TRIAL_PENDINGand target slot is valid, carriesIMAGE_FLAG_TEST_BOOT, and satisfiesversion >= confirmed_version, bootloader persistsBOOT_STATE_TRIAL_ATTEMPTEDto alternating 4 KiB NVS sector before jumping viabootloader_jump_to_app(). Otherwise selectsconfirmed_slot(or highest non-trial version if uninitialized; Slot A wins ties). - Failure: If no valid bootable slot exists (or jump vectors fail), bootloader calls
reset_usb_boot(0, 0)to enter RP2350 ROM BOOTSEL mode for USB recovery.
- Trigger: Power-on, watchdog, or software reset enters bootloader at
- Trial Confirmation & Automatic Rollback (
src/main.c:72-90, 409-421,src/net/ota_update.c):- Trigger: Running app checks
boot_state_is_trial_active(PLANOVI_RUNNING_SLOT)on boot and evaluatesota_trial_health_ready()every 100 ms inNetSysTask. - Validation: Requires all 6 conditions:
system_health_is_ready(),cloud_client_is_connected(),sd_journal_get_state() == SD_JOURNAL_STATE_READY,time_sync_has_trusted_server_time(),telemetry.is_running, and (!telemetry_enabled || meter_count == 0 || telemetry.total_cycles > 0). - State Change: On pass ->
ota_confirm_successful_boot()writes{slot=NONE, phase=BOOT_STATE_IDLE, confirmed_slot=PLANOVI_RUNNING_SLOT, confirmed_version=running_version()}. On 60,000 ms timeout -> recordsPLANOVI_FAULT_OTA_TRIAL_TIMEOUTand reboots (watchdog_mgr_reboot(false)); on reboot, bootloader seesBOOT_STATE_TRIAL_ATTEMPTEDand boots previousconfirmed_slot.
- Trigger: Running app checks
- Offline USB A/B Service Update (
tools/service_update_usb.py):- Trigger: Technician runs CLI against USB-connected converter (dry-run by default;
--executeflashes). - Validation: Verifies manifest,
flags == IMAGE_FLAG_VALID | IMAGE_FLAG_TEST_BOOT, payload SHA-256, header CRC-32, vector table, both ECDSA signatures,target_slot != current_slot, strict monotonic upgradenew_version > current_version, and no existingTRIAL_PENDINGin boot-state Flash (0x103D0000..0x103D2000). - State Change: Writes inactive slot via
picotool load, writesBOOT_STATE_TRIAL_PENDINGto alternating boot-state sector, reboots, and optionally checks confirmation after--wait-seconds.
- Trigger: Technician runs CLI against USB-connected converter (dry-run by default;
- FreeRTOS Health Supervisor & Hardware Watchdog (
src/app/system_health.c,src/hal/watchdog.c):- Trigger:
Healthtask wakes every500 ms(HEALTH_CHECK_PERIOD_MS). - Validation: Checks every bit in
required_components(SYSTEM_HEALTH_NET,SYSTEM_HEALTH_TELEMETRY,SYSTEM_HEALTH_STORAGE) pulsed within<= 10,000 ms(HEALTH_STALE_TIMEOUT_MS). - State Change: All fresh -> clears pending health fault and calls
watchdog_mgr_feed()(HW timeout15,000 ms). Any stale -> stops feeding HW watchdog and recordsPLANOVI_FAULT_HEALTH_TIMEOUTwithstale_mask | (net_context << 8)in watchdog scratch registers -> HW reset after ~15 s.
- Trigger:
- Physical Button & Last-Gasp Power Loss (
src/hal/button.c,src/hal/power_mgr.c,src/main.c):- Button: Debounced
50 msonGPIO 22(active low, pull-up). At boot with unprovisioned SD: holding>= 20 sauthorizessd_fs_format()(button_suppress_until_release()prevents re-trigger). At runtime on release:>= 20 s-> factory reset (sd_journal_force_reprovision()if not ready +config_store_factory_reset()+ reboot);10..19.999 s-> Wi-Fi AP reset toPlanovi-<serial>+ reboot;< 3 s->SHORT_CLICK(ignored);3..9.999 s-> dead zone (no event). - Last Gasp: Falling edge IRQ on
GPIO 26(GPIO_POWER_AC_DETECT) setsPOWER_AC_LOSTand notifiesTelemetryTaskviavTaskNotifyGiveFromISR()to immediately persistPOWER_LOSS_LAST_GASP(code_num=6001).
- Button: Debounced
3. Hard Business Rules, Validations, Calculations & Edge Cases
BR-BOOT-01(4 MiB Contiguous Flash Layout):src/bootloader/flash_layout.h:13-51enforces compile-time#ifchecks acrossPLANOVI_FLASH_SIZE = 0x00400000(4 MiB): Bootloader0x000000..0x00FFFF(64 KiB), Slot A0x010000..0x1EFFFF(1,920 KiB = 256 B header +0x1DFF00payload), Slot B0x1F0000..0x3CFFFF(1,920 KiB), NVS0x3D0000..0x3FFFFF(192 KiB: Boot State A/B0x3D0000..0x3D1FFF[8 KiB], 168 KiB unused gap, Encrypted Config A/B0x3FC000..0x3FFFFF[16 KiB]).BR-BOOT-02(Strict Image Verification Order):bootloader_verify_slot()(src/bootloader/bootloader.c:145-192) rejects any slot failing (1) exact slot address match, (2) magic0x41534C46(ASLF) or0x504C4E56(PLNV), (3) IEEE CRC-32 over header bytes0..251, (4)header_version == 2,IMAGE_FLAG_VALIDset,IMAGE_FLAG_ENCRYPTEDabsent,board_id == "PICO2W-RP2350",8 <= image_size <= 0x1DFF00, 8-byte aligned MSP in[0x20000000, 0x20082000], Thumbentry_point == vectors[1]inside payload bounds, (5) payload SHA-256, or (6) ECDSA P-256 signature over SHA-256 of canonical header (bytes0..251withr,s,crc32zeroed) using OTP OTA pubkey.BR-BOOT-03(One-Shot Trial & Monotonic Anti-Rollback):bootloader_select_slot()(src/bootloader/bootloader.c:209-272) allows aIMAGE_FLAG_TEST_BOOTimage to boot only once whenboot_state.phase == BOOT_STATE_TRIAL_PENDINGandpacked_version >= confirmed_version((major<<24)|(minor<<16)|(patch<<8)|build). Bootloader writesBOOT_STATE_TRIAL_ATTEMPTEDbefore jumping; any crash, watchdog reset, or 60 s confirmation timeout (src/main.c:413) guarantees rollback toconfirmed_slot. Trial images are strictly excluded from fresh/fallback boot selection.BR-BOOT-04(Mandatory OTP Provisioning & ECC Validation):otp_keys_init()(src/security/otp_keys.c:130-198) reads RP2350 OTP viarom_func_otp_access()withOTP_CMD_ECC_BITSand fails startup if any of the 7 regions fail validation:OTP_ROW_MAGIC(0x0500,ASLD/PLNV), serial (0x0082, 1..31 chars[A-Za-z0-9._:@-]+), non-all-0x00/non-all-0xFF32 B AES key (0x0092) and 64 B P-256 OTA pubkey (0x00A2), PEM markers on client cert (0x00C2,<1500B) and key (0x03B0,<400B), and setup password (0x0478, 12..31 printable non-space ASCII with upper+lower+digit+special). Production builds have zero mock fallback.BR-BOOT-05(Heap-Safe mbedTLS Allocator & HW SHA-256 Lock):planovi_mbedtls_calloc()(src/security/mbedtls_platform_freertos.c) denies allocation (NULL) ifxPortGetFreeHeapSize() < bytes + 4096u(MBEDTLS_HEAP_RESERVE_BYTES), preventingvApplicationMallocFailedHook()system reboots during TLS spikes. Weakpico_sha256_lock()/unlock()are overridden with a FreeRTOS priority-inheritance mutex (g_sha256_mutex).BR-BOOT-06(Hardware Watchdog Bounds & Supervision):watchdog_mgr_init()caps hardware timeout atWATCHDOG_RP2350_SAFE_MAX_TIMEOUT_MS = 16000u(src/hal/watchdog.c);system_health.csets HW timeout15000 ms, stale threshold10000 ms, check cadence500 ms, supervisingNetSysTask(SYSTEM_HEALTH_NET) plusTelemetryTaskandSdWriterwhen storage is ready (SYSTEM_HEALTH_TELEMETRY,SYSTEM_HEALTH_STORAGE).BR-BOOT-07(Runtime Network OTA Disabled in v1): Whilesrc/net/ota_update.ccompiles streaming Flash-write/readback/ECDSA verification logic, onlyota_init()andota_confirm_successful_boot()are wired insrc/main.c. All v1 field updates use offline USBtools/service_update_usb.pyrequiring strictnew_version > current_version.BR-BOOT-08(Single-Core Flash Exclusion & UART0 Reservation):CMakeLists.txt:439,460-461setsPICO_FLASH_ASSUME_CORE1_SAFE=1(configNUMBER_OF_CORES = 1), disables UART stdio (pico_enable_stdio_uart(..., 0)), and enables USB CDC stdio (pico_enable_stdio_usb(..., 1)) soUART0(GP0/GP1) never emits console text onto the RS-485 bus.BR-BOOT-09(VSYS ADC Voltage Formula):power_mgr_read_vsys_voltage()(src/hal/power_mgr.c) acquirescyw43_thread_enter()(sharedPICO_VSYS_PINGP29), discards 3 samples, averages 3 samples, and computesadc_avg * (3.3f / 4096.0f) * 3.0f.
4. State Machines & Data Lifecycle
stateDiagram-v2
[*] --> BOOT_STATE_IDLE: Factory UF2 / Confirmed boot
BOOT_STATE_IDLE --> BOOT_STATE_TRIAL_PENDING: service_update_usb.py writes inactive slot + trial request
BOOT_STATE_TRIAL_PENDING --> BOOT_STATE_TRIAL_ATTEMPTED: Bootloader verifies ECDSA+SHA256+anti-rollback & marks attempted before jump
BOOT_STATE_TRIAL_ATTEMPTED --> BOOT_STATE_IDLE: App passes 6-point ota_trial_health_ready() within 60s -> confirmed_slot updated
BOOT_STATE_TRIAL_ATTEMPTED --> ROLLBACK_CONFIRMED: Crash / Watchdog reset / 60s timeout -> next boot skips trial & boots confirmed_slot
ROLLBACK_CONFIRMED --> BOOT_STATE_IDLE: Confirmed slot continues normal operation
BOOT_STATE_IDLE --> ROM_BOOTSEL: Neither Slot A nor Slot B passes verification
- OTA Engine States (
ota_state_t,src/net/ota_update.h):IDLE->DOWNLOADING->VERIFYING->READY_TO_APPLY->APPLYING(orERROR). Currently unwired at runtime. - Fault Diagnostic Codes (
planovi_fault_reason_t,src/app/fault_diagnostics.h):NONE (0),HARDFAULT (1),STACK_OVERFLOW (2),MALLOC_FAILED (3),HEALTH_TIMEOUT (4),OTA_TRIAL_TIMEOUT (5)persisted inwatchdog_hw->scratch[0..7]with magic0xA51A0000u.
5. Technical Contract (Inputs -> Processing -> Side Effects)
- Inputs: RP2350 OTP ECC rows (
0x0082..0x0501), Flash XIP slots (0x10010000,0x101F0000), NVS boot state (0x103D0000..0x103D1FFF),GPIO 22button,GPIO 26AC detect IRQ,GP29VSYS ADC, USBpicotoolcommands. - Processing: ECDSA P-256 + SHA-256 verification, ping-pong Flash sector writes via
flash_safe_execute(), FreeRTOS 1000 Hz preemptive scheduler (160 KiBheap_4, 11 tasks including transientRebootand SDK/RTOS tasks), HardFault/malloc/stack-overflow capture into watchdog scratch registers. - Side Effects: Direct XIP jump (
VTOR/MSPhandoff), Flash erase/program on boot state and NVS, hardware watchdog reboot, ROM BOOTSEL entry, USB CDC diagnostic logs, and Cloud API calls during manufacturing (GET /converters-next-serial,POST /converters/prepare-usb-provisioning,GET /converters/firmware/info,GET /converters/firmware/latest-uf2,POST /converters/{serial}/confirm-flash).
6. Cross-Repository Dependencies
tools/provision_device.py->cloud/api/converters.py| HTTPS (unauthenticated!) |GET /api/v1/converters-next-serial,POST /api/v1/converters/prepare-usb-provisioning,GET /api/v1/converters/firmware/info,GET /api/v1/converters/firmware/latest-uf2,POST /api/v1/converters/{serial}/confirm-flash.CMakeLists.txt-> Pico SDK (2.3.0) & FreeRTOS-Kernel (11.1+) | Build-time external SDK paths (PICO_SDK_PATH,FREERTOS_KERNEL_PATH).
7. Why It Works This Way (Decisions, Trade-offs & Workarounds)
- Ping-Pong 4 KiB Boot State Sectors (
boot_state.c): Alternates0x3D0000/0x3D1000with monotonicgenerationand CRC-32 so power loss mid-erase never destroys the prior valid state. - Pico SDK 2.3.0 PSA RNG Workaround (
CMakeLists.txt:129-150): Manually appends${PICO_MBEDTLS_PATH}/library/psa_crypto_random.cbecause Pico SDK 2.3.0 enables PSA core for TLS 1.3 while omitting that translation unit. CYW43_TASK_STACK_SIZE=2048words (8 KiB) (CMakeLists.txt:434): Doubled from Pico SDK default 4 KiB to prevent stack overflows during post-login HTTP bursts.- Confirmed Bug (
src/main.c:414-417vssrc/hal/watchdog.c:88): On OTA trial timeout,main.cwritesPLANOVI_FAULT_OTA_TRIAL_TIMEOUTintowatchdog_hw->scratch[0], then immediately callswatchdog_mgr_reboot(false)which overwritesscratch[0] = RESET_REASON_SOFTWARE, erasing the fault diagnostic before reboot. [TEAM_WHY_NEEDED: tools/provision_device.py:263 unconditionally passes --allow-unlocked-otp to provision_otp.py (marked LAB ONLY) and never supplies --permissions-file. Is OTP locking deferred for current production batches, or is this a security bug?][TEAM_WHY_NEEDED: tools/provision_otp.py:32-33 still burns OTP_MAGIC_VALUE = 0x41534C44 ("ASLD", rev 1) instead of OTP_MAGIC_PLANOVI = 0x504C4E56 ("PLNV"), and sign_firmware.py still emits 0x41534C46 ("ASLF"). When should new series switch to PLNV?][TEAM_WHY_NEEDED: tools/build_firmware_docker.sh:21-61 silently generates temporary self-signed CA and ephemeral signing keys in /tmp/ if production PEM files are missing, and tools/provision_device.py:28 defaults PLANOVI_API_URL to https://dev-cloud.planovi.app/api/v1. Should release builds fail closed instead?][TEAM_WHY_NEEDED: src/bootloader/flash_layout.h leaves a 168 KiB unused gap inside the 192 KiB NVS partition (0x003D2000..0x003FBFFF), and src/hal/button.c silently drops button holds between 3.0s and 9.999s. Are both intentional (future NVS expansion & accidental-press guard band)?]
8. Debugging, Logs & Common Failure Modes
| Symptom / Error Message | Root Cause in Code | How to Verify / Exact Command | Fix |
|---|---|---|---|
Device drops directly into RP2350 USB RPI-RP2 BOOTSEL on power-up | bootloader_select_slot() returned false (unsigned/corrupt image, wrong board_id, unprovisioned OTP, or signature mismatch) (bootloader_main.c:17) | Inspect image with python3 tools/service_update_usb.py --package <bin> --manifest <json> --public-key tools/ota-public-key.pem and check OTP magic picotool otp get -e 0x0500 | Provision OTP (provision_otp.py) and flash signed planovi_full_factory.uf2 |
Rapid reboot loop every ~15 s; USB CDC prints PLANOVI_FAULT_HEALTH_TIMEOUT with status=0x0N0M | Supervised task (bit 0=NET, 1=TELEMETRY, 2=STORAGE) failed to pulse within 10 s (system_health.c); bits [15:8] give net_context (0=LOOP..9=STORAGE_TRANSFER) | Capture USB CDC boot log via python3 tools/capture_serial.py | Diagnose hung subsystem indicated by stale_mask and net_context |
| USB update rolls back to previous slot after ~60 s | Trial slot failed 1 of 6 ota_trial_health_ready() checks (e.g., no mTLS cloud connect, SD not ready, or no trusted UTC time) (main.c:72-90, 413) | Read 8 KiB boot state (picotool save -r 0x103D0000 0x103D2000) and inspect USB serial logs during the 60 s window | Ensure Wi-Fi/mTLS/SD/time are healthy before upgrading, or fix regression in trial build |
HardFault / StackOverflow / MallocFailed reboot | Task stack exhaustion (configCHECK_FOR_STACK_OVERFLOW=2) or 160 KiB FreeRTOS heap exhaustion (freertos_hooks.c, fault_diagnostics.c) | Connect USB CDC (tools/capture_serial.py) to read retained PC/LR/PSP/PSPLIM/task name from watchdog_hw->scratch[0..7] | Increase offending task stack or reduce dynamic allocations; resolve PC via arm-none-eabi-addr2line on .elf |