diff --git a/.github/workflows/test-configs.yml b/.github/workflows/test-configs.yml index 8373c4e2b0..3df09f992e 100644 --- a/.github/workflows/test-configs.yml +++ b/.github/workflows/test-configs.yml @@ -644,6 +644,19 @@ 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 + + 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/.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/arch.mk b/arch.mk index 3f988e7add..4db06451f0 100644 --- a/arch.mk +++ b/arch.mk @@ -616,6 +616,18 @@ ifeq ($(ARCH),ARM) ifeq ($(TARGET),imx95_m7) CORTEX_M7=1 endif + 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 SPI_TARGET=stm32 diff --git a/config/examples/mcxe31b.config b/config/examples/mcxe31b.config new file mode 100644 index 0000000000..a3485903cd --- /dev/null +++ b/config/examples/mcxe31b.config @@ -0,0 +1,82 @@ +# 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 + +# 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 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 +# 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) +# 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 + +# wolfIP network test in the test-app (optional) +# Adds the "network" console command. Needs a wolfIP checkout, which provides +# 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_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. +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 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"' + +# Debugging options +DEBUG?=0 +DEBUG_SYMBOLS?=0 +DEBUG_UART?=1 diff --git a/docs/Targets.md b/docs/Targets.md index 761efa2b67..4986eacfed 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,193 @@ 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: + `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 + 256-byte header the core fetches the vectors of some interrupts (the EMAC, + 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 + +| 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), including +`network` (see [Network test](#nxp-mcxe31b-network-test)). + +### 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: 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_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_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 +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 +(`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 +(`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). +Set `ENABLE_WOLFIP=1` in `mcxe31b.config` and check the wolfIP path: + +```sh +ENABLE_WOLFIP?=1 +WOLFBOOT_LIB_WOLFIP?=../lib/wolfip +NXP_MCXE_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, with the +script run by Windows Python on a Windows PC on an otherwise idle network: + +| Test | Board receives | Board sends | +|------|----------------|-------------| +| 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 | + +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 (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. + +### 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 with the configured 1 KB header and program it with + `e31b_flash_update.cmm`: + ```sh + 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 + 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..c8f398d4ef --- /dev/null +++ b/hal/mcxe31b.c @@ -0,0 +1,694 @@ +/* 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 +#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. */ +#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" + +/* 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 + * 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 */ +/* 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 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) && --timeout) {} + return (timeout == 0) ? -1 : 0; +} + +/* 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 (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, + * 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; + + 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. */ + 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; + 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; + 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 + +/* 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) +{ + 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; + } + } + + uart_up = 0; + /* Leave LPUART5 alone without its clock: the console stays off */ + 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); + 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; + 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; +} + +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'); + } + 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; + + 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 */ + } + if (stat & LPUART_STAT_RDRF) { + *c = (char)(LPUART_DATA & 0xFF); + return 1; + } + return 0; +} + +#endif /* DEBUG_UART */ +#endif /* !WOLFBOOT_UNIT_TEST_FLASH */ + +/* 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; +} + +/* 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 off; + + *super = 0; + if (address >= FLASH_DATA_BASE) { + *blk = 4; + return 1UL << ((address - FLASH_DATA_BASE) / FLASH_SECTOR_SIZE); + } + *blk = (address - FLASH_BASE) / FLASH_BLOCK_SIZE; + off = (address - FLASH_BASE) % FLASH_BLOCK_SIZE; + if (off < FLASH_SUPER_SECTOR_AREA) { + *super = 1; + return 1UL << (off / FLASH_SUPER_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); +} + +/* 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 */ + 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 */ + cache_disable(); +} +#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. 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]; + uint8_t *buf = (uint8_t *)words; + 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; + end = start + (uint32_t)len; + if (end > FLASH_QUAD_PAGE_SIZE) + end = 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, FLASH_PTR(qpage + off), + FLASH_DWORD_SIZE) != 0) { + if (!flash_dword_erased(qpage + off)) + return -1; + 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 || (uint32_t)len > FLASH_NUM_BLOCKS * FLASH_BLOCK_SIZE) + return -1; + + /* 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; + } + while (len > 0) { + ret = flash_erase_sector(address); + if (ret != 0) + return ret; + address += FLASH_SECTOR_SIZE; + len -= FLASH_SECTOR_SIZE; + } + return 0; +} + +#ifndef WOLFBOOT_UNIT_TEST_FLASH +void RAMFUNCTION hal_flash_unlock(void) +{ +} + +void RAMFUNCTION hal_flash_lock(void) +{ +} +#endif /* !WOLFBOOT_UNIT_TEST_FLASH */ diff --git a/hal/mcxe31b.h b/hal/mcxe31b.h new file mode 100644 index 0000000000..3a0f05bfbe --- /dev/null +++ b/hal/mcxe31b.h @@ -0,0 +1,291 @@ +/* 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 MCX E3 Reference Manual + * (MCXEP172M160FB0RM, Rev. 5). + */ + +#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 + * (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 +#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); +int uart_ready(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..fc09fa3019 --- /dev/null +++ b/hal/mcxe31b.ld @@ -0,0 +1,92 @@ +/* + * 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 + + /* Placed explicitly so it cannot land after _stored_data as an orphan */ + .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 + + .bss (NOLOAD) : + { + _start_bss = .; + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + _end_bss = .; + __bss_end__ = .; + _end = .; + } > RAM + . = ALIGN(4); +} + +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)") + +_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-wolfip.ld b/test-app/ARM-mcxe31b-wolfip.ld new file mode 100644 index 0000000000..dfa4c835fa --- /dev/null +++ b/test-app/ARM-mcxe31b-wolfip.ld @@ -0,0 +1,174 @@ +/* + * 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), 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)) + _end_ramcode_itcm_string = .; + *string.o(.text.memset .text.memcmp) + _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) + *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_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 + /* 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 : + { + _start_text = .; + KEEP(*(.isr_vector)) + *(.text*) + *(.rodata*) + *(.init*) + *(.fini*) + . = 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 : + { + . = ALIGN(4); + KEEP(*(.keystore*)) + } > FLASH + + .edidx : + { + . = ALIGN(4); + *(.ARM.exidx*) + } > FLASH + + _stored_ramcode_itcm = ALIGN(8); + + _stored_data = _stored_ramcode_itcm + SIZEOF(.ramcode_itcm); + + .data : AT (_stored_data) + { + _start_data = .; + KEEP(*(.data*)) + . = ALIGN(4); + KEEP(*(.ramcode)) + . = ALIGN(4); + _end_data = .; + } > RAM + + /* 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 + + .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: 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 */ +_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, 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 */ +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 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 new file mode 100644 index 0000000000..510b1694f3 --- /dev/null +++ b/test-app/ARM-mcxe31b.ld @@ -0,0 +1,91 @@ +/* + * 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 + /* 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") + + /* Placed explicitly so it cannot land after _stored_data as an orphan */ + .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 + + .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: 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 */ +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 bca2573ef6..9d3650ac9e 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 +endif + ifeq ($(TARGET),stm32n6) CFLAGS+=-DRAM_CODE -DDEBUG_UART APP_OBJS+=syscalls.o @@ -1803,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. @@ -1851,6 +1861,40 @@ ifeq ($(ENABLE_WOLFIP),1) ifeq ($(WOLFIP_SPEED_TEST),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) + LSCRIPT_TEMPLATE=ARM-mcxe31b-wolfip.ld + # 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. + 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 + 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 + WOLFIP_CFLAGS_FILTEROUT:=-ffreestanding + # 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_MCXE_EMAC_STATS=1 + endif else WOLFIP_PORT:=nxp_fman WOLFIP_PORT_OBJ:=nxp_fman.o @@ -2023,8 +2067,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 new file mode 100644 index 0000000000..23400bf0c9 --- /dev/null +++ b/test-app/app_mcxe31b.c @@ -0,0 +1,934 @@ +/* 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 ENABLE_WOLFIP +#include "wolfip_tftp_test.h" +#endif + +#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; +#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) +{ + uint32_t start = jiffies; + while ((jiffies - start) < ms) { + __asm__ volatile ("wfi"); + } +} + +/* 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 = (core_clock_hz() / 1000U) - 1U; + 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 ============== */ + +#include "xmodem_rx.c" + +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; + 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"); + 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 */ + /* 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", + (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); +#ifdef ENABLE_WOLFIP +static int cmd_network(const char *args); +#endif + +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"}, +#ifdef ENABLE_WOLFIP + {cmd_network, "network", "Run the wolfIP network test"}, +#endif + {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", part_state_name(boot_state, ret), + 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", part_state_name(update_state, ret), + 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(); +} + +#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 ctrl_c = 0; + + while (uart_getc(&c) > 0) { + if (c == 0x03) + ctrl_c = 1; + } + return ctrl_c; +} +#endif +#endif + +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. + * 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 + + /* 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 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 + * An update left in TESTING is rolled back at the next reset */ + if (version > 1) { + uint8_t state = 0; + 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(); + + 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_heap; /* From linker script: stack region start */ + +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; + + /* Stay below the reserved stack region */ + if (incr < 0 || incr > (unsigned char *)&_end_heap - heap) { + return (void *)-1; + } + + heap += incr; + return prev_heap; +} + +#endif /* TARGET_mcxe31b */ 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."); diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index 3ad2ff3528..3390393a2c 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 */ @@ -76,6 +82,23 @@ extern void nxp_mcxe_enet_irq_handler(void); #endif #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); +#define isr_emac nxp_mcxe_emac_irq_handler +#else +#define isr_emac isr_empty +#endif +#endif + #if defined(TARGET_va416x0) || defined(TARGET_lpc55s69) #define isr_systick SysTick_Handler #elif !defined(APP_HAS_SYSTICK) @@ -94,30 +117,55 @@ 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, 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. */ extern void isr_reset_c(void); __attribute__((naked, used, noreturn)) void isr_reset(void) { __asm__ volatile( + "movs r2, #0\n\t" + "movs r3, #0\n\t" +# ifdef APP_RAM_ECC_INIT "ldr r0, =_start_ecc_ram\n\t" "ldr r1, =_end_ecc_ram\n\t" - "movs r2, #0\n\t" "1:\n\t" "cmp r0, r1\n\t" "bhs 2f\n\t" +# 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" +# endif "b 1b\n\t" "2:\n\t" +# 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" + "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 /* 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; @@ -126,7 +174,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) { @@ -134,6 +181,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; @@ -664,6 +721,12 @@ void (* const IV[])(void) = isr_empty, // DMA1_STREAM7_IRQ 47 +#elif defined(TARGET_mcxe31b) /* For NXP MCXE31B */ + /* IRQs 0-145 unused except 105 = EMAC, 146 = LPUART5 (console) */ + [16 ... (16 + 145)] = isr_empty, + [16 + 105] = isr_emac, + [16 + 146] = isr_lpuart5, + #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/test-app/wolfip_tftp_test.c b/test-app/wolfip_tftp_test.c index 18dab66b8a..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) @@ -42,6 +42,7 @@ /* Port selection: * WOLFIP_PORT_ENETC -> LS1028A ENETC * WOLFIP_PORT_MCXE_ENET -> MCXE247 ENET + * 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) @@ -60,6 +61,24 @@ #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_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_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 +#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" #define WOLFIP_NETDEV_INIT nxp_fman_init @@ -91,10 +110,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 +539,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 +597,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 +706,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 } @@ -702,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); @@ -741,7 +760,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 +793,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); @@ -1073,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 diff --git a/test-app/wolfip_tftp_test.h b/test-app/wolfip_tftp_test.h index 4816205fbf..0bbcd0e1a9 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_MCXE_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/test-app/xmodem_rx.c b/test-app/xmodem_rx.c index c7acc8c914..afb78561f5 100644 --- a/test-app/xmodem_rx.c +++ b/test-app/xmodem_rx.c @@ -1,9 +1,10 @@ /* 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. 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. * diff --git a/tools/scripts/mcxe31b/e31b_debug.cmm b/tools/scripts/mcxe31b/e31b_debug.cmm new file mode 100644 index 0000000000..32502b2510 --- /dev/null +++ b/tools/scripts/mcxe31b/e31b_debug.cmm @@ -0,0 +1,104 @@ +;; 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""" +; 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_mcxe_emac""" +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 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..b9dc89404a --- /dev/null +++ b/tools/unit-tests/unit-flash-mcxe31b.c @@ -0,0 +1,458 @@ +/* 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 + +/* 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); + 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); + + /* 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 + +/* 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); + /* 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); +} +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 + +/* 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"); + 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); + tcase_add_test(tw, test_write_programmed_segment_fails); + 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); + tcase_add_test(te, test_lock_bit_mapping); + 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; +}