From dfe30695b16a0e55c9335bfdbb96459feee915da Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Wed, 18 Nov 2026 12:16:32 -0500 Subject: [PATCH 01/21] initial commit --- .github/workflows/test-configs.yml | 6 + arch.mk | 4 + config/examples/mcxe31b.config | 55 + docs/Targets.md | 110 ++ hal/mcxe31b.c | 586 +++++++++ hal/mcxe31b.h | 288 +++++ hal/mcxe31b.ld | 80 ++ test-app/ARM-mcxe31b.ld | 70 ++ test-app/Makefile | 9 + test-app/app_mcxe31b.c | 1046 +++++++++++++++++ test-app/startup_arm.c | 9 + tools/scripts/mcxe31b/e31b_debug.cmm | 101 ++ .../mcxe31b/e31b_flash_factory_bin.cmm | 106 ++ tools/scripts/mcxe31b/e31b_flash_update.cmm | 92 ++ 14 files changed, 2562 insertions(+) create mode 100644 config/examples/mcxe31b.config create mode 100644 hal/mcxe31b.c create mode 100644 hal/mcxe31b.h create mode 100644 hal/mcxe31b.ld create mode 100644 test-app/ARM-mcxe31b.ld create mode 100644 test-app/app_mcxe31b.c create mode 100644 tools/scripts/mcxe31b/e31b_debug.cmm create mode 100644 tools/scripts/mcxe31b/e31b_flash_factory_bin.cmm create mode 100644 tools/scripts/mcxe31b/e31b_flash_update.cmm diff --git a/.github/workflows/test-configs.yml b/.github/workflows/test-configs.yml index 8373c4e2b0..070b8cd2dc 100644 --- a/.github/workflows/test-configs.yml +++ b/.github/workflows/test-configs.yml @@ -644,6 +644,12 @@ jobs: arch: arm config-file: ./config/examples/mcxe247.config + nxp_mcxe31b_test: + uses: ./.github/workflows/test-build.yml + with: + arch: arm + config-file: ./config/examples/mcxe31b.config + max32666_test: uses: ./.github/workflows/test-build.yml with: diff --git a/arch.mk b/arch.mk index 3f988e7add..63d823d531 100644 --- a/arch.mk +++ b/arch.mk @@ -616,6 +616,10 @@ ifeq ($(ARCH),ARM) ifeq ($(TARGET),imx95_m7) CORTEX_M7=1 endif + ifeq ($(TARGET),mcxe31b) + CORTEX_M7=1 + ARCH_FLASH_OFFSET=0x00400000 + endif ifeq ($(TARGET),stm32l0) CORTEX_M0=1 SPI_TARGET=stm32 diff --git a/config/examples/mcxe31b.config b/config/examples/mcxe31b.config new file mode 100644 index 0000000000..e5e80d9221 --- /dev/null +++ b/config/examples/mcxe31b.config @@ -0,0 +1,55 @@ +# wolfBoot configuration for NXP MCX E31B (FRDM-MCXE31B) +# +# MCXE31B: Cortex-M7, 4 MB code flash (four 1 MB blocks) + 128 KB data flash, +# 8 KB sectors. wolfBoot switches the core from FIRC 48 MHz to the PLL +# (160 MHz) and enables the caches. It runs from flash, with data, bss and the +# RAM_CODE flash routines in the 64 KB CM7_0 DTCM. +# +# Build: cp config/examples/mcxe31b.config .config && make + +ARCH?=ARM +TARGET?=mcxe31b +SIGN?=ECC256 +HASH?=SHA256 +VTOR?=1 +NO_ASM?=0 +NO_MPU=1 +EXT_FLASH?=0 +SPI_FLASH?=0 +ALLOW_DOWNGRADE?=0 + +# Each 64-bit ECC segment of the flash can be programmed only once between +# erases +NVM_FLASH_WRITEONCE?=1 + +WOLFBOOT_VERSION?=0 +V?=0 +SPMATH?=1 +RAM_CODE?=1 +DUALBANK_SWAP?=0 + +# The CM7 DTCM is ECC protected and must be written before it is read +CFLAGS_EXTRA+=-DWOLFBOOT_RAM_ECC_INIT + +# 8KB sectors +WOLFBOOT_SECTOR_SIZE?=0x2000 + +# Memory layout (code flash 0x00400000 - 0x007FFFFF): +# IVT + Bootloader: 0x00400000 - 0x0040FFFF (64 KB) +# Boot Partition: 0x00410000 - 0x005EFFFF (1920 KB) +# Update Partition: 0x005F0000 - 0x007CFFFF (1920 KB) +# Swap Sector: 0x007D0000 - 0x007D1FFF (8 KB) +# 0x007D4000 - 0x007FFFFF is left free: it holds the Secure BAF and, when the +# security firmware feature flag is set, the security firmware. +WOLFBOOT_PARTITION_SIZE?=0x1E0000 +WOLFBOOT_PARTITION_BOOT_ADDRESS?=0x410000 +WOLFBOOT_PARTITION_UPDATE_ADDRESS?=0x5F0000 +WOLFBOOT_PARTITION_SWAP_ADDRESS?=0x7D0000 + +# Console on the MCU-Link VCOM port: LPUART5, PTE14 (TX) and PTE3 (RX), +# 115200 8N1 + +# Debugging options +DEBUG?=0 +DEBUG_SYMBOLS?=0 +DEBUG_UART?=1 diff --git a/docs/Targets.md b/docs/Targets.md index 761efa2b67..421296a6c5 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -48,6 +48,7 @@ This README describes configuration of supported targets. * [NXP RW612](#nxp-rw612) * [NXP S32K1XX](#nxp-s32k1xx) * [NXP MCXE247](#nxp-mcxe247) +* [NXP MCXE31B](#nxp-mcxe31b) * [NXP P1021 PPC](#nxp-qoriq-p1021-ppc) * [NXP T10xx PPC (T1024 / T1040)](#nxp-qoriq-t10xx-ppc-t1024--t1040) * [NXP T2080 PPC](#nxp-qoriq-t2080-ppc) @@ -8067,6 +8068,115 @@ Detach with `SYStem.Down` before testing an update, which relies on a software reset. +## NXP MCXE31B + +The NXP MCX E31B is a Cortex-M7 microcontroller with 4 MB of code flash (four +1 MB blocks), 128 KB of data flash and 512 KB of SRAM. It has its own +bare-metal `mcxe31b` HAL. No SDK is needed. The port targets the FRDM-MCXE31B +board. + +- The boot ROM (Secure BAF) starts wolfBoot through the Image Vector Table + (IVT) that the HAL places at `0x00400000`. +- Flash (C40ASF): 8 KB sectors. Each 64-bit ECC segment can be programmed once + between erases, and a program operation writes up to 128 bytes. +- wolfBoot and the test application use the 64 KB CM7_0 DTCM for data, stack + and the `RAM_CODE` flash routines. The DTCM is ECC protected; the reset + handler clears it before use (`WOLFBOOT_RAM_ECC_INIT`, set by `arch.mk`). +- `hal_init()` switches from the boot ROM's FIRC 48 MHz to the PLL (16 MHz + crystal, reference manual clock "Option A"): core 160 MHz, AIPS_PLAT 80 MHz, + AIPS_SLOW 40 MHz. It first enables the last mile regulator, which the + FRDM-MCXE31B feeds through the Q1 ballast on VRC_CTRL. If a step fails, + wolfBoot stays on FIRC and prints a warning. +- The I-cache and D-cache are on while wolfBoot runs; flash program and erase + invalidate the D-cache over the modified range. Both caches are cleaned and + turned off before the jump to the application. The clocks stay at 160 MHz. + +### NXP MCXE31B: Memory Layout + +| Region | Address Range | Size | +|--------|---------------|------| +| IVT + Bootloader | 0x00400000 - 0x0040FFFF | 64 KB | +| Boot Partition | 0x00410000 - 0x005EFFFF | 1920 KB | +| Update Partition | 0x005F0000 - 0x007CFFFF | 1920 KB | +| Swap Sector | 0x007D0000 - 0x007D1FFF | 8 KB | + +`0x007D4000 - 0x007FFFFF` is not used: the Secure BAF occupies the last 48 KB, +and the security firmware uses the 128 KB below it when its feature flag is +set. The boot ROM uses the lowest valid IVT, so the IVT of wolfBoot at +`0x00400000` always wins. + +### NXP MCXE31B: Building + +```sh +cp config/examples/mcxe31b.config .config +make +``` + +`factory.bin` (wolfBoot plus the signed version 1 test application) must be +programmed at `0x00400000`. + +The console is on the MCU-Link VCOM port (LPUART5, PTE14 TX, PTE3 RX, 115200 +8N1). The test application shows green on the RGB LED for version 1 and blue +for later versions, and has the same console as the +[S32K1xx test application](#nxp-s32k1xx-test-application). + +### NXP MCXE31B: Configuration Options + +| Option | Description | +|--------|-------------| +| `NVM_FLASH_WRITEONCE` | **Required.** A 64-bit ECC segment can be programmed once between erases, so trailer updates erase and rewrite the sector. | +| `RAM_CODE` | **Required.** The flash program and erase routines run from DTCM, so the block being written is not read. The linker script checks this. | +| `DEBUG_UART` | Console output on LPUART5 (MCU-Link VCOM). | + +### NXP MCXE31B: Programming with Lauterbach TRACE32 + +Connect the 10-pin debug cable to J14 and short JP5 to disable the onboard +MCU-Link SWD. TRACE32 R2024.09 has no MCXE31B entry. The S32K314 has the same +debug architecture (AHB-AP 4 = CM7_0, MDM-AP 6, SDA-AP 7) and flash +controller, so use `SYStem.CPU S32K314-M7` with SWD (JTAG on J14 does not +work). Program `factory.bin` at `0x00400000`. + +Scripts for this are in `tools/scripts/mcxe31b`. They find the build output +relative to their own location, so run them from the wolfBoot checkout, for +example `DO /tools/scripts/mcxe31b/e31b_flash_factory_bin.cmm`: + +| Script | Purpose | +|--------|---------| +| `e31b_debug.cmm` | Reset and halt the CPU, then load the `wolfboot.elf` and `test-app/image.elf` symbols | +| `e31b_flash_factory_bin.cmm` | Program `factory.bin`, erase the update partition and swap sector, then reset and detach | +| `e31b_flash_update.cmm` | Program `test-app/image_v2_signed.bin` into the update partition, then reset and detach | + +Each script writes a log to the TRACE32 system directory (`~~`). + +The flash scripts run the TRACE32 S32K3 flash algorithm (`s32k3x4.bin`) from +the DTCM, which they clear first so its ECC is valid. They leave the data +flash and the Secure BAF area untouched. The factory script refuses a file +without the IVT marker at offset 0. + +`SYStem.Up` sometimes reports a debug port time-out while the boot ROM runs. +`e31b_debug.cmm` then attaches, and finds the core halted at the reset vector. + +While TRACE32 is attached, it halts the CPU at the reset vector on every reset. +Detach with `SYStem.Down` before testing an update, which relies on a software +reset. + +### NXP MCXE31B: Testing an update + +Tested on the FRDM-MCXE31B: + +1. Program `factory.bin` with `e31b_flash_factory_bin.cmm`. wolfBoot boots + version 1 and the RGB LED is green. +2. Sign version 2 and program it with `e31b_flash_update.cmm`: + ```sh + tools/keytools/sign --ecc256 --sha256 test-app/image.bin wolfboot_signing_private_key.der 2 + ``` +3. On the console, `status` shows the update. `trigger` then `reboot` swaps + the partitions. Version 2 boots, finds the TESTING state and marks itself + successful. The RGB LED is blue. + +The console `update` command receives a signed image over XMODEM-CRC into the +update partition instead, and triggers it. + ## TI Hercules TMS570LC435 See [/config/examples/ti-tms570lc435.config](/config/examples/ti-tms570lc435.config) for example configuration. diff --git a/hal/mcxe31b.c b/hal/mcxe31b.c new file mode 100644 index 0000000000..c0ac77d773 --- /dev/null +++ b/hal/mcxe31b.c @@ -0,0 +1,586 @@ +/* mcxe31b.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + * + * HAL for NXP MCXE31B (Cortex-M7, 4MB C40ASF code flash + 128KB data flash) + * Tested on FRDM-MCXE31B. + */ + +#include +#include +#include "image.h" +#include "hal.h" +#include "printf.h" + +/* Override RAMFUNCTION for test-app: when RAM_CODE is set but not __WOLFBOOT, + * we still need flash functions to run from RAM for self-programming. */ +#if defined(RAM_CODE) && !defined(__WOLFBOOT) + #undef RAMFUNCTION + #define RAMFUNCTION __attribute__((used,section(".ramcode"),long_call)) +#endif + +#define DSB() __asm__ volatile ("dsb") +#define ISB() __asm__ volatile ("isb") + +#define __get_PRIMASK() ({ \ + uint32_t primask; \ + __asm__ volatile ("mrs %0, primask" : "=r" (primask)); \ + primask; \ +}) + +#define __set_PRIMASK(primask) \ + __asm__ volatile ("msr primask, %0" :: "r" (primask) : "memory") + +#define __disable_irq() \ + __asm__ volatile ("cpsid i" ::: "memory") + +#include "mcxe31b.h" + +/* ============== Image Vector Table (IVT) ============== */ +/* The Secure BAF boot ROM scans for this 256-byte structure at the start of + * each code flash block (0x00400000 first) and starts CM7_0 at the vector + * table it points to. */ + +#ifdef __WOLFBOOT + +extern uint32_t _start_vector; + +const uint32_t __attribute__((section(".ivt"))) mcxe31b_ivt[64] = { + IVT_MARKER, /* 0x00: IVT marker */ + IVT_BCW_CM7_0_ENABLE, /* 0x04: boot config: start CM7_0, no SWT0 */ + 0, /* 0x08: reserved */ + (uint32_t)&_start_vector, /* 0x0C: CM7_0 start address */ + 0, /* 0x10: reserved */ + 0, /* 0x14: CM7_1 start address (n/a) */ + 0, /* 0x18: reserved */ + 0, /* 0x1C: CM7_2 start address (n/a) */ + 0, /* 0x20: reserved */ + 0, /* 0x24: LC configuration word address */ + /* 0x28 - 0xFF: reserved (zero) */ +}; + +#endif /* __WOLFBOOT */ + +/* ============== Clocks ============== */ + +#define CLOCK_TIMEOUT 1000000 + +/* Enable a partition 1 peripheral clock by its MC_ME clock request number */ +static void mc_me_clock_enable(uint32_t req) +{ + uint32_t cofb = req / 32; + uint32_t bit = 1UL << (req % 32); + + if (MC_ME_PRTN1_COFB_STAT(cofb) & bit) + return; + MC_ME_PRTN1_COFB_CLKEN(cofb) |= bit; + MC_ME_PRTN1_PUPD = MC_ME_PRTN_PUPD_PCUD; + MC_ME_CTL_KEY = MC_ME_CTL_KEY_KEY; + MC_ME_CTL_KEY = MC_ME_CTL_KEY_INVKEY; + while (!(MC_ME_PRTN1_COFB_STAT(cofb) & bit)) {} +} + +/* Busy wait for at least n core cycles */ +static void delay_cycles(uint32_t n) +{ + volatile uint32_t i; + for (i = 0; i < n; i++) {} +} + +/* Switch the system clocks from FIRC 48 MHz to the PLL using the RM + * "Option A" (high performance) configuration: FXOSC 16 MHz -> PLL VCO + * 960 MHz -> ODIV2 480 MHz -> PHI0 160 MHz. On failure the system stays + * on FIRC. */ +static int clock_init(void) +{ + /* MUX_0 dividers (DIV + 1): CORE 160, AIPS_PLAT 80, AIPS_SLOW 40, + * HSE 80, DCM 40, LBIST 40, QSPI_MEM 160 MHz */ + static const uint8_t mux0_div[MC_CGM_MUX0_NUM_DIV] = { + 0, 1, 3, 1, 3, 3, 0 + }; + uint32_t timeout; + int i; + + /* Already running from the PLL, e.g. the test-app started by wolfBoot */ + if (MC_CGM_CSS_SELSTAT(MC_CGM_MUX0_CSS) == MC_CGM_SEL_PLL_PHI0) + return 0; + + mc_me_clock_enable(MC_ME_REQ_FXOSC); + mc_me_clock_enable(MC_ME_REQ_PLL); + + /* Last mile regulator: it supplies the core above FIRC speed. Start the + * V15 ballast, wait for its soft start and for V15, then hand over. */ + if (!(PMC_CONFIG & PMC_CONFIG_LMEN)) { + PMC_CONFIG |= PMC_CONFIG_LMBCTLEN; + delay_cycles(FIRC_FREQ / 20000); /* 50 us */ + timeout = CLOCK_TIMEOUT; + while ((PMC_LVSC & PMC_LVSC_LVD15S) && --timeout) {} + if (timeout == 0) + return -1; + PMC_LVSC = PMC_LVSC_LVD15F; + PMC_CONFIG |= PMC_CONFIG_LMEN; + delay_cycles(FIRC_FREQ / 500000); /* 2 us before a clock change */ + } + + /* FXOSC: crystal mode with the reset end-of-count and gain values */ + if (!(FXOSC_STAT & FXOSC_STAT_OSC_STAT)) { + FXOSC_CTRL = FXOSC_CTRL_COMP_EN | FXOSC_CTRL_EOCV(0x9D) | + FXOSC_CTRL_GM_SEL(0xC) | FXOSC_CTRL_OSCON; + timeout = CLOCK_TIMEOUT; + while (!(FXOSC_STAT & FXOSC_STAT_OSC_STAT) && --timeout) {} + if (timeout == 0) + return -1; + } + + /* PLL: 16 MHz / 1 * 60 = 960 MHz VCO, / 2 = 480 MHz, PHI0 / 3 */ + PLL_PLLODIV(0) = 0; + PLL_PLLODIV(1) = 0; + PLL_PLLCR = PLL_PLLCR_PLLPD; + PLL_PLLDV = PLL_PLLDV_RESERVED | PLL_PLLDV_ODIV2(2) | PLL_PLLDV_RDIV(1) | + PLL_PLLDV_MFI(60); + PLL_PLLFM = PLL_PLLFM_SSCGBYP; + PLL_PLLFD = 0; + PLL_PLLODIV(0) = PLL_PLLODIV_DIV(2); + PLL_PLLCR = 0; + timeout = CLOCK_TIMEOUT; + while (!(PLL_PLLSR & PLL_PLLSR_LOCK) && --timeout) {} + if (timeout == 0) { + PLL_PLLCR = PLL_PLLCR_PLLPD; + return -1; + } + PLL_PLLODIV(0) = PLL_PLLODIV_DE | PLL_PLLODIV_DIV(2); + + /* SRAM0 needs a read wait state above 120 MHz. Nothing runs from SRAM0 + * here, so it can be changed safely. */ + PRAMC0_PRCR1 |= PRAMC_PRCR1_FT_DIS; + + /* Program all MUX_0 dividers together, with the crossbar halt + * handshake, then switch the mux to PHI0 */ + MC_CGM_MUX0_DIV_TRIG_CTRL = MC_CGM_DIV_TRIG_CTRL_TCTL | + MC_CGM_DIV_TRIG_CTRL_HHEN; + for (i = 0; i < MC_CGM_MUX0_NUM_DIV; i++) + MC_CGM_MUX0_DC(i) = MC_CGM_DC_DE | MC_CGM_DC_DIV(mux0_div[i]); + MC_CGM_MUX0_DIV_TRIG = 0xFFFFFFFFUL; + while (MC_CGM_MUX0_DIV_UPD_STAT & MC_CGM_DIV_UPD_STAT_DIV_STAT) {} + + MC_CGM_MUX0_CSC = MC_CGM_CSC_SELCTL(MC_CGM_SEL_PLL_PHI0) | + MC_CGM_CSC_CLK_SW; + timeout = CLOCK_TIMEOUT; + while (((MC_CGM_MUX0_CSS & MC_CGM_CSS_SWIP) || + MC_CGM_CSS_SELSTAT(MC_CGM_MUX0_CSS) != MC_CGM_SEL_PLL_PHI0) && + --timeout) {} + if (timeout == 0) + return -1; + return 0; +} + +/* ============== Caches ============== */ + +/* Code and data flash are in the Cortex-M7 "Code" region (normal memory, + * write-through cacheable with the default memory map), so the D-cache can + * hold flash contents that a program or erase has changed. The TCMs are not + * cached. */ +static void RAMFUNCTION dcache_invalidate_range(uint32_t addr, uint32_t len) +{ + uint32_t line; + + if (!(SCB_CCR & SCB_CCR_DC)) + return; + DSB(); + for (line = addr & ~(CACHE_LINE_SIZE - 1); line < addr + len; + line += CACHE_LINE_SIZE) { + SCB_DCIMVAC = line; + } + DSB(); + ISB(); +} + +/* Operate on every D-cache line by set/way: DCISW invalidates, DCCISW cleans + * and invalidates */ +static void dcache_setway(volatile uint32_t *op) +{ + uint32_t sets, ways, ccsidr; + + SCB_CSSELR = 0; /* L1 data cache */ + DSB(); + ccsidr = SCB_CCSIDR; + sets = (ccsidr >> 13) & 0x7FFF; + do { + ways = (ccsidr >> 3) & 0x3FF; + do { + *op = ((sets & 0x1FF) << 5) | ((ways & 0x3) << 30); + } while (ways-- != 0); + } while (sets-- != 0); + DSB(); +} + +static void cache_enable(void) +{ + if (!(SCB_CCR & SCB_CCR_IC)) { + DSB(); + ISB(); + SCB_ICIALLU = 0; + DSB(); + ISB(); + SCB_CCR |= SCB_CCR_IC; + DSB(); + ISB(); + } + if (!(SCB_CCR & SCB_CCR_DC)) { + dcache_setway(&SCB_DCISW); + SCB_CCR |= SCB_CCR_DC; + DSB(); + ISB(); + } +} + +/* Hand over with both caches off and empty */ +static void cache_disable(void) +{ + if (SCB_CCR & SCB_CCR_DC) { + dcache_setway(&SCB_DCCISW); + SCB_CCR &= ~SCB_CCR_DC; + DSB(); + ISB(); + } + if (SCB_CCR & SCB_CCR_IC) { + DSB(); + ISB(); + SCB_CCR &= ~SCB_CCR_IC; + SCB_ICIALLU = 0; + DSB(); + ISB(); + } +} + +#ifdef DEBUG_UART + +#ifndef UART_BAUDRATE +#define UART_BAUDRATE 115200 +#endif + +/* LPUART5 functional clock, from the clock configuration actually in use + * (the PLL setup may have failed and left the system on FIRC) */ +static uint32_t aips_slow_clk(void) +{ + uint32_t src = FIRC_FREQ; + + if (MC_CGM_CSS_SELSTAT(MC_CGM_MUX0_CSS) == MC_CGM_SEL_PLL_PHI0) + src = PLL_PHI0_FREQ; + return src / (MC_CGM_DC_GET_DIV(MC_CGM_MUX0_DC(MC_CGM_DIV_AIPS_SLOW)) + 1); +} + +void uart_init(void) +{ + uint32_t clk = aips_slow_clk(); + uint32_t osr, sbr, err; + uint32_t best_osr = 16, best_sbr = 1, best_err = 0xFFFFFFFFUL; + + /* Pick the oversampling ratio (8..32) with the smallest baud error */ + for (osr = 8; osr <= 32; osr++) { + sbr = (clk + (UART_BAUDRATE * osr / 2)) / (UART_BAUDRATE * osr); + if (sbr == 0 || sbr > 0x1FFF) + continue; + err = clk / (osr * sbr); + err = (err > UART_BAUDRATE) ? err - UART_BAUDRATE : + UART_BAUDRATE - err; + if (err < best_err) { + best_err = err; + best_osr = osr; + best_sbr = sbr; + } + } + + mc_me_clock_enable(MC_ME_REQ_LPUART5); + + /* Pin mux: TX output, RX input routed through IMCR */ + SIUL2_MSCR(UART_TX_PAD) = SIUL2_MSCR_OBE | SIUL2_MSCR_SSS(UART_TX_SSS); + SIUL2_MSCR(UART_RX_PAD) = SIUL2_MSCR_IBE; + SIUL2_IMCR(UART_RX_IMCR) = UART_RX_IMCR_SSS; + + LPUART_CTRL = 0; + LPUART_BAUD = ((best_osr - 1) << LPUART_BAUD_OSR_SHIFT) | + (best_sbr << LPUART_BAUD_SBR_SHIFT); + LPUART_CTRL = LPUART_CTRL_TE | LPUART_CTRL_RE; +} + +void RAMFUNCTION uart_tx(uint8_t byte) +{ + while (!(LPUART_STAT & LPUART_STAT_TDRE)) {} + LPUART_DATA = byte; +} + +void uart_write(const char* buf, unsigned int sz) +{ + unsigned int i; + for (i = 0; i < sz; i++) { + if (buf[i] == '\n') { + uart_tx('\r'); + } + uart_tx(buf[i]); + } + while (!(LPUART_STAT & LPUART_STAT_TC)) {} +} + +/* Non-blocking read: returns 1 if a character was read, 0 otherwise */ +int RAMFUNCTION uart_read(char* c) +{ + uint32_t stat = LPUART_STAT; + + if (stat & (LPUART_STAT_OR | LPUART_STAT_NF | LPUART_STAT_FE | + LPUART_STAT_PF)) { + LPUART_STAT = stat; /* write 1 to clear */ + } + if (stat & LPUART_STAT_RDRF) { + *c = (char)(LPUART_DATA & 0xFF); + return 1; + } + return 0; +} + +#endif /* DEBUG_UART */ + +/* Return the PFLASH lock register and bit covering a flash address. The first + * 768 KB of each code block is locked per 64 KB super sector, the last 256 KB + * (and the data flash) per 8 KB sector. */ +static volatile uint32_t* RAMFUNCTION flash_lock_reg(uint32_t address, + uint32_t *bit) +{ + uint32_t blk, off; + + if (address >= FLASH_DATA_BASE) { + *bit = 1UL << ((address - FLASH_DATA_BASE) / FLASH_SECTOR_SIZE); + return &PFLASH_SPELOCK(4); + } + blk = (address - FLASH_BASE) / FLASH_BLOCK_SIZE; + off = (address - FLASH_BASE) % FLASH_BLOCK_SIZE; + if (off < FLASH_SUPER_SECTOR_AREA) { + *bit = 1UL << (off / FLASH_SUPER_SECTOR_SIZE); + return &PFLASH_SSPELOCK(blk); + } + *bit = 1UL << ((off - FLASH_SUPER_SECTOR_AREA) / FLASH_SECTOR_SIZE); + return &PFLASH_SPELOCK(blk); +} + +/* Clearing and restoring the line buffer invalidates stale reads of + * the flash array after a program or erase */ +static void RAMFUNCTION flash_invalidate_buffers(void) +{ + uint32_t pfcr0 = PFLASH_PFCR0; + uint32_t pfcr1 = PFLASH_PFCR1; + uint32_t mask = PFLASH_PFCR_CBFEN | PFLASH_PFCR_DBFEN; + + PFLASH_PFCR0 = pfcr0 & ~mask; + PFLASH_PFCR1 = pfcr1 & ~mask; + DSB(); + PFLASH_PFCR0 = pfcr0; + PFLASH_PFCR1 = pfcr1; + DSB(); + ISB(); +} + +/* Run the high voltage step of a program (PGM) or erase (ERS) sequence whose + * interlock writes (PEADR_L and DATA) are already done. addr/len is the + * flash range that the operation modifies. */ +static int RAMFUNCTION flash_hv_operation(uint32_t op, uint32_t addr, + uint32_t len) +{ + int ret = 0; + uint32_t primask; + + /* No flash fetches (e.g. interrupt handlers) while the controller is + * busy: reading the block being modified is a read-while-write error */ + primask = __get_PRIMASK(); + __disable_irq(); + + C40ASF_MCR = op; + C40ASF_MCR = op | C40ASF_MCR_EHV; + while (!(C40ASF_MCRS & C40ASF_MCRS_DONE)) {} + if (!(C40ASF_MCRS & C40ASF_MCRS_PEG) || + (C40ASF_MCRS & C40ASF_MCRS_ERR_MASK)) { + ret = -1; + } + C40ASF_MCR = op; + C40ASF_MCR = 0; + + flash_invalidate_buffers(); + dcache_invalidate_range(addr, len); + __set_PRIMASK(primask); + return ret; +} + +static void RAMFUNCTION flash_prepare(void) +{ + while (!(C40ASF_MCRS & C40ASF_MCRS_DONE)) {} + /* Clear sticky errors from earlier operations (write 1 to clear) */ + C40ASF_MCRS = C40ASF_MCRS_ERR_MASK; +} + +/* Program up to one quad page (128 bytes). words[] holds the whole quad page + * image; only words whose bit is set in mask are written to DATAn, the + * others receive no program pulses. */ +static int RAMFUNCTION flash_program_qpage(uint32_t qpage, + const uint32_t *words, uint32_t mask) +{ + volatile uint32_t *lock; + uint32_t bit; + int i, ret; + int first = 1; + + flash_prepare(); + lock = flash_lock_reg(qpage, &bit); + *lock &= ~bit; + + for (i = 0; i < (FLASH_QUAD_PAGE_SIZE / 4); i++) { + if (!(mask & (1UL << i))) + continue; + if (first) { + /* Interlock write: selects the quad page to program */ + PFLASH_PEADR_L = qpage + (i * 4); + first = 0; + } + C40ASF_DATA(i) = words[i]; + } + ret = flash_hv_operation(C40ASF_MCR_PGM, qpage, FLASH_QUAD_PAGE_SIZE); + *lock |= bit; + return ret; +} + +static int RAMFUNCTION flash_erase_sector(uint32_t address) +{ + volatile uint32_t *lock; + uint32_t bit; + int ret; + + flash_prepare(); + lock = flash_lock_reg(address, &bit); + *lock &= ~bit; + + /* Erase interlock write: sector address plus one DATA write */ + PFLASH_PEADR_L = address; + C40ASF_DATA(0) = 0; + ret = flash_hv_operation(C40ASF_MCR_ERS, address, FLASH_SECTOR_SIZE); + *lock |= bit; + return ret; +} + +void hal_init(void) +{ + /* SWT0 is disabled because the IVT boot configuration word does not + * request it */ + int clk_ret = clock_init(); + + cache_enable(); + +#ifdef DEBUG_UART + uart_init(); +#endif + +#if defined(DEBUG_UART) && defined(__WOLFBOOT) +#ifdef WOLFBOOT_REPRODUCIBLE_BUILD + wolfBoot_printf("wolfBoot Version: %s\n", LIBWOLFBOOT_VERSION_STRING); +#else + wolfBoot_printf("wolfBoot Version: %s (%s %s)\n", + LIBWOLFBOOT_VERSION_STRING, __DATE__, __TIME__); +#endif + if (clk_ret != 0) + wolfBoot_printf("PLL setup failed: running from FIRC 48 MHz\n"); +#else + (void)clk_ret; +#endif +} + +void hal_prepare_boot(void) +{ +#ifdef DEBUG_UART + /* Leave the UART idle so the application can reinitialize it */ + while (!(LPUART_STAT & LPUART_STAT_TC)) {} + LPUART_CTRL = 0; +#endif + /* The application starts with the clocks left at 160 MHz and with both + * caches off */ + cache_disable(); +} + +/* Program any length at any address. Writes are split per quad page; each + * 64-bit ECC segment that changes is merged with the current flash contents + * and programmed once. Segments that are unchanged are skipped, because the + * C40ASF allows only one program per ECC segment between erases. */ +int RAMFUNCTION hal_flash_write(uint32_t address, const uint8_t *data, int len) +{ + uint32_t words[FLASH_QUAD_PAGE_SIZE / 4]; + uint8_t *buf = (uint8_t *)words; + uint32_t qpage, start, end, off, mask; + int ret; + + while (len > 0) { + qpage = address & ~(FLASH_QUAD_PAGE_SIZE - 1); + start = address - qpage; + end = start + (uint32_t)len; + if (end > FLASH_QUAD_PAGE_SIZE) + end = FLASH_QUAD_PAGE_SIZE; + + memcpy(buf, (const void *)qpage, FLASH_QUAD_PAGE_SIZE); + memcpy(buf + start, data, end - start); + + mask = 0; + for (off = start & ~(FLASH_DWORD_SIZE - 1); off < end; + off += FLASH_DWORD_SIZE) { + if (memcmp(buf + off, (const void *)(qpage + off), + FLASH_DWORD_SIZE) != 0) { + mask |= 3UL << (off / 4); + } + } + if (mask != 0) { + ret = flash_program_qpage(qpage, words, mask); + if (ret != 0) + return ret; + } + data += end - start; + address += end - start; + len -= (int)(end - start); + } + return 0; +} + +int RAMFUNCTION hal_flash_erase(uint32_t address, int len) +{ + int ret; + + if (len <= 0) + return -1; + + address &= ~(FLASH_SECTOR_SIZE - 1); + while (len > 0) { + ret = flash_erase_sector(address); + if (ret != 0) + return ret; + address += FLASH_SECTOR_SIZE; + len -= FLASH_SECTOR_SIZE; + } + return 0; +} + +void RAMFUNCTION hal_flash_unlock(void) +{ +} + +void RAMFUNCTION hal_flash_lock(void) +{ +} diff --git a/hal/mcxe31b.h b/hal/mcxe31b.h new file mode 100644 index 0000000000..743b4d6331 --- /dev/null +++ b/hal/mcxe31b.h @@ -0,0 +1,288 @@ +/* mcxe31b.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + * + * Register definitions for NXP MCXE31B (Cortex-M7, 4MB C40ASF flash). + * Register offsets and fields from the MCXE31x Reference Manual Rev. 3. + */ + +#ifndef MCXE31B_H +#define MCXE31B_H + +#include + +/* ============== Clock ============== */ + +/* The boot ROM (Secure BAF) leaves the core on FIRC 48 MHz. hal_init() + * switches to the PLL with the RM "Option A" (high performance) dividers: + * CORE_CLK 160 MHz, AIPS_PLAT_CLK 80 MHz, AIPS_SLOW_CLK 40 MHz (LPUART1..7 + * functional clock), HSE_CLK 80 MHz. */ +#define FIRC_FREQ 48000000UL +#define FXOSC_FREQ 16000000UL /* FRDM-MCXE31B Y1 crystal */ +#define PLL_PHI0_FREQ 160000000UL +#ifndef CLOCK_SPEED +#define CLOCK_SPEED PLL_PHI0_FREQ +#endif + +/* MC_CGM clock mux 0 (system clocks) */ +#define MC_CGM_BASE 0x402D8000UL +#define MC_CGM_MUX0_CSC (*(volatile uint32_t *)(MC_CGM_BASE + 0x300)) +#define MC_CGM_MUX0_CSS (*(volatile uint32_t *)(MC_CGM_BASE + 0x304)) +#define MC_CGM_MUX0_DC(n) (*(volatile uint32_t *)(MC_CGM_BASE + 0x308 + ((n) * 4))) +#define MC_CGM_MUX0_DIV_TRIG_CTRL (*(volatile uint32_t *)(MC_CGM_BASE + 0x334)) +#define MC_CGM_MUX0_DIV_TRIG (*(volatile uint32_t *)(MC_CGM_BASE + 0x338)) +#define MC_CGM_MUX0_DIV_UPD_STAT (*(volatile uint32_t *)(MC_CGM_BASE + 0x33C)) + +#define MC_CGM_CSC_SELCTL(x) (((x) & 0xFUL) << 24) +#define MC_CGM_CSC_CLK_SW (1UL << 2) +#define MC_CGM_CSS_SELSTAT(r) (((r) >> 24) & 0xFUL) +#define MC_CGM_CSS_SWIP (1UL << 16) +#define MC_CGM_SEL_FIRC 0x0 +#define MC_CGM_SEL_PLL_PHI0 0x8 +#define MC_CGM_DC_DE (1UL << 31) +#define MC_CGM_DC_DIV(x) (((x) & 0x7UL) << 16) +#define MC_CGM_DC_GET_DIV(r) (((r) >> 16) & 0x7UL) +#define MC_CGM_DIV_TRIG_CTRL_TCTL (1UL << 0) +#define MC_CGM_DIV_TRIG_CTRL_HHEN (1UL << 31) +#define MC_CGM_DIV_UPD_STAT_DIV_STAT (1UL << 0) + +/* MUX_0 dividers: CORE, AIPS_PLAT, AIPS_SLOW, HSE, DCM, LBIST, QSPI_MEM */ +#define MC_CGM_DIV_CORE_CLK 0 +#define MC_CGM_DIV_AIPS_PLAT 1 +#define MC_CGM_DIV_AIPS_SLOW 2 +#define MC_CGM_DIV_HSE 3 +#define MC_CGM_DIV_DCM 4 +#define MC_CGM_DIV_LBIST 5 +#define MC_CGM_DIV_QSPI_MEM 6 +#define MC_CGM_MUX0_NUM_DIV 7 + +/* FXOSC (fast crystal oscillator) */ +#define FXOSC_BASE 0x402D4000UL +#define FXOSC_CTRL (*(volatile uint32_t *)(FXOSC_BASE + 0x0)) +#define FXOSC_STAT (*(volatile uint32_t *)(FXOSC_BASE + 0x4)) +#define FXOSC_CTRL_OSCON (1UL << 0) +#define FXOSC_CTRL_GM_SEL(x) (((x) & 0xFUL) << 4) +#define FXOSC_CTRL_EOCV(x) (((x) & 0xFFUL) << 16) +#define FXOSC_CTRL_COMP_EN (1UL << 24) +#define FXOSC_STAT_OSC_STAT (1UL << 31) + +/* PLLDIG */ +#define PLL_BASE 0x402E0000UL +#define PLL_PLLCR (*(volatile uint32_t *)(PLL_BASE + 0x00)) +#define PLL_PLLSR (*(volatile uint32_t *)(PLL_BASE + 0x04)) +#define PLL_PLLDV (*(volatile uint32_t *)(PLL_BASE + 0x08)) +#define PLL_PLLFM (*(volatile uint32_t *)(PLL_BASE + 0x0C)) +#define PLL_PLLFD (*(volatile uint32_t *)(PLL_BASE + 0x10)) +#define PLL_PLLODIV(n) (*(volatile uint32_t *)(PLL_BASE + 0x80 + ((n) * 4))) +#define PLL_PLLCR_PLLPD (1UL << 31) +#define PLL_PLLSR_LOCK (1UL << 2) +#define PLL_PLLDV_MFI(x) ((x) & 0xFFUL) +#define PLL_PLLDV_RDIV(x) (((x) & 0x7UL) << 12) +#define PLL_PLLDV_ODIV2(x) (((x) & 0x3FUL) << 25) +#define PLL_PLLDV_RESERVED 0x003F0000UL /* keep at reset value */ +#define PLL_PLLFM_SSCGBYP (1UL << 30) +#define PLL_PLLODIV_DE (1UL << 31) +#define PLL_PLLODIV_DIV(x) (((x) & 0xFUL) << 16) + +/* PMC: the last mile regulator must be on to run above FIRC. On the + * FRDM-MCXE31B it builds V15 through an external NPN (Q1) driven by + * VRC_CTRL. */ +#define PMC_BASE 0x402E8000UL +#define PMC_LVSC (*(volatile uint32_t *)(PMC_BASE + 0x0)) +#define PMC_CONFIG (*(volatile uint32_t *)(PMC_BASE + 0x4)) +#define PMC_LVSC_LVD15F (1UL << 5) +#define PMC_LVSC_LVD15S (1UL << 13) +#define PMC_CONFIG_LMEN (1UL << 0) +#define PMC_CONFIG_LMBCTLEN (1UL << 1) + +/* PRAMC_0 (SRAM0 controller): one read wait state above 120 MHz */ +#define PRAMC0_PRCR1 (*(volatile uint32_t *)0x40264000UL) +#define PRAMC_PRCR1_FT_DIS (1UL << 0) + +/* ============== Flash memory map ============== */ + +#define FLASH_BASE 0x00400000UL +#define FLASH_BLOCK_SIZE 0x00100000UL /* 4 x 1 MB code flash blocks */ +#define FLASH_NUM_BLOCKS 4 +#define FLASH_DATA_BASE 0x10000000UL /* Data flash = block 4 */ +#define FLASH_DATA_SIZE 0x00020000UL /* 128 KB */ +#define FLASH_SECTOR_SIZE 0x2000UL /* 8 KB */ +#define FLASH_SUPER_SECTOR_SIZE 0x10000UL /* 64 KB */ +/* Each 1 MB block: first 768 KB locked per super sector, last 256 KB per + * sector */ +#define FLASH_SUPER_SECTOR_AREA 0x000C0000UL +#define FLASH_QUAD_PAGE_SIZE 128 /* Max bytes per program op */ +#define FLASH_DWORD_SIZE 8 /* ECC granularity */ + +/* ============== Image Vector Table (IVT) ============== */ + +#define IVT_MARKER 0x5AA55AA5UL +#define IVT_BCW_CM7_0_ENABLE (1UL << 0) +#define IVT_BCW_APP_SWT_INIT (1UL << 5) + +/* ============== C40ASF flash controller ============== */ + +#define C40ASF_BASE 0x402EC000UL +#define C40ASF_MCR (*(volatile uint32_t *)(C40ASF_BASE + 0x000)) +#define C40ASF_MCRS (*(volatile uint32_t *)(C40ASF_BASE + 0x004)) +#define C40ASF_DATA(n) (*(volatile uint32_t *)(C40ASF_BASE + 0x100 + ((n) * 4))) + +#define C40ASF_MCR_EHV (1UL << 0) +#define C40ASF_MCR_ERS (1UL << 4) +#define C40ASF_MCR_ESS (1UL << 5) +#define C40ASF_MCR_PGM (1UL << 8) + +#define C40ASF_MCRS_PES (1UL << 16) +#define C40ASF_MCRS_PEP (1UL << 17) +#define C40ASF_MCRS_RWE (1UL << 20) +#define C40ASF_MCRS_PEG (1UL << 14) +#define C40ASF_MCRS_DONE (1UL << 15) +#define C40ASF_MCRS_ERR_MASK (C40ASF_MCRS_PES | C40ASF_MCRS_PEP | \ + C40ASF_MCRS_RWE) + +/* ============== PFLASH controller ============== */ + +#define PFLASH_BASE 0x40268000UL +#define PFLASH_PFCR0 (*(volatile uint32_t *)(PFLASH_BASE + 0x000)) +#define PFLASH_PFCR1 (*(volatile uint32_t *)(PFLASH_BASE + 0x004)) +#define PFLASH_PEADR_L (*(volatile uint32_t *)(PFLASH_BASE + 0x300)) +/* Sector lock: blocks 0-3 = code flash, 4 = data flash */ +#define PFLASH_SPELOCK(blk) (*(volatile uint32_t *)(PFLASH_BASE + 0x340 + ((blk) * 4))) +/* Super sector lock: blocks 0-3 only */ +#define PFLASH_SSPELOCK(blk) (*(volatile uint32_t *)(PFLASH_BASE + 0x35C + ((blk) * 4))) + +/* Line buffer enables; clearing them also invalidates the buffers */ +#define PFLASH_PFCR_CBFEN (1UL << 0) +#define PFLASH_PFCR_DBFEN (1UL << 1) + +/* ============== MC_ME (mode entry / clock gating) ============== */ + +#define MC_ME_BASE 0x402DC000UL +#define MC_ME_CTL_KEY (*(volatile uint32_t *)(MC_ME_BASE + 0x000)) +#define MC_ME_MODE_CONF (*(volatile uint32_t *)(MC_ME_BASE + 0x004)) +#define MC_ME_MODE_UPD (*(volatile uint32_t *)(MC_ME_BASE + 0x008)) +#define MC_ME_PRTN1_PUPD (*(volatile uint32_t *)(MC_ME_BASE + 0x304)) +#define MC_ME_PRTN1_COFB_STAT(n) (*(volatile uint32_t *)(MC_ME_BASE + 0x310 + ((n) * 4))) +#define MC_ME_PRTN1_COFB_CLKEN(n) (*(volatile uint32_t *)(MC_ME_BASE + 0x330 + ((n) * 4))) + +#define MC_ME_CTL_KEY_KEY 0x00005AF0UL +#define MC_ME_CTL_KEY_INVKEY 0x0000A50FUL +#define MC_ME_MODE_CONF_FUNC_RST (1UL << 1) +#define MC_ME_MODE_UPD_MODE_UPD (1UL << 0) +#define MC_ME_PRTN_PUPD_PCUD (1UL << 0) + +/* Partition 1 clock requests: REQn = COFB(n / 32) bit (n % 32) */ +#define MC_ME_REQ_FXOSC 53 +#define MC_ME_REQ_PLL 56 +#define MC_ME_REQ_LPUART5 79 + +/* ============== SIUL2 (pin mux and GPIO) ============== */ + +#define SIUL2_BASE 0x40290000UL +#define SIUL2_MSCR(n) (*(volatile uint32_t *)(SIUL2_BASE + 0x240 + ((n) * 4))) +/* IMCR numbers as listed in the IOMUX file (512 and up) */ +#define SIUL2_IMCR(n) (*(volatile uint32_t *)(SIUL2_BASE + 0xA40 + (((n) - 512) * 4))) +/* 8-bit GPIO data registers, byte-swapped within each 32-bit word */ +#define SIUL2_GPDO(n) (*(volatile uint8_t *)(SIUL2_BASE + 0x1300 + ((n) + 3 - 2 * ((n) % 4)))) +#define SIUL2_GPDI(n) (*(volatile uint8_t *)(SIUL2_BASE + 0x1500 + ((n) + 3 - 2 * ((n) % 4)))) + +#define SIUL2_MSCR_OBE (1UL << 21) +#define SIUL2_MSCR_IBE (1UL << 19) +#define SIUL2_MSCR_SSS(x) ((x) & 0xFUL) + +/* Pad numbers: port * 32 + pin */ +#define PAD_PTB22 54 +#define PAD_PTC14 78 +#define PAD_PTC16 80 +#define PAD_PTE3 131 +#define PAD_PTE14 142 + +/* FRDM-MCXE31B: MCU-Link VCOM is LPUART5 on PTE14 (TX) / PTE3 (RX) */ +#define UART_TX_PAD PAD_PTE14 +#define UART_TX_SSS 4 +#define UART_RX_PAD PAD_PTE3 +#define UART_RX_IMCR 704 +#define UART_RX_IMCR_SSS 1 + +/* FRDM-MCXE31B: RGB LED D1 */ +#define LED_RED_PAD PAD_PTC16 +#define LED_GREEN_PAD PAD_PTB22 +#define LED_BLUE_PAD PAD_PTC14 + +/* ============== LPUART ============== */ + +#define LPUART5_BASE 0x4033C000UL +#define LPUART_BAUD (*(volatile uint32_t *)(LPUART5_BASE + 0x10)) +#define LPUART_STAT (*(volatile uint32_t *)(LPUART5_BASE + 0x14)) +#define LPUART_CTRL (*(volatile uint32_t *)(LPUART5_BASE + 0x18)) +#define LPUART_DATA (*(volatile uint32_t *)(LPUART5_BASE + 0x1C)) + +#define LPUART_BAUD_SBR_SHIFT 0 +#define LPUART_BAUD_OSR_SHIFT 24 +#define LPUART_STAT_RDRF (1UL << 21) +#define LPUART_STAT_TC (1UL << 22) +#define LPUART_STAT_TDRE (1UL << 23) +#define LPUART_STAT_OR (1UL << 19) +#define LPUART_STAT_NF (1UL << 18) +#define LPUART_STAT_FE (1UL << 17) +#define LPUART_STAT_PF (1UL << 16) +#define LPUART_CTRL_RE (1UL << 18) +#define LPUART_CTRL_TE (1UL << 19) +#define LPUART_CTRL_RIE (1UL << 21) +#define LPUART_IRQn 146 /* LPUART5 */ + +/* ============== Cortex-M7 caches ============== */ + +#define SCB_CCR (*(volatile uint32_t *)0xE000ED14UL) +#define SCB_CCR_DC (1UL << 16) +#define SCB_CCR_IC (1UL << 17) +#define SCB_CCSIDR (*(volatile uint32_t *)0xE000ED80UL) +#define SCB_CSSELR (*(volatile uint32_t *)0xE000ED84UL) +#define SCB_ICIALLU (*(volatile uint32_t *)0xE000EF50UL) +#define SCB_DCIMVAC (*(volatile uint32_t *)0xE000EF5CUL) +#define SCB_DCISW (*(volatile uint32_t *)0xE000EF60UL) +#define SCB_DCCISW (*(volatile uint32_t *)0xE000EF74UL) +#define CACHE_LINE_SIZE 32 + +/* ============== NVIC ============== */ + +#define NVIC_ISER(n) (*(volatile uint32_t *)(0xE000E100UL + ((n) * 4))) +#define NVIC_IPR(n) (*(volatile uint8_t *)(0xE000E400UL + (n))) +#define NVIC_PRIO_BITS 4 +#define NVIC_EnableIRQ(irq) (NVIC_ISER((irq) >> 5) = (1UL << ((irq) & 0x1F))) +#define NVIC_SetPriority(irq, prio) \ + (NVIC_IPR(irq) = (uint8_t)(((prio) << (8 - NVIC_PRIO_BITS)) & 0xFF)) + +/* ============== SysTick ============== */ + +#define SYST_CSR (*(volatile uint32_t *)0xE000E010) +#define SYST_RVR (*(volatile uint32_t *)0xE000E014) +#define SYST_CVR (*(volatile uint32_t *)0xE000E018) +#define SYST_CSR_ENABLE (1UL << 0) +#define SYST_CSR_TICKINT (1UL << 1) +#define SYST_CSR_CLKSOURCE (1UL << 2) + +#ifdef DEBUG_UART +void uart_init(void); +void uart_tx(uint8_t byte); +void uart_write(const char* buf, unsigned int sz); +int uart_read(char* c); +#endif + +#endif /* MCXE31B_H */ diff --git a/hal/mcxe31b.ld b/hal/mcxe31b.ld new file mode 100644 index 0000000000..57b3d0f846 --- /dev/null +++ b/hal/mcxe31b.ld @@ -0,0 +1,80 @@ +/* + * Linker script for wolfBoot on NXP MCXE31B + * + * Flash: the boot ROM reads the Image Vector Table (IVT) at 0x00400000 and + * starts CM7_0 at the vector table it points to (0x00400400 here). + * + * RAM: wolfBoot uses only the 64 KB CM7_0 DTCM (0x20000000). DTCM is ECC + * protected and must be written before it is read; the reset handler clears + * [_start_ecc_ram, _end_ecc_ram) first (WOLFBOOT_RAM_ECC_INIT). Unlike system + * SRAM, DTCM accepts 32-bit writes for ECC init and can execute code, so it + * also holds the RAM_CODE flash routines. + */ + +MEMORY +{ + FLASH (rx) : ORIGIN = @ARCH_FLASH_OFFSET@, LENGTH = @BOOTLOADER_PARTITION_SIZE@ + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x10000 /* 64 KB DTCM */ +} + +SECTIONS +{ + .text : + { + _start_text = .; + KEEP(*(.ivt)) + . = 0x400; + _start_vector = .; + KEEP(*(.isr_vector)) + *(.text*) + *(.rodata*) + *(.init*) + *(.fini*) + . = ALIGN(4); + _end_text = .; + } > FLASH + + .edidx : + { + . = ALIGN(4); + *(.ARM.exidx*) + } > FLASH + + _stored_data = .; + + .data : AT (_stored_data) + { + _start_data = .; + KEEP(*(.data*)) + . = ALIGN(4); + KEEP(*(.ramcode)) + . = ALIGN(4); + _end_data = .; + } > RAM + + .bss (NOLOAD) : + { + _start_bss = .; + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + _end_bss = .; + __bss_end__ = .; + _end = .; + } > RAM + . = ALIGN(4); +} + +END_STACK = ORIGIN(RAM) + LENGTH(RAM); + +ASSERT(hal_flash_write >= ORIGIN(RAM) && hal_flash_erase >= ORIGIN(RAM), + "MCXE31B flash routines must run from RAM (RAM_CODE=1)") + +_start_ecc_ram = ORIGIN(RAM); +_end_ecc_ram = ORIGIN(RAM) + LENGTH(RAM); + +_wolfboot_partition_boot_address = @WOLFBOOT_PARTITION_BOOT_ADDRESS@; +_wolfboot_partition_size = @WOLFBOOT_PARTITION_SIZE@; +_wolfboot_partition_update_address = @WOLFBOOT_PARTITION_UPDATE_ADDRESS@; +_wolfboot_partition_swap_address = @WOLFBOOT_PARTITION_SWAP_ADDRESS@; diff --git a/test-app/ARM-mcxe31b.ld b/test-app/ARM-mcxe31b.ld new file mode 100644 index 0000000000..412244103b --- /dev/null +++ b/test-app/ARM-mcxe31b.ld @@ -0,0 +1,70 @@ +/* + * Linker script for wolfBoot test application on NXP MCXE31B + * + * Application runs from boot partition after wolfBoot header + * + * RAM: the 64 KB CM7_0 DTCM (0x20000000), which wolfBoot has already + * ECC-initialized. It also holds the RAM_CODE flash routines. + */ + +MEMORY +{ + FLASH (rx) : ORIGIN = @WOLFBOOT_TEST_APP_ADDRESS@, LENGTH = @WOLFBOOT_TEST_APP_SIZE@ + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x10000 /* 64 KB DTCM */ +} + +SECTIONS +{ + .text : + { + _start_text = .; + KEEP(*(.isr_vector)) + *(.text*) + *(.rodata*) + *(.init*) + *(.fini*) + . = ALIGN(4); + _end_text = .; + } > FLASH + + .edidx : + { + . = ALIGN(4); + *(.ARM.exidx*) + } > FLASH + + _stored_data = .; + + .data : AT (_stored_data) + { + _start_data = .; + KEEP(*(.data*)) + . = ALIGN(4); + KEEP(*(.ramcode)) + . = ALIGN(4); + _end_data = .; + } > RAM + + .bss (NOLOAD) : + { + _start_bss = .; + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + _end_bss = .; + __bss_end__ = .; + _end = .; + } > RAM + . = ALIGN(4); +} + +/* Partition info for libwolfboot */ +_wolfboot_partition_boot_address = @WOLFBOOT_PARTITION_BOOT_ADDRESS@; +_wolfboot_partition_size = @WOLFBOOT_PARTITION_SIZE@; +_wolfboot_partition_update_address = @WOLFBOOT_PARTITION_UPDATE_ADDRESS@; +_wolfboot_partition_swap_address = @WOLFBOOT_PARTITION_SWAP_ADDRESS@; + +/* Stack and heap indicators */ +_start_heap = _end; +_end_stack = ORIGIN(RAM) + LENGTH(RAM); diff --git a/test-app/Makefile b/test-app/Makefile index bca2573ef6..65e2033580 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1153,6 +1153,15 @@ ifeq ($(TARGET),s32k1xx) CFLAGS+=-DRAM_CODE -DDEBUG_UART endif +ifeq ($(TARGET),mcxe31b) + LSCRIPT_TEMPLATE=ARM-mcxe31b.ld + ifneq ($(SIGN),NONE) + APP_OBJS+=../src/keystore.o + endif + CFLAGS+=-DAPP_HAS_SYSTICK + CFLAGS+=-DRAM_CODE -DDEBUG_UART +endif + ifeq ($(TARGET),stm32n6) CFLAGS+=-DRAM_CODE -DDEBUG_UART APP_OBJS+=syscalls.o diff --git a/test-app/app_mcxe31b.c b/test-app/app_mcxe31b.c new file mode 100644 index 0000000000..abfd8671df --- /dev/null +++ b/test-app/app_mcxe31b.c @@ -0,0 +1,1046 @@ +/* app_mcxe31b.c + * + * Test bare-metal application for NXP MCXE31B + * Features: + * - LED indicator based on firmware version (Green=v1, Blue=v>1) + * - Interactive console with commands + * - XMODEM firmware update support + * - Partition and keystore information display + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include +#include +#include +#include +#include +#include "hal.h" +#include "../hal/mcxe31b.h" +#include "wolfboot/wolfboot.h" +#include "keystore.h" +#include "target.h" +#include "image.h" + +#ifdef TARGET_mcxe31b + +/* RAMFUNCTION for test-app: code that runs during flash operations must be in RAM */ +#ifdef RAM_CODE + #define APP_RAMFUNCTION __attribute__((used,section(".ramcode"),long_call)) +#else + #define APP_RAMFUNCTION +#endif + +/* ============== SysTick Timer ============== */ + +static volatile uint32_t jiffies = 0; + +/* SysTick interrupt handler - called isr_systick to match startup_arm.c */ +void isr_systick(void) +{ + jiffies++; +} + +static void delay_ms(uint32_t ms) +{ + uint32_t start = jiffies; + while ((jiffies - start) < ms) { + __asm__ volatile ("wfi"); + } +} + +static void systick_init(void) +{ + /* Configure SysTick for 1ms tick */ + SYST_RVR = (CLOCK_SPEED / 1000) - 1; + SYST_CVR = 0; + SYST_CSR = SYST_CSR_ENABLE | SYST_CSR_TICKINT | SYST_CSR_CLKSOURCE; +} + +/* ============== LED Functions ============== */ + +/* FRDM-MCXE31B RGB LED D1, active low */ +static void led_init(void) +{ + SIUL2_GPDO(LED_RED_PAD) = 1; + SIUL2_GPDO(LED_GREEN_PAD) = 1; + SIUL2_GPDO(LED_BLUE_PAD) = 1; + SIUL2_MSCR(LED_RED_PAD) = SIUL2_MSCR_OBE; + SIUL2_MSCR(LED_GREEN_PAD) = SIUL2_MSCR_OBE; + SIUL2_MSCR(LED_BLUE_PAD) = SIUL2_MSCR_OBE; +} + +static void led_green_on(void) +{ + SIUL2_GPDO(LED_GREEN_PAD) = 0; +} + +static void led_green_off(void) +{ + SIUL2_GPDO(LED_GREEN_PAD) = 1; +} + +static void led_blue_on(void) +{ + SIUL2_GPDO(LED_BLUE_PAD) = 0; +} + +static void led_blue_off(void) +{ + SIUL2_GPDO(LED_BLUE_PAD) = 1; +} + +static void APP_RAMFUNCTION led_red_on(void) +{ + SIUL2_GPDO(LED_RED_PAD) = 0; +} + +static void APP_RAMFUNCTION led_red_off(void) +{ + SIUL2_GPDO(LED_RED_PAD) = 1; +} + +static void led_toggle_version(uint32_t version) +{ + if (version == 1) { + SIUL2_GPDO(LED_GREEN_PAD) ^= 1; + } else { + SIUL2_GPDO(LED_BLUE_PAD) ^= 1; + } +} + +/* Set LED based on version: Green for v1, Blue for v>1 */ +static void led_set_version(uint32_t version) +{ + /* Turn off both first */ + led_green_off(); + led_blue_off(); + + if (version == 1) { + led_green_on(); + } else if (version > 1) { + led_blue_on(); + } +} + +/* ============== System Control ============== */ + +/* Functional reset through MC_ME */ +void arch_reboot(void) +{ + MC_ME_MODE_CONF = MC_ME_MODE_CONF_FUNC_RST; + MC_ME_MODE_UPD = MC_ME_MODE_UPD_MODE_UPD; + MC_ME_CTL_KEY = MC_ME_CTL_KEY_KEY; + MC_ME_CTL_KEY = MC_ME_CTL_KEY_INVKEY; + while (1) { + __asm__ volatile ("wfi"); + } +} + +/* ============== UART / Printf Support ============== */ + +#ifdef DEBUG_UART +/* UART functions are declared in mcxe31b.h and implemented in hal/mcxe31b.c */ + +/* Flag to block text output during XMODEM transfer */ +static volatile int xmodem_active = 0; + +/* ============== UART RX Interrupt Buffering ============== */ +#define UART_RX_BUF_SIZE 512 +static volatile uint8_t uart_rx_buf[UART_RX_BUF_SIZE]; +static volatile uint32_t uart_rx_head = 0; /* Write index (ISR writes here) */ +static volatile uint32_t uart_rx_tail = 0; /* Read index (app reads from here) */ + +/* Console LPUART RX Interrupt Handler */ +void isr_debug_uart(void) +{ + uint32_t stat = LPUART_STAT; + + /* Clear only the error flags (write 1 to clear) - do NOT write other bits */ + uint32_t errors = stat & (LPUART_STAT_OR | LPUART_STAT_NF | LPUART_STAT_FE | LPUART_STAT_PF); + if (errors) { + LPUART_STAT = errors; /* Write 1 to clear only error flags */ + } + + /* Read all available bytes from FIFO */ + while (LPUART_STAT & LPUART_STAT_RDRF) { + uint8_t c = (uint8_t)(LPUART_DATA & 0xFF); + uint32_t next_head = (uart_rx_head + 1) % UART_RX_BUF_SIZE; + + /* Store byte if buffer not full */ + if (next_head != uart_rx_tail) { + uart_rx_buf[uart_rx_head] = c; + uart_rx_head = next_head; + } + /* else: buffer full, discard byte */ + } +} + +/* Read from RX buffer (for XMODEM) - returns number of bytes read + * Must be RAMFUNCTION since it's called during flash operations */ +static int APP_RAMFUNCTION uart_rx_isr(uint8_t *buf, int max_len) +{ + int count = 0; + + while (count < max_len && uart_rx_tail != uart_rx_head) { + buf[count++] = uart_rx_buf[uart_rx_tail]; + uart_rx_tail = (uart_rx_tail + 1) % UART_RX_BUF_SIZE; + } + + return count; +} + +/* Check if RX data available */ +static int uart_rx_available(void) +{ + return (uart_rx_head != uart_rx_tail) ? 1 : 0; +} + +/* Read single character from RX buffer (for console) - returns 1 if char read, 0 if none */ +static int uart_getc(char *c) +{ + if (uart_rx_tail != uart_rx_head) { + *c = uart_rx_buf[uart_rx_tail]; + uart_rx_tail = (uart_rx_tail + 1) % UART_RX_BUF_SIZE; + return 1; + } + return 0; +} + +/* Enable LPUART RX interrupt */ +static void uart_rx_irq_enable(void) +{ + /* Set interrupt priority lower than SysTick (higher number = lower priority) + * SysTick defaults to priority 0, so set LPUART to 2 to ensure + * jiffies keeps incrementing even during heavy UART traffic. */ + NVIC_SetPriority(LPUART_IRQn, 2); + + /* Enable LPUART interrupt in NVIC */ + NVIC_EnableIRQ(LPUART_IRQn); + + /* Enable Receiver Interrupt in LPUART */ + LPUART_CTRL |= LPUART_CTRL_RIE; +} + +/* Print hex buffer (similar to stm32h5 style) */ +#define LINE_LEN 16 +static void print_hex(const uint8_t* buffer, uint32_t length, int dumpChars) +{ + uint32_t i, sz; + + if (buffer == NULL) { + printf("\tNULL\r\n"); + return; + } + + while (length > 0) { + sz = length; + if (sz > LINE_LEN) + sz = LINE_LEN; + + printf("\t"); + for (i = 0; i < LINE_LEN; i++) { + if (i < length) + printf("%02x ", buffer[i]); + else + printf(" "); + } + if (dumpChars) { + printf("| "); + for (i = 0; i < sz; i++) { + if (buffer[i] > 31 && buffer[i] < 127) + printf("%c", buffer[i]); + else + printf("."); + } + } + printf("\r\n"); + + buffer += sz; + length -= sz; + } +} +#endif /* DEBUG_UART */ + +/* ============== Partition State Names ============== */ + +static const char* part_state_name(uint8_t state, int state_retval) +{ + /* wolfBoot_get_partition_state() returns 0 when it read a state */ + if (state_retval != 0) { + return "(no trailer)"; + } + switch (state) { + case IMG_STATE_NEW: return "NEW"; + case IMG_STATE_UPDATING: return "UPDATING"; + case IMG_STATE_TESTING: return "TESTING"; + case IMG_STATE_SUCCESS: return "SUCCESS"; + default: return "UNKNOWN"; + } +} + +/* ============== Key Type Names ============== */ + +static const char* key_type_name(uint32_t type) +{ + switch (type) { + case AUTH_KEY_ECC256: return "ECDSA P-256 (secp256r1)"; + case AUTH_KEY_ECC384: return "ECDSA P-384 (secp384r1)"; + case AUTH_KEY_ECC521: return "ECDSA P-521 (secp521r1)"; + case AUTH_KEY_RSA2048: return "RSA-2048"; + case AUTH_KEY_RSA3072: return "RSA-3072"; + case AUTH_KEY_RSA4096: return "RSA-4096"; + case AUTH_KEY_ED25519: return "Ed25519"; + case AUTH_KEY_ED448: return "Ed448"; + case AUTH_KEY_LMS: return "LMS"; + case AUTH_KEY_XMSS: return "XMSS"; + case AUTH_KEY_ML_DSA: return "ML-DSA"; + default: return "Unknown"; + } +} + +static const char* hash_type_name(void) +{ +#ifdef WOLFBOOT_HASH_SHA256 + return "SHA-256"; +#elif defined(WOLFBOOT_HASH_SHA384) + return "SHA-384"; +#elif defined(WOLFBOOT_HASH_SHA512) + return "SHA-512"; +#elif defined(WOLFBOOT_HASH_SHA3_384) + return "SHA3-384"; +#endif + return "Unknown"; +} + +/* ============== Information Display ============== */ + +#ifdef DEBUG_UART +static void print_partition_info(void) +{ + uint32_t boot_ver, update_ver; + uint8_t boot_state = 0, update_state = 0; + int boot_state_valid, update_state_valid; + + boot_ver = wolfBoot_current_firmware_version(); + update_ver = wolfBoot_update_firmware_version(); + + boot_state_valid = wolfBoot_get_partition_state(PART_BOOT, &boot_state); + update_state_valid = wolfBoot_get_partition_state(PART_UPDATE, &update_state); + + printf("\r\n=== Partition Information ===\r\n"); + + printf("Boot Partition:\r\n"); + printf(" Address: 0x%08lX\r\n", (unsigned long)WOLFBOOT_PARTITION_BOOT_ADDRESS); + printf(" Version: %lu\r\n", (unsigned long)boot_ver); + printf(" State: %s\r\n", part_state_name(boot_state, boot_state_valid)); + + printf("Update Partition:\r\n"); + printf(" Address: 0x%08lX\r\n", (unsigned long)WOLFBOOT_PARTITION_UPDATE_ADDRESS); + printf(" Version: %lu\r\n", (unsigned long)update_ver); + printf(" State: %s\r\n", part_state_name(update_state, update_state_valid)); + + printf("Swap Partition:\r\n"); + printf(" Address: 0x%08lX\r\n", (unsigned long)WOLFBOOT_PARTITION_SWAP_ADDRESS); + printf(" Size: %lu bytes\r\n", (unsigned long)WOLFBOOT_SECTOR_SIZE); +} + +static void print_keystore_info(void) +{ +#ifndef WOLFBOOT_NO_SIGN + uint32_t n_keys; + int i; + + printf("\r\n=== Keystore Information ===\r\n"); + + n_keys = keystore_num_pubkeys(); + printf("Number of public keys: %lu\r\n", (unsigned long)n_keys); + printf("Hash: %s\r\n", hash_type_name()); + + for (i = 0; i < (int)n_keys; i++) { + uint32_t size = keystore_get_size(i); + uint32_t type = keystore_get_key_type(i); + uint8_t* keybuf = keystore_get_buffer(i); + + printf("\r\nKey #%d:\r\n", i); + printf(" Algorithm: %s\r\n", key_type_name(type)); + printf(" Size: %lu bytes\r\n", (unsigned long)size); + printf(" Data:\r\n"); + print_hex(keybuf, size, 0); + } +#else + printf("\r\n=== Keystore Information ===\r\n"); + printf("Signing disabled (SIGN=NONE)\r\n"); +#endif /* !WOLFBOOT_NO_SIGN */ +} + +/* ============== XMODEM Transfer ============== */ + +#define XSOH 0x01 +#define XEOT 0x04 +#define XACK 0x06 +#define XNAK 0x15 +#define XCAN 0x18 +#define XCRC 'C' /* Request CRC mode */ + +#define XMODEM_PAYLOAD_SIZE 128 +#define XMODEM_PACKET_SIZE_CRC (3 + XMODEM_PAYLOAD_SIZE + 2) /* SOH + blk + ~blk + data + CRC16 */ +#define XMODEM_TIMEOUT_MS 1000 + +/* CRC-16-CCITT for XMODEM-CRC mode */ +static uint16_t APP_RAMFUNCTION crc16_ccitt(const uint8_t* data, int len) +{ + uint16_t crc = 0; + int i, j; + for (i = 0; i < len; i++) { + crc ^= ((uint16_t)data[i] << 8); + for (j = 0; j < 8; j++) { + if (crc & 0x8000) { + crc = (crc << 1) ^ 0x1021; + } else { + crc <<= 1; + } + } + } + return crc; +} + +/* Raw byte transmit for XMODEM (declared in hal, runs from RAM) */ +extern void uart_tx(uint8_t byte); + +/* RAM-based memory copy for use during flash operations */ +static void APP_RAMFUNCTION ram_memcpy(void *dst, const void *src, uint32_t len) +{ + uint8_t *d = (uint8_t *)dst; + const uint8_t *s = (const uint8_t *)src; + while (len--) { + *d++ = *s++; + } +} + +static void APP_RAMFUNCTION xmodem_cancel(void) +{ + int i; + for (i = 0; i < 10; i++) { + uart_tx(XCAN); + } +} + +/* XMODEM receive state - passed to RAM function */ +typedef struct { + uint32_t dst_offset; + int result; + /* Debug counters */ + uint32_t pkts_received; + uint32_t pkts_crc_fail; + uint32_t pkts_num_fail; + uint32_t pkts_soh_fail; + uint32_t timeouts; +} xmodem_state_t; + +/* Core XMODEM-CRC receive loop - runs entirely from RAM during flash operations + * Uses XMODEM-CRC mode (133-byte packets with 16-bit CRC) + * Returns: 0 on success, -1 on error + */ +static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) +{ + uint8_t xpkt[XMODEM_PACKET_SIZE_CRC]; + uint8_t payload[XMODEM_PAYLOAD_SIZE]; + uint8_t pkt_num = 0, pkt_num_expected = 0xFF; + uint32_t t_size = 0; + uint32_t now; + uint32_t i = 0; + int transfer_started = 0; + int eot_expected = 0; + int ret = -1; + + state->dst_offset = 0; + state->result = -1; + state->pkts_received = 0; + state->pkts_crc_fail = 0; + state->pkts_num_fail = 0; + state->pkts_soh_fail = 0; + state->timeouts = 0; + + /* Send 'C' to request CRC mode (XMODEM-CRC) */ + uart_tx(XCRC); + + while (1) { + now = jiffies; /* Direct access to volatile - faster than function call */ + i = 0; + + /* Receive packet - uses interrupt-buffered RX to avoid FIFO overflow */ + while (i < XMODEM_PACKET_SIZE_CRC) { + int r = uart_rx_isr(&xpkt[i], XMODEM_PACKET_SIZE_CRC - i); + if (r > 0) { + i += r; + now = jiffies; + if (i >= 1 && xpkt[0] == XEOT) { + break; /* End of transmission */ + } + } else if (jiffies > (now + XMODEM_TIMEOUT_MS)) { + now = jiffies; + state->timeouts++; + if (i == 0) { + uart_tx(XCRC); /* Request CRC mode again */ + } + i = 0; + } + } + + /* Check for EOT */ + if (xpkt[0] == XEOT) { + uart_tx(XACK); + led_red_on(); /* Indicate transfer complete */ + ret = 0; + break; + } else if (eot_expected) { + uart_tx(XNAK); + ret = -1; + break; + } + + /* Validate SOH */ + if (xpkt[0] != XSOH) { + state->pkts_soh_fail++; + continue; + } + state->pkts_received++; + + /* Validate packet number */ + pkt_num = xpkt[1]; + if ((uint8_t)(~xpkt[2]) == pkt_num) { + uint16_t recv_crc, calc_crc; + + if (!transfer_started) { + pkt_num_expected = pkt_num; + transfer_started = 1; + } else if (pkt_num_expected != pkt_num) { + uart_tx(XNAK); + continue; + } + + /* Toggle LED to show activity */ + if ((pkt_num & 0x0F) == 0) { + led_red_on(); + } else if ((pkt_num & 0x0F) == 8) { + led_red_off(); + } + + /* Validate CRC-16 - XMODEM-CRC uses CRC over DATA bytes only */ + recv_crc = ((uint16_t)xpkt[XMODEM_PACKET_SIZE_CRC - 2] << 8) | + xpkt[XMODEM_PACKET_SIZE_CRC - 1]; + calc_crc = crc16_ccitt(xpkt + 3, XMODEM_PAYLOAD_SIZE); + + if (recv_crc == calc_crc) { + /* Copy payload using RAM-based memcpy */ + ram_memcpy(payload, xpkt + 3, XMODEM_PAYLOAD_SIZE); + + /* Send ACK first, then write to flash. + * This allows sender to prepare next packet while we write. + * Risk: if write fails, we've already ACKed - but that's rare. + */ + uart_tx(XACK); + + /* Write to flash */ + ret = hal_flash_write(WOLFBOOT_PARTITION_UPDATE_ADDRESS + state->dst_offset, + payload, XMODEM_PAYLOAD_SIZE); + if (ret != 0) { + xmodem_cancel(); + /* No printf here - we're in RAM */ + break; + } + pkt_num_expected++; + state->dst_offset += XMODEM_PAYLOAD_SIZE; + + /* Get expected size from header (offset 4 = image size) */ + if (t_size == 0 && state->dst_offset >= 8) { + t_size = *(uint32_t*)(payload + 4) + IMAGE_HEADER_SIZE; + } + + if (t_size > 0 && state->dst_offset >= t_size) { + eot_expected = 1; + } + } else { + state->pkts_crc_fail++; + uart_tx(XNAK); + } + } else { + state->pkts_num_fail++; + uart_tx(XNAK); + } + } + + state->result = ret; + return ret; +} + +static int cmd_update_xmodem(void) +{ + xmodem_state_t state; + int ret; + uint32_t erase_addr; + int erase_ret; + char c; + + printf("Erasing update partition...\r\n"); +#ifdef DEBUG_FLASH + printf(" Address: 0x%08lX\r\n", (unsigned long)WOLFBOOT_PARTITION_UPDATE_ADDRESS); + printf(" Size: 0x%08lX (%lu bytes)\r\n", + (unsigned long)WOLFBOOT_PARTITION_SIZE, + (unsigned long)WOLFBOOT_PARTITION_SIZE); +#endif + + hal_flash_unlock(); + +#ifdef DEBUG_FLASH + /* Erase sector by sector with debug output */ + erase_addr = WOLFBOOT_PARTITION_UPDATE_ADDRESS; + while (erase_addr < WOLFBOOT_PARTITION_UPDATE_ADDRESS + WOLFBOOT_PARTITION_SIZE) { + printf(" Erasing sector at 0x%08lX...", (unsigned long)erase_addr); + fflush(stdout); + + erase_ret = hal_flash_erase(erase_addr, WOLFBOOT_SECTOR_SIZE); + if (erase_ret != 0) { + printf(" FAILED (%d)\r\n", erase_ret); + hal_flash_lock(); + return -1; + } + printf(" OK\r\n"); + erase_addr += WOLFBOOT_SECTOR_SIZE; + } +#else + (void)erase_addr; + (void)erase_ret; + hal_flash_erase(WOLFBOOT_PARTITION_UPDATE_ADDRESS, WOLFBOOT_PARTITION_SIZE); +#endif + + printf("Done.\r\n"); + printf("Waiting for XMODEM transfer...\r\n"); + printf("(Send file now using XMODEM-CRC protocol)\r\n"); + + /* Flush all printf output before starting XMODEM */ + fflush(stdout); + /* Wait for UART TX to complete */ + while (!(LPUART_STAT & LPUART_STAT_TC)) {} + + /* Drain any pending RX data before starting XMODEM */ + while (uart_getc(&c) > 0) {} /* Use ISR buffer, not hardware */ + + /* Small delay to ensure clean start */ + delay_ms(100); + + /* Block all printf output during XMODEM */ + xmodem_active = 1; + + /* Run the receive loop from RAM */ + ret = xmodem_receive_ram(&state); + + /* Re-enable printf output */ + xmodem_active = 0; + + hal_flash_lock(); + + /* Wait for sender to finish and drain any pending RX data. + * This prevents printf output from mixing with XMODEM retransmits. */ + delay_ms(3000); /* Wait for sender to give up */ + while (uart_read(&c) > 0) {} /* Drain RX buffer */ + + printf("\r\nTransfer %s\r\n", (ret == 0) ? "complete!" : "failed."); + printf("XMODEM stats: recv=%lu, crc_fail=%lu, num_fail=%lu, soh_fail=%lu, timeouts=%lu\r\n", + (unsigned long)state.pkts_received, (unsigned long)state.pkts_crc_fail, + (unsigned long)state.pkts_num_fail, (unsigned long)state.pkts_soh_fail, + (unsigned long)state.timeouts); + + if (ret == 0) { + uint32_t update_ver = wolfBoot_update_firmware_version(); + if (update_ver != 0) { + printf("New firmware version: %lu\r\n", (unsigned long)update_ver); + printf("Triggering update...\r\n"); + wolfBoot_update_trigger(); + printf("Reboot to apply update.\r\n"); + } else { + printf("Warning: No valid image detected\r\n"); + } + } + + led_red_off(); + return ret; +} + +/* ============== Console Commands ============== */ + +static int cmd_help(const char *args); +static int cmd_info(const char *args); +static int cmd_success(const char *args); +static int cmd_reboot(const char *args); +static int cmd_update(const char *args); +static int cmd_timestamp(const char *args); +static int cmd_trigger(const char *args); +static int cmd_status(const char *args); + +typedef struct { + int (*fn)(const char *args); + const char* name; + const char* help; +} console_cmd_t; + +static const console_cmd_t commands[] = { + {cmd_help, "help", "Show this help message"}, + {cmd_info, "info", "Display partition and key info"}, + {cmd_status, "status", "Show partition versions and states"}, + {cmd_success, "success", "Mark firmware as successful"}, + {cmd_trigger, "trigger", "Trigger update (if update image in flash)"}, + {cmd_update, "update", "Update firmware via XMODEM"}, + {cmd_timestamp, "timestamp", "Show current system time"}, + {cmd_reboot, "reboot", "Reboot the system"}, + {NULL, NULL, NULL} +}; + +static int cmd_help(const char *args) +{ + int i; + (void)args; + printf("\r\nAvailable commands:\r\n"); + for (i = 0; commands[i].name != NULL; i++) { + printf(" %s - %s\r\n", commands[i].name, commands[i].help); + } + return 0; +} + +static int cmd_info(const char *args) +{ + (void)args; + print_partition_info(); + print_keystore_info(); + return 0; +} + +static int cmd_success(const char *args) +{ + (void)args; + wolfBoot_success(); + printf("Firmware marked as successful.\r\n"); + return 0; +} + +static int cmd_timestamp(const char *args) +{ + (void)args; + printf("Current systick: %lu ms\r\n", (unsigned long)jiffies); + return 0; +} + +static int cmd_status(const char *args) +{ + uint32_t boot_ver, update_ver; + uint8_t boot_state, update_state; + int ret; + (void)args; + + boot_ver = wolfBoot_current_firmware_version(); + update_ver = wolfBoot_update_firmware_version(); + + printf("\r\n=== Partition Status ===\r\n"); + printf("Boot Partition: v%lu @ 0x%lX\r\n", + (unsigned long)boot_ver, (unsigned long)WOLFBOOT_PARTITION_BOOT_ADDRESS); + + ret = wolfBoot_get_partition_state(PART_BOOT, &boot_state); + if (ret == 0) { + printf(" State: %s (0x%02X)\r\n", + (boot_state == IMG_STATE_SUCCESS) ? "SUCCESS" : + (boot_state == IMG_STATE_TESTING) ? "TESTING" : + (boot_state == IMG_STATE_UPDATING) ? "UPDATING" : "NEW", + boot_state); + } else { + printf(" State: (no trailer)\r\n"); + } + + printf("Update Partition: v%lu @ 0x%lX\r\n", + (unsigned long)update_ver, (unsigned long)WOLFBOOT_PARTITION_UPDATE_ADDRESS); + + ret = wolfBoot_get_partition_state(PART_UPDATE, &update_state); + if (ret == 0) { + printf(" State: %s (0x%02X)\r\n", + (update_state == IMG_STATE_SUCCESS) ? "SUCCESS" : + (update_state == IMG_STATE_TESTING) ? "TESTING" : + (update_state == IMG_STATE_UPDATING) ? "UPDATING" : "NEW", + update_state); + } else { + printf(" State: (no trailer)\r\n"); + } + + if (update_ver > 0 && update_ver > boot_ver) { + printf("\r\nUpdate available! Use 'trigger' command to start update.\r\n"); + } + + return 0; +} + +static int cmd_trigger(const char *args) +{ + uint32_t update_ver; + (void)args; + + update_ver = wolfBoot_update_firmware_version(); + if (update_ver == 0) { + printf("No update image found in update partition.\r\n"); + return -1; + } + + printf("Update image version: %lu\r\n", (unsigned long)update_ver); + printf("Triggering update...\r\n"); + wolfBoot_update_trigger(); + printf("Update triggered. Use 'reboot' to start update.\r\n"); + return 0; +} + +static int cmd_reboot(const char *args) +{ + (void)args; + printf("Rebooting...\r\n"); + fflush(stdout); + delay_ms(100); /* Allow UART to flush */ + arch_reboot(); + return 0; +} + +static int cmd_update(const char *args) +{ + (void)args; + return cmd_update_xmodem(); +} + +static int parse_command(const char* cmd) +{ + int i; + for (i = 0; commands[i].name != NULL; i++) { + if (strcmp(cmd, commands[i].name) == 0) { + return commands[i].fn(NULL); + } + } + printf("Unknown command: %s\r\n", cmd); + printf("Type 'help' for available commands.\r\n"); + return -1; +} + +#define CMD_BUF_SIZE 64 + +static void console_loop(void) +{ + char cmd[CMD_BUF_SIZE]; + int idx; + char c; + + while (1) { + printf("\r\ncmd> "); + fflush(stdout); + idx = 0; + + while (idx < CMD_BUF_SIZE - 1) { + int ret = uart_getc(&c); + if (ret > 0) { + if (c == '\r' || c == '\n') { + printf("\r\n"); + break; + } else if (c == 0x08 || c == 0x7F) { /* Backspace */ + if (idx > 0) { + printf("\b \b"); + fflush(stdout); + idx--; + } + } else if (c >= 32 && c < 127) { + printf("%c", c); + fflush(stdout); + cmd[idx++] = c; + } + } + /* No delay - tight polling loop for responsive input */ + } + + cmd[idx] = '\0'; + if (idx > 0) { + parse_command(cmd); + } + } +} +#endif /* DEBUG_UART */ + +/* ============== Main Entry Point ============== */ + +void main(void) +{ + uint32_t version; + + /* Clocks (kept at 160 MHz when started by wolfBoot), caches and UART. + * SWT0 stays off: the IVT boot configuration word does not enable it. */ + hal_init(); + +#ifdef DEBUG_UART + /* Enable interrupt-based RX buffering for reliable XMODEM transfers */ + uart_rx_irq_enable(); + /* Disable stdout buffering to prevent delayed output during XMODEM */ + setvbuf(stdout, NULL, _IONBF, 0); +#endif + + /* Initialize test-app hardware */ + systick_init(); + led_init(); + + /* Enable interrupts */ + __asm__ volatile ("cpsie i"); + + /* Get current firmware version */ + version = wolfBoot_current_firmware_version(); + + /* Set LED based on version: Green for v1, Blue for v>1 */ + led_set_version(version); + +#ifdef DEBUG_UART + printf("\r\n"); + printf("========================================\r\n"); + printf("MCXE31B wolfBoot Test Application\r\n"); + printf("Copyright 2025-2026 wolfSSL Inc.\r\n"); + printf("========================================\r\n"); + printf("Firmware Version: %lu\r\n", (unsigned long)version); + + /* Auto-mark success for testing if version > 1 */ + if (version > 1) { + uint8_t state = 0; + wolfBoot_get_partition_state(PART_BOOT, &state); + if (state == IMG_STATE_TESTING) { + printf("Testing state detected, marking success...\r\n"); + wolfBoot_success(); + } + } + + /* Show initial info */ + print_partition_info(); + + printf("\r\nType 'help' for available commands.\r\n"); + + /* Enter interactive console */ + console_loop(); +#else + /* No UART - just blink LED */ + while (1) { + led_toggle_version(version); + delay_ms(500); + } +#endif +} + +/* ============== Syscalls for printf support ============== */ + +int _getpid(void) +{ + return 1; +} + +int _kill(int pid, int sig) +{ + (void)pid; + (void)sig; + return -1; +} + +void _exit(int status) +{ + _kill(status, -1); + while (1) {} +} + +int _read(int file, char *ptr, int len) +{ + (void)file; + (void)ptr; + (void)len; + return -1; +} + +int _write(int file, char *ptr, int len) +{ + (void)file; +#ifdef DEBUG_UART + /* Block text output during XMODEM to prevent protocol interference */ + if (!xmodem_active) { + uart_write(ptr, len); + } +#else + (void)ptr; +#endif + return len; +} + +int _close(int file) +{ + (void)file; + return -1; +} + +int _isatty(int file) +{ + (void)file; + return 1; +} + +int _lseek(int file, int ptr, int dir) +{ + (void)file; + (void)ptr; + (void)dir; + return 0; +} + +int _fstat(int file, struct stat *st) +{ + (void)file; + st->st_mode = S_IFCHR; + return 0; +} + +/* Back-end for malloc, used for printf */ +extern unsigned int _end; /* From linker script: end of BSS */ +extern unsigned int _end_stack; /* From linker script: end of RAM */ + +void *_sbrk(int incr) +{ + static unsigned char *heap = NULL; + unsigned char *prev_heap; + + if (heap == NULL) { + heap = (unsigned char *)&_end; + } + + prev_heap = heap; + + /* Align increment to 4 bytes */ + if (((incr >> 2) << 2) != incr) + incr = ((incr >> 2) + 1) << 2; + + /* Check we don't overflow into the stack */ + if ((heap + incr) > (unsigned char *)&_end_stack) { + return (void *)-1; + } + + heap += incr; + return prev_heap; +} + +#endif /* TARGET_mcxe31b */ diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index 3ad2ff3528..823d076cf2 100644 --- a/test-app/startup_arm.c +++ b/test-app/startup_arm.c @@ -76,6 +76,10 @@ extern void nxp_mcxe_enet_irq_handler(void); #endif #endif +#ifdef TARGET_mcxe31b +extern void isr_debug_uart(void); +#endif + #if defined(TARGET_va416x0) || defined(TARGET_lpc55s69) #define isr_systick SysTick_Handler #elif !defined(APP_HAS_SYSTICK) @@ -664,6 +668,11 @@ void (* const IV[])(void) = isr_empty, // DMA1_STREAM7_IRQ 47 +#elif defined(TARGET_mcxe31b) /* For NXP MCXE31B */ + /* IRQs 0-145 unused, 146 = LPUART5 (console) */ + [16 ... (16 + 145)] = isr_empty, + [16 + 146] = isr_debug_uart, + #elif defined(TARGET_va416x0) /* For Vorago VA416xx */ /* IRQ 0 through TXEV_IRQn (195), for 212 entries. wolfBoot points VTOR * at this table; see docs/Targets.md for the alignment it needs. */ diff --git a/tools/scripts/mcxe31b/e31b_debug.cmm b/tools/scripts/mcxe31b/e31b_debug.cmm new file mode 100644 index 0000000000..27254c03bf --- /dev/null +++ b/tools/scripts/mcxe31b/e31b_debug.cmm @@ -0,0 +1,101 @@ +;; e31b_debug.cmm +;; +;; Connect TRACE32 to the NXP MCXE31B (FRDM-MCXE31B) and halt the CPU at the +;; reset vector, then load the wolfBoot and test-app symbols. +;; No arguments: DO e31b_debug.cmm +;; +;; Board setup (UM12330): +;; - Lauterbach 10-pin cable on J14 (SWD/JTAG 2x5 header) +;; - JP5 SHORTED: disables the onboard MCU-Link SWD so it does not fight +;; the external probe on SWDIO/SWCLK +;; - The MCU-Link VCOM console (LPUART5, 115200 8N1) stays available +;; +;; Notes: +;; - TRACE32 R2024.09 has no MCXE31B entry. The S32K314 has the same debug +;; architecture (AHB-AP 4 = CM7_0, MDM-AP 6, SDA-AP 7) and flash +;; controller. Only SWD works on J14. +;; - SYStem.Up resets the chip and halts it at the reset vector, but often +;; reports a debug port time-out while the boot ROM runs. Attaching +;; afterwards finds the core halted. +;; - All output, including errors, is logged to ~~/e31b_debug.log +;; - The ELF files are loaded from the wolfBoot checkout this script is in. + +; wolfBoot root: three levels above this script +&basedir=OS.PPD()+"\..\..\.." + +AREA.OPEN A000 "~~/e31b_debug.log" /Create /NoFileCache +PRINT "e31b_debug.cmm " DATE.DATE() " " DATE.TIME() + +RESet +SYStem.RESet +SYStem.CPU S32K314-M7 +SYStem.CONFIG.DEBUGPORTTYPE SWD +SYStem.Option DUALPORT ON +SYStem.MemAccess DAP +Trace.DISable + +; reset and halt at the reset vector, retrying with a slow debug clock +SYStem.JtagClock 10MHz +PRINT "[1] SYStem.Up @ 10MHz" +ON ERROR CONTinue +SYStem.Up +ON ERROR inherit + +IF !SYStem.Up() +( + PRINT "[2] SYStem.Mode Attach @ 10MHz" + ON ERROR CONTinue + SYStem.Mode Attach + ON ERROR inherit +) + +IF !SYStem.Up() +( + PRINT "[3] SYStem.Up @ 1MHz" + SYStem.Down + SYStem.JtagClock 1MHz + ON ERROR CONTinue + SYStem.Up + ON ERROR inherit +) + +IF !SYStem.Up() +( + PRINT %ERROR "MCXE31B: connection failed (check JP5 shorted, cable on J14, board powered)" + AREA.CLOSE A000 + ENDDO +) + +IF STATE.RUN() +( + ON ERROR CONTinue + Break + ON ERROR inherit +) + +IF STATE.RUN() +( + PRINT %ERROR "MCXE31B: connected but CPU did not halt" + AREA.CLOSE A000 + ENDDO +) + +PRINT "MCXE31B halted, PC=0x"+FORMAT.HEX(8.,Register(PC))+" SP=0x"+FORMAT.HEX(8.,Register(SP)) +AREA.CLOSE A000 + +mode.hll + +IF OS.FILE("&basedir\wolfboot.elf") + data.load.elf "&basedir\wolfboot.elf" /nocode +IF OS.FILE("&basedir\test-app\image.elf") + data.load.elf "&basedir\test-app\image.elf" /nocode /noclear +; The ELF files hold the paths of the build machine. Look the sources up in +; this checkout instead, so it also works when TRACE32 runs on another host +; (e.g. Windows with the checkout in WSL). +; Sources are found by file name in these directories. +sYmbol.SourcePATH.SetBaseDir "&basedir" +&srcdirs="""&basedir"" ""&basedir\src"" ""&basedir\hal"" ""&basedir\test-app""" +&srcdirs="&srcdirs ""&basedir\lib\wolfssl\wolfcrypt\src""" +sYmbol.SourcePATH.Set &srcdirs + +ENDDO diff --git a/tools/scripts/mcxe31b/e31b_flash_factory_bin.cmm b/tools/scripts/mcxe31b/e31b_flash_factory_bin.cmm new file mode 100644 index 0000000000..8f67fb149d --- /dev/null +++ b/tools/scripts/mcxe31b/e31b_flash_factory_bin.cmm @@ -0,0 +1,106 @@ +;; e31b_flash_factory_bin.cmm +;; +;; Program factory.bin (wolfBoot + signed test app) into the NXP MCXE31B +;; (FRDM-MCXE31B) and erase the update partition and swap sector. +;; No arguments: DO e31b_flash_factory_bin.cmm +;; +;; Connects with e31b_debug.cmm (reset and halt), programs the image with the +;; TRACE32 S32K3 flash algorithm, verifies it, resets the board to boot and +;; detaches the debugger. +;; Range erased and programmed: 0x00400000--0x007D1FFF (IVT + bootloader, +;; boot partition, update partition, swap sector). factory.bin must fit in the +;; bootloader + boot partition without the partition's last two sectors +;; (0x00400000--0x005EBFFF): with NVM_FLASH_WRITEONCE wolfBoot keeps the boot +;; state there and erases those sectors when it updates it. The data flash at +;; 0x10000000 and the Secure BAF area from 0x007D4000 are left as is. +;; The addresses match config/examples/mcxe31b.config. Update them here if the +;; partition layout is changed. +;; +;; factory.bin starts with the Image Vector Table that the boot ROM looks for +;; at 0x00400000. Without its marker the boot ROM does not start wolfBoot, so +;; the marker is checked in the file before anything is erased. +;; Output is logged to ~~/e31b_flash_factory_bin.log +;; factory.bin is taken from the wolfBoot checkout this script is in. + +; This script's directory, and the wolfBoot root three levels above it +&scriptdir=OS.PPD() +&basedir="&scriptdir\..\..\.." +&file="&basedir\factory.bin" +&start=0x00400000 +&end=0x007D1FFF +; factory.bin (bootloader + boot partition) must end before the boot +; partition's two trailer sectors (0x5EC000--0x5EFFFF) +&maxsize=0x1EC000 +&ivt_marker=0x5AA55AA5 + +DO "&scriptdir\e31b_debug.cmm" + +AREA.OPEN A000 "~~/e31b_flash_factory_bin.log" /Create /NoFileCache +PRINT "e31b_flash_factory_bin.cmm " DATE.DATE() " " DATE.TIME() + +IF !SYStem.Up()||STATE.RUN() +( + PRINT %ERROR "not connected or CPU not halted, see ~~/e31b_debug.log" + AREA.CLOSE A000 + ENDDO +) +IF !OS.FILE("&file") +( + PRINT %ERROR "&file not found" + AREA.CLOSE A000 + ENDDO +) +&size=OS.FILE.SIZE("&file") +IF &size>&maxsize +( + PRINT %ERROR "&file does not fit before the boot partition trailer (0x5EC000)" + AREA.CLOSE A000 + ENDDO +) + +; Refuse an image the boot ROM would not start +Data.LOAD.Binary "&file" VM:&start +IF Data.Long(VM:&start)!=&ivt_marker +( + PRINT %ERROR "&file: no IVT marker at 0x00400000, not programming" + AREA.CLOSE A000 + ENDDO +) + +; The flash algorithm runs from the CM7_0 DTCM, which is ECC protected and +; must be written before it is read +Data.Set SD:0x20000000++0xFFFF %Long 0 + +; S32K3 flash algorithm, code flash without the Secure BAF area +FLASH.RESet +FLASH.Create 1. 0x00400000--0x007D3FFF 0x2000 TARGET Long +FLASH.TARGET 0x20000000 0x20002000 0x1000 ~~/demo/arm/flash/long/s32k3x4.bin + +; Sectors in range not covered by the file are erased +PRINT "programming &file (" FORMAT.Decimal(0.,&size) " bytes) at "+FORMAT.HEX(8.,&start) +FLASH.ReProgram &start--&end /Erase +Data.LOAD.Binary "&file" &start +FLASH.ReProgram OFF + +Data.LOAD.Binary "&file" &start /DIFF +IF FOUND() +( + PRINT %ERROR "verify FAILED, not resetting" + AREA.CLOSE A000 + ENDDO +) +PRINT "verify OK" +FLASH.RESet + +; Reset and boot +AREA.CLOSE A000 +DO "&scriptdir\e31b_debug.cmm" +AREA.OPEN A000 "~~/e31b_flash_factory_bin.log" /Append /NoFileCache +Go +; Detach: while attached, TRACE32 catches every reset at the reset vector, so +; a software reset (e.g. to start a firmware update) would leave the CPU halted +SYStem.Down +PRINT "done, board running, debugger detached" +AREA.CLOSE A000 + +ENDDO diff --git a/tools/scripts/mcxe31b/e31b_flash_update.cmm b/tools/scripts/mcxe31b/e31b_flash_update.cmm new file mode 100644 index 0000000000..cd90964d59 --- /dev/null +++ b/tools/scripts/mcxe31b/e31b_flash_update.cmm @@ -0,0 +1,92 @@ +;; e31b_flash_update.cmm +;; +;; Program the signed update image into the update partition of the NXP +;; MCXE31B (FRDM-MCXE31B). +;; No arguments: DO e31b_flash_update.cmm +;; +;; Connects with e31b_debug.cmm (reset and halt), programs the image with the +;; TRACE32 S32K3 flash algorithm, verifies it, resets the board to boot and +;; detaches the debugger. +;; Range erased and programmed: 0x005F0000--0x007CFFFF. Every other flash area +;; is left as is. The update is not triggered: use the test-app console +;; command "trigger" followed by "reboot". +;; The image must not reach the partition's last two sectors +;; (0x007CC000--0x007CFFFF): with NVM_FLASH_WRITEONCE wolfBoot keeps the update +;; state there and erases those sectors when the update is triggered, so the +;; image may be at most 0x1DC000 bytes. +;; The addresses match config/examples/mcxe31b.config. Update them here if the +;; partition layout is changed. +;; Output is logged to ~~/e31b_flash_update.log +;; The image is taken from the wolfBoot checkout this script is in. + +; This script's directory, and the wolfBoot root three levels above it +&scriptdir=OS.PPD() +&basedir="&scriptdir\..\..\.." +&file="&basedir\test-app\image_v2_signed.bin" +&start=0x005F0000 +&end=0x007CFFFF +; Partition size less the two trailer sectors +&maxsize=0x1DC000 + +DO "&scriptdir\e31b_debug.cmm" + +AREA.OPEN A000 "~~/e31b_flash_update.log" /Create /NoFileCache +PRINT "e31b_flash_update.cmm " DATE.DATE() " " DATE.TIME() + +IF !SYStem.Up()||STATE.RUN() +( + PRINT %ERROR "not connected or CPU not halted, see ~~/e31b_debug.log" + AREA.CLOSE A000 + ENDDO +) +IF !OS.FILE("&file") +( + PRINT %ERROR "&file not found" + AREA.CLOSE A000 + ENDDO +) +&size=OS.FILE.SIZE("&file") +IF &size>&maxsize +( + PRINT %ERROR "&file does not fit before the update partition trailer (0x1DC000 bytes)" + AREA.CLOSE A000 + ENDDO +) + +; The flash algorithm runs from the CM7_0 DTCM, which is ECC protected and +; must be written before it is read +Data.Set SD:0x20000000++0xFFFF %Long 0 + +; S32K3 flash algorithm, code flash without the Secure BAF area +FLASH.RESet +FLASH.Create 1. 0x00400000--0x007D3FFF 0x2000 TARGET Long +FLASH.TARGET 0x20000000 0x20002000 0x1000 ~~/demo/arm/flash/long/s32k3x4.bin + +; Sectors in range not covered by the file are erased +PRINT "programming &file (" FORMAT.Decimal(0.,&size) " bytes) at "+FORMAT.HEX(8.,&start) +FLASH.ReProgram &start--&end /Erase +Data.LOAD.Binary "&file" &start +FLASH.ReProgram OFF + +Data.LOAD.Binary "&file" &start /DIFF +IF FOUND() +( + PRINT %ERROR "verify FAILED" + AREA.CLOSE A000 + ENDDO +) +PRINT "verify OK" +FLASH.RESet + +; Reset and boot +AREA.CLOSE A000 +DO "&scriptdir\e31b_debug.cmm" +AREA.OPEN A000 "~~/e31b_flash_update.log" /Append /NoFileCache +Go +; Detach: while attached, TRACE32 catches every reset at the reset vector, so +; the software reset that starts the update would leave the CPU halted +SYStem.Down +PRINT "done, board running, debugger detached" +AREA.CLOSE A000 + +ENDDO From 0a5ed186ea0d913d6cbd89e7c853a02a0ff11413 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Wed, 18 Nov 2026 14:39:44 -0500 Subject: [PATCH 02/21] add wolfip support --- config/examples/mcxe31b.config | 27 +++++++ docs/Targets.md | 56 +++++++++++++- test-app/ARM-mcxe31b-wolfip.ld | 109 +++++++++++++++++++++++++++ test-app/Makefile | 23 ++++++ test-app/app_mcxe31b.c | 67 ++++++++++++++++ test-app/startup_arm.c | 18 ++++- test-app/wolfip_tftp_test.c | 36 ++++++--- test-app/wolfip_tftp_test.h | 8 +- tools/scripts/mcxe31b/e31b_debug.cmm | 3 + 9 files changed, 334 insertions(+), 13 deletions(-) create mode 100644 test-app/ARM-mcxe31b-wolfip.ld diff --git a/config/examples/mcxe31b.config b/config/examples/mcxe31b.config index e5e80d9221..35e5e51e59 100644 --- a/config/examples/mcxe31b.config +++ b/config/examples/mcxe31b.config @@ -34,6 +34,16 @@ CFLAGS_EXTRA+=-DWOLFBOOT_RAM_ECC_INIT # 8KB sectors WOLFBOOT_SECTOR_SIZE?=0x2000 +# Word-at-a-time memcpy/memset in src/string.c (bootloader and test-app). The +# Cortex-M7 loads unaligned words, so memcpy copies words even when source and +# destination alignments differ. +CFLAGS_EXTRA+=-DFAST_MEMCPY + +# The application's vector table follows the image header and is used in +# place (VTOR). The table must be 1 KB aligned, or the core fetches the vectors +# of some IRQs (e.g. EMAC, 105) from the wrong slots. +IMAGE_HEADER_SIZE?=1024 + # Memory layout (code flash 0x00400000 - 0x007FFFFF): # IVT + Bootloader: 0x00400000 - 0x0040FFFF (64 KB) # Boot Partition: 0x00410000 - 0x005EFFFF (1920 KB) @@ -49,6 +59,23 @@ WOLFBOOT_PARTITION_SWAP_ADDRESS?=0x7D0000 # Console on the MCU-Link VCOM port: LPUART5, PTE14 (TX) and PTE3 (RX), # 115200 8N1 +# wolfIP network test in the test-app (optional) +# Adds the "network" console command. Needs a wolfIP checkout, which provides +# the nxp_mcxe31b_emac driver (EMAC, RMII to the LAN8741 PHY). The driver is +# interrupt driven; NXP_MCXE31B_EMAC_IRQ=0 makes it poll the EMAC instead. +ENABLE_WOLFIP?=0 +WOLFBOOT_LIB_WOLFIP?=../lib/wolfip +NXP_MCXE31B_EMAC_IRQ?=1 +# By default the command acquires a DHCP lease and runs a TCP and UDP +# throughput server on port 9, driven from the host by +# tools/scripts/wolfip_speed.py. +WOLFIP_SPEED_TEST?=1 +# WOLFBOOT_TEST_TFTP=1 makes the command fetch a file over TFTP instead (it +# overrides WOLFIP_SPEED_TEST). The file must fit the 128 KB receive buffer. +# With both set to 0 the command only acquires a DHCP lease. +WOLFBOOT_TEST_TFTP?=0 +CFLAGS_EXTRA+=-DHOST_IP_STR='"192.168.50.1"' -DTFTP_FILENAME='"wolfip_test.bin"' + # Debugging options DEBUG?=0 DEBUG_SYMBOLS?=0 diff --git a/docs/Targets.md b/docs/Targets.md index 421296a6c5..4445cb763e 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -8090,6 +8090,13 @@ board. - The I-cache and D-cache are on while wolfBoot runs; flash program and erase invalidate the D-cache over the modified range. Both caches are cleaned and turned off before the jump to the application. The clocks stay at 160 MHz. +- `mcxe31b.config` sets `IMAGE_HEADER_SIZE=1024`, so the application starts + 1 KB into the boot partition. The application's vector table is used in + place, and with up to 163 entries it must be 1 KB aligned: with the default + 256-byte header the core fetches the vectors of some interrupts (the EMAC, + IRQ 105, among them) from the wrong slots. +- `mcxe31b.config` sets `FAST_MEMCPY`, the word-at-a-time `memcpy` and + `memset` of `src/string.c`, for wolfBoot and the test application. ### NXP MCXE31B: Memory Layout @@ -8128,6 +8135,50 @@ for later versions, and has the same console as the | `RAM_CODE` | **Required.** The flash program and erase routines run from DTCM, so the block being written is not read. The linker script checks this. | | `DEBUG_UART` | Console output on LPUART5 (MCU-Link VCOM). | +### NXP MCXE31B: Network test + +The test application can run a wolfIP throughput test or a DHCP and TFTP test +over the board's Ethernet port (RMII to a LAN8741A PHY, 50 MHz reference clock +from the board oscillator). This is optional and needs a wolfIP checkout, whose +`nxp_mcxe31b_emac` port is a standalone driver for the EMAC (Synopsys Ethernet +QoS), its clocks and pins, and the PHY (no vendor SDK). The test app builds it +interrupt driven (`NXP_MCXE31B_EMAC_IRQ=1`, EMAC IRQ 105 routed in +`test-app/startup_arm.c`); `NXP_MCXE31B_EMAC_IRQ=0` makes it poll the EMAC +instead. `test-app/ARM-mcxe31b-wolfip.ld` keeps the driver's descriptor rings +and frame buffers in the DTCM, which the core does not cache and the EMAC DMA +reaches through its backdoor port, and places the wolfIP stack state, with +9 KB TCP receive and transmit buffers per socket, and the TFTP receive buffer +in SRAM. SRAM is ECC protected: the reset handler clears all 320 KB of it +with 64-bit stores (`APP_RAM_ECC_INIT`) before it is used. Set +`ENABLE_WOLFIP=1` in `mcxe31b.config` and check the wolfIP path: + +```sh +ENABLE_WOLFIP?=1 +WOLFBOOT_LIB_WOLFIP?=../lib/wolfip +NXP_MCXE31B_EMAC_IRQ?=1 +WOLFIP_SPEED_TEST?=1 +WOLFBOOT_TEST_TFTP?=0 +``` + +Type `network` on the console to run the test. It works the same way as the +[MCXE247 network test](#nxp-mcxe247-network-test): by default it acquires a +DHCP lease and runs a TCP and UDP throughput server on port 9, driven from a +PC on the same network with `python3 tools/scripts/wolfip_speed.py `. +Ctrl-C on the console stops the server. Measured on the FRDM-MCXE31B at +160 MHz, 100 Mbit/s full duplex, interrupt driven, 10 s per test: + +| Test | Board receives | Board sends | +|------|----------------|-------------| +| TCP, one direction | 92.3 Mbit/s | 72.5 Mbit/s | +| TCP, both directions | 38.2 Mbit/s | 30.6 Mbit/s | +| UDP, one direction | 95.7 Mbit/s (no loss) | 78.5 Mbit/s | +| UDP, both directions | 71.8 Mbit/s | 71.8 Mbit/s | + +With `WOLFBOOT_TEST_TFTP=1` the command fetches `TFTP_FILENAME` from +`HOST_IP_STR` instead (128 KB at most) and prints its size and checksum +followed by `WOLFIP_TEST: PASS` or `WOLFIP_TEST: FAIL`. Both the interrupt +driven and the polled build pass this test. + ### NXP MCXE31B: Programming with Lauterbach TRACE32 Connect the 10-pin debug cable to J14 and short JP5 to disable the onboard @@ -8166,9 +8217,10 @@ Tested on the FRDM-MCXE31B: 1. Program `factory.bin` with `e31b_flash_factory_bin.cmm`. wolfBoot boots version 1 and the RGB LED is green. -2. Sign version 2 and program it with `e31b_flash_update.cmm`: +2. Sign version 2 with the configured 1 KB header and program it with + `e31b_flash_update.cmm`: ```sh - tools/keytools/sign --ecc256 --sha256 test-app/image.bin wolfboot_signing_private_key.der 2 + IMAGE_HEADER_SIZE=1024 tools/keytools/sign --ecc256 --sha256 test-app/image.bin wolfboot_signing_private_key.der 2 ``` 3. On the console, `status` shows the update. `trigger` then `reboot` swaps the partitions. Version 2 boots, finds the TESTING state and marks itself diff --git a/test-app/ARM-mcxe31b-wolfip.ld b/test-app/ARM-mcxe31b-wolfip.ld new file mode 100644 index 0000000000..6748917a63 --- /dev/null +++ b/test-app/ARM-mcxe31b-wolfip.ld @@ -0,0 +1,109 @@ +/* + * Linker script for the wolfBoot test application on NXP MCXE31B with wolfIP + * + * The application runs from the boot partition after the wolfBoot header. + * + * RAM is the 64 KB CM7_0 DTCM (0x20000000), which wolfBoot has already + * ECC-initialized: data, the RAM_CODE flash routines, .bss, heap and stack. + * The core does not cache the DTCM and the EMAC DMA reaches it through its + * backdoor port, so the EMAC driver's descriptor rings and frame buffers + * (its .bss) live there with no cache maintenance. + * + * The wolfIP stack state (sockets and their buffers) and the TFTP receive + * buffer go in the 320 KB SRAM (0x20400000), which the core caches and only + * the core uses. SRAM is ECC protected and holds no valid ECC after + * power-on. With APP_RAM_ECC_INIT the reset handler clears + * [_start_ecc_ram, _end_ecc_ram) with 64-bit stores (SRAM ECC words are 64 + * bits) before anything reads it; that clear is also what zeroes the SRAM + * section: it is not part of .bss. + */ + +MEMORY +{ + FLASH (rx) : ORIGIN = @WOLFBOOT_TEST_APP_ADDRESS@, LENGTH = @WOLFBOOT_TEST_APP_SIZE@ + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x10000 /* 64 KB DTCM */ + SRAM (rw) : ORIGIN = 0x20400000, LENGTH = 0x50000 /* 320 KB SRAM */ +} + +SECTIONS +{ + .text : + { + _start_text = .; + KEEP(*(.isr_vector)) + *(.text*) + *(.rodata*) + *(.init*) + *(.fini*) + . = ALIGN(4); + _end_text = .; + } > FLASH + + .keystore : + { + . = ALIGN(4); + KEEP(*(.keystore*)) + } > FLASH + + .edidx : + { + . = ALIGN(4); + *(.ARM.exidx*) + } > FLASH + + _stored_data = .; + + .data : AT (_stored_data) + { + _start_data = .; + KEEP(*(.data*)) + . = ALIGN(4); + KEEP(*(.ramcode)) + . = ALIGN(4); + _end_data = .; + } > RAM + + /* wolfIP and network test state, zero-filled by the APP_RAM_ECC_INIT + * clear. It comes before .bss so that these input sections are taken + * before the .bss* rule below. */ + .bss_sram (NOLOAD) : + { + . = ALIGN(8); + *wolfip.o(.bss .bss.* COMMON) + *wolftftp.o(.bss .bss.* COMMON) + *wolfip_tftp_test.o(.bss .bss.* COMMON) + . = ALIGN(8); + } > SRAM + + .bss (NOLOAD) : + { + _start_bss = .; + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + _end_bss = .; + __bss_end__ = .; + _end = .; + } > RAM + . = ALIGN(4); +} + +/* Partition info for libwolfboot */ +_wolfboot_partition_boot_address = @WOLFBOOT_PARTITION_BOOT_ADDRESS@; +_wolfboot_partition_size = @WOLFBOOT_PARTITION_SIZE@; +_wolfboot_partition_update_address = @WOLFBOOT_PARTITION_UPDATE_ADDRESS@; +_wolfboot_partition_swap_address = @WOLFBOOT_PARTITION_SWAP_ADDRESS@; + +/* Stack and heap indicators */ +_start_heap = _end; +_end_stack = ORIGIN(RAM) + LENGTH(RAM); + +/* SRAM cleared at reset with APP_RAM_ECC_INIT */ +_start_ecc_ram = ORIGIN(SRAM); +_end_ecc_ram = ORIGIN(SRAM) + LENGTH(SRAM); + +/* The EMAC driver's buffers must be in the DTCM */ +ASSERT(_end_bss <= ORIGIN(RAM) + LENGTH(RAM), "DTCM overflow") +/* Keep room above .bss for the stack and the heap used by printf */ +ASSERT(_end_stack - _end >= 0x2000, "not enough RAM left for the stack") diff --git a/test-app/Makefile b/test-app/Makefile index 65e2033580..6a09c6d303 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1860,6 +1860,29 @@ ifeq ($(ENABLE_WOLFIP),1) ifeq ($(WOLFIP_SPEED_TEST),1) CFLAGS+=-DNXP_MCXE_ENET_STATS=1 endif + else ifeq ($(TARGET),mcxe31b) + WOLFIP_PORT:=nxp_mcxe31b_emac + WOLFIP_PORT_OBJ:=nxp_mcxe31b_emac.o + # wolfIP state in SRAM, EMAC rings in the DTCM (ARM-mcxe31b-wolfip.ld) + LSCRIPT_TEMPLATE=ARM-mcxe31b-wolfip.ld + # Clear all of SRAM at reset, before it is read (ECC) + CFLAGS+=-DAPP_RAM_ECC_INIT + # NXP_MCXE31B_EMAC_IRQ=0 polls the EMAC instead of using its interrupt + NXP_MCXE31B_EMAC_IRQ?=1 + CFLAGS+=-DWOLFIP_PORT_MCXE31B_EMAC + CFLAGS+=-DNXP_MCXE31B_EMAC_IRQ=$(NXP_MCXE31B_EMAC_IRQ) + CFLAGS+=-DTFTP_RAM_MAX=0x20000U + # Six full segments of TCP buffering per socket + CFLAGS+=-DRXBUF_SIZE=9216 -DTXBUF_SIZE=9216 + # remove -ffreestanding so small memcpy's can be inlined + WOLFIP_CFLAGS_FILTEROUT:=-ffreestanding + # Take at most 8 frames per wolfIP_poll() so the app can drain a socket + # between batches + WOLFIP_CFLAGS_ADD:=-O2 -DWOLFIP_POLL_BUDGET=8 + # Driver cycle counters for the throughput test's CPU breakdown + ifeq ($(WOLFIP_SPEED_TEST),1) + CFLAGS+=-DNXP_MCXE31B_EMAC_STATS=1 + endif else WOLFIP_PORT:=nxp_fman WOLFIP_PORT_OBJ:=nxp_fman.o diff --git a/test-app/app_mcxe31b.c b/test-app/app_mcxe31b.c index abfd8671df..c42903e6da 100644 --- a/test-app/app_mcxe31b.c +++ b/test-app/app_mcxe31b.c @@ -37,6 +37,9 @@ #include "keystore.h" #include "target.h" #include "image.h" +#ifdef ENABLE_WOLFIP +#include "wolfip_tftp_test.h" +#endif #ifdef TARGET_mcxe31b @@ -50,12 +53,46 @@ /* ============== SysTick Timer ============== */ static volatile uint32_t jiffies = 0; +#ifdef ENABLE_WOLFIP +/* Upper 32 bits of the ms count, so the network timebase does not wrap */ +static volatile uint32_t jiffies_hi = 0; +#endif /* SysTick interrupt handler - called isr_systick to match startup_arm.c */ void isr_systick(void) { jiffies++; +#ifdef ENABLE_WOLFIP + if (jiffies == 0U) { + jiffies_hi++; + } +#endif +} + +#ifdef ENABLE_WOLFIP +/* Millisecond timebase for wolfip_tftp_test.c. 64 bits, so it is monotonic + * across the 32-bit wrap of jiffies. */ +uint64_t wolfip_test_get_ms(void) +{ + uint32_t hi, lo; + + /* Read again if SysTick carried into the upper word in between */ + do { + hi = jiffies_hi; + lo = jiffies; + } while (hi != jiffies_hi); + + return ((uint64_t)hi << 32) | lo; +} + +#ifndef DEBUG_UART +/* No console: the network test cannot be cancelled */ +int wolfip_test_abort(void) +{ + return 0; } +#endif +#endif static void delay_ms(uint32_t ms) { @@ -694,6 +731,9 @@ static int cmd_update(const char *args); static int cmd_timestamp(const char *args); static int cmd_trigger(const char *args); static int cmd_status(const char *args); +#ifdef ENABLE_WOLFIP +static int cmd_network(const char *args); +#endif typedef struct { int (*fn)(const char *args); @@ -709,6 +749,9 @@ static const console_cmd_t commands[] = { {cmd_trigger, "trigger", "Trigger update (if update image in flash)"}, {cmd_update, "update", "Update firmware via XMODEM"}, {cmd_timestamp, "timestamp", "Show current system time"}, +#ifdef ENABLE_WOLFIP + {cmd_network, "network", "Run the wolfIP network test"}, +#endif {cmd_reboot, "reboot", "Reboot the system"}, {NULL, NULL, NULL} }; @@ -827,6 +870,30 @@ static int cmd_update(const char *args) return cmd_update_xmodem(); } +#ifdef ENABLE_WOLFIP +static int cmd_network(const char *args) +{ + (void)args; + wolfip_tftp_test_report(); + return 0; +} + +#ifdef DEBUG_UART +/* Non-zero when Ctrl-C arrived on the console. Other input is discarded. */ +int wolfip_test_abort(void) +{ + char c; + int abort = 0; + + while (uart_getc(&c) > 0) { + if (c == 0x03) + abort = 1; + } + return abort; +} +#endif +#endif + static int parse_command(const char* cmd) { int i; diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index 823d076cf2..15607a08fa 100644 --- a/test-app/startup_arm.c +++ b/test-app/startup_arm.c @@ -78,6 +78,13 @@ extern void nxp_mcxe_enet_irq_handler(void); #ifdef TARGET_mcxe31b extern void isr_debug_uart(void); +/* MCXE31B EMAC common interrupt (IRQ 105) */ +#if defined(NXP_MCXE31B_EMAC_IRQ) && (NXP_MCXE31B_EMAC_IRQ == 1) +extern void nxp_mcxe31b_emac_irq_handler(void); +#define isr_emac nxp_mcxe31b_emac_irq_handler +#else +#define isr_emac isr_empty +#endif #endif #if defined(TARGET_va416x0) || defined(TARGET_lpc55s69) @@ -109,10 +116,18 @@ void isr_reset(void) "ldr r0, =_start_ecc_ram\n\t" "ldr r1, =_end_ecc_ram\n\t" "movs r2, #0\n\t" +#ifdef TARGET_mcxe31b + /* SRAM ECC words are 64 bits: [_start, _end) is 8-byte aligned */ + "movs r3, #0\n\t" +#endif "1:\n\t" "cmp r0, r1\n\t" "bhs 2f\n\t" +#ifdef TARGET_mcxe31b + "strd r2, r3, [r0], #8\n\t" +#else "str r2, [r0], #4\n\t" +#endif "b 1b\n\t" "2:\n\t" "b isr_reset_c\n\t" @@ -669,8 +684,9 @@ void (* const IV[])(void) = #elif defined(TARGET_mcxe31b) /* For NXP MCXE31B */ - /* IRQs 0-145 unused, 146 = LPUART5 (console) */ + /* IRQs 0-145 unused except 105 = EMAC, 146 = LPUART5 (console) */ [16 ... (16 + 145)] = isr_empty, + [16 + 105] = isr_emac, [16 + 146] = isr_debug_uart, #elif defined(TARGET_va416x0) /* For Vorago VA416xx */ diff --git a/test-app/wolfip_tftp_test.c b/test-app/wolfip_tftp_test.c index 18dab66b8a..9328503ac2 100644 --- a/test-app/wolfip_tftp_test.c +++ b/test-app/wolfip_tftp_test.c @@ -42,6 +42,7 @@ /* Port selection: * WOLFIP_PORT_ENETC -> LS1028A ENETC * WOLFIP_PORT_MCXE_ENET -> MCXE247 ENET + * WOLFIP_PORT_MCXE31B_EMAC -> MCXE31B EMAC * else QorIQ FMan * Driver entry points are wrapped so the bring-up code below is port-agnostic. */ #if defined(WOLFIP_PORT_ENETC) @@ -60,6 +61,23 @@ #define WOLFIP_NETDEV_LINK_UP nxp_mcxe_enet_link_up #define WOLFIP_NETDEV_STOP nxp_mcxe_enet_stop #define WOLFIP_NETDEV_NAME "MCXE247 ENET" +#if NXP_MCXE_ENET_STATS +#define WOLFIP_NETDEV_STATS struct nxp_mcxe_enet_stats +#define WOLFIP_NETDEV_STATS_GET nxp_mcxe_enet_stats_get +#define WOLFIP_NETDEV_STATS_RESET nxp_mcxe_enet_stats_reset +#endif +#elif defined(WOLFIP_PORT_MCXE31B_EMAC) +#include "nxp_mcxe31b_emac.h" +#define WOLFIP_NETDEV_INIT nxp_mcxe31b_emac_init +#define WOLFIP_NETDEV_PHY_ADDR nxp_mcxe31b_emac_phy_addr +#define WOLFIP_NETDEV_PHY_READ nxp_mcxe31b_emac_phy_read +#define WOLFIP_NETDEV_LINK_UP nxp_mcxe31b_emac_link_up +#define WOLFIP_NETDEV_NAME "MCXE31B EMAC" +#if NXP_MCXE31B_EMAC_STATS +#define WOLFIP_NETDEV_STATS struct nxp_mcxe31b_emac_stats +#define WOLFIP_NETDEV_STATS_GET nxp_mcxe31b_emac_stats_get +#define WOLFIP_NETDEV_STATS_RESET nxp_mcxe31b_emac_stats_reset +#endif #else #include "nxp_fman.h" #define WOLFIP_NETDEV_INIT nxp_fman_init @@ -91,10 +109,10 @@ #endif /* Millisecond clock from a free-running counter, self-contained (no bootloader - * symbol). wolfIP timers are coarse so exactness is moot. The MCXE247 comes - * first: a host build of the unit tests (which defines + * symbol). wolfIP timers are coarse so exactness is moot. The Cortex-M + * targets come first: a host build of the unit tests (which defines * WOLFIP_PORT_MCXE_ENET) may run on an AArch64 machine. */ -#if defined(WOLFIP_PORT_MCXE_ENET) +#if defined(WOLFIP_TEST_APP_TIMEBASE) /* 1 ms SysTick count, kept by the target app. */ #define SYST_CVR_REG (*(volatile uint32_t *)0xE000E018UL) @@ -520,13 +538,13 @@ static int run_tftp_fetch(struct wolfIP *s) /* How often the server checks for Ctrl-C on the console */ #define SPEED_ABORT_POLL_MS 100U -#ifdef WOLFIP_PORT_MCXE_ENET +#ifdef WOLFIP_TEST_APP_TIMEBASE #define SPEED_ABORT() wolfip_test_abort() #else #define SPEED_ABORT() 0 #endif -#if defined(WOLFIP_PORT_MCXE_ENET) && NXP_MCXE_ENET_STATS +#ifdef WOLFIP_NETDEV_STATS /* The driver enables the DWT cycle counter */ #define SPEED_PROFILE 1 #define SPEED_CYCLES() (*(volatile uint32_t *)0xE0001004UL) @@ -578,7 +596,7 @@ static struct wolfIP_sockaddr_in speed_peer; static uint8_t speed_rxbuf[SPEED_UDP_MAX]; static uint8_t speed_txbuf[SPEED_UDP_MAX]; #if SPEED_PROFILE -static struct nxp_mcxe_enet_stats speed_drv; +static WOLFIP_NETDEV_STATS speed_drv; #endif static void speed_put32(uint8_t *p, uint32_t v) @@ -687,7 +705,7 @@ static void speed_window_start(uint64_t now) speed.start_ms = now; speed.started = 1U; #if SPEED_PROFILE - nxp_mcxe_enet_stats_reset(); + WOLFIP_NETDEV_STATS_RESET(); #endif } @@ -741,7 +759,7 @@ static void speed_stop(uint64_t now) speed_ended_idx = (speed_ended_idx + 1U) % SPEED_ENDED_NUM; } #if SPEED_PROFILE - nxp_mcxe_enet_stats_get(&speed_drv); + WOLFIP_NETDEV_STATS_GET(&speed_drv); #endif speed_print(); } @@ -774,7 +792,7 @@ static void speed_reply(struct wolfIP *s, const struct wolfIP_sockaddr_in *to, speed_put32(r + 112, speed.test_num); #if SPEED_PROFILE if (speed.active != 0U) - nxp_mcxe_enet_stats_get(&speed_drv); + WOLFIP_NETDEV_STATS_GET(&speed_drv); speed_put32(r + 12, speed_drv.core_hz); speed_put32(r + 24, speed_drv.rx_frames); speed_put32(r + 28, speed_drv.tx_frames); diff --git a/test-app/wolfip_tftp_test.h b/test-app/wolfip_tftp_test.h index 4816205fbf..ab23844035 100644 --- a/test-app/wolfip_tftp_test.h +++ b/test-app/wolfip_tftp_test.h @@ -34,7 +34,13 @@ int wolfip_tftp_test_run(void); * Convenience wrapper so each target app's main() is a single call. */ void wolfip_tftp_test_report(void); -#ifdef WOLFIP_PORT_MCXE_ENET +/* Cortex-M ports without a free-running timer of their own take the time + * and the stop request from the target app */ +#if defined(WOLFIP_PORT_MCXE_ENET) || defined(WOLFIP_PORT_MCXE31B_EMAC) +#define WOLFIP_TEST_APP_TIMEBASE +#endif + +#ifdef WOLFIP_TEST_APP_TIMEBASE /* Milliseconds since start, monotonic. Provided by the target app. */ uint64_t wolfip_test_get_ms(void); diff --git a/tools/scripts/mcxe31b/e31b_debug.cmm b/tools/scripts/mcxe31b/e31b_debug.cmm index 27254c03bf..67df602835 100644 --- a/tools/scripts/mcxe31b/e31b_debug.cmm +++ b/tools/scripts/mcxe31b/e31b_debug.cmm @@ -96,6 +96,9 @@ IF OS.FILE("&basedir\test-app\image.elf") sYmbol.SourcePATH.SetBaseDir "&basedir" &srcdirs="""&basedir"" ""&basedir\src"" ""&basedir\hal"" ""&basedir\test-app""" &srcdirs="&srcdirs ""&basedir\lib\wolfssl\wolfcrypt\src""" +; wolfIP and its MCXE31B port (test-app built with ENABLE_WOLFIP=1) +&srcdirs="&srcdirs ""&basedir\lib\wolfip\src"" ""&basedir\lib\wolfip\src\tftp""" +&srcdirs="&srcdirs ""&basedir\lib\wolfip\src\port\nxp_mcxe31b_emac""" sYmbol.SourcePATH.Set &srcdirs ENDDO From 4d279fe9948baccac626f8d6a18e9c73113153e6 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 23 Nov 2026 13:23:17 -0500 Subject: [PATCH 03/21] wolfip perf improvements --- docs/Targets.md | 25 ++++++++++++------ test-app/ARM-mcxe31b-wolfip.ld | 48 +++++++++++++++++++++++++++++----- test-app/Makefile | 9 ++++--- test-app/startup_arm.c | 28 ++++++++++++++++++++ 4 files changed, 91 insertions(+), 19 deletions(-) diff --git a/docs/Targets.md b/docs/Targets.md index 4445cb763e..4c1923f76f 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -8147,10 +8147,15 @@ interrupt driven (`NXP_MCXE31B_EMAC_IRQ=1`, EMAC IRQ 105 routed in instead. `test-app/ARM-mcxe31b-wolfip.ld` keeps the driver's descriptor rings and frame buffers in the DTCM, which the core does not cache and the EMAC DMA reaches through its backdoor port, and places the wolfIP stack state, with -9 KB TCP receive and transmit buffers per socket, and the TFTP receive buffer -in SRAM. SRAM is ECC protected: the reset handler clears all 320 KB of it -with 64-bit stores (`APP_RAM_ECC_INIT`) before it is used. Set -`ENABLE_WOLFIP=1` in `mcxe31b.config` and check the wolfIP path: +9 KB TCP receive and transmit buffers per socket, the TFTP receive buffer and +libwolfboot's 8 KB flash sector buffer (`NVM_CACHE`) in SRAM. SRAM is ECC +protected: the reset handler clears all 320 KB of it with 64-bit stores +(`APP_RAM_ECC_INIT`) before it is used. The hottest network code (8.7 KB: +runs from the ITCM: the reset handler clears the ITCM and copies it there +(`APP_RAMCODE_ITCM`). wolfIP takes at most 16 frames per `wolfIP_poll()` +(`WOLFIP_POLL_BUDGET=16`). The driver uses 8 transmit and 4 receive +descriptors (19 KB of DTCM). +Set `ENABLE_WOLFIP=1` in `mcxe31b.config` and check the wolfIP path: ```sh ENABLE_WOLFIP?=1 @@ -8169,10 +8174,14 @@ Ctrl-C on the console stops the server. Measured on the FRDM-MCXE31B at | Test | Board receives | Board sends | |------|----------------|-------------| -| TCP, one direction | 92.3 Mbit/s | 72.5 Mbit/s | -| TCP, both directions | 38.2 Mbit/s | 30.6 Mbit/s | -| UDP, one direction | 95.7 Mbit/s (no loss) | 78.5 Mbit/s | -| UDP, both directions | 71.8 Mbit/s | 71.8 Mbit/s | +| TCP, one direction | 83-89 Mbit/s | 86.1 Mbit/s | +| TCP, both directions | 52.4-53.0 Mbit/s | 39.5 Mbit/s | +| UDP, one direction | 95.7 Mbit/s (no loss) | 95.7 Mbit/s | +| UDP, both directions | 93.5-95.3 Mbit/s | 95.7 Mbit/s | + +UDP in one direction runs at the line rate, and both directions at once come +close to it: the board drops 0.4-2.4% of what it receives. TCP is limited by the +CPU. With `WOLFBOOT_TEST_TFTP=1` the command fetches `TFTP_FILENAME` from `HOST_IP_STR` instead (128 KB at most) and prints its size and checksum diff --git a/test-app/ARM-mcxe31b-wolfip.ld b/test-app/ARM-mcxe31b-wolfip.ld index 6748917a63..49dc707548 100644 --- a/test-app/ARM-mcxe31b-wolfip.ld +++ b/test-app/ARM-mcxe31b-wolfip.ld @@ -9,24 +9,51 @@ * backdoor port, so the EMAC driver's descriptor rings and frame buffers * (its .bss) live there with no cache maintenance. * - * The wolfIP stack state (sockets and their buffers) and the TFTP receive - * buffer go in the 320 KB SRAM (0x20400000), which the core caches and only - * the core uses. SRAM is ECC protected and holds no valid ECC after + * The wolfIP stack state (sockets and their buffers), the TFTP receive + * buffer and libwolfboot's flash sector buffer (NVM_CACHE) go in the 320 KB + * SRAM (0x20400000), which the core caches and only the core uses. SRAM is + * ECC protected and holds no valid ECC after * power-on. With APP_RAM_ECC_INIT the reset handler clears * [_start_ecc_ram, _end_ecc_ram) with 64-bit stores (SRAM ECC words are 64 * bits) before anything reads it; that clear is also what zeroes the SRAM * section: it is not part of .bss. + * + * The hottest code runs from the 32 KB ITCM (.ramcode_itcm). The first + * 1 KB of the ITCM is left unused, so that writes through a NULL pointer do + * not land on code. */ MEMORY { FLASH (rx) : ORIGIN = @WOLFBOOT_TEST_APP_ADDRESS@, LENGTH = @WOLFBOOT_TEST_APP_SIZE@ + ITCM (rx) : ORIGIN = 0x00000400, LENGTH = 0x7C00 /* 31 KB ITCM */ RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x10000 /* 64 KB DTCM */ SRAM (rw) : ORIGIN = 0x20400000, LENGTH = 0x50000 /* 320 KB SRAM */ } SECTIONS { + /* Hot code run from the ITCM. It comes first so that these input + * sections are taken before the .text* rule below. */ + .ramcode_itcm : AT (_stored_ramcode_itcm) + { + . = ALIGN(8); + _start_ramcode_itcm = .; + KEEP(*string.o(.ramcode)) + *string.o(.text.memset .text.memcmp) + *wolfip.o(.text.csum_add .text.transport_checksum) + *wolfip.o(.text.iphdr_set_checksum .text.wolfIP_poll) + *wolfip.o(.text.fifo_next .text.fifo_peek .text.fifo_push) + *wolfip.o(.text.fifo_pop .text.fifo_can_push_len) + *wolfip.o(.text.tcp_snd_nxt .text.tcp_calc_win .text.wolfIP_sock_send) + *wolfip.o(.text.wolfIP_route_lookup_internal .text.arp_neighbor_index) + *nxp_mcxe31b_emac.o(.text.eth_poll .text.eth_send) + *nxp_mcxe31b_emac.o(.text.eth_poll_stats .text.eth_send_stats) + *nxp_mcxe31b_emac.o(.text.nxp_mcxe31b_emac_irq_handler) + . = ALIGN(8); + _end_ramcode_itcm = .; + } > ITCM + .text : { _start_text = .; @@ -51,7 +78,9 @@ SECTIONS *(.ARM.exidx*) } > FLASH - _stored_data = .; + _stored_ramcode_itcm = ALIGN(8); + + _stored_data = _stored_ramcode_itcm + SIZEOF(.ramcode_itcm); .data : AT (_stored_data) { @@ -63,15 +92,16 @@ SECTIONS _end_data = .; } > RAM - /* wolfIP and network test state, zero-filled by the APP_RAM_ECC_INIT - * clear. It comes before .bss so that these input sections are taken - * before the .bss* rule below. */ + /* wolfIP and network test state and the libwolfboot sector buffer, + * zero-filled by the APP_RAM_ECC_INIT clear. It comes before .bss so + * that these input sections are taken before the .bss* rule below. */ .bss_sram (NOLOAD) : { . = ALIGN(8); *wolfip.o(.bss .bss.* COMMON) *wolftftp.o(.bss .bss.* COMMON) *wolfip_tftp_test.o(.bss .bss.* COMMON) + *libwolfboot.o(.bss.NVM_CACHE) . = ALIGN(8); } > SRAM @@ -99,6 +129,10 @@ _wolfboot_partition_swap_address = @WOLFBOOT_PARTITION_SWAP_ADDRESS@; _start_heap = _end; _end_stack = ORIGIN(RAM) + LENGTH(RAM); +/* ITCM cleared at reset with APP_RAMCODE_ITCM, before the code is copied */ +_start_ecc_itcm = 0x00000000; +_end_ecc_itcm = 0x00008000; + /* SRAM cleared at reset with APP_RAM_ECC_INIT */ _start_ecc_ram = ORIGIN(SRAM); _end_ecc_ram = ORIGIN(SRAM) + LENGTH(SRAM); diff --git a/test-app/Makefile b/test-app/Makefile index 6a09c6d303..1f82e911c0 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1867,18 +1867,19 @@ ifeq ($(ENABLE_WOLFIP),1) LSCRIPT_TEMPLATE=ARM-mcxe31b-wolfip.ld # Clear all of SRAM at reset, before it is read (ECC) CFLAGS+=-DAPP_RAM_ECC_INIT + # Hot code in the ITCM (.ramcode_itcm in ARM-mcxe31b-wolfip.ld) + CFLAGS+=-DAPP_RAMCODE_ITCM # NXP_MCXE31B_EMAC_IRQ=0 polls the EMAC instead of using its interrupt NXP_MCXE31B_EMAC_IRQ?=1 CFLAGS+=-DWOLFIP_PORT_MCXE31B_EMAC CFLAGS+=-DNXP_MCXE31B_EMAC_IRQ=$(NXP_MCXE31B_EMAC_IRQ) CFLAGS+=-DTFTP_RAM_MAX=0x20000U - # Six full segments of TCP buffering per socket + # Six full segments of TCP buffering per socket. CFLAGS+=-DRXBUF_SIZE=9216 -DTXBUF_SIZE=9216 # remove -ffreestanding so small memcpy's can be inlined WOLFIP_CFLAGS_FILTEROUT:=-ffreestanding - # Take at most 8 frames per wolfIP_poll() so the app can drain a socket - # between batches - WOLFIP_CFLAGS_ADD:=-O2 -DWOLFIP_POLL_BUDGET=8 + # Take at most 16 frames per wolfIP_poll() + WOLFIP_CFLAGS_ADD:=-O2 -DWOLFIP_POLL_BUDGET=16 # Driver cycle counters for the throughput test's CPU breakdown ifeq ($(WOLFIP_SPEED_TEST),1) CFLAGS+=-DNXP_MCXE31B_EMAC_STATS=1 diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index 15607a08fa..f8625aa3c8 100644 --- a/test-app/startup_arm.c +++ b/test-app/startup_arm.c @@ -28,6 +28,12 @@ extern unsigned int _start_bss; extern unsigned int _end_bss; extern unsigned int _end_stack; extern unsigned int _start_heap; +#ifdef APP_RAMCODE_ITCM +/* Hot code copied from flash to the ITCM at reset */ +extern unsigned int _stored_ramcode_itcm; +extern unsigned int _start_ramcode_itcm; +extern unsigned int _end_ramcode_itcm; +#endif #ifdef APP_RAMCODE_L /* Hot code copied from flash to a second RAM region at reset, and .bss * placed there */ @@ -130,6 +136,18 @@ void isr_reset(void) #endif "b 1b\n\t" "2:\n\t" +#ifdef APP_RAMCODE_ITCM + /* The ITCM holds no valid ECC either: clear it before the hot + * code is copied in, also with 64-bit stores */ + "ldr r0, =_start_ecc_itcm\n\t" + "ldr r1, =_end_ecc_itcm\n\t" + "3:\n\t" + "cmp r0, r1\n\t" + "bhs 4f\n\t" + "strd r2, r3, [r0], #8\n\t" + "b 3b\n\t" + "4:\n\t" +#endif "b isr_reset_c\n\t" ); } @@ -153,6 +171,16 @@ void isr_reset(void) dst++; src++; } +#ifdef APP_RAMCODE_ITCM + src = (unsigned int *) &_stored_ramcode_itcm; + dst = (unsigned int *) &_start_ramcode_itcm; + while (dst < (unsigned int *)&_end_ramcode_itcm) { + *dst = *src; + dst++; + src++; + } + __asm__ volatile ("dsb\n\tisb" ::: "memory"); +#endif #ifdef APP_RAMCODE_L src = (unsigned int *) &_stored_ramcode_l; dst = (unsigned int *) &_start_ramcode_l; From 189821ff561fbbdee4ad2be7d6aecdce32ff331f Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 23 Nov 2026 14:07:01 -0500 Subject: [PATCH 04/21] rename from e31b_emac to mcxe_emac for more general use --- config/examples/mcxe31b.config | 6 +++--- docs/Targets.md | 15 ++++++++------- hal/mcxe31b.c | 6 +++--- hal/mcxe31b.h | 6 ++++-- test-app/ARM-mcxe31b-wolfip.ld | 6 +++--- test-app/Makefile | 16 ++++++++-------- test-app/startup_arm.c | 6 +++--- test-app/wolfip_tftp_test.c | 22 +++++++++++----------- test-app/wolfip_tftp_test.h | 2 +- tools/scripts/mcxe31b/e31b_debug.cmm | 2 +- 10 files changed, 45 insertions(+), 42 deletions(-) diff --git a/config/examples/mcxe31b.config b/config/examples/mcxe31b.config index 35e5e51e59..8849fb0a32 100644 --- a/config/examples/mcxe31b.config +++ b/config/examples/mcxe31b.config @@ -61,11 +61,11 @@ WOLFBOOT_PARTITION_SWAP_ADDRESS?=0x7D0000 # wolfIP network test in the test-app (optional) # Adds the "network" console command. Needs a wolfIP checkout, which provides -# the nxp_mcxe31b_emac driver (EMAC, RMII to the LAN8741 PHY). The driver is -# interrupt driven; NXP_MCXE31B_EMAC_IRQ=0 makes it poll the EMAC instead. +# the nxp_mcxe_emac driver (EMAC, RMII to the LAN8741 PHY). The driver is +# interrupt driven; NXP_MCXE_EMAC_IRQ=0 makes it poll the EMAC instead. ENABLE_WOLFIP?=0 WOLFBOOT_LIB_WOLFIP?=../lib/wolfip -NXP_MCXE31B_EMAC_IRQ?=1 +NXP_MCXE_EMAC_IRQ?=1 # By default the command acquires a DHCP lease and runs a TCP and UDP # throughput server on port 9, driven from the host by # tools/scripts/wolfip_speed.py. diff --git a/docs/Targets.md b/docs/Targets.md index 4c1923f76f..d4b3f7f27d 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -8140,10 +8140,10 @@ for later versions, and has the same console as the The test application can run a wolfIP throughput test or a DHCP and TFTP test over the board's Ethernet port (RMII to a LAN8741A PHY, 50 MHz reference clock from the board oscillator). This is optional and needs a wolfIP checkout, whose -`nxp_mcxe31b_emac` port is a standalone driver for the EMAC (Synopsys Ethernet +`nxp_mcxe_emac` port is a standalone driver for the EMAC (Synopsys Ethernet QoS), its clocks and pins, and the PHY (no vendor SDK). The test app builds it -interrupt driven (`NXP_MCXE31B_EMAC_IRQ=1`, EMAC IRQ 105 routed in -`test-app/startup_arm.c`); `NXP_MCXE31B_EMAC_IRQ=0` makes it poll the EMAC +interrupt driven (`NXP_MCXE_EMAC_IRQ=1`, EMAC IRQ 105 routed in +`test-app/startup_arm.c`); `NXP_MCXE_EMAC_IRQ=0` makes it poll the EMAC instead. `test-app/ARM-mcxe31b-wolfip.ld` keeps the driver's descriptor rings and frame buffers in the DTCM, which the core does not cache and the EMAC DMA reaches through its backdoor port, and places the wolfIP stack state, with @@ -8160,7 +8160,7 @@ Set `ENABLE_WOLFIP=1` in `mcxe31b.config` and check the wolfIP path: ```sh ENABLE_WOLFIP?=1 WOLFBOOT_LIB_WOLFIP?=../lib/wolfip -NXP_MCXE31B_EMAC_IRQ?=1 +NXP_MCXE_EMAC_IRQ?=1 WOLFIP_SPEED_TEST?=1 WOLFBOOT_TEST_TFTP?=0 ``` @@ -8170,11 +8170,12 @@ Type `network` on the console to run the test. It works the same way as the DHCP lease and runs a TCP and UDP throughput server on port 9, driven from a PC on the same network with `python3 tools/scripts/wolfip_speed.py `. Ctrl-C on the console stops the server. Measured on the FRDM-MCXE31B at -160 MHz, 100 Mbit/s full duplex, interrupt driven, 10 s per test: +160 MHz, 100 Mbit/s full duplex, interrupt driven, 10 s per test, with the +script run by Windows Python on a Windows PC on an otherwise idle network: | Test | Board receives | Board sends | |------|----------------|-------------| -| TCP, one direction | 83-89 Mbit/s | 86.1 Mbit/s | +| TCP, one direction | 88-90 Mbit/s | 86 Mbit/s | | TCP, both directions | 52.4-53.0 Mbit/s | 39.5 Mbit/s | | UDP, one direction | 95.7 Mbit/s (no loss) | 95.7 Mbit/s | | UDP, both directions | 93.5-95.3 Mbit/s | 95.7 Mbit/s | @@ -8184,7 +8185,7 @@ close to it: the board drops 0.4-2.4% of what it receives. TCP is limited by the CPU. With `WOLFBOOT_TEST_TFTP=1` the command fetches `TFTP_FILENAME` from -`HOST_IP_STR` instead (128 KB at most) and prints its size and checksum +`HOST_IP_STR` instead (40 KB at most) and prints its size and checksum followed by `WOLFIP_TEST: PASS` or `WOLFIP_TEST: FAIL`. Both the interrupt driven and the polled build pass this test. diff --git a/hal/mcxe31b.c b/hal/mcxe31b.c index c0ac77d773..028db819b6 100644 --- a/hal/mcxe31b.c +++ b/hal/mcxe31b.c @@ -104,9 +104,9 @@ static void delay_cycles(uint32_t n) } /* Switch the system clocks from FIRC 48 MHz to the PLL using the RM - * "Option A" (high performance) configuration: FXOSC 16 MHz -> PLL VCO - * 960 MHz -> ODIV2 480 MHz -> PHI0 160 MHz. On failure the system stays - * on FIRC. */ + * "Option A" (high performance) configuration (MCXEP172M160FB0RM Rev. 5, + * Table 134): FXOSC 16 MHz -> PLL VCO 960 MHz -> ODIV2 480 MHz -> PHI0 + * 160 MHz. On failure the system stays on FIRC. */ static int clock_init(void) { /* MUX_0 dividers (DIV + 1): CORE 160, AIPS_PLAT 80, AIPS_SLOW 40, diff --git a/hal/mcxe31b.h b/hal/mcxe31b.h index 743b4d6331..2e0e6f4b21 100644 --- a/hal/mcxe31b.h +++ b/hal/mcxe31b.h @@ -19,7 +19,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA * * Register definitions for NXP MCXE31B (Cortex-M7, 4MB C40ASF flash). - * Register offsets and fields from the MCXE31x Reference Manual Rev. 3. + * Register offsets and fields from the MCX E3 Reference Manual + * (MCXEP172M160FB0RM, Rev. 5). */ #ifndef MCXE31B_H @@ -30,7 +31,8 @@ /* ============== Clock ============== */ /* The boot ROM (Secure BAF) leaves the core on FIRC 48 MHz. hal_init() - * switches to the PLL with the RM "Option A" (high performance) dividers: + * switches to the PLL with the RM "Option A" (high performance) dividers + * (MCXEP172M160FB0RM Rev. 5, 23.7.2.1, Table 134): * CORE_CLK 160 MHz, AIPS_PLAT_CLK 80 MHz, AIPS_SLOW_CLK 40 MHz (LPUART1..7 * functional clock), HSE_CLK 80 MHz. */ #define FIRC_FREQ 48000000UL diff --git a/test-app/ARM-mcxe31b-wolfip.ld b/test-app/ARM-mcxe31b-wolfip.ld index 49dc707548..f4c041a11d 100644 --- a/test-app/ARM-mcxe31b-wolfip.ld +++ b/test-app/ARM-mcxe31b-wolfip.ld @@ -47,9 +47,9 @@ SECTIONS *wolfip.o(.text.fifo_pop .text.fifo_can_push_len) *wolfip.o(.text.tcp_snd_nxt .text.tcp_calc_win .text.wolfIP_sock_send) *wolfip.o(.text.wolfIP_route_lookup_internal .text.arp_neighbor_index) - *nxp_mcxe31b_emac.o(.text.eth_poll .text.eth_send) - *nxp_mcxe31b_emac.o(.text.eth_poll_stats .text.eth_send_stats) - *nxp_mcxe31b_emac.o(.text.nxp_mcxe31b_emac_irq_handler) + *nxp_mcxe_emac.o(.text.eth_poll .text.eth_send) + *nxp_mcxe_emac.o(.text.eth_poll_stats .text.eth_send_stats) + *nxp_mcxe_emac.o(.text.nxp_mcxe_emac_irq_handler) . = ALIGN(8); _end_ramcode_itcm = .; } > ITCM diff --git a/test-app/Makefile b/test-app/Makefile index 1f82e911c0..d7e5c4fba3 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1861,19 +1861,19 @@ ifeq ($(ENABLE_WOLFIP),1) CFLAGS+=-DNXP_MCXE_ENET_STATS=1 endif else ifeq ($(TARGET),mcxe31b) - WOLFIP_PORT:=nxp_mcxe31b_emac - WOLFIP_PORT_OBJ:=nxp_mcxe31b_emac.o + WOLFIP_PORT:=nxp_mcxe_emac + WOLFIP_PORT_OBJ:=nxp_mcxe_emac.o # wolfIP state in SRAM, EMAC rings in the DTCM (ARM-mcxe31b-wolfip.ld) LSCRIPT_TEMPLATE=ARM-mcxe31b-wolfip.ld # Clear all of SRAM at reset, before it is read (ECC) CFLAGS+=-DAPP_RAM_ECC_INIT # Hot code in the ITCM (.ramcode_itcm in ARM-mcxe31b-wolfip.ld) CFLAGS+=-DAPP_RAMCODE_ITCM - # NXP_MCXE31B_EMAC_IRQ=0 polls the EMAC instead of using its interrupt - NXP_MCXE31B_EMAC_IRQ?=1 - CFLAGS+=-DWOLFIP_PORT_MCXE31B_EMAC - CFLAGS+=-DNXP_MCXE31B_EMAC_IRQ=$(NXP_MCXE31B_EMAC_IRQ) - CFLAGS+=-DTFTP_RAM_MAX=0x20000U + # NXP_MCXE_EMAC_IRQ=0 polls the EMAC instead of using its interrupt + NXP_MCXE_EMAC_IRQ?=1 + CFLAGS+=-DWOLFIP_PORT_MCXE_EMAC + CFLAGS+=-DNXP_MCXE_EMAC_IRQ=$(NXP_MCXE_EMAC_IRQ) + CFLAGS+=-DTFTP_RAM_MAX=0xA000U # Six full segments of TCP buffering per socket. CFLAGS+=-DRXBUF_SIZE=9216 -DTXBUF_SIZE=9216 # remove -ffreestanding so small memcpy's can be inlined @@ -1882,7 +1882,7 @@ ifeq ($(ENABLE_WOLFIP),1) WOLFIP_CFLAGS_ADD:=-O2 -DWOLFIP_POLL_BUDGET=16 # Driver cycle counters for the throughput test's CPU breakdown ifeq ($(WOLFIP_SPEED_TEST),1) - CFLAGS+=-DNXP_MCXE31B_EMAC_STATS=1 + CFLAGS+=-DNXP_MCXE_EMAC_STATS=1 endif else WOLFIP_PORT:=nxp_fman diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index f8625aa3c8..eb309b19de 100644 --- a/test-app/startup_arm.c +++ b/test-app/startup_arm.c @@ -85,9 +85,9 @@ extern void nxp_mcxe_enet_irq_handler(void); #ifdef TARGET_mcxe31b extern void isr_debug_uart(void); /* MCXE31B EMAC common interrupt (IRQ 105) */ -#if defined(NXP_MCXE31B_EMAC_IRQ) && (NXP_MCXE31B_EMAC_IRQ == 1) -extern void nxp_mcxe31b_emac_irq_handler(void); -#define isr_emac nxp_mcxe31b_emac_irq_handler +#if defined(NXP_MCXE_EMAC_IRQ) && (NXP_MCXE_EMAC_IRQ == 1) +extern void nxp_mcxe_emac_irq_handler(void); +#define isr_emac nxp_mcxe_emac_irq_handler #else #define isr_emac isr_empty #endif diff --git a/test-app/wolfip_tftp_test.c b/test-app/wolfip_tftp_test.c index 9328503ac2..992142bf0a 100644 --- a/test-app/wolfip_tftp_test.c +++ b/test-app/wolfip_tftp_test.c @@ -42,7 +42,7 @@ /* Port selection: * WOLFIP_PORT_ENETC -> LS1028A ENETC * WOLFIP_PORT_MCXE_ENET -> MCXE247 ENET - * WOLFIP_PORT_MCXE31B_EMAC -> MCXE31B EMAC + * WOLFIP_PORT_MCXE_EMAC -> MCX E EMAC (MCXE31B) * else QorIQ FMan * Driver entry points are wrapped so the bring-up code below is port-agnostic. */ #if defined(WOLFIP_PORT_ENETC) @@ -66,17 +66,17 @@ #define WOLFIP_NETDEV_STATS_GET nxp_mcxe_enet_stats_get #define WOLFIP_NETDEV_STATS_RESET nxp_mcxe_enet_stats_reset #endif -#elif defined(WOLFIP_PORT_MCXE31B_EMAC) -#include "nxp_mcxe31b_emac.h" -#define WOLFIP_NETDEV_INIT nxp_mcxe31b_emac_init -#define WOLFIP_NETDEV_PHY_ADDR nxp_mcxe31b_emac_phy_addr -#define WOLFIP_NETDEV_PHY_READ nxp_mcxe31b_emac_phy_read -#define WOLFIP_NETDEV_LINK_UP nxp_mcxe31b_emac_link_up +#elif defined(WOLFIP_PORT_MCXE_EMAC) +#include "nxp_mcxe_emac.h" +#define WOLFIP_NETDEV_INIT nxp_mcxe_emac_init +#define WOLFIP_NETDEV_PHY_ADDR nxp_mcxe_emac_phy_addr +#define WOLFIP_NETDEV_PHY_READ nxp_mcxe_emac_phy_read +#define WOLFIP_NETDEV_LINK_UP nxp_mcxe_emac_link_up #define WOLFIP_NETDEV_NAME "MCXE31B EMAC" -#if NXP_MCXE31B_EMAC_STATS -#define WOLFIP_NETDEV_STATS struct nxp_mcxe31b_emac_stats -#define WOLFIP_NETDEV_STATS_GET nxp_mcxe31b_emac_stats_get -#define WOLFIP_NETDEV_STATS_RESET nxp_mcxe31b_emac_stats_reset +#if NXP_MCXE_EMAC_STATS +#define WOLFIP_NETDEV_STATS struct nxp_mcxe_emac_stats +#define WOLFIP_NETDEV_STATS_GET nxp_mcxe_emac_stats_get +#define WOLFIP_NETDEV_STATS_RESET nxp_mcxe_emac_stats_reset #endif #else #include "nxp_fman.h" diff --git a/test-app/wolfip_tftp_test.h b/test-app/wolfip_tftp_test.h index ab23844035..0bbcd0e1a9 100644 --- a/test-app/wolfip_tftp_test.h +++ b/test-app/wolfip_tftp_test.h @@ -36,7 +36,7 @@ void wolfip_tftp_test_report(void); /* Cortex-M ports without a free-running timer of their own take the time * and the stop request from the target app */ -#if defined(WOLFIP_PORT_MCXE_ENET) || defined(WOLFIP_PORT_MCXE31B_EMAC) +#if defined(WOLFIP_PORT_MCXE_ENET) || defined(WOLFIP_PORT_MCXE_EMAC) #define WOLFIP_TEST_APP_TIMEBASE #endif diff --git a/tools/scripts/mcxe31b/e31b_debug.cmm b/tools/scripts/mcxe31b/e31b_debug.cmm index 67df602835..32502b2510 100644 --- a/tools/scripts/mcxe31b/e31b_debug.cmm +++ b/tools/scripts/mcxe31b/e31b_debug.cmm @@ -98,7 +98,7 @@ sYmbol.SourcePATH.SetBaseDir "&basedir" &srcdirs="&srcdirs ""&basedir\lib\wolfssl\wolfcrypt\src""" ; wolfIP and its MCXE31B port (test-app built with ENABLE_WOLFIP=1) &srcdirs="&srcdirs ""&basedir\lib\wolfip\src"" ""&basedir\lib\wolfip\src\tftp""" -&srcdirs="&srcdirs ""&basedir\lib\wolfip\src\port\nxp_mcxe31b_emac""" +&srcdirs="&srcdirs ""&basedir\lib\wolfip\src\port\nxp_mcxe_emac""" sYmbol.SourcePATH.Set &srcdirs ENDDO From 6fbba9dfb2e059e41facd6b872b2f6bd810f58ed Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Wed, 25 Nov 2026 14:53:57 -0500 Subject: [PATCH 05/21] address copilot/fenrir issues --- test-app/app_mcxe31b.c | 68 +++++++++++++++++++++++++++++++++--------- 1 file changed, 54 insertions(+), 14 deletions(-) diff --git a/test-app/app_mcxe31b.c b/test-app/app_mcxe31b.c index c42903e6da..d2fe5f249b 100644 --- a/test-app/app_mcxe31b.c +++ b/test-app/app_mcxe31b.c @@ -102,10 +102,21 @@ static void delay_ms(uint32_t ms) } } +/* CORE_CLK as it is configured: hal_init() stays on FIRC when the PLL setup + * fails */ +static uint32_t core_clock_hz(void) +{ + uint32_t src = FIRC_FREQ; + + if (MC_CGM_CSS_SELSTAT(MC_CGM_MUX0_CSS) == MC_CGM_SEL_PLL_PHI0) + src = PLL_PHI0_FREQ; + return src / (MC_CGM_DC_GET_DIV(MC_CGM_MUX0_DC(MC_CGM_DIV_CORE_CLK)) + 1U); +} + static void systick_init(void) { /* Configure SysTick for 1ms tick */ - SYST_RVR = (CLOCK_SPEED / 1000) - 1; + SYST_RVR = (core_clock_hz() / 1000U) - 1U; SYST_CVR = 0; SYST_CSR = SYST_CSR_ENABLE | SYST_CSR_TICKINT | SYST_CSR_CLKSOURCE; } @@ -439,6 +450,9 @@ static void print_keystore_info(void) #define XMODEM_PAYLOAD_SIZE 128 #define XMODEM_PACKET_SIZE_CRC (3 + XMODEM_PAYLOAD_SIZE + 2) /* SOH + blk + ~blk + data + CRC16 */ #define XMODEM_TIMEOUT_MS 1000 +/* Space in the update partition below its trailer sectors */ +#define XMODEM_MAX_SIZE (WOLFBOOT_PARTITION_SIZE - \ + (WOLFBOOT_TRAILER_SECTORS * WOLFBOOT_SECTOR_SIZE)) /* CRC-16-CCITT for XMODEM-CRC mode */ static uint16_t APP_RAMFUNCTION crc16_ccitt(const uint8_t* data, int len) @@ -501,10 +515,12 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) uint8_t payload[XMODEM_PAYLOAD_SIZE]; uint8_t pkt_num = 0, pkt_num_expected = 0xFF; uint32_t t_size = 0; + uint32_t img_size; uint32_t now; uint32_t i = 0; int transfer_started = 0; int eot_expected = 0; + int dup; int ret = -1; state->dst_offset = 0; @@ -547,10 +563,6 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) led_red_on(); /* Indicate transfer complete */ ret = 0; break; - } else if (eot_expected) { - uart_tx(XNAK); - ret = -1; - break; } /* Validate SOH */ @@ -565,9 +577,14 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) if ((uint8_t)(~xpkt[2]) == pkt_num) { uint16_t recv_crc, calc_crc; + dup = 0; if (!transfer_started) { pkt_num_expected = pkt_num; transfer_started = 1; + } else if (state->dst_offset > 0U && + pkt_num == (uint8_t)(pkt_num_expected - 1U)) { + /* The last block again: the sender missed its ACK */ + dup = 1; } else if (pkt_num_expected != pkt_num) { uart_tx(XNAK); continue; @@ -585,7 +602,30 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) xpkt[XMODEM_PACKET_SIZE_CRC - 1]; calc_crc = crc16_ccitt(xpkt + 3, XMODEM_PAYLOAD_SIZE); - if (recv_crc == calc_crc) { + if (recv_crc == calc_crc && dup) { + /* Already written: only ACK it again */ + uart_tx(XACK); + } else if (recv_crc == calc_crc) { + /* A block past the end of the image, or one that would reach + * the trailer sectors of the update partition */ + if (eot_expected || + state->dst_offset + XMODEM_PAYLOAD_SIZE > XMODEM_MAX_SIZE) { + xmodem_cancel(); + ret = -1; + break; + } + /* The image size (header offset 4) must fit, checked before + * the first block is ACKed or written */ + if (state->dst_offset == 0U) { + ram_memcpy(&img_size, xpkt + 3 + 4, sizeof(img_size)); + if (img_size > XMODEM_MAX_SIZE - IMAGE_HEADER_SIZE) { + xmodem_cancel(); + ret = -1; + break; + } + t_size = img_size + IMAGE_HEADER_SIZE; + } + /* Copy payload using RAM-based memcpy */ ram_memcpy(payload, xpkt + 3, XMODEM_PAYLOAD_SIZE); @@ -606,12 +646,7 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) pkt_num_expected++; state->dst_offset += XMODEM_PAYLOAD_SIZE; - /* Get expected size from header (offset 4 = image size) */ - if (t_size == 0 && state->dst_offset >= 8) { - t_size = *(uint32_t*)(payload + 4) + IMAGE_HEADER_SIZE; - } - - if (t_size > 0 && state->dst_offset >= t_size) { + if (state->dst_offset >= t_size) { eot_expected = 1; } } else { @@ -664,8 +699,13 @@ static int cmd_update_xmodem(void) } #else (void)erase_addr; - (void)erase_ret; - hal_flash_erase(WOLFBOOT_PARTITION_UPDATE_ADDRESS, WOLFBOOT_PARTITION_SIZE); + erase_ret = hal_flash_erase(WOLFBOOT_PARTITION_UPDATE_ADDRESS, + WOLFBOOT_PARTITION_SIZE); + if (erase_ret != 0) { + printf("Erase FAILED (%d)\r\n", erase_ret); + hal_flash_lock(); + return -1; + } #endif printf("Done.\r\n"); From 9fff1942c4f51bab0fc797616a32c9cd39aa5332 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Tue, 1 Dec 2026 01:55:30 -0500 Subject: [PATCH 06/21] mcxe31b: opt in to the unaligned memcpy FAST_MEMCPY's unaligned-source word path now also needs FAST_MEMCPY_UNALIGNED (03718e4a). Set it to keep the word copies this port was tuned with; nothing here memcpy's from peripheral registers. --- config/examples/mcxe31b.config | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/config/examples/mcxe31b.config b/config/examples/mcxe31b.config index 8849fb0a32..bc8b6c363f 100644 --- a/config/examples/mcxe31b.config +++ b/config/examples/mcxe31b.config @@ -35,9 +35,11 @@ CFLAGS_EXTRA+=-DWOLFBOOT_RAM_ECC_INIT WOLFBOOT_SECTOR_SIZE?=0x2000 # Word-at-a-time memcpy/memset in src/string.c (bootloader and test-app). The -# Cortex-M7 loads unaligned words, so memcpy copies words even when source and -# destination alignments differ. -CFLAGS_EXTRA+=-DFAST_MEMCPY +# Cortex-M7 loads unaligned words from RAM and flash, so with +# FAST_MEMCPY_UNALIGNED memcpy copies words even when source and destination +# alignments differ. Nothing on this target copies from peripheral registers +# with memcpy. +CFLAGS_EXTRA+=-DFAST_MEMCPY -DFAST_MEMCPY_UNALIGNED # The application's vector table follows the image header and is used in # place (VTOR). The table must be 1 KB aligned, or the core fetches the vectors From 10abbe7b26b70688ea29a45d6f1c43372b1d18b9 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Tue, 1 Dec 2026 09:36:11 -0500 Subject: [PATCH 07/21] fix xmodem eot issue --- test-app/app_mcxe31b.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test-app/app_mcxe31b.c b/test-app/app_mcxe31b.c index d2fe5f249b..bb489ac985 100644 --- a/test-app/app_mcxe31b.c +++ b/test-app/app_mcxe31b.c @@ -557,8 +557,13 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) } } - /* Check for EOT */ + /* Check for EOT: refused until the whole image is in flash */ if (xpkt[0] == XEOT) { + if (!eot_expected) { + xmodem_cancel(); + ret = -1; + break; + } uart_tx(XACK); led_red_on(); /* Indicate transfer complete */ ret = 0; From 3fed3beb4879c487af0103065b22d1ca25d640f3 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 4 Dec 2026 11:56:23 -0500 Subject: [PATCH 08/21] mcxe31b: stop the EMAC after the network test, use the stats macro - Map WOLFIP_NETDEV_STOP to nxp_mcxe_emac_stop(), so the EMAC is stopped on every exit of the network test as on the MCXE247. - speed_start() resets the driver stats through WOLFIP_NETDEV_STATS_RESET instead of the MCXE247 function. --- test-app/wolfip_tftp_test.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test-app/wolfip_tftp_test.c b/test-app/wolfip_tftp_test.c index 992142bf0a..d0b95787ff 100644 --- a/test-app/wolfip_tftp_test.c +++ b/test-app/wolfip_tftp_test.c @@ -72,6 +72,7 @@ #define WOLFIP_NETDEV_PHY_ADDR nxp_mcxe_emac_phy_addr #define WOLFIP_NETDEV_PHY_READ nxp_mcxe_emac_phy_read #define WOLFIP_NETDEV_LINK_UP nxp_mcxe_emac_link_up +#define WOLFIP_NETDEV_STOP nxp_mcxe_emac_stop #define WOLFIP_NETDEV_NAME "MCXE31B EMAC" #if NXP_MCXE_EMAC_STATS #define WOLFIP_NETDEV_STATS struct nxp_mcxe_emac_stats @@ -720,7 +721,7 @@ static void speed_start(uint8_t proto, uint8_t mode, uint64_t now) speed.active = 1U; #if SPEED_PROFILE /* also for a test whose window never starts */ - nxp_mcxe_enet_stats_reset(); + WOLFIP_NETDEV_STATS_RESET(); #endif if (proto == SPEED_PROTO_TCP || mode == 't') speed_window_start(now); From 4b20a3f1a9c160ffa9b98dd9697cf2d0c500bac1 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 4 Dec 2026 13:14:12 -0500 Subject: [PATCH 09/21] mcxe31b: check the test-app link, document header size and memcpy - Linker scripts stop the build when the vector table is not 1 KB aligned (IMAGE_HEADER_SIZE=1024) and when the flash load images overflow FLASH. - The wolfIP linker script also asserts that memcpy and wolfIP's csum_add are in .ramcode_itcm; string.o is built with __WOLFBOOT, so memcpy is in .ramcode also when the test-app builds it. - Targets.md: fix the garbled ITCM sentence, document FAST_MEMCPY_UNALIGNED with the measured TCP rates without it, how to change the image header size, and the network console command. --- docs/Targets.md | 30 ++++++++++++++++++++++-------- test-app/ARM-mcxe31b-wolfip.ld | 22 +++++++++++++++++++++- test-app/ARM-mcxe31b.ld | 9 +++++++++ test-app/Makefile | 5 ++++- 4 files changed, 56 insertions(+), 10 deletions(-) diff --git a/docs/Targets.md b/docs/Targets.md index d4b3f7f27d..e2513a1cdb 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -8094,9 +8094,19 @@ board. 1 KB into the boot partition. The application's vector table is used in place, and with up to 163 entries it must be 1 KB aligned: with the default 256-byte header the core fetches the vectors of some interrupts (the EMAC, - IRQ 105, among them) from the wrong slots. -- `mcxe31b.config` sets `FAST_MEMCPY`, the word-at-a-time `memcpy` and - `memset` of `src/string.c`, for wolfBoot and the test application. + IRQ 105, among them) from the wrong slots. The test application's linker + scripts stop the build when the vector table is not 1 KB aligned. + A bootloader finds the application at its own header size, so wolfBoot + built with one header size cannot boot an image signed with another. To + change the size, rebuild with the new `IMAGE_HEADER_SIZE`, program + `factory.bin` with `e31b_flash_factory_bin.cmm` (which also erases the + update partition and swap sector), and sign every update image again with + the new size (see [Testing an update](#nxp-mcxe31b-testing-an-update)). +- `mcxe31b.config` sets `FAST_MEMCPY` and `FAST_MEMCPY_UNALIGNED`, the + word-at-a-time `memcpy` and `memset` of `src/string.c`, for wolfBoot and the + test application. The Cortex-M7 loads unaligned words from RAM and flash, so + `memcpy` copies words even when the source and destination alignments + differ. Without `FAST_MEMCPY_UNALIGNED` it copies those bytes one at a time. ### NXP MCXE31B: Memory Layout @@ -8125,7 +8135,8 @@ programmed at `0x00400000`. The console is on the MCU-Link VCOM port (LPUART5, PTE14 TX, PTE3 RX, 115200 8N1). The test application shows green on the RGB LED for version 1 and blue for later versions, and has the same console as the -[S32K1xx test application](#nxp-s32k1xx-test-application). +[S32K1xx test application](#nxp-s32k1xx-test-application), including +`network` (see [Network test](#nxp-mcxe31b-network-test)). ### NXP MCXE31B: Configuration Options @@ -8150,10 +8161,13 @@ reaches through its backdoor port, and places the wolfIP stack state, with 9 KB TCP receive and transmit buffers per socket, the TFTP receive buffer and libwolfboot's 8 KB flash sector buffer (`NVM_CACHE`) in SRAM. SRAM is ECC protected: the reset handler clears all 320 KB of it with 64-bit stores -(`APP_RAM_ECC_INIT`) before it is used. The hottest network code (8.7 KB: -runs from the ITCM: the reset handler clears the ITCM and copies it there -(`APP_RAMCODE_ITCM`). wolfIP takes at most 16 frames per `wolfIP_poll()` -(`WOLFIP_POLL_BUDGET=16`). The driver uses 8 transmit and 4 receive +(`APP_RAM_ECC_INIT`) before it is used. The hottest network code: +(`memcpy`, `memset` and `memcmp`, wolfIP's checksum, poll loop, FIFO and TCP +send path, and the driver's poll, send and interrupt handler) runs from the +ITCM: the reset handler clears the ITCM and copies it there +(`APP_RAMCODE_ITCM`). The linker script stops the build when `memcpy` or the +wolfIP checksum is missing from the ITCM. wolfIP takes at most 16 frames per +`wolfIP_poll()` (`WOLFIP_POLL_BUDGET=16`). The driver uses 8 transmit and 4 receive descriptors (19 KB of DTCM). Set `ENABLE_WOLFIP=1` in `mcxe31b.config` and check the wolfIP path: diff --git a/test-app/ARM-mcxe31b-wolfip.ld b/test-app/ARM-mcxe31b-wolfip.ld index f4c041a11d..352b1c368e 100644 --- a/test-app/ARM-mcxe31b-wolfip.ld +++ b/test-app/ARM-mcxe31b-wolfip.ld @@ -40,8 +40,12 @@ SECTIONS . = ALIGN(8); _start_ramcode_itcm = .; KEEP(*string.o(.ramcode)) + _end_ramcode_itcm_string = .; *string.o(.text.memset .text.memcmp) - *wolfip.o(.text.csum_add .text.transport_checksum) + _start_ramcode_itcm_csum = .; + *wolfip.o(.text.csum_add) + _end_ramcode_itcm_csum = .; + *wolfip.o(.text.transport_checksum) *wolfip.o(.text.iphdr_set_checksum .text.wolfIP_poll) *wolfip.o(.text.fifo_next .text.fifo_peek .text.fifo_push) *wolfip.o(.text.fifo_pop .text.fifo_can_push_len) @@ -53,6 +57,13 @@ SECTIONS . = ALIGN(8); _end_ramcode_itcm = .; } > ITCM + /* Both rules can match nothing without an error: memcpy needs string.o + * built with RAM_CODE and __WOLFBOOT, and csum_add (static) could be + * inlined */ + ASSERT(memcpy >= _start_ramcode_itcm && memcpy < _end_ramcode_itcm_string, + "memcpy is not in .ramcode_itcm") + ASSERT(_end_ramcode_itcm_csum > _start_ramcode_itcm_csum, + "wolfIP csum_add is not in .ramcode_itcm") .text : { @@ -65,6 +76,10 @@ SECTIONS . = ALIGN(4); _end_text = .; } > FLASH + /* The vector table is used in place, and with up to 163 entries VTOR + * needs it 1 KB aligned: IMAGE_HEADER_SIZE=1024 (mcxe31b.config) */ + ASSERT(_start_text % 1024 == 0, + "vector table not 1 KB aligned: set IMAGE_HEADER_SIZE=1024") .keystore : { @@ -137,6 +152,11 @@ _end_ecc_itcm = 0x00008000; _start_ecc_ram = ORIGIN(SRAM); _end_ecc_ram = ORIGIN(SRAM) + LENGTH(SRAM); +/* The load images after .text are placed by address, so ld does not count + * them against FLASH */ +ASSERT(_stored_data + SIZEOF(.data) <= ORIGIN(FLASH) + LENGTH(FLASH), + "the .ramcode_itcm and .data load images overflow FLASH") + /* The EMAC driver's buffers must be in the DTCM */ ASSERT(_end_bss <= ORIGIN(RAM) + LENGTH(RAM), "DTCM overflow") /* Keep room above .bss for the stack and the heap used by printf */ diff --git a/test-app/ARM-mcxe31b.ld b/test-app/ARM-mcxe31b.ld index 412244103b..20e8fa4840 100644 --- a/test-app/ARM-mcxe31b.ld +++ b/test-app/ARM-mcxe31b.ld @@ -26,6 +26,10 @@ SECTIONS . = ALIGN(4); _end_text = .; } > FLASH + /* The vector table is used in place, and with up to 163 entries VTOR + * needs it 1 KB aligned: IMAGE_HEADER_SIZE=1024 (mcxe31b.config) */ + ASSERT(_start_text % 1024 == 0, + "vector table not 1 KB aligned: set IMAGE_HEADER_SIZE=1024") .edidx : { @@ -68,3 +72,8 @@ _wolfboot_partition_swap_address = @WOLFBOOT_PARTITION_SWAP_ADDRESS@; /* Stack and heap indicators */ _start_heap = _end; _end_stack = ORIGIN(RAM) + LENGTH(RAM); + +/* The .data load image is placed by address, so ld does not count it + * against FLASH */ +ASSERT(_stored_data + SIZEOF(.data) <= ORIGIN(FLASH) + LENGTH(FLASH), + "the .data load image overflows FLASH") diff --git a/test-app/Makefile b/test-app/Makefile index d7e5c4fba3..165918141e 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1867,8 +1867,11 @@ ifeq ($(ENABLE_WOLFIP),1) LSCRIPT_TEMPLATE=ARM-mcxe31b-wolfip.ld # Clear all of SRAM at reset, before it is read (ECC) CFLAGS+=-DAPP_RAM_ECC_INIT - # Hot code in the ITCM (.ramcode_itcm in ARM-mcxe31b-wolfip.ld) + # Hot code in the ITCM (.ramcode_itcm in ARM-mcxe31b-wolfip.ld). memcpy + # is in .ramcode only with __WOLFBOOT, also when the test-app builds + # string.o itself. CFLAGS+=-DAPP_RAMCODE_ITCM + ../src/string.o: CFLAGS+=-D__WOLFBOOT # NXP_MCXE_EMAC_IRQ=0 polls the EMAC instead of using its interrupt NXP_MCXE_EMAC_IRQ?=1 CFLAGS+=-DWOLFIP_PORT_MCXE_EMAC From a382d02613954fd3d1ed1cba581b588e08b9a1d3 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 4 Dec 2026 13:14:16 -0500 Subject: [PATCH 10/21] mcxe31b: use the shared XMODEM receiver app_mcxe31b.c carried a copy of the XMODEM-CRC receiver identical to test-app/xmodem_rx.c. Include xmodem_rx.c instead, as app_s32k1xx.c does, so receiver fixes land once, and rebuild app_mcxe31b.o when it changes. Tested on the FRDM-MCXE31B: an oversized header, blocks past the image, EOT after 2 blocks are cancelled; a repeated block and a repeated last block are ACKed again; a normal transfer completes and version 2 boots. --- test-app/Makefile | 4 +- test-app/app_mcxe31b.c | 228 +---------------------------------------- test-app/xmodem_rx.c | 7 +- 3 files changed, 6 insertions(+), 233 deletions(-) diff --git a/test-app/Makefile b/test-app/Makefile index 165918141e..61aed0464d 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -2059,8 +2059,8 @@ board_$(BOARD).o: $(BOARD_DIR)/wolfHAL_board.c @echo "\t[CC-$(ARCH)] $@" $(Q)$(CC) $(CFLAGS) -c $(OUTPUT_FLAG) $@ $^ -# app_s32k1xx.c includes the XMODEM receiver -app_s32k1xx.o: app_s32k1xx.c xmodem_rx.c +# app_s32k1xx.c and app_mcxe31b.c include the XMODEM receiver +app_s32k1xx.o app_mcxe31b.o: %.o: %.c xmodem_rx.c @echo "\t[CC-$(ARCH)] $@" $(Q)$(CC) $(CFLAGS) -c $(OUTPUT_FLAG) $@ $< diff --git a/test-app/app_mcxe31b.c b/test-app/app_mcxe31b.c index bb489ac985..1984f9e887 100644 --- a/test-app/app_mcxe31b.c +++ b/test-app/app_mcxe31b.c @@ -440,233 +440,7 @@ static void print_keystore_info(void) /* ============== XMODEM Transfer ============== */ -#define XSOH 0x01 -#define XEOT 0x04 -#define XACK 0x06 -#define XNAK 0x15 -#define XCAN 0x18 -#define XCRC 'C' /* Request CRC mode */ - -#define XMODEM_PAYLOAD_SIZE 128 -#define XMODEM_PACKET_SIZE_CRC (3 + XMODEM_PAYLOAD_SIZE + 2) /* SOH + blk + ~blk + data + CRC16 */ -#define XMODEM_TIMEOUT_MS 1000 -/* Space in the update partition below its trailer sectors */ -#define XMODEM_MAX_SIZE (WOLFBOOT_PARTITION_SIZE - \ - (WOLFBOOT_TRAILER_SECTORS * WOLFBOOT_SECTOR_SIZE)) - -/* CRC-16-CCITT for XMODEM-CRC mode */ -static uint16_t APP_RAMFUNCTION crc16_ccitt(const uint8_t* data, int len) -{ - uint16_t crc = 0; - int i, j; - for (i = 0; i < len; i++) { - crc ^= ((uint16_t)data[i] << 8); - for (j = 0; j < 8; j++) { - if (crc & 0x8000) { - crc = (crc << 1) ^ 0x1021; - } else { - crc <<= 1; - } - } - } - return crc; -} - -/* Raw byte transmit for XMODEM (declared in hal, runs from RAM) */ -extern void uart_tx(uint8_t byte); - -/* RAM-based memory copy for use during flash operations */ -static void APP_RAMFUNCTION ram_memcpy(void *dst, const void *src, uint32_t len) -{ - uint8_t *d = (uint8_t *)dst; - const uint8_t *s = (const uint8_t *)src; - while (len--) { - *d++ = *s++; - } -} - -static void APP_RAMFUNCTION xmodem_cancel(void) -{ - int i; - for (i = 0; i < 10; i++) { - uart_tx(XCAN); - } -} - -/* XMODEM receive state - passed to RAM function */ -typedef struct { - uint32_t dst_offset; - int result; - /* Debug counters */ - uint32_t pkts_received; - uint32_t pkts_crc_fail; - uint32_t pkts_num_fail; - uint32_t pkts_soh_fail; - uint32_t timeouts; -} xmodem_state_t; - -/* Core XMODEM-CRC receive loop - runs entirely from RAM during flash operations - * Uses XMODEM-CRC mode (133-byte packets with 16-bit CRC) - * Returns: 0 on success, -1 on error - */ -static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) -{ - uint8_t xpkt[XMODEM_PACKET_SIZE_CRC]; - uint8_t payload[XMODEM_PAYLOAD_SIZE]; - uint8_t pkt_num = 0, pkt_num_expected = 0xFF; - uint32_t t_size = 0; - uint32_t img_size; - uint32_t now; - uint32_t i = 0; - int transfer_started = 0; - int eot_expected = 0; - int dup; - int ret = -1; - - state->dst_offset = 0; - state->result = -1; - state->pkts_received = 0; - state->pkts_crc_fail = 0; - state->pkts_num_fail = 0; - state->pkts_soh_fail = 0; - state->timeouts = 0; - - /* Send 'C' to request CRC mode (XMODEM-CRC) */ - uart_tx(XCRC); - - while (1) { - now = jiffies; /* Direct access to volatile - faster than function call */ - i = 0; - - /* Receive packet - uses interrupt-buffered RX to avoid FIFO overflow */ - while (i < XMODEM_PACKET_SIZE_CRC) { - int r = uart_rx_isr(&xpkt[i], XMODEM_PACKET_SIZE_CRC - i); - if (r > 0) { - i += r; - now = jiffies; - if (i >= 1 && xpkt[0] == XEOT) { - break; /* End of transmission */ - } - } else if (jiffies > (now + XMODEM_TIMEOUT_MS)) { - now = jiffies; - state->timeouts++; - if (i == 0) { - uart_tx(XCRC); /* Request CRC mode again */ - } - i = 0; - } - } - - /* Check for EOT: refused until the whole image is in flash */ - if (xpkt[0] == XEOT) { - if (!eot_expected) { - xmodem_cancel(); - ret = -1; - break; - } - uart_tx(XACK); - led_red_on(); /* Indicate transfer complete */ - ret = 0; - break; - } - - /* Validate SOH */ - if (xpkt[0] != XSOH) { - state->pkts_soh_fail++; - continue; - } - state->pkts_received++; - - /* Validate packet number */ - pkt_num = xpkt[1]; - if ((uint8_t)(~xpkt[2]) == pkt_num) { - uint16_t recv_crc, calc_crc; - - dup = 0; - if (!transfer_started) { - pkt_num_expected = pkt_num; - transfer_started = 1; - } else if (state->dst_offset > 0U && - pkt_num == (uint8_t)(pkt_num_expected - 1U)) { - /* The last block again: the sender missed its ACK */ - dup = 1; - } else if (pkt_num_expected != pkt_num) { - uart_tx(XNAK); - continue; - } - - /* Toggle LED to show activity */ - if ((pkt_num & 0x0F) == 0) { - led_red_on(); - } else if ((pkt_num & 0x0F) == 8) { - led_red_off(); - } - - /* Validate CRC-16 - XMODEM-CRC uses CRC over DATA bytes only */ - recv_crc = ((uint16_t)xpkt[XMODEM_PACKET_SIZE_CRC - 2] << 8) | - xpkt[XMODEM_PACKET_SIZE_CRC - 1]; - calc_crc = crc16_ccitt(xpkt + 3, XMODEM_PAYLOAD_SIZE); - - if (recv_crc == calc_crc && dup) { - /* Already written: only ACK it again */ - uart_tx(XACK); - } else if (recv_crc == calc_crc) { - /* A block past the end of the image, or one that would reach - * the trailer sectors of the update partition */ - if (eot_expected || - state->dst_offset + XMODEM_PAYLOAD_SIZE > XMODEM_MAX_SIZE) { - xmodem_cancel(); - ret = -1; - break; - } - /* The image size (header offset 4) must fit, checked before - * the first block is ACKed or written */ - if (state->dst_offset == 0U) { - ram_memcpy(&img_size, xpkt + 3 + 4, sizeof(img_size)); - if (img_size > XMODEM_MAX_SIZE - IMAGE_HEADER_SIZE) { - xmodem_cancel(); - ret = -1; - break; - } - t_size = img_size + IMAGE_HEADER_SIZE; - } - - /* Copy payload using RAM-based memcpy */ - ram_memcpy(payload, xpkt + 3, XMODEM_PAYLOAD_SIZE); - - /* Send ACK first, then write to flash. - * This allows sender to prepare next packet while we write. - * Risk: if write fails, we've already ACKed - but that's rare. - */ - uart_tx(XACK); - - /* Write to flash */ - ret = hal_flash_write(WOLFBOOT_PARTITION_UPDATE_ADDRESS + state->dst_offset, - payload, XMODEM_PAYLOAD_SIZE); - if (ret != 0) { - xmodem_cancel(); - /* No printf here - we're in RAM */ - break; - } - pkt_num_expected++; - state->dst_offset += XMODEM_PAYLOAD_SIZE; - - if (state->dst_offset >= t_size) { - eot_expected = 1; - } - } else { - state->pkts_crc_fail++; - uart_tx(XNAK); - } - } else { - state->pkts_num_fail++; - uart_tx(XNAK); - } - } - - state->result = ret; - return ret; -} +#include "xmodem_rx.c" static int cmd_update_xmodem(void) { diff --git a/test-app/xmodem_rx.c b/test-app/xmodem_rx.c index c7acc8c914..8edb74be0f 100644 --- a/test-app/xmodem_rx.c +++ b/test-app/xmodem_rx.c @@ -1,9 +1,8 @@ /* xmodem_rx.c * - * XMODEM-CRC receiver of the S32K1xx / MCX E247 test-app: writes the - * received image to the update partition. Included by app_s32k1xx.c, whose - * UART, LED and jiffies helpers it uses, and by the unit test - * tools/unit-tests/unit-xmodem-rx.c with mocks of them. + * XMODEM-CRC receiver common code for test-apps. + * Writes the received image to the update partition. Uses the target's + * UART, LED and jiffies helpers. * * Copyright (C) 2026 wolfSSL Inc. * From 0c97c4465cbeabc5be2ea138f4691c3ab36f3621 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 4 Dec 2026 13:41:06 -0500 Subject: [PATCH 11/21] mcxe31b: fix review nits in startup, speed test and config - The ITCM clear loop zeroes r3 itself instead of relying on the SRAM clear for TARGET_mcxe31b. - Print the "Ctrl-C stops the server" hint whenever the test-app provides wolfip_test_abort(), not only for the MCXE247 ENET port. - mcxe31b.config: the TFTP receive buffer is 40 KB (TFTP_RAM_MAX), not 128 KB. --- config/examples/mcxe31b.config | 3 ++- test-app/startup_arm.c | 3 ++- test-app/wolfip_tftp_test.c | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/config/examples/mcxe31b.config b/config/examples/mcxe31b.config index bc8b6c363f..86254b8672 100644 --- a/config/examples/mcxe31b.config +++ b/config/examples/mcxe31b.config @@ -73,7 +73,8 @@ NXP_MCXE_EMAC_IRQ?=1 # tools/scripts/wolfip_speed.py. WOLFIP_SPEED_TEST?=1 # WOLFBOOT_TEST_TFTP=1 makes the command fetch a file over TFTP instead (it -# overrides WOLFIP_SPEED_TEST). The file must fit the 128 KB receive buffer. +# overrides WOLFIP_SPEED_TEST). The file must fit the 40 KB receive buffer +# (TFTP_RAM_MAX in test-app/Makefile). # With both set to 0 the command only acquires a DHCP lease. WOLFBOOT_TEST_TFTP?=0 CFLAGS_EXTRA+=-DHOST_IP_STR='"192.168.50.1"' -DTFTP_FILENAME='"wolfip_test.bin"' diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index eb309b19de..98c9da07b2 100644 --- a/test-app/startup_arm.c +++ b/test-app/startup_arm.c @@ -138,9 +138,10 @@ void isr_reset(void) "2:\n\t" #ifdef APP_RAMCODE_ITCM /* The ITCM holds no valid ECC either: clear it before the hot - * code is copied in, also with 64-bit stores */ + * code is copied in, also with 64-bit stores (r2 and r3 zero) */ "ldr r0, =_start_ecc_itcm\n\t" "ldr r1, =_end_ecc_itcm\n\t" + "movs r3, #0\n\t" "3:\n\t" "cmp r0, r1\n\t" "bhs 4f\n\t" diff --git a/test-app/wolfip_tftp_test.c b/test-app/wolfip_tftp_test.c index d0b95787ff..b44b19a2ac 100644 --- a/test-app/wolfip_tftp_test.c +++ b/test-app/wolfip_tftp_test.c @@ -1092,7 +1092,7 @@ static int run_speed_server(struct wolfIP *s) wolfBoot_printf("SPEED: TCP and UDP throughput server on port %d\r\n", SPEED_PORT); wolfBoot_printf(" host: python3 tools/scripts/wolfip_speed.py \r\n"); -#ifdef WOLFIP_PORT_MCXE_ENET +#ifdef WOLFIP_TEST_APP_TIMEBASE wolfBoot_printf(" Ctrl-C stops the server\r\n"); #endif From d846f799eaa13d639d8771866368db51eaa0c8d6 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 4 Dec 2026 20:14:44 -0500 Subject: [PATCH 12/21] mcxe31b: range check flash writes and erases, bound clock waits - hal_flash_write() and hal_flash_erase() refuse ranges outside the code and data flash: flash_lock_reg() indexes the lock registers by address, so an out of range address changed unrelated registers. - mc_me_clock_enable() and the MUX_0 divider update wait time out, so clock_init() returns and the system stays on FIRC instead of hanging. uart_init() leaves LPUART5 alone when its clock does not start. Tested on the FRDM-MCXE31B: XMODEM update to version 2, swap, and v2 marked SUCCESS. --- hal/mcxe31b.c | 57 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 49 insertions(+), 8 deletions(-) diff --git a/hal/mcxe31b.c b/hal/mcxe31b.c index 028db819b6..00785f77de 100644 --- a/hal/mcxe31b.c +++ b/hal/mcxe31b.c @@ -82,18 +82,21 @@ const uint32_t __attribute__((section(".ivt"))) mcxe31b_ivt[64] = { #define CLOCK_TIMEOUT 1000000 /* Enable a partition 1 peripheral clock by its MC_ME clock request number */ -static void mc_me_clock_enable(uint32_t req) +/* Returns 0 when the clock runs, -1 when it does not start */ +static int mc_me_clock_enable(uint32_t req) { uint32_t cofb = req / 32; uint32_t bit = 1UL << (req % 32); + uint32_t timeout = CLOCK_TIMEOUT; if (MC_ME_PRTN1_COFB_STAT(cofb) & bit) - return; + return 0; MC_ME_PRTN1_COFB_CLKEN(cofb) |= bit; MC_ME_PRTN1_PUPD = MC_ME_PRTN_PUPD_PCUD; MC_ME_CTL_KEY = MC_ME_CTL_KEY_KEY; MC_ME_CTL_KEY = MC_ME_CTL_KEY_INVKEY; - while (!(MC_ME_PRTN1_COFB_STAT(cofb) & bit)) {} + while (!(MC_ME_PRTN1_COFB_STAT(cofb) & bit) && --timeout) {} + return (timeout == 0) ? -1 : 0; } /* Busy wait for at least n core cycles */ @@ -121,8 +124,10 @@ static int clock_init(void) if (MC_CGM_CSS_SELSTAT(MC_CGM_MUX0_CSS) == MC_CGM_SEL_PLL_PHI0) return 0; - mc_me_clock_enable(MC_ME_REQ_FXOSC); - mc_me_clock_enable(MC_ME_REQ_PLL); + if (mc_me_clock_enable(MC_ME_REQ_FXOSC) != 0 || + mc_me_clock_enable(MC_ME_REQ_PLL) != 0) { + return -1; + } /* Last mile regulator: it supplies the core above FIRC speed. Start the * V15 ballast, wait for its soft start and for V15, then hand over. */ @@ -177,7 +182,13 @@ static int clock_init(void) for (i = 0; i < MC_CGM_MUX0_NUM_DIV; i++) MC_CGM_MUX0_DC(i) = MC_CGM_DC_DE | MC_CGM_DC_DIV(mux0_div[i]); MC_CGM_MUX0_DIV_TRIG = 0xFFFFFFFFUL; - while (MC_CGM_MUX0_DIV_UPD_STAT & MC_CGM_DIV_UPD_STAT_DIV_STAT) {} + timeout = CLOCK_TIMEOUT; + while ((MC_CGM_MUX0_DIV_UPD_STAT & MC_CGM_DIV_UPD_STAT_DIV_STAT) && + --timeout) {} + /* Still on FIRC, with whatever dividers took effect: the UART reads + * them back */ + if (timeout == 0) + return -1; MC_CGM_MUX0_CSC = MC_CGM_CSC_SELCTL(MC_CGM_SEL_PLL_PHI0) | MC_CGM_CSC_CLK_SW; @@ -307,7 +318,9 @@ void uart_init(void) } } - mc_me_clock_enable(MC_ME_REQ_LPUART5); + /* An LPUART5 without clock faults on access: leave it alone */ + if (mc_me_clock_enable(MC_ME_REQ_LPUART5) != 0) + return; /* Pin mux: TX output, RX input routed through IMCR */ SIUL2_MSCR(UART_TX_PAD) = SIUL2_MSCR_OBE | SIUL2_MSCR_SSS(UART_TX_SSS); @@ -356,7 +369,26 @@ int RAMFUNCTION uart_read(char* c) #endif /* DEBUG_UART */ -/* Return the PFLASH lock register and bit covering a flash address. The first +/* Non-zero when [address, address + len) lies in the code flash or in the + * data flash */ +static int RAMFUNCTION flash_range_ok(uint32_t address, uint32_t len) +{ + if (address >= FLASH_BASE && + address - FLASH_BASE <= FLASH_NUM_BLOCKS * FLASH_BLOCK_SIZE && + len <= FLASH_NUM_BLOCKS * FLASH_BLOCK_SIZE - + (address - FLASH_BASE)) { + return 1; + } + if (address >= FLASH_DATA_BASE && + address - FLASH_DATA_BASE <= FLASH_DATA_SIZE && + len <= FLASH_DATA_SIZE - (address - FLASH_DATA_BASE)) { + return 1; + } + return 0; +} + +/* Return the PFLASH lock register and bit covering a flash address + * (checked by flash_range_ok()). The first * 768 KB of each code block is locked per 64 KB super sector, the last 256 KB * (and the data flash) per 8 KB sector. */ static volatile uint32_t* RAMFUNCTION flash_lock_reg(uint32_t address, @@ -529,6 +561,9 @@ int RAMFUNCTION hal_flash_write(uint32_t address, const uint8_t *data, int len) uint32_t qpage, start, end, off, mask; int ret; + /* flash_lock_reg() indexes the lock registers by address */ + if (len < 0 || !flash_range_ok(address, (uint32_t)len)) + return -1; while (len > 0) { qpage = address & ~(FLASH_QUAD_PAGE_SIZE - 1); start = address - qpage; @@ -567,6 +602,12 @@ int RAMFUNCTION hal_flash_erase(uint32_t address, int len) return -1; address &= ~(FLASH_SECTOR_SIZE - 1); + /* Whole sectors from the aligned address. flash_lock_reg() indexes the + * lock registers by address. */ + if (!flash_range_ok(address, ((uint32_t)len + FLASH_SECTOR_SIZE - 1U) & + ~(FLASH_SECTOR_SIZE - 1U))) { + return -1; + } while (len > 0) { ret = flash_erase_sector(address); if (ret != 0) From aa7e641ad30dab7c5d0baadf08c6afdab89c0975 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 4 Dec 2026 20:14:44 -0500 Subject: [PATCH 13/21] mcxe31b: required build options in arch.mk, explicit build errors - arch.mk sets WOLFBOOT_RAM_ECC_INIT for the target, as Targets.md says, instead of the example config, and stops the build without NVM_FLASH_WRITEONCE=1. - test-app: ENABLE_WOLFIP=1 with DEBUG_UART=0 stops with a message instead of a linker assertion on memcpy. - CI: build mcxe31b.config with DEBUG_UART=0. --- .github/workflows/test-configs.yml | 7 +++++++ arch.mk | 8 ++++++++ config/examples/mcxe31b.config | 3 --- test-app/Makefile | 4 ++++ 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test-configs.yml b/.github/workflows/test-configs.yml index 070b8cd2dc..3df09f992e 100644 --- a/.github/workflows/test-configs.yml +++ b/.github/workflows/test-configs.yml @@ -650,6 +650,13 @@ jobs: arch: arm config-file: ./config/examples/mcxe31b.config + nxp_mcxe31b_no_uart_test: + uses: ./.github/workflows/test-build.yml + with: + arch: arm + config-file: ./config/examples/mcxe31b.config + make-args: DEBUG_UART=0 + max32666_test: uses: ./.github/workflows/test-build.yml with: diff --git a/arch.mk b/arch.mk index 63d823d531..4db06451f0 100644 --- a/arch.mk +++ b/arch.mk @@ -619,6 +619,14 @@ ifeq ($(ARCH),ARM) ifeq ($(TARGET),mcxe31b) CORTEX_M7=1 ARCH_FLASH_OFFSET=0x00400000 + # The CM7 DTCM is ECC protected and must be written before it is read + CFLAGS+=-DWOLFBOOT_RAM_ECC_INIT + # Each 64-bit ECC segment can be programmed once between erases: the + # HAL skips unchanged segments, and partition trailers need the + # write-once layout + ifneq ($(NVM_FLASH_WRITEONCE),1) + $(error TARGET=mcxe31b requires NVM_FLASH_WRITEONCE=1) + endif endif ifeq ($(TARGET),stm32l0) CORTEX_M0=1 diff --git a/config/examples/mcxe31b.config b/config/examples/mcxe31b.config index 86254b8672..a3485903cd 100644 --- a/config/examples/mcxe31b.config +++ b/config/examples/mcxe31b.config @@ -28,9 +28,6 @@ SPMATH?=1 RAM_CODE?=1 DUALBANK_SWAP?=0 -# The CM7 DTCM is ECC protected and must be written before it is read -CFLAGS_EXTRA+=-DWOLFBOOT_RAM_ECC_INIT - # 8KB sectors WOLFBOOT_SECTOR_SIZE?=0x2000 diff --git a/test-app/Makefile b/test-app/Makefile index 61aed0464d..907fbeb4b2 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1861,6 +1861,10 @@ ifeq ($(ENABLE_WOLFIP),1) CFLAGS+=-DNXP_MCXE_ENET_STATS=1 endif else ifeq ($(TARGET),mcxe31b) + # The network test is started and reports on the console + ifneq ($(DEBUG_UART),1) + $(error ENABLE_WOLFIP=1 on mcxe31b needs DEBUG_UART=1) + endif WOLFIP_PORT:=nxp_mcxe_emac WOLFIP_PORT_OBJ:=nxp_mcxe_emac.o # wolfIP state in SRAM, EMAC rings in the DTCM (ARM-mcxe31b-wolfip.ld) From a72994fb156263e4874aafd48cd35f39437c26a8 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 4 Dec 2026 20:14:44 -0500 Subject: [PATCH 14/21] test-app: clear the ITCM ECC with APP_ITCM_ECC_INIT The reset handler cleared the ITCM whenever APP_RAMCODE_ITCM was set, which assumes an ECC protected ITCM, and only with APP_RAM_ECC_INIT. Clear it with a separate APP_ITCM_ECC_INIT instead, and build the naked reset handler when either option is set, each loop under its own option. An ITCM without ECC needs only APP_RAMCODE_ITCM. The mcxe31b wolfIP build sets APP_ITCM_ECC_INIT, and its linker script checks the ITCM clear range is 8-byte aligned for the 64-bit stores. --- docs/Targets.md | 5 +++-- test-app/ARM-mcxe31b-wolfip.ld | 5 ++++- test-app/Makefile | 2 ++ test-app/startup_arm.c | 38 ++++++++++++++++++---------------- 4 files changed, 29 insertions(+), 21 deletions(-) diff --git a/docs/Targets.md b/docs/Targets.md index e2513a1cdb..4976990ea7 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -8164,8 +8164,9 @@ protected: the reset handler clears all 320 KB of it with 64-bit stores (`APP_RAM_ECC_INIT`) before it is used. The hottest network code: (`memcpy`, `memset` and `memcmp`, wolfIP's checksum, poll loop, FIFO and TCP send path, and the driver's poll, send and interrupt handler) runs from the -ITCM: the reset handler clears the ITCM and copies it there -(`APP_RAMCODE_ITCM`). The linker script stops the build when `memcpy` or the +ITCM: the reset handler clears the ITCM, which is also ECC protected +(`APP_ITCM_ECC_INIT`), and copies the code there (`APP_RAMCODE_ITCM`). +The linker script stops the build when `memcpy` or the wolfIP checksum is missing from the ITCM. wolfIP takes at most 16 frames per `wolfIP_poll()` (`WOLFIP_POLL_BUDGET=16`). The driver uses 8 transmit and 4 receive descriptors (19 KB of DTCM). diff --git a/test-app/ARM-mcxe31b-wolfip.ld b/test-app/ARM-mcxe31b-wolfip.ld index 352b1c368e..6c4e1691b1 100644 --- a/test-app/ARM-mcxe31b-wolfip.ld +++ b/test-app/ARM-mcxe31b-wolfip.ld @@ -144,9 +144,12 @@ _wolfboot_partition_swap_address = @WOLFBOOT_PARTITION_SWAP_ADDRESS@; _start_heap = _end; _end_stack = ORIGIN(RAM) + LENGTH(RAM); -/* ITCM cleared at reset with APP_RAMCODE_ITCM, before the code is copied */ +/* ITCM cleared at reset with APP_ITCM_ECC_INIT, before the code is copied, + * with 64-bit stores */ _start_ecc_itcm = 0x00000000; _end_ecc_itcm = 0x00008000; +ASSERT(_start_ecc_itcm % 8 == 0 && _end_ecc_itcm % 8 == 0, + "ITCM clear range must be 8-byte aligned") /* SRAM cleared at reset with APP_RAM_ECC_INIT */ _start_ecc_ram = ORIGIN(SRAM); diff --git a/test-app/Makefile b/test-app/Makefile index 907fbeb4b2..c2f12069a2 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1875,6 +1875,8 @@ ifeq ($(ENABLE_WOLFIP),1) # is in .ramcode only with __WOLFBOOT, also when the test-app builds # string.o itself. CFLAGS+=-DAPP_RAMCODE_ITCM + # The ITCM is ECC protected too: clear it at reset, before the copy + CFLAGS+=-DAPP_ITCM_ECC_INIT ../src/string.o: CFLAGS+=-D__WOLFBOOT # NXP_MCXE_EMAC_IRQ=0 polls the EMAC instead of using its interrupt NXP_MCXE_EMAC_IRQ?=1 diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index 98c9da07b2..49d62a317b 100644 --- a/test-app/startup_arm.c +++ b/test-app/startup_arm.c @@ -111,51 +111,54 @@ static unsigned int sp; extern void main(void); -#ifdef APP_RAM_ECC_INIT -/* ECC SRAM words not written since power-on hold no valid ECC. - * Clear [_start_ecc_ram, _end_ecc_ram) */ +#if defined(APP_RAM_ECC_INIT) || defined(APP_ITCM_ECC_INIT) +/* ECC memory not written since power-on holds no valid ECC: clear it + * before C code runs. + * APP_RAM_ECC_INIT: [_start_ecc_ram, _end_ecc_ram), before .data, .bss + * and the stack are used. + * APP_ITCM_ECC_INIT: [_start_ecc_itcm, _end_ecc_itcm), with 64-bit stores, + * before APP_RAMCODE_ITCM copies code in. An ITCM without ECC needs only + * APP_RAMCODE_ITCM. */ extern void isr_reset_c(void); __attribute__((naked, used, noreturn)) void isr_reset(void) { __asm__ volatile( - "ldr r0, =_start_ecc_ram\n\t" - "ldr r1, =_end_ecc_ram\n\t" "movs r2, #0\n\t" -#ifdef TARGET_mcxe31b - /* SRAM ECC words are 64 bits: [_start, _end) is 8-byte aligned */ "movs r3, #0\n\t" -#endif +# ifdef APP_RAM_ECC_INIT + "ldr r0, =_start_ecc_ram\n\t" + "ldr r1, =_end_ecc_ram\n\t" "1:\n\t" "cmp r0, r1\n\t" "bhs 2f\n\t" -#ifdef TARGET_mcxe31b +# ifdef TARGET_mcxe31b + /* SRAM ECC words are 64 bits: [_start, _end) is 8-byte aligned */ "strd r2, r3, [r0], #8\n\t" -#else +# else "str r2, [r0], #4\n\t" -#endif +# endif "b 1b\n\t" "2:\n\t" -#ifdef APP_RAMCODE_ITCM - /* The ITCM holds no valid ECC either: clear it before the hot - * code is copied in, also with 64-bit stores (r2 and r3 zero) */ +# endif /* APP_RAM_ECC_INIT */ +# ifdef APP_ITCM_ECC_INIT + /* [_start, _end) is 8-byte aligned */ "ldr r0, =_start_ecc_itcm\n\t" "ldr r1, =_end_ecc_itcm\n\t" - "movs r3, #0\n\t" "3:\n\t" "cmp r0, r1\n\t" "bhs 4f\n\t" "strd r2, r3, [r0], #8\n\t" "b 3b\n\t" "4:\n\t" -#endif +# endif /* APP_ITCM_ECC_INIT */ "b isr_reset_c\n\t" ); } void isr_reset_c(void) #else void isr_reset(void) -#endif +#endif /* APP_RAM_ECC_INIT || APP_ITCM_ECC_INIT */ { register unsigned int *src, *dst; @@ -164,7 +167,6 @@ void isr_reset(void) boot_time_pin_on_early(); #endif - src = (unsigned int *) &_stored_data; dst = (unsigned int *) &_start_data; while (dst < (unsigned int *)&_end_data) { From 2ff7fc125ea168fc92fd1f8ead7f5604ba612120 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 4 Dec 2026 20:14:44 -0500 Subject: [PATCH 15/21] mcxe31b: drain the XMODEM leftovers from the RX buffer, status names - After a transfer, drain the bytes the LPUART interrupt buffered, instead of reading the LPUART, which the interrupt has already emptied. - status names partition states with part_state_name(), so an unknown state shows as UNKNOWN instead of NEW. - xmodem_rx.c: list the files that include it, the unit test included. --- test-app/app_mcxe31b.c | 13 ++++--------- test-app/xmodem_rx.c | 4 +++- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/test-app/app_mcxe31b.c b/test-app/app_mcxe31b.c index 1984f9e887..e68f65bdad 100644 --- a/test-app/app_mcxe31b.c +++ b/test-app/app_mcxe31b.c @@ -516,7 +516,8 @@ static int cmd_update_xmodem(void) /* Wait for sender to finish and drain any pending RX data. * This prevents printf output from mixing with XMODEM retransmits. */ delay_ms(3000); /* Wait for sender to give up */ - while (uart_read(&c) > 0) {} /* Drain RX buffer */ + /* The RX interrupt holds what arrived: drain its buffer */ + while (uart_getc(&c) > 0) {} printf("\r\nTransfer %s\r\n", (ret == 0) ? "complete!" : "failed."); printf("XMODEM stats: recv=%lu, crc_fail=%lu, num_fail=%lu, soh_fail=%lu, timeouts=%lu\r\n", @@ -625,10 +626,7 @@ static int cmd_status(const char *args) ret = wolfBoot_get_partition_state(PART_BOOT, &boot_state); if (ret == 0) { - printf(" State: %s (0x%02X)\r\n", - (boot_state == IMG_STATE_SUCCESS) ? "SUCCESS" : - (boot_state == IMG_STATE_TESTING) ? "TESTING" : - (boot_state == IMG_STATE_UPDATING) ? "UPDATING" : "NEW", + printf(" State: %s (0x%02X)\r\n", part_state_name(boot_state, ret), boot_state); } else { printf(" State: (no trailer)\r\n"); @@ -639,10 +637,7 @@ static int cmd_status(const char *args) ret = wolfBoot_get_partition_state(PART_UPDATE, &update_state); if (ret == 0) { - printf(" State: %s (0x%02X)\r\n", - (update_state == IMG_STATE_SUCCESS) ? "SUCCESS" : - (update_state == IMG_STATE_TESTING) ? "TESTING" : - (update_state == IMG_STATE_UPDATING) ? "UPDATING" : "NEW", + printf(" State: %s (0x%02X)\r\n", part_state_name(update_state, ret), update_state); } else { printf(" State: (no trailer)\r\n"); diff --git a/test-app/xmodem_rx.c b/test-app/xmodem_rx.c index 8edb74be0f..afb78561f5 100644 --- a/test-app/xmodem_rx.c +++ b/test-app/xmodem_rx.c @@ -2,7 +2,9 @@ * * XMODEM-CRC receiver common code for test-apps. * Writes the received image to the update partition. Uses the target's - * UART, LED and jiffies helpers. + * UART, LED and jiffies helpers. Included by app_s32k1xx.c and + * app_mcxe31b.c, and by tools/unit-tests/unit-xmodem-rx.c, which mocks + * those helpers and the flash. * * Copyright (C) 2026 wolfSSL Inc. * From 9474f8e1beb2053d555fc1f5dd8eeee38dd7aaaf Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 4 Dec 2026 20:38:21 -0500 Subject: [PATCH 16/21] mcxe31b: unit test for the flash write and erase logic Add tools/unit-tests/unit-flash-mcxe31b.c. It compiles only the flash logic of hal/mcxe31b.c (WOLFBOOT_UNIT_TEST_FLASH) and models the C40ASF program and erase steps: one program per 64-bit ECC segment between erases, programs that only clear bits. It covers the quad page split, merging partial writes, skipping unchanged segments, the sector rounding of the erase, the range checks of both, and failures. The HAL reads the flash array through FLASH_PTR(), a plain pointer in the target build, which the test maps onto its flash model. --- .gitignore | 1 + hal/mcxe31b.c | 20 +- tools/unit-tests/Makefile | 7 + tools/unit-tests/unit-flash-mcxe31b.c | 392 ++++++++++++++++++++++++++ 4 files changed, 418 insertions(+), 2 deletions(-) create mode 100644 tools/unit-tests/unit-flash-mcxe31b.c diff --git a/.gitignore b/.gitignore index f1a7bb4295..fa58af26ee 100644 --- a/.gitignore +++ b/.gitignore @@ -668,6 +668,7 @@ tools/unit-tests/unit-elf-phentsize tools/unit-tests/unit-fdt-memrsv-wrap tools/unit-tests/unit-flash-erase-kinetis tools/unit-tests/unit-flash-m2354 +tools/unit-tests/unit-flash-mcxe31b tools/unit-tests/unit-fwtpm-cmd-toctou tools/unit-tests/unit-fwtpm-rsp-overrun tools/unit-tests/unit-hifive1-flash-write diff --git a/hal/mcxe31b.c b/hal/mcxe31b.c index 00785f77de..d2c8b0ccdd 100644 --- a/hal/mcxe31b.c +++ b/hal/mcxe31b.c @@ -24,9 +24,11 @@ #include #include +#ifndef WOLFBOOT_UNIT_TEST_FLASH #include "image.h" #include "hal.h" #include "printf.h" +#endif /* Override RAMFUNCTION for test-app: when RAM_CODE is set but not __WOLFBOOT, * we still need flash functions to run from RAM for self-programming. */ @@ -52,6 +54,15 @@ #include "mcxe31b.h" +/* Reads of the flash array. tools/unit-tests/unit-flash-mcxe31b.c compiles + * only the flash logic (WOLFBOOT_UNIT_TEST_FLASH) and maps this onto its + * flash model. */ +#ifndef FLASH_PTR +#define FLASH_PTR(addr) ((const void *)(uintptr_t)(addr)) +#endif + +#ifndef WOLFBOOT_UNIT_TEST_FLASH + /* ============== Image Vector Table (IVT) ============== */ /* The Secure BAF boot ROM scans for this 256-byte structure at the start of * each code flash block (0x00400000 first) and starts CM7_0 at the vector @@ -368,6 +379,7 @@ int RAMFUNCTION uart_read(char* c) } #endif /* DEBUG_UART */ +#endif /* !WOLFBOOT_UNIT_TEST_FLASH */ /* Non-zero when [address, address + len) lies in the code flash or in the * data flash */ @@ -387,6 +399,7 @@ static int RAMFUNCTION flash_range_ok(uint32_t address, uint32_t len) return 0; } +#ifndef WOLFBOOT_UNIT_TEST_FLASH /* Return the PFLASH lock register and bit covering a flash address * (checked by flash_range_ok()). The first * 768 KB of each code block is locked per 64 KB super sector, the last 256 KB @@ -549,6 +562,7 @@ void hal_prepare_boot(void) * caches off */ cache_disable(); } +#endif /* !WOLFBOOT_UNIT_TEST_FLASH */ /* Program any length at any address. Writes are split per quad page; each * 64-bit ECC segment that changes is merged with the current flash contents @@ -571,13 +585,13 @@ int RAMFUNCTION hal_flash_write(uint32_t address, const uint8_t *data, int len) if (end > FLASH_QUAD_PAGE_SIZE) end = FLASH_QUAD_PAGE_SIZE; - memcpy(buf, (const void *)qpage, FLASH_QUAD_PAGE_SIZE); + memcpy(buf, FLASH_PTR(qpage), FLASH_QUAD_PAGE_SIZE); memcpy(buf + start, data, end - start); mask = 0; for (off = start & ~(FLASH_DWORD_SIZE - 1); off < end; off += FLASH_DWORD_SIZE) { - if (memcmp(buf + off, (const void *)(qpage + off), + if (memcmp(buf + off, FLASH_PTR(qpage + off), FLASH_DWORD_SIZE) != 0) { mask |= 3UL << (off / 4); } @@ -618,6 +632,7 @@ int RAMFUNCTION hal_flash_erase(uint32_t address, int len) return 0; } +#ifndef WOLFBOOT_UNIT_TEST_FLASH void RAMFUNCTION hal_flash_unlock(void) { } @@ -625,3 +640,4 @@ void RAMFUNCTION hal_flash_unlock(void) void RAMFUNCTION hal_flash_lock(void) { } +#endif /* !WOLFBOOT_UNIT_TEST_FLASH */ diff --git a/tools/unit-tests/Makefile b/tools/unit-tests/Makefile index 2b443e2754..271541472b 100644 --- a/tools/unit-tests/Makefile +++ b/tools/unit-tests/Makefile @@ -136,6 +136,7 @@ TESTS+=unit-flash-erase-c0 TESTS+=unit-flash-erase-u3 TESTS+=unit-flash-erase-kinetis TESTS+=unit-flash-m2354 +TESTS+=unit-flash-mcxe31b TESTS+=unit-otp-keystore TESTS+=unit-snvm-keystore TESTS+=unit-snvm-kek @@ -1066,6 +1067,12 @@ unit-flash-erase-kinetis: unit-flash-erase-kinetis.c kinetis_erase_extract.h unit-flash-m2354: unit-flash-m2354.c ../../hal/m2354.c ../../hal/m2354.h gcc -o $@ unit-flash-m2354.c -I../.. $(CFLAGS) $(LDFLAGS) +# unit-flash-mcxe31b includes hal/mcxe31b.c directly (guarded to the flash +# logic via WOLFBOOT_UNIT_TEST_FLASH), so the clock, cache, UART and C40ASF +# register code is excluded and the program and erase steps are modeled. +unit-flash-mcxe31b: unit-flash-mcxe31b.c ../../hal/mcxe31b.c ../../hal/mcxe31b.h + gcc -o $@ unit-flash-mcxe31b.c $(CFLAGS) $(LDFLAGS) + # unit-otp-keystore includes src/flash_otp_keystore.c directly (guarded to its # host-portable code via WOLFBOOT_UNIT_TEST_OTP_KEYSTORE), so it is not a # separate input. diff --git a/tools/unit-tests/unit-flash-mcxe31b.c b/tools/unit-tests/unit-flash-mcxe31b.c new file mode 100644 index 0000000000..63f5dbbb92 --- /dev/null +++ b/tools/unit-tests/unit-flash-mcxe31b.c @@ -0,0 +1,392 @@ +/* unit-flash-mcxe31b.c + * + * Unit tests for the flash logic of hal/mcxe31b.c: the quad page split of + * hal_flash_write(), its 64-bit ECC segment mask (merge partial writes, + * skip unchanged segments), the sector rounding of hal_flash_erase(), and + * the range checks of both. The C40ASF program and erase steps are + * replaced by a model of the flash. + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include +#include +#include +#include + +/* Compile only the flash logic out of hal/mcxe31b.c */ +#define WOLFBOOT_UNIT_TEST_FLASH + +/* RAMFUNCTION must be empty on the host */ +#define RAMFUNCTION + +static const void *mock_flash_ptr(uint32_t addr); +#define FLASH_PTR(addr) mock_flash_ptr((uint32_t)(addr)) + +/* Replace the C40ASF program and erase steps */ +static int flash_program_qpage(uint32_t qpage, const uint32_t *words, + uint32_t mask); +static int flash_erase_sector(uint32_t address); + +#include "../../hal/mcxe31b.c" + +#define CODE_SIZE (FLASH_NUM_BLOCKS * FLASH_BLOCK_SIZE) +#define CODE_END (FLASH_BASE + CODE_SIZE) +#define DATA_END (FLASH_DATA_BASE + FLASH_DATA_SIZE) +#define NUM_SEGS ((CODE_SIZE + FLASH_DATA_SIZE) / FLASH_DWORD_SIZE) + +/* Code flash, then data flash */ +static uint8_t mock_flash[CODE_SIZE + FLASH_DATA_SIZE]; +/* Program operations on each ECC segment since its last erase */ +static uint8_t seg_programs[NUM_SEGS]; + +static int program_calls; +static int erase_calls; +static uint32_t erase_log[16]; +static int fail_at; /* fail the n-th program/erase call, 0: never */ +static int reprograms; /* segments programmed twice between erases */ + +/* Offset of a flash address in mock_flash */ +static uint32_t flash_off(uint32_t addr, uint32_t len) +{ + if (addr >= FLASH_BASE && addr - FLASH_BASE <= CODE_SIZE && + len <= CODE_SIZE - (addr - FLASH_BASE)) { + return addr - FLASH_BASE; + } + ck_assert_msg(addr >= FLASH_DATA_BASE && + addr - FLASH_DATA_BASE <= FLASH_DATA_SIZE && + len <= FLASH_DATA_SIZE - (addr - FLASH_DATA_BASE), + "access outside flash: 0x%08x + %u", addr, len); + return CODE_SIZE + (addr - FLASH_DATA_BASE); +} + +static const void *mock_flash_ptr(uint32_t addr) +{ + return &mock_flash[flash_off(addr, 1)]; +} + +static int flash_program_qpage(uint32_t qpage, const uint32_t *words, + uint32_t mask) +{ + uint32_t off, cur; + int i; + + program_calls++; + if (fail_at != 0 && program_calls + erase_calls == fail_at) + return -1; + ck_assert_uint_eq(qpage % FLASH_QUAD_PAGE_SIZE, 0); + ck_assert_uint_ne(mask, 0); + off = flash_off(qpage, FLASH_QUAD_PAGE_SIZE); + for (i = 0; i < FLASH_QUAD_PAGE_SIZE / 4; i += 2) { + /* Whole ECC segments only */ + ck_assert_uint_eq((mask >> i) & 1U, (mask >> (i + 1)) & 1U); + if (((mask >> i) & 1U) == 0U) + continue; + if (seg_programs[(off + i * 4) / FLASH_DWORD_SIZE]++ != 0) + reprograms++; + } + for (i = 0; i < FLASH_QUAD_PAGE_SIZE / 4; i++) { + if (((mask >> i) & 1U) == 0U) + continue; + /* Programming only clears bits */ + memcpy(&cur, &mock_flash[off + i * 4], sizeof(cur)); + ck_assert_uint_eq(cur & words[i], words[i]); + memcpy(&mock_flash[off + i * 4], &words[i], sizeof(cur)); + } + return 0; +} + +static int flash_erase_sector(uint32_t address) +{ + uint32_t off; + + if (erase_calls < (int)(sizeof(erase_log) / sizeof(erase_log[0]))) + erase_log[erase_calls] = address; + erase_calls++; + if (fail_at != 0 && program_calls + erase_calls == fail_at) + return -1; + ck_assert_uint_eq(address % FLASH_SECTOR_SIZE, 0); + off = flash_off(address, FLASH_SECTOR_SIZE); + memset(&mock_flash[off], 0xFF, FLASH_SECTOR_SIZE); + memset(&seg_programs[off / FLASH_DWORD_SIZE], 0, + FLASH_SECTOR_SIZE / FLASH_DWORD_SIZE); + return 0; +} + +static void setup(void) +{ + memset(mock_flash, 0xFF, sizeof(mock_flash)); + memset(seg_programs, 0, sizeof(seg_programs)); + program_calls = 0; + erase_calls = 0; + fail_at = 0; + reprograms = 0; +} + +static void fill(uint8_t *buf, int len, uint8_t seed) +{ + int i; + + for (i = 0; i < len; i++) + buf[i] = (uint8_t)(seed + i * 7); +} + +static int is_erased(uint32_t addr, uint32_t len) +{ + const uint8_t *p = mock_flash_ptr(addr); + uint32_t i; + + for (i = 0; i < len; i++) { + if (p[i] != 0xFF) + return 0; + } + return 1; +} + +/* A whole aligned quad page is one program of all 16 words */ +START_TEST(test_write_aligned_quad_page) +{ + uint8_t data[FLASH_QUAD_PAGE_SIZE]; + + fill(data, sizeof(data), 1); + ck_assert_int_eq(hal_flash_write(0x410000, data, sizeof(data)), 0); + ck_assert_int_eq(program_calls, 1); + ck_assert_mem_eq(mock_flash_ptr(0x410000), data, sizeof(data)); + ck_assert(is_erased(0x410080, 0x80)); +} +END_TEST + +/* An unaligned write across two quad pages is split at the boundary, and + * the bytes around it stay erased */ +START_TEST(test_write_unaligned_across_quad_pages) +{ + uint8_t data[100]; + + fill(data, sizeof(data), 2); + ck_assert_int_eq(hal_flash_write(0x410000 + 90, data, sizeof(data)), 0); + ck_assert_int_eq(program_calls, 2); + ck_assert_mem_eq(mock_flash_ptr(0x410000 + 90), data, sizeof(data)); + ck_assert(is_erased(0x410000, 90)); + ck_assert(is_erased(0x410000 + 190, 0x100 - 190)); + ck_assert_int_eq(reprograms, 0); +} +END_TEST + +/* A write of a few bytes programs only the segments it touches, merged with + * the erased bytes around it */ +START_TEST(test_write_partial_segment_merges) +{ + const uint8_t data[3] = { 0x11, 0x22, 0x33 }; + + ck_assert_int_eq(hal_flash_write(0x410000 + 6, data, sizeof(data)), 0); + ck_assert_int_eq(program_calls, 1); + /* Bytes 6..8 span segments 0 and 1 */ + ck_assert_uint_eq(seg_programs[(0x10000 + 0) / 8], 1); + ck_assert_uint_eq(seg_programs[(0x10000 + 8) / 8], 1); + ck_assert_uint_eq(seg_programs[(0x10000 + 16) / 8], 0); + ck_assert_mem_eq(mock_flash_ptr(0x410000 + 6), data, sizeof(data)); + ck_assert(is_erased(0x410000, 6)); + ck_assert(is_erased(0x410000 + 9, 7)); +} +END_TEST + +/* Writing what the flash already holds programs nothing */ +START_TEST(test_write_unchanged_is_skipped) +{ + uint8_t data[200]; + + fill(data, sizeof(data), 3); + ck_assert_int_eq(hal_flash_write(0x420010, data, sizeof(data)), 0); + program_calls = 0; + ck_assert_int_eq(hal_flash_write(0x420010, data, sizeof(data)), 0); + ck_assert_int_eq(program_calls, 0); + ck_assert_int_eq(reprograms, 0); +} +END_TEST + +/* A rewrite that changes one segment programs that segment only */ +START_TEST(test_write_skips_unchanged_segments) +{ + uint8_t data[FLASH_QUAD_PAGE_SIZE]; + + memset(data, 0xFF, sizeof(data)); + data[0] = 0x00; + ck_assert_int_eq(hal_flash_write(0x430000, data, sizeof(data)), 0); + data[40] = 0x00; + ck_assert_int_eq(hal_flash_write(0x430000, data, sizeof(data)), 0); + ck_assert_int_eq(program_calls, 2); + ck_assert_int_eq(reprograms, 0); + ck_assert_uint_eq(seg_programs[0x30000 / 8], 1); + ck_assert_uint_eq(seg_programs[(0x30000 + 40) / 8], 1); +} +END_TEST + +/* A long write programs each quad page once */ +START_TEST(test_write_many_quad_pages) +{ + static uint8_t data[FLASH_SECTOR_SIZE]; + + fill(data, sizeof(data), 4); + ck_assert_int_eq(hal_flash_write(0x5F0000, data, sizeof(data)), 0); + ck_assert_int_eq(program_calls, FLASH_SECTOR_SIZE / FLASH_QUAD_PAGE_SIZE); + ck_assert_mem_eq(mock_flash_ptr(0x5F0000), data, sizeof(data)); + ck_assert_int_eq(reprograms, 0); +} +END_TEST + +/* The data flash is writable too */ +START_TEST(test_write_data_flash) +{ + uint8_t data[16]; + + fill(data, sizeof(data), 5); + ck_assert_int_eq(hal_flash_write(DATA_END - 16, data, 16), 0); + ck_assert_mem_eq(mock_flash_ptr(DATA_END - 16), data, 16); +} +END_TEST + +/* The last bytes of the code flash are writable, one more byte is not */ +START_TEST(test_write_range_limits) +{ + uint8_t data[16]; + + fill(data, sizeof(data), 6); + ck_assert_int_eq(hal_flash_write(CODE_END - 16, data, 16), 0); + ck_assert_int_eq(program_calls, 1); + ck_assert_int_eq(hal_flash_write(CODE_END - 15, data, 16), -1); + ck_assert_int_eq(hal_flash_write(CODE_END, data, 1), -1); + ck_assert_int_eq(hal_flash_write(FLASH_BASE - 1, data, 1), -1); + ck_assert_int_eq(hal_flash_write(0, data, 1), -1); + ck_assert_int_eq(hal_flash_write(DATA_END - 15, data, 16), -1); + ck_assert_int_eq(hal_flash_write(FLASH_DATA_BASE - 8, data, 16), -1); + ck_assert_int_eq(hal_flash_write(0xFFFFFFF0UL, data, 16), -1); + ck_assert_int_eq(hal_flash_write(0x410000, data, -1), -1); + ck_assert_int_eq(program_calls, 1); + ck_assert_int_eq(hal_flash_write(0x410000, data, 0), 0); +} +END_TEST + +/* A failed program stops the write and is returned */ +START_TEST(test_write_propagates_failure) +{ + uint8_t data[FLASH_QUAD_PAGE_SIZE * 3]; + + fill(data, sizeof(data), 7); + fail_at = 2; + ck_assert_int_eq(hal_flash_write(0x410000, data, sizeof(data)), -1); + ck_assert_int_eq(program_calls, 2); +} +END_TEST + +/* The erase rounds the address down to a sector and erases whole sectors + * up to address + len */ +START_TEST(test_erase_rounds_to_sectors) +{ + ck_assert_int_eq(hal_flash_erase(0x410000 + 0x100, 1), 0); + ck_assert_int_eq(erase_calls, 1); + ck_assert_uint_eq(erase_log[0], 0x410000); + + erase_calls = 0; + ck_assert_int_eq(hal_flash_erase(0x410000, FLASH_SECTOR_SIZE + 1), 0); + ck_assert_int_eq(erase_calls, 2); + ck_assert_uint_eq(erase_log[0], 0x410000); + ck_assert_uint_eq(erase_log[1], 0x410000 + FLASH_SECTOR_SIZE); +} +END_TEST + +/* An erase clears the data and allows the segments to be programmed again */ +START_TEST(test_erase_then_rewrite) +{ + uint8_t data[32]; + + fill(data, sizeof(data), 8); + ck_assert_int_eq(hal_flash_write(0x440000, data, sizeof(data)), 0); + ck_assert_int_eq(hal_flash_erase(0x440000, FLASH_SECTOR_SIZE), 0); + ck_assert(is_erased(0x440000, FLASH_SECTOR_SIZE)); + fill(data, sizeof(data), 9); + ck_assert_int_eq(hal_flash_write(0x440000, data, sizeof(data)), 0); + ck_assert_mem_eq(mock_flash_ptr(0x440000), data, sizeof(data)); + ck_assert_int_eq(reprograms, 0); +} +END_TEST + +START_TEST(test_erase_range_limits) +{ + ck_assert_int_eq(hal_flash_erase(CODE_END - FLASH_SECTOR_SIZE, + FLASH_SECTOR_SIZE), 0); + ck_assert_int_eq(hal_flash_erase(DATA_END - FLASH_SECTOR_SIZE, + FLASH_SECTOR_SIZE), 0); + ck_assert_int_eq(erase_calls, 2); + ck_assert_int_eq(hal_flash_erase(CODE_END - FLASH_SECTOR_SIZE, + FLASH_SECTOR_SIZE + 1), -1); + ck_assert_int_eq(hal_flash_erase(CODE_END, FLASH_SECTOR_SIZE), -1); + ck_assert_int_eq(hal_flash_erase(FLASH_BASE - FLASH_SECTOR_SIZE, + FLASH_SECTOR_SIZE), -1); + ck_assert_int_eq(hal_flash_erase(DATA_END, 1), -1); + ck_assert_int_eq(hal_flash_erase(0x410000, 0), -1); + ck_assert_int_eq(hal_flash_erase(0x410000, -1), -1); + ck_assert_int_eq(erase_calls, 2); +} +END_TEST + +START_TEST(test_erase_propagates_failure) +{ + fail_at = 2; + ck_assert_int_eq(hal_flash_erase(0x410000, 4 * FLASH_SECTOR_SIZE), -1); + ck_assert_int_eq(erase_calls, 2); +} +END_TEST + +static Suite *mcxe31b_flash_suite(void) +{ + Suite *s = suite_create("flash-mcxe31b"); + TCase *tw = tcase_create("write"); + TCase *te = tcase_create("erase"); + + tcase_add_checked_fixture(tw, setup, NULL); + tcase_add_test(tw, test_write_aligned_quad_page); + tcase_add_test(tw, test_write_unaligned_across_quad_pages); + tcase_add_test(tw, test_write_partial_segment_merges); + tcase_add_test(tw, test_write_unchanged_is_skipped); + tcase_add_test(tw, test_write_skips_unchanged_segments); + tcase_add_test(tw, test_write_many_quad_pages); + tcase_add_test(tw, test_write_data_flash); + tcase_add_test(tw, test_write_range_limits); + tcase_add_test(tw, test_write_propagates_failure); + suite_add_tcase(s, tw); + + tcase_add_checked_fixture(te, setup, NULL); + tcase_add_test(te, test_erase_rounds_to_sectors); + tcase_add_test(te, test_erase_then_rewrite); + tcase_add_test(te, test_erase_range_limits); + tcase_add_test(te, test_erase_propagates_failure); + suite_add_tcase(s, te); + return s; +} + +int main(void) +{ + int failed; + SRunner *sr = srunner_create(mcxe31b_flash_suite()); + + srunner_run_all(sr, CK_NORMAL); + failed = srunner_ntests_failed(sr); + srunner_free(sr); + return (failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; +} From ba218298831b9b6e02c9f7523ef20bf9ef51df0d Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 4 Dec 2026 20:38:21 -0500 Subject: [PATCH 17/21] test-app: select 64-bit SRAM ECC clears with APP_RAM_ECC_64BIT The shared APP_RAM_ECC_INIT reset handler chose 64-bit stores by TARGET_mcxe31b. Select them with APP_RAM_ECC_64BIT instead, set by the mcxe31b wolfIP build, whose linker script now checks the SRAM clear range is 8-byte aligned. Tested on the FRDM-MCXE31B: boots, speed test unchanged. --- docs/Targets.md | 2 +- test-app/ARM-mcxe31b-wolfip.ld | 5 ++++- test-app/Makefile | 5 +++-- test-app/startup_arm.c | 7 ++++--- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/docs/Targets.md b/docs/Targets.md index 4976990ea7..95eb83c776 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -8161,7 +8161,7 @@ reaches through its backdoor port, and places the wolfIP stack state, with 9 KB TCP receive and transmit buffers per socket, the TFTP receive buffer and libwolfboot's 8 KB flash sector buffer (`NVM_CACHE`) in SRAM. SRAM is ECC protected: the reset handler clears all 320 KB of it with 64-bit stores -(`APP_RAM_ECC_INIT`) before it is used. The hottest network code: +(`APP_RAM_ECC_INIT`, `APP_RAM_ECC_64BIT`) before it is used. The hottest network code: (`memcpy`, `memset` and `memcmp`, wolfIP's checksum, poll loop, FIFO and TCP send path, and the driver's poll, send and interrupt handler) runs from the ITCM: the reset handler clears the ITCM, which is also ECC protected diff --git a/test-app/ARM-mcxe31b-wolfip.ld b/test-app/ARM-mcxe31b-wolfip.ld index 6c4e1691b1..15be859d6f 100644 --- a/test-app/ARM-mcxe31b-wolfip.ld +++ b/test-app/ARM-mcxe31b-wolfip.ld @@ -151,9 +151,12 @@ _end_ecc_itcm = 0x00008000; ASSERT(_start_ecc_itcm % 8 == 0 && _end_ecc_itcm % 8 == 0, "ITCM clear range must be 8-byte aligned") -/* SRAM cleared at reset with APP_RAM_ECC_INIT */ +/* SRAM cleared at reset with APP_RAM_ECC_INIT, with 64-bit stores + * (APP_RAM_ECC_64BIT) */ _start_ecc_ram = ORIGIN(SRAM); _end_ecc_ram = ORIGIN(SRAM) + LENGTH(SRAM); +ASSERT(_start_ecc_ram % 8 == 0 && _end_ecc_ram % 8 == 0, + "SRAM clear range must be 8-byte aligned") /* The load images after .text are placed by address, so ld does not count * them against FLASH */ diff --git a/test-app/Makefile b/test-app/Makefile index c2f12069a2..da576048fb 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1869,8 +1869,9 @@ ifeq ($(ENABLE_WOLFIP),1) WOLFIP_PORT_OBJ:=nxp_mcxe_emac.o # wolfIP state in SRAM, EMAC rings in the DTCM (ARM-mcxe31b-wolfip.ld) LSCRIPT_TEMPLATE=ARM-mcxe31b-wolfip.ld - # Clear all of SRAM at reset, before it is read (ECC) - CFLAGS+=-DAPP_RAM_ECC_INIT + # Clear all of SRAM at reset, before it is read (ECC), with 64-bit + # stores: the SRAM ECC words are 64 bits + CFLAGS+=-DAPP_RAM_ECC_INIT -DAPP_RAM_ECC_64BIT # Hot code in the ITCM (.ramcode_itcm in ARM-mcxe31b-wolfip.ld). memcpy # is in .ramcode only with __WOLFBOOT, also when the test-app builds # string.o itself. diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index 49d62a317b..315d1986bc 100644 --- a/test-app/startup_arm.c +++ b/test-app/startup_arm.c @@ -115,7 +115,8 @@ extern void main(void); /* ECC memory not written since power-on holds no valid ECC: clear it * before C code runs. * APP_RAM_ECC_INIT: [_start_ecc_ram, _end_ecc_ram), before .data, .bss - * and the stack are used. + * and the stack are used, with 32-bit stores, or with 64-bit stores for + * 64-bit ECC words with APP_RAM_ECC_64BIT. * APP_ITCM_ECC_INIT: [_start_ecc_itcm, _end_ecc_itcm), with 64-bit stores, * before APP_RAMCODE_ITCM copies code in. An ITCM without ECC needs only * APP_RAMCODE_ITCM. */ @@ -132,8 +133,8 @@ void isr_reset(void) "1:\n\t" "cmp r0, r1\n\t" "bhs 2f\n\t" -# ifdef TARGET_mcxe31b - /* SRAM ECC words are 64 bits: [_start, _end) is 8-byte aligned */ +# ifdef APP_RAM_ECC_64BIT + /* [_start, _end) is 8-byte aligned */ "strd r2, r3, [r0], #8\n\t" # else "str r2, [r0], #4\n\t" From eaac394790479ce0adae41c176f0fe25af98b120 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 4 Dec 2026 20:38:21 -0500 Subject: [PATCH 18/21] s32k1xx: drain the XMODEM leftovers from the RX buffer After a transfer, drain the bytes the LPUART interrupt buffered, instead of reading the LPUART, which the interrupt has already emptied, as on the MCXE31B. --- test-app/app_s32k1xx.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test-app/app_s32k1xx.c b/test-app/app_s32k1xx.c index a79eb031ea..6b4af9f69d 100644 --- a/test-app/app_s32k1xx.c +++ b/test-app/app_s32k1xx.c @@ -523,7 +523,8 @@ static int cmd_update_xmodem(void) { char c; delay_ms(3000); /* Wait for sender to give up */ - while (uart_read(&c) > 0) {} /* Drain RX buffer */ + /* The RX interrupt holds what arrived: drain its buffer */ + while (uart_getc(&c) > 0) {} } printf("\r\nTransfer %s\r\n", (ret == 0) ? "complete!" : "failed."); From 5050424b63710894af370e26cdeca34aec3ebcd4 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Sat, 5 Dec 2026 00:32:51 -0500 Subject: [PATCH 19/21] mcxe31b: fix review findings in the flash, UART and build - hal_flash_write fails on a segment that must change but is already programmed, instead of programming it again and corrupting its ECC - hal_flash_erase covers every sector of an unaligned range - The console functions do nothing until uart_init() has clocked and configured LPUART5; uart_ready() tells the test-app - Linker scripts place .keystore explicitly; the bootloader script checks the .data load image fits - The test-app takes -DDEBUG_UART from DEBUG_UART=1 only, so the no-UART CI job builds a test-app without a console; the LPUART5 vector falls back to isr_empty - Unit tests for both flash fixes; comment and Targets.md updates --- docs/Targets.md | 5 ++- hal/mcxe31b.c | 53 +++++++++++++++++++++++---- hal/mcxe31b.h | 1 + hal/mcxe31b.ld | 12 ++++++ test-app/ARM-mcxe31b.ld | 7 ++++ test-app/Makefile | 5 ++- test-app/app_mcxe31b.c | 6 ++- test-app/startup_arm.c | 8 +++- test-app/wolfip_tftp_test.c | 4 +- tools/unit-tests/unit-flash-mcxe31b.c | 35 +++++++++++++++++- 10 files changed, 117 insertions(+), 19 deletions(-) diff --git a/docs/Targets.md b/docs/Targets.md index 95eb83c776..4986eacfed 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -8089,7 +8089,8 @@ board. wolfBoot stays on FIRC and prints a warning. - The I-cache and D-cache are on while wolfBoot runs; flash program and erase invalidate the D-cache over the modified range. Both caches are cleaned and - turned off before the jump to the application. The clocks stay at 160 MHz. + turned off before the jump to the application. The clocks stay at 160 MHz: + `WOLFBOOT_RESTORE_CLOCK` has no effect on this target. - `mcxe31b.config` sets `IMAGE_HEADER_SIZE=1024`, so the application starts 1 KB into the boot partition. The application's vector table is used in place, and with up to 163 entries it must be 1 KB aligned: with the default @@ -8161,7 +8162,7 @@ reaches through its backdoor port, and places the wolfIP stack state, with 9 KB TCP receive and transmit buffers per socket, the TFTP receive buffer and libwolfboot's 8 KB flash sector buffer (`NVM_CACHE`) in SRAM. SRAM is ECC protected: the reset handler clears all 320 KB of it with 64-bit stores -(`APP_RAM_ECC_INIT`, `APP_RAM_ECC_64BIT`) before it is used. The hottest network code: +(`APP_RAM_ECC_INIT`, `APP_RAM_ECC_64BIT`) before it is used. The hottest network code (`memcpy`, `memset` and `memcmp`, wolfIP's checksum, poll loop, FIFO and TCP send path, and the driver's poll, send and interrupt handler) runs from the ITCM: the reset handler clears the ITCM, which is also ECC protected diff --git a/hal/mcxe31b.c b/hal/mcxe31b.c index d2c8b0ccdd..352d7de580 100644 --- a/hal/mcxe31b.c +++ b/hal/mcxe31b.c @@ -297,6 +297,10 @@ static void cache_disable(void) #define UART_BAUDRATE 115200 #endif +/* Set once LPUART5 is clocked and configured. An LPUART5 without clock + * faults on access, so the console functions do nothing until then. */ +static int uart_up; + /* LPUART5 functional clock, from the clock configuration actually in use * (the PLL setup may have failed and left the system on FIRC) */ static uint32_t aips_slow_clk(void) @@ -329,7 +333,8 @@ void uart_init(void) } } - /* An LPUART5 without clock faults on access: leave it alone */ + uart_up = 0; + /* Leave LPUART5 alone without its clock: the console stays off */ if (mc_me_clock_enable(MC_ME_REQ_LPUART5) != 0) return; @@ -342,10 +347,19 @@ void uart_init(void) LPUART_BAUD = ((best_osr - 1) << LPUART_BAUD_OSR_SHIFT) | (best_sbr << LPUART_BAUD_SBR_SHIFT); LPUART_CTRL = LPUART_CTRL_TE | LPUART_CTRL_RE; + uart_up = 1; +} + +/* Returns 1 when the console is usable, 0 when uart_init() failed */ +int uart_ready(void) +{ + return uart_up; } void RAMFUNCTION uart_tx(uint8_t byte) { + if (!uart_up) + return; while (!(LPUART_STAT & LPUART_STAT_TDRE)) {} LPUART_DATA = byte; } @@ -353,6 +367,9 @@ void RAMFUNCTION uart_tx(uint8_t byte) void uart_write(const char* buf, unsigned int sz) { unsigned int i; + + if (!uart_up) + return; for (i = 0; i < sz; i++) { if (buf[i] == '\n') { uart_tx('\r'); @@ -365,8 +382,11 @@ void uart_write(const char* buf, unsigned int sz) /* Non-blocking read: returns 1 if a character was read, 0 otherwise */ int RAMFUNCTION uart_read(char* c) { - uint32_t stat = LPUART_STAT; + uint32_t stat; + if (!uart_up) + return 0; + stat = LPUART_STAT; if (stat & (LPUART_STAT_OR | LPUART_STAT_NF | LPUART_STAT_FE | LPUART_STAT_PF)) { LPUART_STAT = stat; /* write 1 to clear */ @@ -555,8 +575,10 @@ void hal_prepare_boot(void) { #ifdef DEBUG_UART /* Leave the UART idle so the application can reinitialize it */ - while (!(LPUART_STAT & LPUART_STAT_TC)) {} - LPUART_CTRL = 0; + if (uart_up) { + while (!(LPUART_STAT & LPUART_STAT_TC)) {} + LPUART_CTRL = 0; + } #endif /* The application starts with the clocks left at 160 MHz and with both * caches off */ @@ -564,10 +586,21 @@ void hal_prepare_boot(void) } #endif /* !WOLFBOOT_UNIT_TEST_FLASH */ +/* Non-zero when the 64-bit ECC segment at addr reads as erased */ +static int RAMFUNCTION flash_dword_erased(uint32_t addr) +{ + uint32_t w[FLASH_DWORD_SIZE / 4]; + + memcpy(w, FLASH_PTR(addr), sizeof(w)); + return (w[0] == 0xFFFFFFFFUL) && (w[1] == 0xFFFFFFFFUL); +} + /* Program any length at any address. Writes are split per quad page; each * 64-bit ECC segment that changes is merged with the current flash contents * and programmed once. Segments that are unchanged are skipped, because the - * C40ASF allows only one program per ECC segment between erases. */ + * C40ASF allows only one program per ECC segment between erases. A segment + * that must change but is already programmed (e.g. after a failed erase) + * fails the write: programming it again would corrupt its ECC. */ int RAMFUNCTION hal_flash_write(uint32_t address, const uint8_t *data, int len) { uint32_t words[FLASH_QUAD_PAGE_SIZE / 4]; @@ -593,6 +626,8 @@ int RAMFUNCTION hal_flash_write(uint32_t address, const uint8_t *data, int len) off += FLASH_DWORD_SIZE) { if (memcmp(buf + off, FLASH_PTR(qpage + off), FLASH_DWORD_SIZE) != 0) { + if (!flash_dword_erased(qpage + off)) + return -1; mask |= 3UL << (off / 4); } } @@ -612,12 +647,14 @@ int RAMFUNCTION hal_flash_erase(uint32_t address, int len) { int ret; - if (len <= 0) + if (len <= 0 || (uint32_t)len > FLASH_NUM_BLOCKS * FLASH_BLOCK_SIZE) return -1; - address &= ~(FLASH_SECTOR_SIZE - 1); - /* Whole sectors from the aligned address. flash_lock_reg() indexes the + /* Every sector that overlaps [address, address + len): the bytes below + * an unaligned address are added to len. flash_lock_reg() indexes the * lock registers by address. */ + len += (int)(address & (FLASH_SECTOR_SIZE - 1)); + address &= ~(FLASH_SECTOR_SIZE - 1); if (!flash_range_ok(address, ((uint32_t)len + FLASH_SECTOR_SIZE - 1U) & ~(FLASH_SECTOR_SIZE - 1U))) { return -1; diff --git a/hal/mcxe31b.h b/hal/mcxe31b.h index 2e0e6f4b21..3a0f05bfbe 100644 --- a/hal/mcxe31b.h +++ b/hal/mcxe31b.h @@ -282,6 +282,7 @@ #ifdef DEBUG_UART void uart_init(void); +int uart_ready(void); void uart_tx(uint8_t byte); void uart_write(const char* buf, unsigned int sz); int uart_read(char* c); diff --git a/hal/mcxe31b.ld b/hal/mcxe31b.ld index 57b3d0f846..fc09fa3019 100644 --- a/hal/mcxe31b.ld +++ b/hal/mcxe31b.ld @@ -34,6 +34,13 @@ SECTIONS _end_text = .; } > FLASH + /* Placed explicitly so it cannot land after _stored_data as an orphan */ + .keystore : + { + . = ALIGN(4); + KEEP(*(.keystore*)) + } > FLASH + .edidx : { . = ALIGN(4); @@ -68,6 +75,11 @@ SECTIONS END_STACK = ORIGIN(RAM) + LENGTH(RAM); +/* .data (with the RAM_CODE routines) is placed by address, so ld does not + * count its load image against FLASH */ +ASSERT(_stored_data + SIZEOF(.data) <= ORIGIN(FLASH) + LENGTH(FLASH), + "the .data load image overflows the bootloader partition") + ASSERT(hal_flash_write >= ORIGIN(RAM) && hal_flash_erase >= ORIGIN(RAM), "MCXE31B flash routines must run from RAM (RAM_CODE=1)") diff --git a/test-app/ARM-mcxe31b.ld b/test-app/ARM-mcxe31b.ld index 20e8fa4840..ab672d83ed 100644 --- a/test-app/ARM-mcxe31b.ld +++ b/test-app/ARM-mcxe31b.ld @@ -31,6 +31,13 @@ SECTIONS ASSERT(_start_text % 1024 == 0, "vector table not 1 KB aligned: set IMAGE_HEADER_SIZE=1024") + /* Placed explicitly so it cannot land after _stored_data as an orphan */ + .keystore : + { + . = ALIGN(4); + KEEP(*(.keystore*)) + } > FLASH + .edidx : { . = ALIGN(4); diff --git a/test-app/Makefile b/test-app/Makefile index da576048fb..9d3650ac9e 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1159,7 +1159,7 @@ ifeq ($(TARGET),mcxe31b) APP_OBJS+=../src/keystore.o endif CFLAGS+=-DAPP_HAS_SYSTICK - CFLAGS+=-DRAM_CODE -DDEBUG_UART + CFLAGS+=-DRAM_CODE endif ifeq ($(TARGET),stm32n6) @@ -1812,7 +1812,8 @@ WOLFHSM_CFLAGS:=$(CFLAGS) # Optional wolfIP network stack in the test-app. # ENABLE_WOLFIP=1 wolfIP ethernet port (nxp_fman, nxp_enetc on LS1028A, -# or nxp_mcxe_enet on MCXE247) + a link/PHY smoke test. +# nxp_mcxe_enet on MCXE247 or nxp_mcxe_emac on +# MCXE31B) + a link/PHY smoke test. # WOLFBOOT_TEST_TFTP=1 additionally pull in wolfIP core + TFTP client for # the full network TFTP-fetch test. # Point WOLFBOOT_LIB_WOLFIP at a wolfIP checkout, e.g. diff --git a/test-app/app_mcxe31b.c b/test-app/app_mcxe31b.c index e68f65bdad..ba125be23a 100644 --- a/test-app/app_mcxe31b.c +++ b/test-app/app_mcxe31b.c @@ -774,8 +774,10 @@ void main(void) hal_init(); #ifdef DEBUG_UART - /* Enable interrupt-based RX buffering for reliable XMODEM transfers */ - uart_rx_irq_enable(); + /* Enable interrupt-based RX buffering for reliable XMODEM transfers. + * Without LPUART5 (clock failure) the console stays silent. */ + if (uart_ready()) + uart_rx_irq_enable(); /* Disable stdout buffering to prevent delayed output during XMODEM */ setvbuf(stdout, NULL, _IONBF, 0); #endif diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index 315d1986bc..3390393a2c 100644 --- a/test-app/startup_arm.c +++ b/test-app/startup_arm.c @@ -83,7 +83,13 @@ extern void nxp_mcxe_enet_irq_handler(void); #endif #ifdef TARGET_mcxe31b +/* LPUART5 console receive interrupt, only with a console */ +#ifdef DEBUG_UART extern void isr_debug_uart(void); +#define isr_lpuart5 isr_debug_uart +#else +#define isr_lpuart5 isr_empty +#endif /* MCXE31B EMAC common interrupt (IRQ 105) */ #if defined(NXP_MCXE_EMAC_IRQ) && (NXP_MCXE_EMAC_IRQ == 1) extern void nxp_mcxe_emac_irq_handler(void); @@ -719,7 +725,7 @@ void (* const IV[])(void) = /* IRQs 0-145 unused except 105 = EMAC, 146 = LPUART5 (console) */ [16 ... (16 + 145)] = isr_empty, [16 + 105] = isr_emac, - [16 + 146] = isr_debug_uart, + [16 + 146] = isr_lpuart5, #elif defined(TARGET_va416x0) /* For Vorago VA416xx */ /* IRQ 0 through TXEV_IRQn (195), for 212 entries. wolfBoot points VTOR diff --git a/test-app/wolfip_tftp_test.c b/test-app/wolfip_tftp_test.c index b44b19a2ac..ab483d7139 100644 --- a/test-app/wolfip_tftp_test.c +++ b/test-app/wolfip_tftp_test.c @@ -2,8 +2,8 @@ * * Optional wolfIP network test for the wolfBoot test-app. Ethernet port and ms * timebase are compile-time selected: NXP QorIQ FMan (T2080/T1024/T1040, - * big-endian PowerPC), NXP Layerscape ENETC (LS1028A, AArch64) or the - * NXP MCX E247 ENET (Cortex-M4). Modes: + * big-endian PowerPC), NXP Layerscape ENETC (LS1028A, AArch64), the + * NXP MCX E247 ENET (Cortex-M4) or the NXP MCX E31B EMAC (Cortex-M7). Modes: * default DHCP lease only * WOLFBOOT_TEST_TFTP + TFTP RRQ fetch into RAM, report size+checksum * (optionally verify them via TFTP_EXPECT_SIZE/SUM) diff --git a/tools/unit-tests/unit-flash-mcxe31b.c b/tools/unit-tests/unit-flash-mcxe31b.c index 63f5dbbb92..32c335d803 100644 --- a/tools/unit-tests/unit-flash-mcxe31b.c +++ b/tools/unit-tests/unit-flash-mcxe31b.c @@ -294,8 +294,27 @@ START_TEST(test_write_propagates_failure) } END_TEST -/* The erase rounds the address down to a sector and erases whole sectors - * up to address + len */ +/* Changed data over a programmed segment (e.g. after a failed erase) fails + * the write and programs nothing */ +START_TEST(test_write_programmed_segment_fails) +{ + uint8_t data[16]; + uint8_t other[16]; + + fill(data, sizeof(data), 10); + ck_assert_int_eq(hal_flash_write(0x450000, data, sizeof(data)), 0); + ck_assert_int_eq(program_calls, 1); + fill(other, sizeof(other), 11); + ck_assert_int_eq(hal_flash_write(0x450000, other, sizeof(other)), -1); + /* Second half of the first segment, programmed by the first write */ + ck_assert_int_eq(hal_flash_write(0x450000 + 4, other, 4), -1); + ck_assert_int_eq(program_calls, 1); + ck_assert_int_eq(reprograms, 0); + ck_assert_mem_eq(mock_flash_ptr(0x450000), data, sizeof(data)); +} +END_TEST + +/* The erase covers every sector that overlaps [address, address + len) */ START_TEST(test_erase_rounds_to_sectors) { ck_assert_int_eq(hal_flash_erase(0x410000 + 0x100, 1), 0); @@ -307,6 +326,13 @@ START_TEST(test_erase_rounds_to_sectors) ck_assert_int_eq(erase_calls, 2); ck_assert_uint_eq(erase_log[0], 0x410000); ck_assert_uint_eq(erase_log[1], 0x410000 + FLASH_SECTOR_SIZE); + + /* Unaligned start, crossing into the next sector */ + erase_calls = 0; + ck_assert_int_eq(hal_flash_erase(0x411F00, 0x200), 0); + ck_assert_int_eq(erase_calls, 2); + ck_assert_uint_eq(erase_log[0], 0x410000); + ck_assert_uint_eq(erase_log[1], 0x412000); } END_TEST @@ -339,6 +365,10 @@ START_TEST(test_erase_range_limits) ck_assert_int_eq(hal_flash_erase(FLASH_BASE - FLASH_SECTOR_SIZE, FLASH_SECTOR_SIZE), -1); ck_assert_int_eq(hal_flash_erase(DATA_END, 1), -1); + /* Unaligned: the last sector plus the bytes below the address */ + ck_assert_int_eq(hal_flash_erase(CODE_END - FLASH_SECTOR_SIZE + 0x100, + FLASH_SECTOR_SIZE), -1); + ck_assert_int_eq(hal_flash_erase(0x410000, 0x7FFFFFFF), -1); ck_assert_int_eq(hal_flash_erase(0x410000, 0), -1); ck_assert_int_eq(hal_flash_erase(0x410000, -1), -1); ck_assert_int_eq(erase_calls, 2); @@ -369,6 +399,7 @@ static Suite *mcxe31b_flash_suite(void) tcase_add_test(tw, test_write_data_flash); tcase_add_test(tw, test_write_range_limits); tcase_add_test(tw, test_write_propagates_failure); + tcase_add_test(tw, test_write_programmed_segment_fails); suite_add_tcase(s, tw); tcase_add_checked_fixture(te, setup, NULL); From 6a81d43437543d07172b5f35fc026bc32cf098ef Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Sat, 5 Dec 2026 01:30:28 -0500 Subject: [PATCH 20/21] mcxe31b: confirm updates without a console, bound the heap - The test-app marks a TESTING update successful also with DEBUG_UART=0; only the message needs the console. Without it the update was rolled back at the next reset. - Both test-app linker scripts reserve a 16 KB stack region below the top of the DTCM; _sbrk() stops at its bottom (_end_heap) instead of at the initial stack pointer, and rejects negative increments. --- test-app/ARM-mcxe31b-wolfip.ld | 11 ++++++++--- test-app/ARM-mcxe31b.ld | 7 ++++++- test-app/app_mcxe31b.c | 19 ++++++++++++------- 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/test-app/ARM-mcxe31b-wolfip.ld b/test-app/ARM-mcxe31b-wolfip.ld index 15be859d6f..dfa4c835fa 100644 --- a/test-app/ARM-mcxe31b-wolfip.ld +++ b/test-app/ARM-mcxe31b-wolfip.ld @@ -140,9 +140,14 @@ _wolfboot_partition_size = @WOLFBOOT_PARTITION_SIZE@; _wolfboot_partition_update_address = @WOLFBOOT_PARTITION_UPDATE_ADDRESS@; _wolfboot_partition_swap_address = @WOLFBOOT_PARTITION_SWAP_ADDRESS@; -/* Stack and heap indicators */ +/* Stack and heap: the stack grows down from the top of the DTCM into a + * reserved 16 KB region; the heap (printf) grows up from .bss to the + * bottom of that region, which _sbrk() does not cross */ +_stack_size = 0x4000; _start_heap = _end; _end_stack = ORIGIN(RAM) + LENGTH(RAM); +_end_heap = _end_stack - _stack_size; +ASSERT(_end <= _end_heap, "not enough RAM left for the stack") /* ITCM cleared at reset with APP_ITCM_ECC_INIT, before the code is copied, * with 64-bit stores */ @@ -165,5 +170,5 @@ ASSERT(_stored_data + SIZEOF(.data) <= ORIGIN(FLASH) + LENGTH(FLASH), /* The EMAC driver's buffers must be in the DTCM */ ASSERT(_end_bss <= ORIGIN(RAM) + LENGTH(RAM), "DTCM overflow") -/* Keep room above .bss for the stack and the heap used by printf */ -ASSERT(_end_stack - _end >= 0x2000, "not enough RAM left for the stack") +/* Keep room for the heap used by printf too */ +ASSERT(_end_heap - _end >= 0x1000, "not enough RAM left for the heap") diff --git a/test-app/ARM-mcxe31b.ld b/test-app/ARM-mcxe31b.ld index ab672d83ed..510b1694f3 100644 --- a/test-app/ARM-mcxe31b.ld +++ b/test-app/ARM-mcxe31b.ld @@ -76,9 +76,14 @@ _wolfboot_partition_size = @WOLFBOOT_PARTITION_SIZE@; _wolfboot_partition_update_address = @WOLFBOOT_PARTITION_UPDATE_ADDRESS@; _wolfboot_partition_swap_address = @WOLFBOOT_PARTITION_SWAP_ADDRESS@; -/* Stack and heap indicators */ +/* Stack and heap: the stack grows down from the top of the DTCM into a + * reserved 16 KB region; the heap (printf) grows up from .bss to the + * bottom of that region, which _sbrk() does not cross */ +_stack_size = 0x4000; _start_heap = _end; _end_stack = ORIGIN(RAM) + LENGTH(RAM); +_end_heap = _end_stack - _stack_size; +ASSERT(_end <= _end_heap, "not enough RAM left for the stack") /* The .data load image is placed by address, so ld does not count it * against FLASH */ diff --git a/test-app/app_mcxe31b.c b/test-app/app_mcxe31b.c index ba125be23a..2c5b3a6e21 100644 --- a/test-app/app_mcxe31b.c +++ b/test-app/app_mcxe31b.c @@ -799,20 +799,25 @@ void main(void) printf("\r\n"); printf("========================================\r\n"); printf("MCXE31B wolfBoot Test Application\r\n"); - printf("Copyright 2025-2026 wolfSSL Inc.\r\n"); + printf("Copyright 2026 wolfSSL Inc.\r\n"); printf("========================================\r\n"); printf("Firmware Version: %lu\r\n", (unsigned long)version); +#endif - /* Auto-mark success for testing if version > 1 */ + /* Auto-mark success for testing if version > 1 + * An update left in TESTING is rolled back at the next reset */ if (version > 1) { uint8_t state = 0; - wolfBoot_get_partition_state(PART_BOOT, &state); - if (state == IMG_STATE_TESTING) { + if (wolfBoot_get_partition_state(PART_BOOT, &state) == 0 && + state == IMG_STATE_TESTING) { +#ifdef DEBUG_UART printf("Testing state detected, marking success...\r\n"); +#endif wolfBoot_success(); } } +#ifdef DEBUG_UART /* Show initial info */ print_partition_info(); @@ -900,7 +905,7 @@ int _fstat(int file, struct stat *st) /* Back-end for malloc, used for printf */ extern unsigned int _end; /* From linker script: end of BSS */ -extern unsigned int _end_stack; /* From linker script: end of RAM */ +extern unsigned int _end_heap; /* From linker script: stack region start */ void *_sbrk(int incr) { @@ -917,8 +922,8 @@ void *_sbrk(int incr) if (((incr >> 2) << 2) != incr) incr = ((incr >> 2) + 1) << 2; - /* Check we don't overflow into the stack */ - if ((heap + incr) > (unsigned char *)&_end_stack) { + /* Stay below the reserved stack region */ + if (incr < 0 || incr > (unsigned char *)&_end_heap - heap) { return (void *)-1; } From f5d56d66fd9fcf9f3062606e0a2d2eb076771780 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Sat, 5 Dec 2026 01:51:24 -0500 Subject: [PATCH 21/21] mcxe31b: unit test the flash lock mapping, rename abort - The lock register and bit calculation moves into flash_lock_bit(), which the unit test builds; flash_lock_reg() keeps its behaviour. test_lock_bit_mapping checks the super sector and sector boundaries of every code block, the last sector and the data flash. - wolfip_test_abort(): rename the local abort, which shadowed abort(), to ctrl_c as in app_s32k1xx.c --- hal/mcxe31b.c | 42 ++++++++++++++++++--------- test-app/app_mcxe31b.c | 6 ++-- tools/unit-tests/unit-flash-mcxe31b.c | 35 ++++++++++++++++++++++ 3 files changed, 66 insertions(+), 17 deletions(-) diff --git a/hal/mcxe31b.c b/hal/mcxe31b.c index 352d7de580..c8f398d4ef 100644 --- a/hal/mcxe31b.c +++ b/hal/mcxe31b.c @@ -419,27 +419,41 @@ static int RAMFUNCTION flash_range_ok(uint32_t address, uint32_t len) return 0; } -#ifndef WOLFBOOT_UNIT_TEST_FLASH -/* Return the PFLASH lock register and bit covering a flash address - * (checked by flash_range_ok()). The first - * 768 KB of each code block is locked per 64 KB super sector, the last 256 KB - * (and the data flash) per 8 KB sector. */ -static volatile uint32_t* RAMFUNCTION flash_lock_reg(uint32_t address, - uint32_t *bit) +/* Lock bit covering a flash address (checked by flash_range_ok()). The + * first 768 KB of each code block is locked per 64 KB super sector + * (SSPELOCK), the last 256 KB and the data flash per 8 KB sector + * (SPELOCK). Sets *blk to the block, 0-3 for the code flash and 4 for the + * data flash, *super to 1 for a super sector, and returns the bit. */ +static uint32_t RAMFUNCTION flash_lock_bit(uint32_t address, uint32_t *blk, + int *super) { - uint32_t blk, off; + uint32_t off; + *super = 0; if (address >= FLASH_DATA_BASE) { - *bit = 1UL << ((address - FLASH_DATA_BASE) / FLASH_SECTOR_SIZE); - return &PFLASH_SPELOCK(4); + *blk = 4; + return 1UL << ((address - FLASH_DATA_BASE) / FLASH_SECTOR_SIZE); } - blk = (address - FLASH_BASE) / FLASH_BLOCK_SIZE; + *blk = (address - FLASH_BASE) / FLASH_BLOCK_SIZE; off = (address - FLASH_BASE) % FLASH_BLOCK_SIZE; if (off < FLASH_SUPER_SECTOR_AREA) { - *bit = 1UL << (off / FLASH_SUPER_SECTOR_SIZE); - return &PFLASH_SSPELOCK(blk); + *super = 1; + return 1UL << (off / FLASH_SUPER_SECTOR_SIZE); } - *bit = 1UL << ((off - FLASH_SUPER_SECTOR_AREA) / FLASH_SECTOR_SIZE); + return 1UL << ((off - FLASH_SUPER_SECTOR_AREA) / FLASH_SECTOR_SIZE); +} + +#ifndef WOLFBOOT_UNIT_TEST_FLASH +/* Return the PFLASH lock register and bit covering a flash address */ +static volatile uint32_t* RAMFUNCTION flash_lock_reg(uint32_t address, + uint32_t *bit) +{ + uint32_t blk; + int super; + + *bit = flash_lock_bit(address, &blk, &super); + if (super) + return &PFLASH_SSPELOCK(blk); return &PFLASH_SPELOCK(blk); } diff --git a/test-app/app_mcxe31b.c b/test-app/app_mcxe31b.c index 2c5b3a6e21..23400bf0c9 100644 --- a/test-app/app_mcxe31b.c +++ b/test-app/app_mcxe31b.c @@ -697,13 +697,13 @@ static int cmd_network(const char *args) int wolfip_test_abort(void) { char c; - int abort = 0; + int ctrl_c = 0; while (uart_getc(&c) > 0) { if (c == 0x03) - abort = 1; + ctrl_c = 1; } - return abort; + return ctrl_c; } #endif #endif diff --git a/tools/unit-tests/unit-flash-mcxe31b.c b/tools/unit-tests/unit-flash-mcxe31b.c index 32c335d803..b9dc89404a 100644 --- a/tools/unit-tests/unit-flash-mcxe31b.c +++ b/tools/unit-tests/unit-flash-mcxe31b.c @@ -383,6 +383,40 @@ START_TEST(test_erase_propagates_failure) } END_TEST +/* Lock register and bit for each kind of sector boundary */ +static void check_lock(uint32_t address, uint32_t blk, int super, uint32_t bit) +{ + uint32_t got_blk = 0xFF; + int got_super = -1; + + ck_assert_uint_eq(flash_lock_bit(address, &got_blk, &got_super), bit); + ck_assert_uint_eq(got_blk, blk); + ck_assert_int_eq(got_super, super); +} + +START_TEST(test_lock_bit_mapping) +{ + uint32_t b, base; + + for (b = 0; b < FLASH_NUM_BLOCKS; b++) { + base = FLASH_BASE + b * FLASH_BLOCK_SIZE; + /* Super sectors 0 and 11, then sectors 0 and 31 */ + check_lock(base, b, 1, 1UL << 0); + check_lock(base + 0xBFFFF, b, 1, 1UL << 11); + check_lock(base + 0xC0000, b, 0, 1UL << 0); + check_lock(base + FLASH_BLOCK_SIZE - 1, b, 0, 1UL << 31); + } + /* Inside a super sector and a sector */ + check_lock(0x410000, 0, 1, 1UL << 1); + check_lock(0x4C2000, 0, 0, 1UL << 1); + /* Last sector of block 3 */ + check_lock(CODE_END - FLASH_SECTOR_SIZE, 3, 0, 1UL << 31); + /* Data flash: sectors 0 and 15 */ + check_lock(FLASH_DATA_BASE, 4, 0, 1UL << 0); + check_lock(DATA_END - 1, 4, 0, 1UL << 15); +} +END_TEST + static Suite *mcxe31b_flash_suite(void) { Suite *s = suite_create("flash-mcxe31b"); @@ -407,6 +441,7 @@ static Suite *mcxe31b_flash_suite(void) tcase_add_test(te, test_erase_then_rewrite); tcase_add_test(te, test_erase_range_limits); tcase_add_test(te, test_erase_propagates_failure); + tcase_add_test(te, test_lock_bit_mapping); suite_add_tcase(s, te); return s; }