From 3b196531ec5b2154c048e18c24284ec35f62d47e Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Thu, 12 Nov 2026 23:43:50 -0500 Subject: [PATCH 01/24] mcxe247: standalone interrupt-driven wolfIP driver, TCP/UDP speed test - Build the wolfIP nxp_mcxe_enet port without the MCUXpresso SDK, in interrupt mode, with ENET IRQs 73-75 routed to the driver handler. - IMAGE_HEADER_SIZE=1024 in mcxe247.config: the 179-entry vector table needs 1 KB alignment for VTOR, otherwise the ENET IRQs vector to the wrong handler. - Place the wolfIP state in SRAM_L and use 9 KB TCP buffers per socket. - Speed test: TCP and UDP server on port 9 with rx, tx and bidirectional modes, and a per-test CPU breakdown from the driver cycle counters. Host side: tools/scripts/wolfip_speed.py. - Drop the SDK paths from the TRACE32 debug script and the docs. --- config/examples/mcxe247.config | 19 +- docs/Targets.md | 42 ++- test-app/ARM-s32k1xx-wolfip.ld | 23 +- test-app/Makefile | 27 +- test-app/startup_arm.c | 17 +- test-app/wolfip_tftp_test.c | 460 +++++++++++++++++++++++---- tools/scripts/mcxe247/e247_debug.cmm | 16 +- tools/scripts/wolfip_speed.py | 332 +++++++++++++++++++ 8 files changed, 805 insertions(+), 131 deletions(-) create mode 100644 tools/scripts/wolfip_speed.py diff --git a/config/examples/mcxe247.config b/config/examples/mcxe247.config index 9c3ef149ae..bbaf7bb02c 100644 --- a/config/examples/mcxe247.config +++ b/config/examples/mcxe247.config @@ -36,6 +36,11 @@ CFLAGS_EXTRA+=-DMCXE247 -DWOLFBOOT_RAM_ECC_INIT # 4KB sectors WOLFBOOT_SECTOR_SIZE?=0x1000 +# The application's vector table follows the image header and is used in +# place (VTOR). With 163 interrupts the table must be 1 KB aligned, or the +# core fetches the vectors of IRQ 48 and up from the wrong slots. +IMAGE_HEADER_SIZE?=1024 + # Memory layout (Program Flash 0x00000000 - 0x0017FFFF): # Bootloader: 0x00000000 - 0x0000BFFF (48 KB) # Boot Partition: 0x0000C000 - 0x000C3FFF (736 KB) @@ -54,19 +59,19 @@ CFLAGS_EXTRA+=-DDEBUG_UART_RX_PORT=S32K_PORT_D -DDEBUG_UART_RX_PIN=17 CFLAGS_EXTRA+=-DDEBUG_UART_RX_MUX=PORT_PCR_MUX_ALT3 # wolfIP network test in the test-app (optional) -# Adds the "network" console command. Needs a wolfIP checkout and an MCUXpresso -# SDK (for the fsl_enet driver). +# Adds the "network" console command. Needs a wolfIP checkout, which provides +# the interrupt-driven nxp_mcxe_enet driver. ENABLE_WOLFIP?=0 WOLFBOOT_LIB_WOLFIP?=../lib/wolfip -MCUXPRESSO?=$(PWD)/../NXP/mcuxpresso-sdk/mcuxsdk # Without WOLFBOOT_TEST_TFTP the command only acquires a DHCP lease. The file # must fit the 40 KB receive buffer. WOLFBOOT_TEST_TFTP?=1 CFLAGS_EXTRA+=-DHOST_IP_STR='"192.168.50.1"' -DTFTP_FILENAME='"wolfip_test.bin"' -# WOLFIP_SPEED_TEST=1 makes the command run a TCP throughput server on port 9 -# instead (it never returns; reset the board to stop it). WOLFBOOT_TEST_TFTP -# overrides it: with both set to 1 the command runs the TFTP fetch and the speed -# server is never started. +# WOLFIP_SPEED_TEST=1 makes the command run a TCP and UDP throughput server on +# port 9 instead, driven from the host by tools/scripts/wolfip_speed.py (it +# never returns; reset the board to stop it). WOLFBOOT_TEST_TFTP overrides it: +# with both set to 1 the command runs the TFTP fetch and the speed server is +# never started. WOLFIP_SPEED_TEST?=0 # Debugging options diff --git a/docs/Targets.md b/docs/Targets.md index 0ea53df945..927f4126fb 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7800,19 +7800,27 @@ apply to the MCXE247, with these differences: the rest of the 252 KB, so an application that enables ERM interrupts must write its RAM before reading it. The network test app clears all of SRAM_U at reset (`APP_RAM_ECC_INIT`). +- `mcxe247.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 163 interrupts it must be 1 KB aligned: with the default 256-byte + header the core fetches the vectors of IRQ 48 and up (the ENET interrupts + among them) from the wrong slots. ### NXP MCXE247: Network test The test application can run a wolfIP DHCP and TFTP test over the board's -Ethernet port. This is optional and is the only part of the port that needs the -MCUXpresso SDK, which provides the `fsl_enet` driver. Set `ENABLE_WOLFIP=1` in -`mcxe247.config`, check the wolfIP and SDK paths, then set the TFTP server and -file: +Ethernet port. This is optional and needs a wolfIP checkout, whose +`nxp_mcxe_enet` port is a standalone ENET and LAN8741 driver (no vendor SDK). +The test app builds it interrupt driven (`NXP_MCXE_ENET_IRQ=1`, with ENET IRQs +73-75 routed in `test-app/startup_arm.c`). The wolfIP stack state, with 9 KB +TCP receive and transmit buffers per socket, is placed in SRAM_L by +`test-app/ARM-s32k1xx-wolfip.ld`; the rest of the app uses SRAM_U. Set +`ENABLE_WOLFIP=1` in +`mcxe247.config`, check the wolfIP path, then set the TFTP server and file: ```sh ENABLE_WOLFIP?=1 WOLFBOOT_LIB_WOLFIP?=../lib/wolfip -MCUXPRESSO?=$(PWD)/../NXP/mcuxpresso-sdk/mcuxsdk WOLFBOOT_TEST_TFTP?=1 CFLAGS_EXTRA+=-DHOST_IP_STR='"192.168.50.1"' -DTFTP_FILENAME='"wolfip_test.bin"' ``` @@ -7823,18 +7831,24 @@ the file into RAM (40 KB at most), and prints its size and checksum followed by To measure throughput instead, set `WOLFBOOT_TEST_TFTP=0` and `WOLFIP_SPEED_TEST=1`. After the DHCP lease, the `network` command runs a TCP -server on port 9 that discards what it receives and sends data whenever the -connection can take it. It prints the receive and transmit rates when the -connection closes. Drive it from the PC with `` set to the address the board -printed: +and UDP throughput server on port 9. Drive it from a PC on the same network +with `` set to the address the board printed (Python 3, no extra +packages): ```sh -# board receives -dd if=/dev/zero bs=1460 count=10000 | nc 9 -# board sends -nc 9 /dev/null +python3 tools/scripts/wolfip_speed.py ``` +The script runs six tests of 10 s each: TCP and UDP, each with the board +only receiving (`rx`), only sending (`tx`) and both at once (`bidir`). +It prints a table of the rates and UDP loss. With this build the driver also +counts its own core cycles (`NXP_MCXE_ENET_STATS=1`), so the table also shows +how the CPU time divides between the driver, the frame copies, wolfIP and the +main loop. `--tests` picks a subset, `--time` sets the duration and `--rate` +limits the UDP send rate to the board, e.g. to find the highest rate without +loss. The board prints the same counters on the console after each test. +Plain `nc 9` still works as a bidirectional TCP test. + The server never returns to the console; reset the board to stop it. `WOLFBOOT_TEST_TFTP` takes priority: with both options set to 1, the command runs the TFTP fetch and the speed server is never started. @@ -7851,7 +7865,7 @@ example `DO /tools/scripts/mcxe247/e247_flash_factory_bin.cmm`: | Script | Purpose | |--------|---------| -| `e247_debug.cmm` | Reset and halt the CPU, then load the `wolfboot.elf` and `test-app/image.elf` symbols. Takes the MCUXpresso SDK path as an optional argument, used to find the ENET driver sources (default: `../NXP/mcuxpresso-sdk/mcuxsdk` next to the checkout) | +| `e247_debug.cmm` | Reset and halt the CPU, then load the `wolfboot.elf` and `test-app/image.elf` symbols | | `e247_flash_factory_bin.cmm` | Program `factory.bin`, erase the update partition and swap sector, then reset and detach | | `e247_flash_update.cmm` | Program `test-app/image_v2_signed.bin` into the update partition, then reset and detach | diff --git a/test-app/ARM-s32k1xx-wolfip.ld b/test-app/ARM-s32k1xx-wolfip.ld index fafe522ad7..879bbccf8f 100644 --- a/test-app/ARM-s32k1xx-wolfip.ld +++ b/test-app/ARM-s32k1xx-wolfip.ld @@ -2,17 +2,22 @@ * Linker script for the wolfBoot test application on NXP S32K148/MCXE247 with wolfIP * * The application runs from the boot partition after the wolfBoot header. - * RAM is all of SRAM_U, which the ENET DMA uses and is outside the code cache. + * RAM is SRAM_U. The wolfIP stack state (wolfip.o .bss: sockets and their + * buffers) goes in SRAM_L, which the ENET DMA and eDMA reach through its + * backdoor port. Both are outside the code cache while it is disabled (the + * default); enabling the cache for SRAM_L would break the DMA coherency. * * 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), all - * of RAM including the heap and stack, with word stores before the stack is - * used. This keeps the ECC valid and the ERM free of error events. + * APP_RAM_ECC_INIT the reset handler clears [_start_ecc_ram, _end_ecc_ram), + * SRAM_L and SRAM_U including the heap and stack, with word stores before the + * stack is used. This keeps the ECC valid and the ERM free of error events, + * and is also what zeroes the SRAM_L section: it is not part of .bss. */ MEMORY { FLASH (rx) : ORIGIN = @WOLFBOOT_TEST_APP_ADDRESS@, LENGTH = @WOLFBOOT_TEST_APP_SIZE@ + RAM_L (rwx) : ORIGIN = 0x1FFE0000, LENGTH = 0x20000 /* 128KB SRAM_L */ RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x1F000 /* 124KB SRAM_U */ } @@ -48,6 +53,14 @@ SECTIONS _end_data = .; } > RAM + /* wolfIP stack state, zero-filled by the APP_RAM_ECC_INIT clear */ + .bss_sram_l (NOLOAD) : + { + . = ALIGN(16); + *wolfip.o(.bss .bss.* COMMON) + . = ALIGN(4); + } > RAM_L + .bss (NOLOAD) : { _start_bss = .; @@ -72,7 +85,7 @@ _start_heap = _end; _end_stack = ORIGIN(RAM) + LENGTH(RAM); /* RAM cleared at reset with APP_RAM_ECC_INIT */ -_start_ecc_ram = ORIGIN(RAM); +_start_ecc_ram = ORIGIN(RAM_L); _end_ecc_ram = ORIGIN(RAM) + LENGTH(RAM); /* Keep room above .bss for the stack and the heap used by printf */ diff --git a/test-app/Makefile b/test-app/Makefile index 0616529149..3babe5b2c3 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1781,30 +1781,23 @@ ifeq ($(ENABLE_WOLFIP),1) ifeq ($(filter -DMCXE247,$(CFLAGS_EXTRA)),) $(error ENABLE_WOLFIP=1 on s32k1xx is only supported on MCXE247) endif - ifeq ($(wildcard $(MCUXPRESSO)/drivers/enet/fsl_enet.c),) - $(error ENABLE_WOLFIP=1 on MCXE247 needs MCUXPRESSO set to an MCUXpresso SDK checkout) - endif WOLFIP_PORT:=nxp_mcxe_enet WOLFIP_PORT_OBJ:=nxp_mcxe_enet.o LSCRIPT_TEMPLATE=ARM-s32k1xx-wolfip.ld # Clear all of SRAM_U at reset, before the stack is used (ECC) CFLAGS+=-DAPP_RAM_ECC_INIT - # The generic MCUXPRESSO_* defaults describe a different part - MCXE247_DEVICE:=$(MCUXPRESSO)/devices/MCX/MCXE/MCXE247 - CFLAGS+=-DWOLFIP_PORT_MCXE_ENET -DCPU_MCXE247VLL + # Standalone driver, interrupt driven: startup_arm.c routes ENET IRQs + # 73-75 to nxp_mcxe_enet_irq_handler() + CFLAGS+=-DWOLFIP_PORT_MCXE_ENET -DNXP_MCXE_ENET_IRQ=1 # The TFTP receive buffer shares the 124KB of SRAM_U CFLAGS+=-DTFTP_RAM_MAX=0xA000U - CFLAGS+=-I$(MCXE247_DEVICE) -I$(MCXE247_DEVICE)/drivers - CFLAGS+=-I$(MCXE247_DEVICE)/../periph0 - CFLAGS+=-I$(MCUXPRESSO)/drivers/common -I$(MCUXPRESSO)/drivers/enet - CFLAGS+=-I$(MCUXPRESSO)/components/phy - CFLAGS+=-I$(MCUXPRESSO)/components/phy/device/phylan8741 - CFLAGS+=-I$(MCUXPRESSO)/arch/arm/CMSIS/Core/Include - APP_OBJS+=$(MCUXPRESSO)/drivers/enet/fsl_enet.o - APP_OBJS+=$(MCUXPRESSO)/drivers/common/fsl_common.o - APP_OBJS+=$(MCUXPRESSO)/drivers/common/fsl_common_arm.o - APP_OBJS+=$(MCXE247_DEVICE)/drivers/fsl_clock.o - APP_OBJS+=$(MCUXPRESSO)/components/phy/device/phylan8741/fsl_phylan8741.o + # wolfIP state is in the 128KB of SRAM_L (ARM-s32k1xx-wolfip.ld): six + # full segments of TCP buffering per socket + CFLAGS+=-DRXBUF_SIZE=9216 -DTXBUF_SIZE=9216 + # Driver cycle counters for the throughput test's CPU breakdown + ifeq ($(WOLFIP_SPEED_TEST),1) + CFLAGS+=-DNXP_MCXE_ENET_STATS=1 + endif else WOLFIP_PORT:=nxp_fman WOLFIP_PORT_OBJ:=nxp_fman.o diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index 8de8219caa..be9e9e4581 100644 --- a/test-app/startup_arm.c +++ b/test-app/startup_arm.c @@ -55,6 +55,17 @@ extern void isr_debug_uart(void); #define isr_lpuart1 isr_debug_uart #define isr_lpuart2 isr_empty #endif +/* MCXE247 ENET transmit, receive and error interrupts (IRQ 73-75) */ +#if defined(MCXE247) && defined(NXP_MCXE_ENET_IRQ) && (NXP_MCXE_ENET_IRQ == 1) +extern void nxp_mcxe_enet_irq_handler(void); +#define isr_irq73 nxp_mcxe_enet_irq_handler +#define isr_irq74 nxp_mcxe_enet_irq_handler +#define isr_irq75 nxp_mcxe_enet_irq_handler +#else +#define isr_irq73 isr_empty +#define isr_irq74 isr_empty +#define isr_irq75 isr_empty +#endif #endif #if defined(TARGET_va416x0) || defined(TARGET_lpc55s69) @@ -560,9 +571,9 @@ void (* const IV[])(void) = isr_empty, // CAN0_MB16_31 70 isr_empty, // FTM0_Ch0_Ch1 71 isr_empty, // FTM0_Ch2_Ch3 72 - isr_empty, // FTM0_Ch4_Ch5 73 - isr_empty, // FTM0_Ch6_Ch7 74 - isr_empty, // FTM0_Fault 75 + isr_irq73, // FTM0_Ch4_Ch5 73 (MCXE247: ENET_Transmit) + isr_irq74, // FTM0_Ch6_Ch7 74 (MCXE247: ENET_Receive) + isr_irq75, // FTM0_Fault 75 (MCXE247: ENET_Error) isr_empty, // FTM0_Ovf_Reload 76 isr_empty, // FTM1_Ch0_Ch1 77 isr_empty, // FTM1_Ch2_Ch3 78 diff --git a/test-app/wolfip_tftp_test.c b/test-app/wolfip_tftp_test.c index aae400177c..ab4b3b4134 100644 --- a/test-app/wolfip_tftp_test.c +++ b/test-app/wolfip_tftp_test.c @@ -3,11 +3,12 @@ * 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 - * MCUXpresso fsl_enet driver (MCXE247, Cortex-M4). Modes: + * NXP MCX E247 ENET (Cortex-M4). Modes: * default DHCP lease only * WOLFBOOT_TEST_TFTP + TFTP RRQ fetch into RAM, report size+checksum * (optionally verify them via TFTP_EXPECT_SIZE/SUM) - * WOLFIP_SPEED_TEST + TCP throughput server on port 9 (benchmark) + * WOLFIP_SPEED_TEST + TCP and UDP throughput server on port 9 + * (benchmark, host side tools/scripts/wolfip_speed.py) * * Copyright (C) 2026 wolfSSL Inc. * @@ -40,7 +41,7 @@ /* Port selection: * WOLFIP_PORT_ENETC -> LS1028A ENETC - * WOLFIP_PORT_MCXE_ENET -> MCXE247 ENET (MCUXpresso fsl_enet) + * WOLFIP_PORT_MCXE_ENET -> MCXE247 ENET * else QorIQ FMan * Driver entry points are wrapped so the bring-up code below is port-agnostic. */ #if defined(WOLFIP_PORT_ENETC) @@ -441,112 +442,431 @@ static int run_tftp_fetch(struct wolfIP *s) #endif /* WOLFBOOT_TEST_TFTP */ #ifdef WOLFIP_SPEED_TEST -/* ---- Benchmark: one-connection TCP throughput server on port 9 ------- * - * RX sinks everything the peer sends; TX pushes a chargen buffer whenever - * writable. Prints B/s on close. - * RX (board sinks): dd if=/dev/zero bs=1460 count=N | nc 9 - * TX (board sources): nc 9 /dev/null */ -#define SPEED_PORT 9 -static int speed_listen_fd = -1; -static int speed_client_fd = -1; -static uint64_t speed_rx_bytes, speed_tx_bytes, speed_start_ms; -static uint8_t speed_buf[1460]; +/* ---- Benchmark: TCP and UDP throughput server on port 9 ------------- * + * Driven from a host by tools/scripts/wolfip_speed.py. Directions are + * named from the board: rx = the board receives, tx = the board sends, + * bidir = both at once. + * + * TCP: the first byte the client sends picks the direction: 'r' rx, + * 't' tx, anything else bidir (so plain "nc 9" stays bidirectional). + * The test ends when the client closes. + * + * UDP: each datagram starts with a SPEED_HDR_LEN byte header, big-endian: + * [0] SPEED_MAGIC [1] command [2..3] board datagram size + * [4..7] sequence [8..11] board send duration in ms + * Commands to the board: + * 'r' data to count (starts an rx test) + * 'b' data to count; the first one starts a bidir test and the board + * sends to the client for the given duration + * 't' start a tx test: the board sends to the client for the duration + * 'q' end the current UDP test and reply with an 'S' stats datagram + * The board's own datagrams carry command 'd'. + * + * The 'S' reply describes the last test, TCP or UDP, so the host can fetch + * the board's counters after a TCP test too. Each finished test is also + * printed on the console. */ +#define SPEED_PORT 9 +#define SPEED_MAGIC 0x57U /* 'W' */ +#define SPEED_HDR_LEN 12 +#define SPEED_UDP_MAX 1472U /* largest unfragmented payload */ +#define SPEED_TCP_CHUNK 1460U +#define SPEED_BURST 32 +#define SPEED_PROTO_TCP 1U +#define SPEED_PROTO_UDP 2U +#define SPEED_REPLY_LEN 108 + +#if defined(WOLFIP_PORT_MCXE_ENET) && NXP_MCXE_ENET_STATS +/* The driver enables the DWT cycle counter */ +#define SPEED_PROFILE 1 +#define SPEED_CYCLES() (*(volatile uint32_t *)0xE0001004UL) +#else +#define SPEED_PROFILE 0 +#define SPEED_CYCLES() 0U +#endif + +struct speed_state { + uint64_t rx_bytes; + uint64_t tx_bytes; + uint64_t cyc_total; /* core cycles in the test window */ + uint64_t cyc_busy; /* of which in wolfIP_poll() and socket calls */ + uint64_t start_ms; + uint64_t end_ms; + uint64_t stream_end_ms; + uint32_t rx_pkts; + uint32_t tx_pkts; + uint32_t tx_seq; + uint32_t stream_len; + uint32_t polls; /* wolfIP_poll() calls in the test window */ + uint8_t proto; + uint8_t mode; /* 'r', 't', 'b'; 0 until a TCP client sends */ + uint8_t active; + uint8_t streaming; +}; + +static int speed_listen_fd = -1; +static int speed_client_fd = -1; +static int speed_udp_fd = -1; +static struct speed_state speed; +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; +#endif + +static void speed_put32(uint8_t *p, uint32_t v) +{ + p[0] = (uint8_t)(v >> 24); + p[1] = (uint8_t)(v >> 16); + p[2] = (uint8_t)(v >> 8); + p[3] = (uint8_t)v; +} + +static void speed_put64(uint8_t *p, uint64_t v) +{ + speed_put32(p, (uint32_t)(v >> 32)); + speed_put32(p + 4, (uint32_t)v); +} + +static uint32_t speed_get32(const uint8_t *p) +{ + return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | + ((uint32_t)p[2] << 8) | (uint32_t)p[3]; +} + +static const char *speed_mode_name(uint8_t mode) +{ + if (mode == 'r') + return "rx"; + if (mode == 't') + return "tx"; + if (mode == 'b') + return "bidir"; + return "?"; +} + +static uint32_t speed_kbps(uint64_t bytes, uint32_t ms) +{ + return (uint32_t)((bytes * 8ULL) / ms); +} + +#if SPEED_PROFILE +/* part/total in tenths of a percent */ +static uint32_t speed_permille(uint64_t part, uint64_t total) +{ + if (total == 0U) + return 0U; + return (uint32_t)((part * 1000ULL) / total); +} + +static void speed_print_pct(const char *name, uint64_t part) +{ + uint32_t pm = speed_permille(part, speed.cyc_total); + + wolfBoot_printf(" %s %u.%u%%", name, (unsigned)(pm / 10U), + (unsigned)(pm % 10U)); +} +#endif static void speed_print(void) { - uint64_t ms = now_ms() - speed_start_ms; - if (ms == 0) ms = 1; - wolfBoot_printf("SPEED done %ums RX %u B (~%u B/s) TX %u B (~%u B/s)\r\n", - (unsigned)ms, (unsigned)speed_rx_bytes, - (unsigned)((speed_rx_bytes * 1000ULL) / ms), - (unsigned)speed_tx_bytes, - (unsigned)((speed_tx_bytes * 1000ULL) / ms)); + uint32_t ms = (uint32_t)(speed.end_ms - speed.start_ms); +#if SPEED_PROFILE + uint64_t drv = speed_drv.rx_cycles + speed_drv.tx_cycles + + speed_drv.idle_cycles; + uint64_t stack = (speed.cyc_busy > drv) ? speed.cyc_busy - drv : 0U; + uint32_t frames = speed_drv.rx_frames + speed_drv.tx_frames; +#endif + + if (ms == 0U) + ms = 1U; + wolfBoot_printf("SPEED %s %s: %u ms rx %u B %u kbit/s tx %u B %u kbit/s\r\n", + (speed.proto == SPEED_PROTO_TCP) ? "tcp" : "udp", + speed_mode_name(speed.mode), (unsigned)ms, + (unsigned)speed.rx_bytes, (unsigned)speed_kbps(speed.rx_bytes, ms), + (unsigned)speed.tx_bytes, (unsigned)speed_kbps(speed.tx_bytes, ms)); + if (speed.proto == SPEED_PROTO_UDP) { + wolfBoot_printf(" datagrams rx %u tx %u\r\n", + (unsigned)speed.rx_pkts, (unsigned)speed.tx_pkts); + } +#if SPEED_PROFILE + wolfBoot_printf(" cpu %u MHz:", (unsigned)(speed_drv.core_hz / 1000000U)); + speed_print_pct("drv-rx", speed_drv.rx_cycles); + speed_print_pct("drv-tx", speed_drv.tx_cycles); + speed_print_pct("drv-idle", speed_drv.idle_cycles); + speed_print_pct("wolfIP", stack); + speed_print_pct("loop", speed.cyc_total - speed.cyc_busy); + wolfBoot_printf("\r\n of which:"); + speed_print_pct("copy", speed_drv.copy_cycles); + speed_print_pct("tx-ring-full", speed_drv.tx_wait_cycles); + wolfBoot_printf("\r\n frames rx %u tx %u, wolfIP %u cycles/frame," + " %u polls, %u cycles/poll\r\n", + (unsigned)speed_drv.rx_frames, (unsigned)speed_drv.tx_frames, + (unsigned)((frames > 0U) ? (stack / frames) : 0U), + (unsigned)speed.polls, + (unsigned)((speed.polls > 0U) ? (speed.cyc_busy / speed.polls) : 0U)); +#endif +} + +static void speed_start(uint8_t proto, uint8_t mode, uint64_t now) +{ + zmem(&speed, sizeof(speed)); + speed.proto = proto; + speed.mode = mode; + speed.start_ms = now; + speed.active = 1U; +#if SPEED_PROFILE + nxp_mcxe_enet_stats_reset(); +#endif +} + +static void speed_stop(uint64_t now) +{ + if (speed.active == 0U) + return; + speed.active = 0U; + speed.streaming = 0U; + speed.end_ms = now; +#if SPEED_PROFILE + nxp_mcxe_enet_stats_get(&speed_drv); +#endif + speed_print(); } +/* Send the 'S' stats datagram for the last (or running) test. */ +static void speed_reply(struct wolfIP *s, const struct wolfIP_sockaddr_in *to, + uint64_t now) +{ + uint8_t r[SPEED_REPLY_LEN]; + uint64_t end = (speed.active != 0U) ? now : speed.end_ms; + + zmem(r, sizeof(r)); + r[0] = SPEED_MAGIC; + r[1] = 'S'; + r[2] = 1U; /* layout version */ + r[3] = speed.proto; + r[4] = speed.mode; + r[5] = speed.active; + speed_put32(r + 8, (uint32_t)(end - speed.start_ms)); + speed_put32(r + 16, speed.rx_pkts); + speed_put32(r + 20, speed.tx_pkts); + speed_put64(r + 32, speed.rx_bytes); + speed_put64(r + 40, speed.tx_bytes); + speed_put64(r + 48, speed.cyc_total); + speed_put64(r + 56, speed.cyc_busy); + speed_put32(r + 104, speed.polls); +#if SPEED_PROFILE + if (speed.active != 0U) + nxp_mcxe_enet_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); + speed_put64(r + 64, speed_drv.rx_cycles); + speed_put64(r + 72, speed_drv.tx_cycles); + speed_put64(r + 80, speed_drv.idle_cycles); + speed_put64(r + 88, speed_drv.copy_cycles); + speed_put64(r + 96, speed_drv.tx_wait_cycles); +#endif + (void)wolfIP_sock_sendto(s, speed_udp_fd, r, sizeof(r), 0, + (const struct wolfIP_sockaddr *)to, sizeof(*to)); +} + +/* Accept one TCP client at a time; a close ends the test. */ static void speed_cb(int fd, uint16_t event, void *arg) { struct wolfIP *s = (struct wolfIP *)arg; - int n, k; + int c; if (fd == speed_listen_fd) { - if (event & CB_EVENT_READABLE) { - int c = wolfIP_sock_accept(s, speed_listen_fd, NULL, NULL); + if ((event & CB_EVENT_READABLE) != 0U) { + c = wolfIP_sock_accept(s, speed_listen_fd, NULL, NULL); if (c >= 0) { if (speed_client_fd >= 0) { (void)wolfIP_sock_close(s, c); - } else { + } + else { speed_client_fd = c; - speed_rx_bytes = 0; speed_tx_bytes = 0; - speed_start_ms = now_ms(); wolfIP_register_callback(s, c, speed_cb, s); - wolfBoot_printf("SPEED client connected\r\n"); + speed_start(SPEED_PROTO_TCP, 0U, now_ms()); } } } return; } - if (fd != speed_client_fd) + if (fd == speed_client_fd && (event & CB_EVENT_CLOSED) != 0U) { + speed_stop(now_ms()); + (void)wolfIP_sock_close(s, fd); + speed_client_fd = -1; + } +} + +static void speed_tcp_pump(struct wolfIP *s) +{ + int n; + int k; + + if (speed_client_fd < 0) + return; + for (k = 0; k < SPEED_BURST; k++) { + n = wolfIP_sock_recvfrom(s, speed_client_fd, speed_rxbuf, + SPEED_TCP_CHUNK, 0, NULL, NULL); + if (n <= 0) + break; + if (speed.mode == 0U) { + if (speed_rxbuf[0] == 'r' || speed_rxbuf[0] == 't') { + speed.mode = speed_rxbuf[0]; + n--; /* the direction byte is not data */ + } + else { + speed.mode = 'b'; + } + } + speed.rx_bytes += (uint32_t)n; + } + if (speed.mode != 't' && speed.mode != 'b') return; + for (k = 0; k < SPEED_BURST; k++) { + n = wolfIP_sock_send(s, speed_client_fd, speed_txbuf, + SPEED_TCP_CHUNK, 0); + if (n <= 0) + break; + speed.tx_bytes += (uint32_t)n; + } +} - if (event & CB_EVENT_READABLE) { - k = 0; - do { - n = wolfIP_sock_recvfrom(s, fd, speed_buf, sizeof(speed_buf), 0, - NULL, NULL); - if (n > 0) - speed_rx_bytes += (uint64_t)n; - } while (n > 0 && ++k < 32); +static void speed_udp_recv(struct wolfIP *s, uint64_t now) +{ + struct wolfIP_sockaddr_in from; + socklen_t from_len; + uint32_t len; + uint8_t cmd; + int n; + int k; + + for (k = 0; k < SPEED_BURST; k++) { + from_len = sizeof(from); + n = wolfIP_sock_recvfrom(s, speed_udp_fd, speed_rxbuf, + sizeof(speed_rxbuf), 0, (struct wolfIP_sockaddr *)&from, + &from_len); + if (n <= 0) + break; + if (n < SPEED_HDR_LEN || speed_rxbuf[0] != SPEED_MAGIC) + continue; + cmd = speed_rxbuf[1]; + if (cmd == 'q') { + if (speed.proto == SPEED_PROTO_UDP) + speed_stop(now); + speed_reply(s, &from, now); + continue; + } + if (cmd != 'r' && cmd != 'b' && cmd != 't') + continue; + if (speed.active != 0U && speed.proto == SPEED_PROTO_TCP) + continue; /* a TCP test is running */ + if (speed.active == 0U) { + speed_start(SPEED_PROTO_UDP, cmd, now); + speed_peer = from; + if (cmd != 'r') { + len = ((uint32_t)speed_rxbuf[2] << 8) | speed_rxbuf[3]; + if (len < (uint32_t)SPEED_HDR_LEN || len > SPEED_UDP_MAX) + len = SPEED_UDP_MAX; + speed.stream_len = len; + speed.stream_end_ms = now + speed_get32(speed_rxbuf + 8); + speed.streaming = 1U; + } + } + if (cmd != 't') { + speed.rx_bytes += (uint32_t)n; + speed.rx_pkts++; + } } - if (event & CB_EVENT_WRITABLE) { - k = 0; - do { - n = wolfIP_sock_send(s, fd, speed_buf, sizeof(speed_buf), 0); - if (n > 0) - speed_tx_bytes += (uint64_t)n; - } while (n > 0 && ++k < 32); +} + +static void speed_udp_send(struct wolfIP *s, uint64_t now) +{ + int n; + int k; + + if (speed.streaming == 0U) + return; + if (now >= speed.stream_end_ms) { + speed.streaming = 0U; + if (speed.mode == 't') + speed_stop(now); + return; } - if (event & CB_EVENT_CLOSED) { - speed_print(); - (void)wolfIP_sock_close(s, fd); - speed_client_fd = -1; + speed_txbuf[0] = SPEED_MAGIC; + speed_txbuf[1] = 'd'; + speed_txbuf[2] = 0U; + speed_txbuf[3] = 0U; + for (k = 0; k < SPEED_BURST; k++) { + speed_put32(speed_txbuf + 4, speed.tx_seq); + n = wolfIP_sock_sendto(s, speed_udp_fd, speed_txbuf, + speed.stream_len, 0, (const struct wolfIP_sockaddr *)&speed_peer, + sizeof(speed_peer)); + if (n <= 0) + break; + speed.tx_seq++; + speed.tx_pkts++; + speed.tx_bytes += (uint32_t)n; } } -static int run_speed_server(struct wolfIP *s) +static int speed_open(struct wolfIP *s, int type) { struct wolfIP_sockaddr_in addr; + int fd; - speed_listen_fd = wolfIP_sock_socket(s, AF_INET, IPSTACK_SOCK_STREAM, 0); - if (speed_listen_fd < 0) { - wolfBoot_printf("SPEED: socket failed\r\n"); + fd = wolfIP_sock_socket(s, AF_INET, type, 0); + if (fd < 0) return -1; - } - wolfIP_register_callback(s, speed_listen_fd, speed_cb, s); zmem(&addr, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = ee16(SPEED_PORT); - if (wolfIP_sock_bind(s, speed_listen_fd, - (struct wolfIP_sockaddr *)&addr, sizeof(addr)) < 0) { - wolfBoot_printf("SPEED: bind to port %d failed\r\n", SPEED_PORT); - (void)wolfIP_sock_close(s, speed_listen_fd); - speed_listen_fd = -1; + if (wolfIP_sock_bind(s, fd, (struct wolfIP_sockaddr *)&addr, + sizeof(addr)) < 0 || + (type == IPSTACK_SOCK_STREAM && + wolfIP_sock_listen(s, fd, 1) < 0)) { + (void)wolfIP_sock_close(s, fd); return -1; } - if (wolfIP_sock_listen(s, speed_listen_fd, 1) < 0) { - wolfBoot_printf("SPEED: listen on port %d failed\r\n", SPEED_PORT); - (void)wolfIP_sock_close(s, speed_listen_fd); - speed_listen_fd = -1; + return fd; +} + +static int run_speed_server(struct wolfIP *s) +{ + uint64_t now; + uint32_t c_prev; + uint32_t c_poll; + uint32_t c_done; + + speed_listen_fd = speed_open(s, IPSTACK_SOCK_STREAM); + speed_udp_fd = speed_open(s, IPSTACK_SOCK_DGRAM); + if (speed_listen_fd < 0 || speed_udp_fd < 0) { + wolfBoot_printf("SPEED: cannot open port %d\r\n", SPEED_PORT); return -1; } - - wolfBoot_printf("SPEED: TCP throughput server on port %d. Drive from host:\r\n", - SPEED_PORT); - wolfBoot_printf(" RX: dd if=/dev/zero bs=1460 count=20000 | nc %d\r\n", - SPEED_PORT); - wolfBoot_printf(" TX: nc %d /dev/null\r\n", + wolfIP_register_callback(s, speed_listen_fd, speed_cb, s); + wolfBoot_printf("SPEED: TCP and UDP throughput server on port %d\r\n", SPEED_PORT); - for (;;) - (void)wolfIP_poll(s, now_ms()); + wolfBoot_printf(" host: python3 tools/scripts/wolfip_speed.py \r\n"); + + c_prev = SPEED_CYCLES(); + for (;;) { + now = now_ms(); + c_poll = SPEED_CYCLES(); + (void)wolfIP_poll(s, now); + speed_tcp_pump(s); + speed_udp_recv(s, now); + speed_udp_send(s, now); + c_done = SPEED_CYCLES(); + if (speed.active != 0U) { + speed.cyc_busy += c_done - c_poll; + speed.cyc_total += c_done - c_prev; + speed.polls++; + } + c_prev = c_done; + } /* not reached */ } #endif /* WOLFIP_SPEED_TEST */ diff --git a/tools/scripts/mcxe247/e247_debug.cmm b/tools/scripts/mcxe247/e247_debug.cmm index 6367cddbca..c6e99c242f 100644 --- a/tools/scripts/mcxe247/e247_debug.cmm +++ b/tools/scripts/mcxe247/e247_debug.cmm @@ -2,10 +2,7 @@ ;; ;; Connect TRACE32 to the NXP MCXE247 (FRDM-MCXE247) and halt the CPU at the ;; reset vector, then load the wolfBoot and test-app symbols. -;; Usage: DO e247_debug.cmm [""] -;; The SDK dir is only used to find the fsl_enet and PHY driver sources of a -;; test-app built with ENABLE_WOLFIP=1. It defaults to the MCUXPRESSO path in -;; mcxe247.config (../NXP/mcuxpresso-sdk/mcuxsdk, next to the checkout). +;; No arguments: DO e247_debug.cmm ;; ;; Board setup (UM12286): ;; - Lauterbach 10-pin cable on J14 (SWD/JTAG 2x5 header) @@ -19,12 +16,8 @@ ;; - All output, including errors, is logged to ~~/e247_debug.log ;; - The ELF files are loaded from the wolfBoot checkout this script is in. -PARAMETERS &sdkdir - ; wolfBoot root: three levels above this script &basedir=OS.PPD()+"\..\..\.." -IF "&sdkdir"=="" - &sdkdir="&basedir\..\NXP\mcuxpresso-sdk\mcuxsdk" AREA.OPEN A000 "~~/e247_debug.log" /Create /NoFileCache PRINT "e247_debug.cmm " DATE.DATE() " " DATE.TIME() @@ -94,13 +87,6 @@ sYmbol.SourcePATH.SetBaseDir "&basedir" ; wolfIP and its MCXE247 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_enet""" -; MCUXpresso SDK drivers used by the wolfIP port, if the SDK is there -IF OS.DIR("&sdkdir") -( - &srcdirs="&srcdirs ""&sdkdir\drivers\enet"" ""&sdkdir\drivers\common""" - &srcdirs="&srcdirs ""&sdkdir\devices\MCX\MCXE\MCXE247\drivers""" - &srcdirs="&srcdirs ""&sdkdir\components\phy\device\phylan8741""" -) sYmbol.SourcePATH.Set &srcdirs ENDDO diff --git a/tools/scripts/wolfip_speed.py b/tools/scripts/wolfip_speed.py new file mode 100644 index 0000000000..4476770c35 --- /dev/null +++ b/tools/scripts/wolfip_speed.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +"""Host side of the wolfBoot test-app wolfIP throughput test. + +Build the test-app with ENABLE_WOLFIP=1 WOLFBOOT_TEST_TFTP=0 +WOLFIP_SPEED_TEST=1, boot it, then run from a host on the same network: + + python3 tools/scripts/wolfip_speed.py [--time 10] [--tests ...] + +Directions are named from the board: rx = the board receives, tx = the +board sends, bidir = both at once. Each test runs over TCP or UDP port 9 +(protocol in test-app/wolfip_tftp_test.c), then fetches the board's own +counters with a UDP query, including the CPU breakdown when the port +driver provides cycle counters (NXP MCX E247: NXP_MCXE_ENET_STATS). + +Reported rates: "rx" is what the board received, timed by the board; "tx" +is what this host received from the board, timed by the host. UDP loss is +datagrams sent but not received, per direction. + +Standard library only; runs on Linux, macOS and Windows. +""" + +import argparse +import socket +import struct +import sys +import threading +import time + +MAGIC = 0x57 +HDR = struct.Struct(">BBHII") # magic, cmd, size, seq, dur_ms +REPLY_LEN = 108 +TESTS = ["tcp-rx", "tcp-tx", "tcp-bidir", "udp-rx", "udp-tx", "udp-bidir"] + + +class Stats: + """Decoded 'S' reply (layout version 1).""" + + def __init__(self, data): + (self.proto, self.mode, self.active) = struct.unpack_from(">BBB", data, 3) + (self.ms, self.hz, self.rx_pkts, self.tx_pkts, self.rx_frames, + self.tx_frames) = struct.unpack_from(">6I", data, 8) + (self.rx_bytes, self.tx_bytes, self.cyc_total, self.cyc_busy, + self.drv_rx, self.drv_tx, self.drv_idle, self.copy, + self.tx_wait) = struct.unpack_from(">9Q", data, 32) + (self.polls,) = struct.unpack_from(">I", data, 104) + + def pct(self, cycles): + return 100.0 * cycles / self.cyc_total if self.cyc_total else 0.0 + + def cpu(self): + """CPU shares in %, or None when the board has no cycle counters.""" + if self.hz == 0 or self.cyc_total == 0: + return None + drv = self.drv_rx + self.drv_tx + self.drv_idle + return { + "drv-rx": self.pct(self.drv_rx), + "drv-tx": self.pct(self.drv_tx), + "drv-idle": self.pct(self.drv_idle), + "wolfIP": self.pct(max(self.cyc_busy - drv, 0)), + "loop": self.pct(self.cyc_total - self.cyc_busy), + "copy": self.pct(self.copy), + "ring-full": self.pct(self.tx_wait), + } + + +def mbps(nbytes, secs): + return nbytes * 8.0 / secs / 1e6 if secs > 0 else 0.0 + + +def udp_socket(): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4 << 20) + s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1 << 20) + return s + + +def query(sock, addr, want_proto, timeout=5.0): + """Send 'q' until the board reports the finished test of want_proto.""" + deadline = time.monotonic() + timeout + sock.settimeout(0.3) + while time.monotonic() < deadline: + sock.sendto(HDR.pack(MAGIC, ord("q"), 0, 0, 0), addr) + end = time.monotonic() + 0.3 + while time.monotonic() < end: + try: + data, _ = sock.recvfrom(2048) + except socket.timeout: + break + if len(data) >= REPLY_LEN and data[0] == MAGIC and data[1] == ord("S"): + st = Stats(data) + if st.active == 0 and st.proto == want_proto: + return st + raise RuntimeError("no stats reply from the board") + + +def drain(sock): + sock.settimeout(0) + try: + while True: + sock.recvfrom(2048) + except (BlockingIOError, socket.error): + pass + + +class Pacer: + """Spread sends to rate_mbps (0 = as fast as possible).""" + + def __init__(self, rate_mbps, size): + self.gap = size * 8.0 / (rate_mbps * 1e6) if rate_mbps > 0 else 0.0 + self.next = time.perf_counter() + + def wait(self): + if self.gap == 0.0: + return + self.next += self.gap + while time.perf_counter() < self.next: + pass + + +def tcp_test(ip, port, mode, secs): + """Returns (host bytes sent, host bytes received, host seconds).""" + s = socket.create_connection((ip, port), timeout=5) + s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + s.sendall(mode.encode()) + sent = [0] + recvd = [0] + stop = time.monotonic() + secs + buf = bytes(65536) + + def sender(): + while time.monotonic() < stop: + s.sendall(buf) + sent[0] += len(buf) + + def receiver(): + s.settimeout(0.5) + while time.monotonic() < stop: + try: + n = len(s.recv(65536)) + except socket.timeout: + continue + if n == 0: + break + recvd[0] += n + + t0 = time.monotonic() + workers = [] + if mode in ("r", "b"): + workers.append(threading.Thread(target=sender)) + if mode in ("t", "b"): + workers.append(threading.Thread(target=receiver)) + for w in workers: + w.start() + for w in workers: + w.join() + elapsed = time.monotonic() - t0 + s.close() + return sent[0], recvd[0], elapsed + + +def udp_test(sock, addr, mode, secs, size, rate): + """Returns (datagrams sent, datagrams received, bytes received, secs).""" + dur_ms = int(secs * 1000) + sent = [0] + got = [0, 0] # datagrams, bytes + first = [None] + last = [None] + stop_rx = threading.Event() + + def receiver(): + sock.settimeout(0.2) + idle_limit = 1.0 + while not stop_rx.is_set(): + try: + data, _ = sock.recvfrom(2048) + except socket.timeout: + if last[0] is not None and time.monotonic() - last[0] > idle_limit: + break + continue + if len(data) >= HDR.size and data[0] == MAGIC and data[1] == ord("d"): + now = time.monotonic() + if first[0] is None: + first[0] = now + last[0] = now + got[0] += 1 + got[1] += len(data) + + payload = bytearray(size) + t0 = time.monotonic() + rx = None + if mode in ("t", "b"): + rx = threading.Thread(target=receiver) + rx.start() + if mode == "t": + sock.sendto(HDR.pack(MAGIC, ord("t"), size, 0, dur_ms), addr) + time.sleep(1.0) + if got[0] == 0: # start lost: try once more + sock.sendto(HDR.pack(MAGIC, ord("t"), size, 0, dur_ms), addr) + else: + cmd = ord(mode) + pacer = Pacer(rate, size) + stop = t0 + secs + seq = 0 + while time.monotonic() < stop: + HDR.pack_into(payload, 0, MAGIC, cmd, size, seq, dur_ms) + try: + sock.sendto(payload, addr) + except (BlockingIOError, OSError): + continue + seq += 1 + pacer.wait() + sent[0] = seq + if rx is not None: + rx.join(timeout=secs + 5) + stop_rx.set() + rx.join() + span = (last[0] - first[0]) if (first[0] is not None and last[0] != first[0]) else (time.monotonic() - t0) + return sent[0], got[0], got[1], span + + +def run_test(name, args): + proto, direction = name.split("-") + mode = {"rx": "r", "tx": "t", "bidir": "b"}[direction] + addr = (args.ip, args.port) + ctl = udp_socket() + try: + drain(ctl) + if proto == "tcp": + h_sent, h_recv, h_secs = tcp_test(args.ip, args.port, mode, args.time) + st = query(ctl, addr, 1) + host_tx = mbps(h_recv, h_secs) + loss_rx = loss_tx = None + else: + # End any UDP test left running, so this one starts fresh + ctl.sendto(HDR.pack(MAGIC, ord("q"), 0, 0, 0), addr) + time.sleep(0.3) + drain(ctl) + sent, got, got_bytes, span = udp_test(ctl, addr, mode, args.time, + args.size, args.rate) + st = query(ctl, addr, 2) + host_tx = mbps(got_bytes, span) + loss_rx = (100.0 * (sent - st.rx_pkts) / sent) if sent else None + loss_tx = (100.0 * (st.tx_pkts - got) / st.tx_pkts) if st.tx_pkts else None + finally: + ctl.close() + board_secs = st.ms / 1000.0 + return { + "test": name, + "rx": mbps(st.rx_bytes, board_secs) if mode != "t" else None, + "tx": host_tx if mode != "r" else None, + "loss_rx": loss_rx if mode != "t" else None, + "loss_tx": loss_tx if mode != "r" else None, + "stats": st, + } + + +def fmt(v, spec="{:6.2f}", width=6): + return spec.format(v) if v is not None else "-".rjust(width) + + +def print_table(results): + cpu_cols = ["drv-rx", "drv-tx", "drv-idle", "wolfIP", "loop", "copy"] + print() + print("Mbit/s: rx = received by the board, tx = sent by the board." + " CPU in % of the test window.") + head = "{:<10} {:>6} {:>6} {:>7} {:>7}".format( + "test", "rx", "tx", "rxloss%", "txloss%") + has_cpu = any(r["stats"].cpu() is not None for r in results) + if has_cpu: + head += " " + " ".join("{:>8}".format(c) for c in cpu_cols) + print(head) + for r in results: + line = "{:<10} {} {} {} {}".format( + r["test"], fmt(r["rx"]), fmt(r["tx"]), + fmt(r["loss_rx"], "{:7.1f}", 7), fmt(r["loss_tx"], "{:7.1f}", 7)) + cpu = r["stats"].cpu() + if cpu is not None: + line += " " + " ".join("{:8.1f}".format(cpu[c]) for c in cpu_cols) + print(line) + for r in results: + st = r["stats"] + if st.hz: + frames = st.rx_frames + st.tx_frames + drv = st.drv_rx + st.drv_tx + st.drv_idle + stack = max(st.cyc_busy - drv, 0) + print("{:<10} {} MHz, frames rx {} tx {}, cycles/frame: wolfIP {}, " + "drv-rx {}, drv-tx {}; {} polls, {} cycles/poll".format( + r["test"], st.hz // 1000000, st.rx_frames, st.tx_frames, + stack // frames if frames else 0, + st.drv_rx // st.rx_frames if st.rx_frames else 0, + st.drv_tx // st.tx_frames if st.tx_frames else 0, + st.polls, st.cyc_busy // st.polls if st.polls else 0)) + + +def main(): + p = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + p.add_argument("ip", help="board IP address") + p.add_argument("--port", type=int, default=9) + p.add_argument("--time", type=float, default=10.0, help="seconds per test") + p.add_argument("--size", type=int, default=1472, + help="UDP datagram payload bytes (12..1472)") + p.add_argument("--rate", type=float, default=0.0, + help="UDP send rate to the board in Mbit/s (0 = unlimited)") + p.add_argument("--tests", default=",".join(TESTS), + help="comma separated subset of: " + ",".join(TESTS)) + p.add_argument("--pause", type=float, default=1.0, + help="seconds between tests") + args = p.parse_args() + + if not 12 <= args.size <= 1472: + p.error("--size must be 12..1472") + names = [t.strip() for t in args.tests.split(",") if t.strip()] + for t in names: + if t not in TESTS: + p.error("unknown test " + t) + + results = [] + for i, name in enumerate(names): + if i: + time.sleep(args.pause) + print("running {} for {:g} s...".format(name, args.time), flush=True) + try: + results.append(run_test(name, args)) + except (OSError, RuntimeError) as e: + print(" {} failed: {}".format(name, e), file=sys.stderr) + if results: + print_table(results) + return 0 if len(results) == len(names) else 1 + + +if __name__ == "__main__": + sys.exit(main()) From 53b56d8bf73b4f0f7d1a6d301aaaa1fb0889adb9 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 13 Nov 2026 15:01:20 -0500 Subject: [PATCH 02/24] mcxe247: stop the speed test with Ctrl-C, harden the UDP tests - Ctrl-C on the console stops the throughput server - UDP datagrams carry a session id chosen by the host for each test. The board ignores data of a finished test, so datagrams still queued on the way cannot start a new test, and the host ignores board datagrams of an earlier test. - wolfip_speed.py sends UDP at 100 Mbit/s on the wire by default instead of as fast as the host can, and warns when --rate 0 is used. --- config/examples/mcxe247.config | 7 ++--- docs/Targets.md | 9 ++++-- test-app/app_s32k1xx.c | 21 +++++++++++++ test-app/wolfip_tftp_test.c | 57 +++++++++++++++++++++++++++++++--- test-app/wolfip_tftp_test.h | 4 +++ tools/scripts/wolfip_speed.py | 48 +++++++++++++++++++--------- 6 files changed, 121 insertions(+), 25 deletions(-) diff --git a/config/examples/mcxe247.config b/config/examples/mcxe247.config index bbaf7bb02c..dc6aef3059 100644 --- a/config/examples/mcxe247.config +++ b/config/examples/mcxe247.config @@ -68,10 +68,9 @@ WOLFBOOT_LIB_WOLFIP?=../lib/wolfip WOLFBOOT_TEST_TFTP?=1 CFLAGS_EXTRA+=-DHOST_IP_STR='"192.168.50.1"' -DTFTP_FILENAME='"wolfip_test.bin"' # WOLFIP_SPEED_TEST=1 makes the command run a TCP and UDP throughput server on -# port 9 instead, driven from the host by tools/scripts/wolfip_speed.py (it -# never returns; reset the board to stop it). WOLFBOOT_TEST_TFTP overrides it: -# with both set to 1 the command runs the TFTP fetch and the speed server is -# never started. +# port 9 instead, driven from the host by tools/scripts/wolfip_speed.py. +# WOLFBOOT_TEST_TFTP overrides it: with both set to 1 the command runs the TFTP +# fetch and the speed server is never started. WOLFIP_SPEED_TEST?=0 # Debugging options diff --git a/docs/Targets.md b/docs/Targets.md index 927f4126fb..dd2377fb2a 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7845,11 +7845,14 @@ It prints a table of the rates and UDP loss. With this build the driver also counts its own core cycles (`NXP_MCXE_ENET_STATS=1`), so the table also shows how the CPU time divides between the driver, the frame copies, wolfIP and the main loop. `--tests` picks a subset, `--time` sets the duration and `--rate` -limits the UDP send rate to the board, e.g. to find the highest rate without -loss. The board prints the same counters on the console after each test. +sets the UDP send rate to the board, 100 Mbit/s on the wire by default; lower +it to find the highest rate without loss. Do not raise it above the link rate: +a fast host (WSL can send 2 Gbit/s) queues the excess and keeps feeding it to +the board long after the test, so the board stops answering. The board prints +the same counters on the console after each test. Plain `nc 9` still works as a bidirectional TCP test. -The server never returns to the console; reset the board to stop it. +Press Ctrl-C on the console to stop the server and return to the `cmd>` prompt. `WOLFBOOT_TEST_TFTP` takes priority: with both options set to 1, the command runs the TFTP fetch and the speed server is never started. diff --git a/test-app/app_s32k1xx.c b/test-app/app_s32k1xx.c index 65f71720cf..7262f40287 100644 --- a/test-app/app_s32k1xx.c +++ b/test-app/app_s32k1xx.c @@ -89,6 +89,14 @@ uint64_t wolfip_test_get_ms(void) 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) @@ -886,6 +894,19 @@ static int cmd_network(const char *args) wolfip_tftp_test_report(); return 0; } + +/* Non-zero when Ctrl-C arrived on the console. Other input is discarded. */ +int wolfip_test_abort(void) +{ + char c; + int abort = 0; + + while (uart_getc(&c) > 0) { + if (c == 0x03) + abort = 1; + } + return abort; +} #endif static int parse_command(const char* cmd) diff --git a/test-app/wolfip_tftp_test.c b/test-app/wolfip_tftp_test.c index ab4b3b4134..4df764d8a2 100644 --- a/test-app/wolfip_tftp_test.c +++ b/test-app/wolfip_tftp_test.c @@ -454,6 +454,9 @@ static int run_tftp_fetch(struct wolfIP *s) * UDP: each datagram starts with a SPEED_HDR_LEN byte header, big-endian: * [0] SPEED_MAGIC [1] command [2..3] board datagram size * [4..7] sequence [8..11] board send duration in ms + * [12..15] session: a non-zero id the host picks for each test. Data of + * a test that has ended is ignored, so datagrams still queued + * on the way cannot start a new test. * Commands to the board: * 'r' data to count (starts an rx test) * 'b' data to count; the first one starts a bidir test and the board @@ -464,10 +467,10 @@ static int run_tftp_fetch(struct wolfIP *s) * * The 'S' reply describes the last test, TCP or UDP, so the host can fetch * the board's counters after a TCP test too. Each finished test is also - * printed on the console. */ + * printed on the console. Ctrl-C on the console stops the server. */ #define SPEED_PORT 9 #define SPEED_MAGIC 0x57U /* 'W' */ -#define SPEED_HDR_LEN 12 +#define SPEED_HDR_LEN 16 #define SPEED_UDP_MAX 1472U /* largest unfragmented payload */ #define SPEED_TCP_CHUNK 1460U #define SPEED_BURST 32 @@ -475,6 +478,14 @@ static int run_tftp_fetch(struct wolfIP *s) #define SPEED_PROTO_UDP 2U #define SPEED_REPLY_LEN 108 +/* How often the server checks for Ctrl-C on the console */ +#define SPEED_ABORT_POLL_MS 100U +#ifdef WOLFIP_PORT_MCXE_ENET +#define SPEED_ABORT() wolfip_test_abort() +#else +#define SPEED_ABORT() 0 +#endif + #if defined(WOLFIP_PORT_MCXE_ENET) && NXP_MCXE_ENET_STATS /* The driver enables the DWT cycle counter */ #define SPEED_PROFILE 1 @@ -497,6 +508,7 @@ struct speed_state { uint32_t tx_seq; uint32_t stream_len; uint32_t polls; /* wolfIP_poll() calls in the test window */ + uint32_t session; /* UDP test id from the host, 0 for TCP */ uint8_t proto; uint8_t mode; /* 'r', 't', 'b'; 0 until a TCP client sends */ uint8_t active; @@ -507,6 +519,7 @@ static int speed_listen_fd = -1; static int speed_client_fd = -1; static int speed_udp_fd = -1; static struct speed_state speed; +static uint32_t speed_ended_session; /* last UDP test that ended */ static struct wolfIP_sockaddr_in speed_peer; static uint8_t speed_rxbuf[SPEED_UDP_MAX]; static uint8_t speed_txbuf[SPEED_UDP_MAX]; @@ -627,6 +640,7 @@ static void speed_stop(uint64_t now) speed.active = 0U; speed.streaming = 0U; speed.end_ms = now; + speed_ended_session = speed.session; #if SPEED_PROFILE nxp_mcxe_enet_stats_get(&speed_drv); #endif @@ -739,6 +753,7 @@ static void speed_udp_recv(struct wolfIP *s, uint64_t now) struct wolfIP_sockaddr_in from; socklen_t from_len; uint32_t len; + uint32_t session; uint8_t cmd; int n; int k; @@ -763,8 +778,14 @@ static void speed_udp_recv(struct wolfIP *s, uint64_t now) continue; if (speed.active != 0U && speed.proto == SPEED_PROTO_TCP) continue; /* a TCP test is running */ + session = speed_get32(speed_rxbuf + 12); + if (session == 0U || session == speed_ended_session) + continue; /* left over from a finished test */ + if (speed.active != 0U && session != speed.session) + speed_stop(now); /* the host started a new test */ if (speed.active == 0U) { speed_start(SPEED_PROTO_UDP, cmd, now); + speed.session = session; speed_peer = from; if (cmd != 'r') { len = ((uint32_t)speed_rxbuf[2] << 8) | speed_rxbuf[3]; @@ -799,6 +820,8 @@ static void speed_udp_send(struct wolfIP *s, uint64_t now) speed_txbuf[1] = 'd'; speed_txbuf[2] = 0U; speed_txbuf[3] = 0U; + speed_put32(speed_txbuf + 8, 0U); + speed_put32(speed_txbuf + 12, speed.session); for (k = 0; k < SPEED_BURST; k++) { speed_put32(speed_txbuf + 4, speed.tx_seq); n = wolfIP_sock_sendto(s, speed_udp_fd, speed_txbuf, @@ -833,9 +856,25 @@ static int speed_open(struct wolfIP *s, int type) return fd; } +/* Close the server's sockets, ending a running test first. */ +static void speed_close(struct wolfIP *s) +{ + speed_stop(now_ms()); + if (speed_client_fd >= 0) + (void)wolfIP_sock_close(s, speed_client_fd); + if (speed_listen_fd >= 0) + (void)wolfIP_sock_close(s, speed_listen_fd); + if (speed_udp_fd >= 0) + (void)wolfIP_sock_close(s, speed_udp_fd); + speed_client_fd = -1; + speed_listen_fd = -1; + speed_udp_fd = -1; +} + static int run_speed_server(struct wolfIP *s) { uint64_t now; + uint64_t abort_check; uint32_t c_prev; uint32_t c_poll; uint32_t c_done; @@ -844,16 +883,24 @@ static int run_speed_server(struct wolfIP *s) speed_udp_fd = speed_open(s, IPSTACK_SOCK_DGRAM); if (speed_listen_fd < 0 || speed_udp_fd < 0) { wolfBoot_printf("SPEED: cannot open port %d\r\n", SPEED_PORT); + speed_close(s); return -1; } wolfIP_register_callback(s, speed_listen_fd, speed_cb, 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"); + wolfBoot_printf(" Ctrl-C stops the server\r\n"); + abort_check = now_ms() + SPEED_ABORT_POLL_MS; c_prev = SPEED_CYCLES(); for (;;) { now = now_ms(); + if (now >= abort_check) { + abort_check = now + SPEED_ABORT_POLL_MS; + if (SPEED_ABORT() != 0) + break; + } c_poll = SPEED_CYCLES(); (void)wolfIP_poll(s, now); speed_tcp_pump(s); @@ -867,7 +914,9 @@ static int run_speed_server(struct wolfIP *s) } c_prev = c_done; } - /* not reached */ + speed_close(s); + wolfBoot_printf("SPEED: stopped\r\n"); + return 0; } #endif /* WOLFIP_SPEED_TEST */ @@ -879,7 +928,7 @@ int wolfip_tftp_test_run(void) #if defined(WOLFBOOT_TEST_TFTP) return run_tftp_fetch(s); #elif defined(WOLFIP_SPEED_TEST) - return run_speed_server(s); /* loops forever */ + return run_speed_server(s); /* until Ctrl-C */ #else return 0; /* DHCP lease only, no transfer */ #endif diff --git a/test-app/wolfip_tftp_test.h b/test-app/wolfip_tftp_test.h index f589d12504..4816205fbf 100644 --- a/test-app/wolfip_tftp_test.h +++ b/test-app/wolfip_tftp_test.h @@ -37,6 +37,10 @@ void wolfip_tftp_test_report(void); #ifdef WOLFIP_PORT_MCXE_ENET /* Milliseconds since start, monotonic. Provided by the target app. */ uint64_t wolfip_test_get_ms(void); + +/* Non-zero when the user asked to stop (Ctrl-C on the console). Provided by + * the target app; polled by the throughput server. */ +int wolfip_test_abort(void); #endif #endif /* WOLFIP_TFTP_TEST_H */ diff --git a/tools/scripts/wolfip_speed.py b/tools/scripts/wolfip_speed.py index 4476770c35..07e5c5f047 100644 --- a/tools/scripts/wolfip_speed.py +++ b/tools/scripts/wolfip_speed.py @@ -20,6 +20,7 @@ """ import argparse +import random import socket import struct import sys @@ -27,8 +28,11 @@ import time MAGIC = 0x57 -HDR = struct.Struct(">BBHII") # magic, cmd, size, seq, dur_ms +HDR = struct.Struct(">BBHIII") # magic, cmd, size, seq, dur_ms, session REPLY_LEN = 108 +# Ethernet preamble, header, FCS and gap plus IPv4 and UDP headers: what a +# datagram costs on the wire beyond its payload +WIRE_OVERHEAD = 8 + 14 + 4 + 12 + 20 + 8 TESTS = ["tcp-rx", "tcp-tx", "tcp-bidir", "udp-rx", "udp-tx", "udp-bidir"] @@ -79,7 +83,7 @@ def query(sock, addr, want_proto, timeout=5.0): deadline = time.monotonic() + timeout sock.settimeout(0.3) while time.monotonic() < deadline: - sock.sendto(HDR.pack(MAGIC, ord("q"), 0, 0, 0), addr) + sock.sendto(HDR.pack(MAGIC, ord("q"), 0, 0, 0, 0), addr) end = time.monotonic() + 0.3 while time.monotonic() < end: try: @@ -103,10 +107,11 @@ def drain(sock): class Pacer: - """Spread sends to rate_mbps (0 = as fast as possible).""" + """Spread sends to rate_mbps on the wire (0 = as fast as possible).""" def __init__(self, rate_mbps, size): - self.gap = size * 8.0 / (rate_mbps * 1e6) if rate_mbps > 0 else 0.0 + bits = (size + WIRE_OVERHEAD) * 8.0 + self.gap = bits / (rate_mbps * 1e6) if rate_mbps > 0 else 0.0 self.next = time.perf_counter() def wait(self): @@ -161,6 +166,7 @@ def receiver(): def udp_test(sock, addr, mode, secs, size, rate): """Returns (datagrams sent, datagrams received, bytes received, secs).""" dur_ms = int(secs * 1000) + session = random.randint(1, 0xFFFFFFFF) sent = [0] got = [0, 0] # datagrams, bytes first = [None] @@ -177,7 +183,9 @@ def receiver(): if last[0] is not None and time.monotonic() - last[0] > idle_limit: break continue - if len(data) >= HDR.size and data[0] == MAGIC and data[1] == ord("d"): + if (len(data) >= HDR.size and data[0] == MAGIC and + data[1] == ord("d") and + HDR.unpack_from(data)[5] == session): now = time.monotonic() if first[0] is None: first[0] = now @@ -192,17 +200,18 @@ def receiver(): rx = threading.Thread(target=receiver) rx.start() if mode == "t": - sock.sendto(HDR.pack(MAGIC, ord("t"), size, 0, dur_ms), addr) + sock.sendto(HDR.pack(MAGIC, ord("t"), size, 0, dur_ms, session), addr) time.sleep(1.0) if got[0] == 0: # start lost: try once more - sock.sendto(HDR.pack(MAGIC, ord("t"), size, 0, dur_ms), addr) + sock.sendto(HDR.pack(MAGIC, ord("t"), size, 0, dur_ms, session), + addr) else: cmd = ord(mode) pacer = Pacer(rate, size) stop = t0 + secs seq = 0 while time.monotonic() < stop: - HDR.pack_into(payload, 0, MAGIC, cmd, size, seq, dur_ms) + HDR.pack_into(payload, 0, MAGIC, cmd, size, seq, dur_ms, session) try: sock.sendto(payload, addr) except (BlockingIOError, OSError): @@ -232,7 +241,7 @@ def run_test(name, args): loss_rx = loss_tx = None else: # End any UDP test left running, so this one starts fresh - ctl.sendto(HDR.pack(MAGIC, ord("q"), 0, 0, 0), addr) + ctl.sendto(HDR.pack(MAGIC, ord("q"), 0, 0, 0, 0), addr) time.sleep(0.3) drain(ctl) sent, got, got_bytes, span = udp_test(ctl, addr, mode, args.time, @@ -298,22 +307,33 @@ def main(): p.add_argument("--port", type=int, default=9) p.add_argument("--time", type=float, default=10.0, help="seconds per test") p.add_argument("--size", type=int, default=1472, - help="UDP datagram payload bytes (12..1472)") - p.add_argument("--rate", type=float, default=0.0, - help="UDP send rate to the board in Mbit/s (0 = unlimited)") + help="UDP datagram payload bytes (16..1472)") + p.add_argument("--rate", type=float, default=100.0, + help="UDP send rate to the board in Mbit/s on the wire " + "(default 100, " + "the board's link rate; 0 = unlimited). A fast host " + "can send far more than the link carries; the excess " + "queues in the host and reaches the board for " + "seconds after the test") p.add_argument("--tests", default=",".join(TESTS), help="comma separated subset of: " + ",".join(TESTS)) p.add_argument("--pause", type=float, default=1.0, help="seconds between tests") args = p.parse_args() - if not 12 <= args.size <= 1472: - p.error("--size must be 12..1472") + if not HDR.size <= args.size <= 1472: + p.error("--size must be {}..1472".format(HDR.size)) names = [t.strip() for t in args.tests.split(",") if t.strip()] for t in names: if t not in TESTS: p.error("unknown test " + t) + if args.rate <= 0 and any(n.startswith("udp-") and n != "udp-tx" + for n in names): + print("warning: --rate 0 sends as fast as this host can. Anything " + "above the link rate queues in the host and keeps reaching the " + "board, which may not answer for a minute or more.", + file=sys.stderr) results = [] for i, name in enumerate(names): if i: From 78e7233452eb22a1e9ed0c03c6e0db43cba3d1e5 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 13 Nov 2026 16:28:18 -0500 Subject: [PATCH 03/24] mcxe247: build wolfIP without -ffreestanding -ffreestanding disables the compiler builtins, so every small fixed-size memcpy in wolfIP (one per 16-bit word in the transport checksum, header field accessors) became a call to the byte-wise memcpy in src/string.c. That was most of the stack's CPU time. Building the wolfIP sources hosted lets the compiler inline them. Measured with tools/scripts/wolfip_speed.py at 48 MHz, Mbit/s: TCP rx 4.3 -> 6.9, TCP tx 4.1 -> 6.3, UDP rx 5.5 -> 9.1, UDP tx 5.4 -> 9.0. --- test-app/Makefile | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test-app/Makefile b/test-app/Makefile index 3babe5b2c3..4c2c717b37 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1794,6 +1794,10 @@ ifeq ($(ENABLE_WOLFIP),1) # wolfIP state is in the 128KB of SRAM_L (ARM-s32k1xx-wolfip.ld): six # full segments of TCP buffering per socket CFLAGS+=-DRXBUF_SIZE=9216 -DTXBUF_SIZE=9216 + # Build wolfIP hosted: -ffreestanding turns every small fixed-size + # memcpy (checksum words, header fields) into a call to the byte-wise + # memcpy in src/string.c, which cost most of the stack's CPU time + WOLFIP_CFLAGS_OUT:=-ffreestanding # Driver cycle counters for the throughput test's CPU breakdown ifeq ($(WOLFIP_SPEED_TEST),1) CFLAGS+=-DNXP_MCXE_ENET_STATS=1 @@ -1827,7 +1831,7 @@ ifeq ($(ENABLE_WOLFIP),1) # wolfIP TUs need the port headers first (so config.h resolves to the # port copy) and tolerate wolfIP's own style; drop -Werror/-Wstack-usage. WOLFIP_CFLAGS:=-I"$(WOLFIP_PORTDIR)" -I"$(WOLFBOOT_LIB_WOLFIP)" \ - $(filter-out -Werror -Wstack-usage=$(STACK_USAGE_LIMIT),$(CFLAGS)) \ + $(filter-out -Werror -Wstack-usage=$(STACK_USAGE_LIMIT) $(WOLFIP_CFLAGS_OUT),$(CFLAGS)) \ -DWOLFIP_ENABLE_TFTP=$(if $(filter 1,$(WOLFBOOT_TEST_TFTP)),1,0) \ -Wno-unused -Wno-sign-compare -Wno-missing-field-initializers endif From 244e0cdd7845ad08c2c4e92842c3b2465373c22a Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Sun, 15 Nov 2026 13:32:14 -0500 Subject: [PATCH 04/24] improve FAST_MEMCPY with word copies and cortex-m unaligned reads --- config/examples/mcxe247.config | 4 ++++ src/string.c | 41 +++++++++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/config/examples/mcxe247.config b/config/examples/mcxe247.config index dc6aef3059..69a5d01717 100644 --- a/config/examples/mcxe247.config +++ b/config/examples/mcxe247.config @@ -32,6 +32,10 @@ DUALBANK_SWAP?=0 # (0x1FFFC000-0x20002FFF) at reset so its ECC is valid. The rest of SRAM is the # application's to initialize. CFLAGS_EXTRA+=-DMCXE247 -DWOLFBOOT_RAM_ECC_INIT +# Word-at-a-time memcpy/memset in src/string.c (bootloader and test-app). The +# Cortex-M4 loads unaligned words, so memcpy copies words even when source and +# destination alignments differ; about doubles the wolfIP network test rates. +CFLAGS_EXTRA+=-DFAST_MEMCPY # 4KB sectors WOLFBOOT_SECTOR_SIZE?=0x1000 diff --git a/src/string.c b/src/string.c index 3475f00d82..d93c6d1084 100644 --- a/src/string.c +++ b/src/string.c @@ -302,13 +302,52 @@ size_t strlen(const char *s) #undef RAMFUNCTION #define RAMFUNCTION #endif +#if defined(FAST_MEMCPY) && defined(__ARM_FEATURE_UNALIGNED) && \ + defined(__GNUC__) +/* A 32-bit word at any address. aligned(1) lets the compiler emit a plain + * (unaligned) word access; may_alias lets it alias the byte buffers. */ +typedef uint32_t __attribute__((aligned(1), may_alias)) wb_u32_unaligned; +#endif void RAMFUNCTION *memcpy(void *dst, const void *src, size_t n) { size_t i; const char *s = (const char *)src; char *d = (char *)dst; -#ifdef FAST_MEMCPY +#if defined(FAST_MEMCPY) && defined(__ARM_FEATURE_UNALIGNED) && \ + defined(__GNUC__) + /* The core loads words from any address (e.g. ARMv7-M with + * CCR.UNALIGN_TRP clear), so the source alignment does not matter: + * align the destination, then copy words. Network stacks copy payloads + * at 2 mod 4 offsets, which the aligned-only path below never speeds + * up. Normal memory only, as for any word access. */ + if (n >= 2 * sizeof(uint32_t)) { + while (((size_t)d & (sizeof(uint32_t) - 1)) != 0) { + *d++ = *s++; + n--; + } + while (n >= 4 * sizeof(uint32_t)) { + uint32_t w0 = ((const wb_u32_unaligned *)s)[0]; + uint32_t w1 = ((const wb_u32_unaligned *)s)[1]; + uint32_t w2 = ((const wb_u32_unaligned *)s)[2]; + uint32_t w3 = ((const wb_u32_unaligned *)s)[3]; + + ((wb_u32_unaligned *)d)[0] = w0; + ((wb_u32_unaligned *)d)[1] = w1; + ((wb_u32_unaligned *)d)[2] = w2; + ((wb_u32_unaligned *)d)[3] = w3; + d += 4 * sizeof(uint32_t); + s += 4 * sizeof(uint32_t); + n -= 4 * sizeof(uint32_t); + } + while (n >= sizeof(uint32_t)) { + *(wb_u32_unaligned *)d = *(const wb_u32_unaligned *)s; + d += sizeof(uint32_t); + s += sizeof(uint32_t); + n -= sizeof(uint32_t); + } + } +#elif defined(FAST_MEMCPY) /* is 32-bit aligned pointer */ if (((size_t)dst & (sizeof(unsigned long)-1)) == 0 && ((size_t)src & (sizeof(unsigned long)-1)) == 0) From f1757576f41669bcc040dd9db385d91b5bdc1ace Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Sun, 15 Nov 2026 23:33:42 -0500 Subject: [PATCH 05/24] run cpu at 80 MHz and turn on flash code cache --- config/examples/mcxe247.config | 6 ++ docs/Targets.md | 14 +++- hal/s32k1xx.c | 138 +++++++++++++++++++++++++++++++-- hal/s32k1xx.h | 47 ++++++++++- test-app/app_s32k1xx.c | 11 ++- 5 files changed, 204 insertions(+), 12 deletions(-) diff --git a/config/examples/mcxe247.config b/config/examples/mcxe247.config index 69a5d01717..8c3f38b4e4 100644 --- a/config/examples/mcxe247.config +++ b/config/examples/mcxe247.config @@ -37,6 +37,12 @@ CFLAGS_EXTRA+=-DMCXE247 -DWOLFBOOT_RAM_ECC_INIT # destination alignments differ; about doubles the wolfIP network test rates. CFLAGS_EXTRA+=-DFAST_MEMCPY +# Run at 80 MHz from the 8 MHz crystal (SOSC + SPLL) with the 4 KB flash code +# cache on. wolfBoot returns clock and cache to their reset state before it +# starts the application; the test-app then switches both on again. +# Remove to run from the 48 MHz internal oscillator. +CFLAGS_EXTRA+=-DS32K1XX_CLOCK_80MHZ -DS32K1XX_CODE_CACHE + # 4KB sectors WOLFBOOT_SECTOR_SIZE?=0x1000 diff --git a/docs/Targets.md b/docs/Targets.md index dd2377fb2a..e8cbf3a72a 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7597,7 +7597,9 @@ The following build options are available for the S32K1xx HAL: | `WATCHDOG` | Enable the watchdog during wolfBoot operation. wolfBoot calls `wolfBoot_watchdog_feed()` from its hash and copy/erase loops -- a weak no-op a port overrides to service its watchdog (e.g. external MAX6316-MAX6322, see `hal/renesas-rx.c`). | | `WATCHDOG_TIMEOUT_MS` | Watchdog timeout in milliseconds when `WATCHDOG` is enabled (default: 1000ms). | | `S32K1XX_CLOCK_HSRUN` | Enable HSRUN mode (112 MHz). Requires external crystal and SPLL (not fully implemented). | -| `DEBUG_UART` | Enable LPUART1 debug output. | +| `S32K1XX_CLOCK_80MHZ` | Run wolfBoot at 80 MHz (RUN mode) from the external crystal through the SPLL, instead of the 48 MHz FIRC. The crystal frequency is `S32K1XX_SOSC_FREQ` (default 8 MHz). The clock is switched back before the application starts; the s32k1xx test-app switches to 80 MHz again with `s32k1xx_clock_80mhz()`. Tested on the MCXE247 only. | +| `S32K1XX_CODE_CACHE` | Enable the 4 KB LMEM code cache for flash while wolfBoot runs. It is invalidated after every flash erase and program command, and disabled before the application starts; the s32k1xx test-app enables it again with `s32k1xx_code_cache_enable()`. Tested on the MCXE247 only. | +| `DEBUG_UART` | Enable LPUART debug output. | | `DEBUG_HARDFAULT` | Enable detailed hard fault debugging output. | | `S32K144`, `S32K146`, `S32K148` | Select variant (default is S32K142). Affects flash/SRAM size definitions. | | `WOLFBOOT_FOPT` | Override the Flash Option Byte (FOPT) in the Flash Configuration Field (FCF at 0x40D). Default is `0xFF`. Set via `CFLAGS_EXTRA+=-DWOLFBOOT_FOPT=0xF7` in your `.config` file. See FOPT bit field table below. | @@ -7805,6 +7807,16 @@ apply to the MCXE247, with these differences: and with 163 interrupts it must be 1 KB aligned: with the default 256-byte header the core fetches the vectors of IRQ 48 and up (the ENET interrupts among them) from the wrong slots. +- `mcxe247.config` sets `S32K1XX_CLOCK_80MHZ` and `S32K1XX_CODE_CACHE`, which + run wolfBoot at 80 MHz from the board's 8 MHz crystal with the code cache on. + On the FRDM-MCXE247 this cuts the time from `wolfBoot_start` to the jump to + the application from about 205 ms to about 128 ms (88 KB image, + ECDSA P-256 with SHA-256, including the console messages). The application + still starts with the cache disabled and the clock on the 8 MHz SIRC + (`WOLFBOOT_RESTORE_CLOCK`, the default) or the 48 MHz FIRC. The test-app + then switches to 80 MHz and enables the cache again. SRAM_L, where the + network test keeps the wolfIP state, is not behind the cache (only flash + is cacheable). ### NXP MCXE247: Network test diff --git a/hal/s32k1xx.c b/hal/s32k1xx.c index 97879845bb..00e276cff3 100644 --- a/hal/s32k1xx.c +++ b/hal/s32k1xx.c @@ -202,18 +202,69 @@ static void clock_init_firc(void) while (!(SCG_FIRCCSR & SCG_FIRCCSR_FIRCVLD)) {} } +#ifdef S32K1XX_CLOCK_80MHZ +#if defined(S32K1XX_CLOCK_HSRUN) +#error "S32K1XX_CLOCK_80MHZ and S32K1XX_CLOCK_HSRUN are mutually exclusive" +#endif + +/* Crystal on the SOSC (EXTAL/XTAL) pins */ +#ifndef S32K1XX_SOSC_FREQ +#define S32K1XX_SOSC_FREQ 8000000UL +#endif + +/* VCO_CLK = SOSC / (PREDIV + 1) * (MULT + 16) = 320 MHz, SPLL_CLK = 160 MHz */ +#define SPLL_VCO_FREQ 320000000UL +#define SPLL_MULT ((SPLL_VCO_FREQ / S32K1XX_SOSC_FREQ) - 16UL) +#if (SPLL_VCO_FREQ % S32K1XX_SOSC_FREQ) != 0 || \ + (SPLL_VCO_FREQ / S32K1XX_SOSC_FREQ) < 16 || \ + (SPLL_VCO_FREQ / S32K1XX_SOSC_FREQ) > 47 +#error "S32K1XX_SOSC_FREQ cannot produce a 320 MHz VCO with PREDIV=0" +#endif + +/* RUN mode at 80 MHz (reference manual "Normal RUN" example): + * SOSC -> SPLL 160 MHz -> CORE/SYS 80 MHz (/2), BUS 40 MHz (/2 of core), + * FLASH 26.67 MHz (/3 of core, the RUN mode maximum). + */ static void clock_init_spll(void) { - /* S32K1xx SPLL requires SOSC as source (FIRC cannot be used directly). - * For 112 MHz with 8 MHz SOSC: PREDIV=0, MULT=28 -> VCO=224 MHz, SPLL=112 MHz - * VCO range: 180-320 MHz, SPLL_CLK = VCO / 2 - * - * Currently using FIRC 48 MHz directly. TODO: Add SOSC + SPLL for 112 MHz. - */ - SCG_SPLLCSR &= ~SCG_SPLLCSR_SPLLEN; - SCG_SPLLDIV = (2UL << 8) | (4UL << 0); /* SPLLDIV1=/2, SPLLDIV2=/4 */ + /* SOSC: crystal, high range (required when it feeds the SPLL) */ + SCG_SOSCCSR = 0; + SCG_SOSCDIV = (1UL << 8) | (1UL << 0); /* SOSCDIV1=/1, SOSCDIV2=/1 */ + SCG_SOSCCFG = SCG_SOSCCFG_RANGE_HIGH | SCG_SOSCCFG_EREFS; + SCG_SOSCCSR = SCG_SOSCCSR_SOSCEN; + while (!(SCG_SOSCCSR & SCG_SOSCCSR_SOSCVLD)) {} + + /* SPLL: SPLLCFG can only be written while the SPLL is disabled */ + SCG_SPLLCSR = 0; + SCG_SPLLDIV = (2UL << SCG_SPLLDIV_SPLLDIV1_SHIFT) | /* /2: 80 MHz */ + (3UL << SCG_SPLLDIV_SPLLDIV2_SHIFT); /* /4: 40 MHz */ + SCG_SPLLCFG = (SPLL_MULT << SCG_SPLLCFG_MULT_SHIFT) | + (0UL << SCG_SPLLCFG_PREDIV_SHIFT); + SCG_SPLLCSR = SCG_SPLLCSR_SPLLEN; + while (!(SCG_SPLLCSR & SCG_SPLLCSR_SPLLVLD)) {} + + /* Switch the system clock to the SPLL */ + SCG_RCCR = SCG_xCCR_SCS_SPLL | + (1UL << SCG_xCCR_DIVCORE_SHIFT) | + (1UL << SCG_xCCR_DIVBUS_SHIFT) | + (2UL << SCG_xCCR_DIVSLOW_SHIFT); + while ((SCG_CSR & SCG_CSR_SCS_MASK) != SCG_CSR_SCS_SPLL) {} +} + +/* Stop the SPLL and SOSC once the system clock no longer uses them */ +static void clock_stop_spll(void) +{ + SCG_SPLLCSR = 0; + SCG_SOSCCSR = 0; } +void s32k1xx_clock_80mhz(void) +{ + if ((SCG_CSR & SCG_CSR_SCS_MASK) != SCG_CSR_SCS_SPLL) + clock_init_spll(); +} +#endif /* S32K1XX_CLOCK_80MHZ */ + static void clock_init(void) { /* Initialize FIRC to 48 MHz */ @@ -233,6 +284,10 @@ static void clock_init(void) /* Wait for clock switch */ while ((SCG_CSR & SCG_CSR_SCS_MASK) != SCG_CSR_SCS_FIRC) {} +#ifdef S32K1XX_CLOCK_80MHZ + clock_init_spll(); +#endif + #ifdef S32K1XX_CLOCK_HSRUN /* HSRUN mode (112 MHz) - requires SOSC + SPLL (not fully implemented yet) * TODO: Add SOSC initialization and SPLL configuration for true 112 MHz @@ -256,6 +311,52 @@ static void clock_init(void) #endif } +/* ============== Code Cache ============== */ + +#ifdef S32K1XX_CODE_CACHE +/* The cache is write-through for Program Flash (region 0). Flash erase and + * program commands bypass it, so it is invalidated after each command. */ +static void RAMFUNCTION cache_invalidate(void) +{ + if (LMEM_PCCCR & LMEM_PCCCR_ENCACHE) { + LMEM_PCCCR |= LMEM_PCCCR_INVW0 | LMEM_PCCCR_INVW1 | LMEM_PCCCR_GO; + while (LMEM_PCCCR & LMEM_PCCCR_GO) {} + } +} + +static void cache_enable(void) +{ + /* FlexNVM (region 2) must not be cached on MCXE247. A region can only + * be demoted, until the next reset. */ + LMEM_PCCRMR &= ~LMEM_PCCRMR_R2_MASK; + + /* The tags are not cleared at reset: invalidate, then enable */ + LMEM_PCCCR = LMEM_PCCCR_INVW0 | LMEM_PCCCR_INVW1 | LMEM_PCCCR_GO; + while (LMEM_PCCCR & LMEM_PCCCR_GO) {} + LMEM_PCCCR = LMEM_PCCCR_ENCACHE; + DSB(); + ISB(); +} + +static void cache_disable(void) +{ + cache_invalidate(); + LMEM_PCCCR = 0; + DSB(); + ISB(); +} +#else +#define cache_invalidate() do {} while (0) +#endif /* S32K1XX_CODE_CACHE */ + +#ifdef S32K1XX_CODE_CACHE +void s32k1xx_code_cache_enable(void) +{ + if ((LMEM_PCCCR & LMEM_PCCCR_ENCACHE) == 0U) + cache_enable(); +} +#endif + /* ============== UART Functions ============== */ #ifdef DEBUG_UART @@ -401,6 +502,7 @@ static int RAMFUNCTION flash_program_phrase(uint32_t address, const uint8_t *dat /* Wait for completion */ flash_wait_complete(); + cache_invalidate(); #ifdef WATCHDOG /* Refresh watchdog after flash operation */ @@ -441,6 +543,7 @@ static int RAMFUNCTION flash_erase_sector_internal(uint32_t address) /* Wait for completion */ flash_wait_complete(); + cache_invalidate(); /* Re-enable interrupts */ __set_PRIMASK(primask); @@ -468,6 +571,10 @@ void hal_init(void) /* Initialize clocks */ clock_init(); +#ifdef S32K1XX_CODE_CACHE + cache_enable(); +#endif + /* Enable clock to flash controller */ PCC_FTFC |= PCC_CGC; @@ -502,11 +609,26 @@ void hal_prepare_boot(void) LPUART_CTRL = 0; #endif +#ifdef S32K1XX_CODE_CACHE + /* Leave the cache as it is after reset (disabled) for the application */ + cache_disable(); +#endif + #ifdef WOLFBOOT_RESTORE_CLOCK /* Restore clock to SIRC (8 MHz) before booting application. * This gives the application a known clock state to start from. */ clock_restore_sirc(); +#elif defined(S32K1XX_CLOCK_80MHZ) + /* Return to the default FIRC 48 MHz RUN configuration */ + SCG_RCCR = SCG_xCCR_SCS_FIRC | + (0UL << SCG_xCCR_DIVCORE_SHIFT) | + (0UL << SCG_xCCR_DIVBUS_SHIFT) | + (1UL << SCG_xCCR_DIVSLOW_SHIFT); + while ((SCG_CSR & SCG_CSR_SCS_MASK) != SCG_CSR_SCS_FIRC) {} +#endif +#ifdef S32K1XX_CLOCK_80MHZ + clock_stop_spll(); #endif /* Re-enable watchdog before booting application. diff --git a/hal/s32k1xx.h b/hal/s32k1xx.h index 16c080eeaa..e047d49667 100644 --- a/hal/s32k1xx.h +++ b/hal/s32k1xx.h @@ -35,10 +35,13 @@ * - SPLL: System PLL (up to 160 MHz VCO, /2 for SPLL_CLK) * * Run modes: - * - RUN: Up to 80 MHz core clock (requires SPLL, currently using FIRC at 48 MHz) + * - RUN: Up to 80 MHz core clock (requires SOSC + SPLL) * - HSRUN: Up to 112 MHz core clock (requires SOSC + SPLL, not implemented yet) * * Default: RUN mode with FIRC at 48 MHz (no external crystal required) + * S32K1XX_CLOCK_80MHZ: RUN mode at 80 MHz from SOSC + SPLL. The crystal + * frequency is S32K1XX_SOSC_FREQ (default 8 MHz). + * S32K1XX_CODE_CACHE: enable the LMEM code cache for flash. * To enable HSRUN mode (112 MHz), define S32K1XX_CLOCK_HSRUN (requires SOSC + SPLL) */ @@ -69,10 +72,14 @@ #define SYST_CSR_CLKSOURCE (1UL << 2) #define SYST_CSR_COUNTFLAG (1UL << 16) -/* Clock speed (FIRC = 48 MHz) */ +/* Core clock: FIRC = 48 MHz, or the SPLL at 80 MHz */ #ifndef CLOCK_SPEED +#ifdef S32K1XX_CLOCK_80MHZ +#define CLOCK_SPEED 80000000UL +#else #define CLOCK_SPEED 48000000UL #endif +#endif /* ============== NVIC - Nested Vectored Interrupt Controller ============== */ #define NVIC_BASE (0xE000E100UL) @@ -153,6 +160,30 @@ #define SCG_SPLLCFG_MULT_SHIFT 16 #define SCG_SPLLCFG_PREDIV_SHIFT 8 +/* SPLL DIV fields: 1 = /1, 2 = /2, 3 = /4, 4 = /8 */ +#define SCG_SPLLDIV_SPLLDIV1_SHIFT 0 +#define SCG_SPLLDIV_SPLLDIV2_SHIFT 8 + +/* SOSC CSR fields */ +#define SCG_SOSCCSR_SOSCEN (1UL << 0) +#define SCG_SOSCCSR_SOSCVLD (1UL << 24) + +/* SOSC CFG fields */ +#define SCG_SOSCCFG_EREFS (1UL << 2) /* Use the crystal oscillator */ +#define SCG_SOSCCFG_RANGE_HIGH (3UL << 4) /* 8-40 MHz, required for SPLL */ + +/* LMEM - Local Memory Controller (4 KB code cache) */ +#define LMEM_BASE (0xE0082000UL) +#define LMEM_PCCCR (*(volatile uint32_t *)(LMEM_BASE + 0x000UL)) /* Cache control */ +#define LMEM_PCCRMR (*(volatile uint32_t *)(LMEM_BASE + 0x020UL)) /* Cache regions mode */ + +#define LMEM_PCCCR_ENCACHE (1UL << 0) +#define LMEM_PCCCR_INVW0 (1UL << 24) +#define LMEM_PCCCR_INVW1 (1UL << 26) +#define LMEM_PCCCR_GO (1UL << 31) +/* Region 2 (FlexNVM, 0x10000000) mode. It must be non-cacheable on MCXE247. */ +#define LMEM_PCCRMR_R2_MASK (3UL << 26) + /* SMC - System Mode Controller */ #define SMC_BASE (0x4007E000UL) #define SMC_PMPROT (*(volatile uint32_t *)(SMC_BASE + 0x000UL)) @@ -657,6 +688,18 @@ * They use the LPUART instance and pins configured by the DEBUG_UART_* macros. */ +#ifdef S32K1XX_CLOCK_80MHZ +/* Switch the core to 80 MHz (SOSC + SPLL). For an application started by + * wolfBoot, which hands over on the SIRC or FIRC. The LPUART keeps its FIRC + * clock. */ +void s32k1xx_clock_80mhz(void); +#endif +#ifdef S32K1XX_CODE_CACHE +/* Enable the LMEM code cache for flash. The HAL flash erase and program + * functions invalidate it. */ +void s32k1xx_code_cache_enable(void); +#endif + #ifdef DEBUG_UART /* Initialize the UART with configured LPUART and pins */ void uart_init(void); diff --git a/test-app/app_s32k1xx.c b/test-app/app_s32k1xx.c index 7262f40287..09b96001c9 100644 --- a/test-app/app_s32k1xx.c +++ b/test-app/app_s32k1xx.c @@ -332,7 +332,8 @@ static void print_hex(const uint8_t* buffer, uint32_t length, int dumpChars) static const char* part_state_name(uint8_t state, int state_retval) { - if (state_retval == 0) { + /* wolfBoot_get_partition_state() returns 0 when it read a state */ + if (state_retval != 0) { return "(no trailer)"; } switch (state) { @@ -1007,6 +1008,14 @@ void main(void) /* Ensure FIRC clock is running at 48 MHz for UART */ clock_ensure_firc(); +#ifdef S32K1XX_CLOCK_80MHZ + /* wolfBoot hands over on SIRC or FIRC: run the core at 80 MHz. The UART + * stays on FIRC; SysTick follows CLOCK_SPEED. */ + s32k1xx_clock_80mhz(); +#endif +#ifdef S32K1XX_CODE_CACHE + s32k1xx_code_cache_enable(); +#endif #ifdef DEBUG_UART /* Reinitialize UART - bootloader may have changed settings in hal_prepare_boot */ From a26b40b307ae8959b54cdf04b2d3d34d62777a18 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 16 Nov 2026 00:12:53 -0500 Subject: [PATCH 06/24] mcxe247: build wolfIP with -O2 and a poll budget of 8 wolfIP is CPU bound on the MCXE247. -O2 on the wolfIP objects is 10-18% faster than -Os for 12KB more flash (80 MHz, code cache on): tcp-rx 24.1 -> 27.0, tcp-tx 22.0 -> 25.9, udp-tx 38.2 -> 41.8 Mbit/s. With the faster stack the driver keeps up with a line-rate UDP flood, and wolfIP_poll() took up to 128 frames per call into a socket that holds six datagrams, so udp-rx fell to 7.6 Mbit/s. Limiting the budget to 8 frames lets the speed server drain the socket between batches: udp-rx 36.9 -> 45.1 Mbit/s. WOLFIP_POLL_BUDGET needs the wolfIP change that makes it overridable. --- test-app/Makefile | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/test-app/Makefile b/test-app/Makefile index 4c2c717b37..5a0e1a3efe 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1798,6 +1798,12 @@ ifeq ($(ENABLE_WOLFIP),1) # memcpy (checksum words, header fields) into a call to the byte-wise # memcpy in src/string.c, which cost most of the stack's CPU time WOLFIP_CFLAGS_OUT:=-ffreestanding + # The stack is CPU bound: -O2 (after the global -Os) is 10-18% faster for + # 12KB more flash. Take at most 8 frames per wolfIP_poll() so the app can + # drain a socket between batches; with the default 128 a line-rate UDP + # flood fills the 6-datagram socket buffer and most frames are processed + # only to be dropped + WOLFIP_CFLAGS_ADD:=-O2 -DWOLFIP_POLL_BUDGET=8 # Driver cycle counters for the throughput test's CPU breakdown ifeq ($(WOLFIP_SPEED_TEST),1) CFLAGS+=-DNXP_MCXE_ENET_STATS=1 @@ -1833,7 +1839,7 @@ ifeq ($(ENABLE_WOLFIP),1) WOLFIP_CFLAGS:=-I"$(WOLFIP_PORTDIR)" -I"$(WOLFBOOT_LIB_WOLFIP)" \ $(filter-out -Werror -Wstack-usage=$(STACK_USAGE_LIMIT) $(WOLFIP_CFLAGS_OUT),$(CFLAGS)) \ -DWOLFIP_ENABLE_TFTP=$(if $(filter 1,$(WOLFBOOT_TEST_TFTP)),1,0) \ - -Wno-unused -Wno-sign-compare -Wno-missing-field-initializers + -Wno-unused -Wno-sign-compare -Wno-missing-field-initializers $(WOLFIP_CFLAGS_ADD) endif ifeq ($(WOLFHSM_CLIENT),1) From 4b1de67c3b41876256780567afdd81cb9739881d Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 16 Nov 2026 00:37:09 -0500 Subject: [PATCH 07/24] wolfip_speed.py: receive in the sender thread for UDP bidir The receiver thread gave up the GIL on every recvfrom() and then waited for the pacer's busy-wait loop to release it, so the host dropped most of what the board sent (55-92% loss). Bidir now drains the socket between sends in one thread and collects the board's last datagrams afterwards. UDP bidir board tx as received by the host: 8.4 -> 21.5 Mbit/s, 0% loss. --- tools/scripts/wolfip_speed.py | 53 ++++++++++++++++++++++++++--------- 1 file changed, 39 insertions(+), 14 deletions(-) diff --git a/tools/scripts/wolfip_speed.py b/tools/scripts/wolfip_speed.py index 07e5c5f047..b15f46206d 100644 --- a/tools/scripts/wolfip_speed.py +++ b/tools/scripts/wolfip_speed.py @@ -114,12 +114,16 @@ def __init__(self, rate_mbps, size): self.gap = bits / (rate_mbps * 1e6) if rate_mbps > 0 else 0.0 self.next = time.perf_counter() - def wait(self): + def wait(self, idle=None): + """idle, if given, runs while waiting (at least once per call).""" + if idle is not None: + idle() if self.gap == 0.0: return self.next += self.gap while time.perf_counter() < self.next: - pass + if idle is not None: + idle() def tcp_test(ip, port, mode, secs): @@ -173,7 +177,18 @@ def udp_test(sock, addr, mode, secs, size, rate): last = [None] stop_rx = threading.Event() - def receiver(): + def count(data): + if (len(data) >= HDR.size and data[0] == MAGIC and + data[1] == ord("d") and + HDR.unpack_from(data)[5] == session): + now = time.monotonic() + if first[0] is None: + first[0] = now + last[0] = now + got[0] += 1 + got[1] += len(data) + + def receiver(deadline=None): sock.settimeout(0.2) idle_limit = 1.0 while not stop_rx.is_set(): @@ -182,21 +197,22 @@ def receiver(): except socket.timeout: if last[0] is not None and time.monotonic() - last[0] > idle_limit: break + if deadline is not None and time.monotonic() > deadline: + break continue - if (len(data) >= HDR.size and data[0] == MAGIC and - data[1] == ord("d") and - HDR.unpack_from(data)[5] == session): - now = time.monotonic() - if first[0] is None: - first[0] = now - last[0] = now - got[0] += 1 - got[1] += len(data) + count(data) + + def drain_rx(): + try: + while True: + count(sock.recvfrom(2048)[0]) + except (BlockingIOError, InterruptedError): + pass payload = bytearray(size) t0 = time.monotonic() rx = None - if mode in ("t", "b"): + if mode == "t": rx = threading.Thread(target=receiver) rx.start() if mode == "t": @@ -206,19 +222,28 @@ def receiver(): sock.sendto(HDR.pack(MAGIC, ord("t"), size, 0, dur_ms, session), addr) else: + # bidir receives in this thread, between sends: a receiver thread + # would wait for the GIL after every recvfrom() while the pacer + # spins, and the host would drop most of what the board sends cmd = ord(mode) + idle = drain_rx if mode == "b" else None pacer = Pacer(rate, size) stop = t0 + secs seq = 0 + sock.setblocking(False) while time.monotonic() < stop: HDR.pack_into(payload, 0, MAGIC, cmd, size, seq, dur_ms, session) try: sock.sendto(payload, addr) except (BlockingIOError, OSError): + if idle is not None: + idle() continue seq += 1 - pacer.wait() + pacer.wait(idle) sent[0] = seq + if mode == "b": + receiver(time.monotonic() + 5) # the board's tail if rx is not None: rx.join(timeout=secs + 5) stop_rx.set() From 2e2e9959b6916d277b4c22f70f43e010c19a205d Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 16 Nov 2026 01:15:06 -0500 Subject: [PATCH 08/24] mcxe247: make the wolfIP speed test the default network test With ENABLE_WOLFIP=1 the network command now runs the TCP and UDP throughput server (WOLFIP_SPEED_TEST=1); the TFTP fetch is opt-in with WOLFBOOT_TEST_TFTP=1. Update the config comments and docs/Targets.md. --- config/examples/mcxe247.config | 16 +++++++-------- docs/Targets.md | 37 +++++++++++++++++++++------------- 2 files changed, 31 insertions(+), 22 deletions(-) diff --git a/config/examples/mcxe247.config b/config/examples/mcxe247.config index 8c3f38b4e4..7c9984571e 100644 --- a/config/examples/mcxe247.config +++ b/config/examples/mcxe247.config @@ -73,15 +73,15 @@ CFLAGS_EXTRA+=-DDEBUG_UART_RX_MUX=PORT_PCR_MUX_ALT3 # the interrupt-driven nxp_mcxe_enet driver. ENABLE_WOLFIP?=0 WOLFBOOT_LIB_WOLFIP?=../lib/wolfip -# Without WOLFBOOT_TEST_TFTP the command only acquires a DHCP lease. The file -# must fit the 40 KB receive buffer. -WOLFBOOT_TEST_TFTP?=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. +# 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"' -# WOLFIP_SPEED_TEST=1 makes the command run a TCP and UDP throughput server on -# port 9 instead, driven from the host by tools/scripts/wolfip_speed.py. -# WOLFBOOT_TEST_TFTP overrides it: with both set to 1 the command runs the TFTP -# fetch and the speed server is never started. -WOLFIP_SPEED_TEST?=0 # Debugging options DEBUG?=0 diff --git a/docs/Targets.md b/docs/Targets.md index e8cbf3a72a..d55def640b 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7820,30 +7820,26 @@ apply to the MCXE247, with these differences: ### NXP MCXE247: Network test -The test application can run a wolfIP DHCP and TFTP test over the board's -Ethernet port. This is optional and needs a wolfIP checkout, whose +The test application can run a wolfIP throughput test or a DHCP and TFTP test +over the board's Ethernet port. This is optional and needs a wolfIP checkout, whose `nxp_mcxe_enet` port is a standalone ENET and LAN8741 driver (no vendor SDK). The test app builds it interrupt driven (`NXP_MCXE_ENET_IRQ=1`, with ENET IRQs 73-75 routed in `test-app/startup_arm.c`). The wolfIP stack state, with 9 KB TCP receive and transmit buffers per socket, is placed in SRAM_L by `test-app/ARM-s32k1xx-wolfip.ld`; the rest of the app uses SRAM_U. Set `ENABLE_WOLFIP=1` in -`mcxe247.config`, check the wolfIP path, then set the TFTP server and file: +`mcxe247.config` and check the wolfIP path: ```sh ENABLE_WOLFIP?=1 WOLFBOOT_LIB_WOLFIP?=../lib/wolfip -WOLFBOOT_TEST_TFTP?=1 -CFLAGS_EXTRA+=-DHOST_IP_STR='"192.168.50.1"' -DTFTP_FILENAME='"wolfip_test.bin"' +WOLFIP_SPEED_TEST?=1 +WOLFBOOT_TEST_TFTP?=0 ``` -Type `network` on the console to run the test. It acquires a DHCP lease, fetches -the file into RAM (40 KB at most), and prints its size and checksum followed by -`WOLFIP_TEST: PASS` or `WOLFIP_TEST: FAIL`. - -To measure throughput instead, set `WOLFBOOT_TEST_TFTP=0` and -`WOLFIP_SPEED_TEST=1`. After the DHCP lease, the `network` command runs a TCP -and UDP throughput server on port 9. Drive it from a PC on the same network +Type `network` on the console to run the test. By default +(`WOLFIP_SPEED_TEST=1`) it acquires a DHCP lease and runs a TCP and UDP +throughput server on port 9. Drive it from a PC on the same network with `` set to the address the board printed (Python 3, no extra packages): @@ -7865,8 +7861,21 @@ the same counters on the console after each test. Plain `nc 9` still works as a bidirectional TCP test. Press Ctrl-C on the console to stop the server and return to the `cmd>` prompt. -`WOLFBOOT_TEST_TFTP` takes priority: with both options set to 1, the command -runs the TFTP fetch and the speed server is never started. + +For the TFTP test, set `WOLFBOOT_TEST_TFTP=1` and the server and file in +`HOST_IP_STR` and `TFTP_FILENAME`: + +```sh +WOLFBOOT_TEST_TFTP?=1 +CFLAGS_EXTRA+=-DHOST_IP_STR='"192.168.50.1"' -DTFTP_FILENAME='"wolfip_test.bin"' +``` + +The `network` command then acquires a DHCP lease, fetches the file into RAM +(40 KB at most), and prints its size and checksum followed by +`WOLFIP_TEST: PASS` or `WOLFIP_TEST: FAIL`. `WOLFBOOT_TEST_TFTP` takes +priority: with both options set to 1, the command runs the TFTP fetch and the +speed server is never started. With both set to 0 it only acquires a DHCP +lease. ### NXP MCXE247: Programming with Lauterbach TRACE32 From 5aff80fa409d59834693a2fa67596c6ba2398ba7 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 16 Nov 2026 02:24:54 -0500 Subject: [PATCH 09/24] mcxe247: run memcpy and the wolfIP checksum from SRAM_L memcpy (already in SRAM_U as RAM code) and wolfIP's csum_add() were the hottest code. In SRAM_U the core fetches code over the system bus, which the copies' own data accesses also use; SRAM_L is fetched over the code bus in parallel. A .ramcode_l section in ARM-s32k1xx-wolfip.ld takes string.o's .ramcode and wolfip.o's .text.csum_add ahead of the .text rule, loads after .edidx in flash, and is copied at reset (APP_RAMCODE_L in startup_arm.c). .keystore is now placed in flash explicitly; the new layout had made it an orphan in SRAM_L. 332 bytes of SRAM_L. 80 MHz, code cache on: tcp-rx 29.2 -> 33.8, tcp-tx 28.7 -> 33.1, udp-rx 56.0 -> 66.6, udp-tx 49.6 -> 60.4, udp-bidir 23.6+26.5 -> 28.9+32.5 Mbit/s. TFTP test and a flash write from the test-app pass. --- docs/Targets.md | 5 ++++- test-app/ARM-s32k1xx-wolfip.ld | 28 +++++++++++++++++++++++++++- test-app/Makefile | 2 ++ test-app/startup_arm.c | 15 +++++++++++++++ 4 files changed, 48 insertions(+), 2 deletions(-) diff --git a/docs/Targets.md b/docs/Targets.md index d55def640b..779d67bb36 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7826,7 +7826,10 @@ over the board's Ethernet port. This is optional and needs a wolfIP checkout, wh The test app builds it interrupt driven (`NXP_MCXE_ENET_IRQ=1`, with ENET IRQs 73-75 routed in `test-app/startup_arm.c`). The wolfIP stack state, with 9 KB TCP receive and transmit buffers per socket, is placed in SRAM_L by -`test-app/ARM-s32k1xx-wolfip.ld`; the rest of the app uses SRAM_U. Set +`test-app/ARM-s32k1xx-wolfip.ld`, together with the hottest code (`memcpy` and +wolfIP's checksum loop), which the core then fetches over its code bus in +parallel with data on the system bus. The +rest of the app uses SRAM_U. Set `ENABLE_WOLFIP=1` in `mcxe247.config` and check the wolfIP path: diff --git a/test-app/ARM-s32k1xx-wolfip.ld b/test-app/ARM-s32k1xx-wolfip.ld index 879bbccf8f..859a12962e 100644 --- a/test-app/ARM-s32k1xx-wolfip.ld +++ b/test-app/ARM-s32k1xx-wolfip.ld @@ -6,6 +6,9 @@ * buffers) goes in SRAM_L, which the ENET DMA and eDMA reach through its * backdoor port. Both are outside the code cache while it is disabled (the * default); enabling the cache for SRAM_L would break the DMA coherency. + * The hottest code (memcpy and wolfIP's checksum loop) runs from SRAM_L too + * (.ramcode_l), so the core fetches it over the code bus while its data + * accesses use the system bus. * * 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), @@ -23,6 +26,21 @@ MEMORY SECTIONS { + /* Hot code run from SRAM_L, which the core fetches over its code bus in + * parallel with its data accesses (code in SRAM_U shares the system bus + * with the data). It comes first so that these input sections are taken + * before the .text* rule below; its load image follows .edidx in flash + * and is copied at reset (APP_RAMCODE_L). */ + .ramcode_l : AT (_stored_ramcode_l) + { + . = ALIGN(4); + _start_ramcode_l = .; + KEEP(*string.o(.ramcode)) + *wolfip.o(.text.csum_add) + . = ALIGN(4); + _end_ramcode_l = .; + } > RAM_L + .text : { _start_text = .; @@ -35,13 +53,21 @@ SECTIONS _end_text = .; } > FLASH + .keystore : + { + . = ALIGN(4); + KEEP(*(.keystore*)) + } > FLASH + .edidx : { . = ALIGN(4); *(.ARM.exidx*) } > FLASH - _stored_data = .; + _stored_ramcode_l = ALIGN(4); + + _stored_data = _stored_ramcode_l + SIZEOF(.ramcode_l); .data : AT (_stored_data) { diff --git a/test-app/Makefile b/test-app/Makefile index 5a0e1a3efe..4eb2e85a02 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1786,6 +1786,8 @@ ifeq ($(ENABLE_WOLFIP),1) LSCRIPT_TEMPLATE=ARM-s32k1xx-wolfip.ld # Clear all of SRAM_U at reset, before the stack is used (ECC) CFLAGS+=-DAPP_RAM_ECC_INIT + # Hot code in SRAM_L (.ramcode_l in ARM-s32k1xx-wolfip.ld) + CFLAGS+=-DAPP_RAMCODE_L # Standalone driver, interrupt driven: startup_arm.c routes ENET IRQs # 73-75 to nxp_mcxe_enet_irq_handler() CFLAGS+=-DWOLFIP_PORT_MCXE_ENET -DNXP_MCXE_ENET_IRQ=1 diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index be9e9e4581..9c2bc607a2 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_L +/* Hot code copied from flash to a second RAM region at reset */ +extern unsigned int _stored_ramcode_l; +extern unsigned int _start_ramcode_l; +extern unsigned int _end_ramcode_l; +#endif #ifdef TARGET_stm32f4 extern void isr_tim2(void); @@ -126,6 +132,15 @@ void isr_reset(void) dst++; src++; } +#ifdef APP_RAMCODE_L + src = (unsigned int *) &_stored_ramcode_l; + dst = (unsigned int *) &_start_ramcode_l; + while (dst < (unsigned int *)&_end_ramcode_l) { + *dst = *src; + dst++; + src++; + } +#endif dst = &_start_bss; while (dst < (unsigned int *)&_end_bss) { From b3588e1e0c369c2085e1ddff946626cc25867be2 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 16 Nov 2026 12:54:19 -0500 Subject: [PATCH 10/24] mcxe247: run the wolfIP speed test in HSRUN at 112 MHz s32k1xx_clock_hsrun() enters HSRUN on the FIRC, then runs the core from the SPLL at 112 MHz (bus 56 MHz, flash 28 MHz), as the SDK's BOARD_BootClockHSRUN does. s32k1xx_clock_run() returns to RUN at 80 MHz. The SOSC and SPLL setup is split into helpers that the 80 MHz path now shares. With S32K1XX_HSRUN_SPEED_TEST the test-app's network command runs the speed server in HSRUN and switches back when it stops, so flash writes from the console still work. mcxe247.config sets it. The SMC register offsets were the Kinetis layout. On the S32K1xx and MCXE247 VERID and PARAM come first: PMPROT is at 0x08, PMCTRL at 0x0C and PMSTAT at 0x14. Before, the HSRUN enable went to a read-only register, so S32K1XX_CLOCK_HSRUN could never enter HSRUN either. 112 MHz vs 80 MHz: tcp-rx 33.8 -> 45.7, tcp-tx 33.1 -> 43.7, udp-rx 66.6 -> 95.6 (line rate), udp-tx 60.4 -> 75.8, udp-bidir 28.9+32.5 -> 38.0+42.8 Mbit/s. After the server stops, a flash write (success) works and HSRUN can be entered again. --- config/examples/mcxe247.config | 8 ++- docs/Targets.md | 7 ++- hal/s32k1xx.c | 106 +++++++++++++++++++++++++++++---- hal/s32k1xx.h | 12 +++- test-app/app_s32k1xx.c | 32 +++++++++- 5 files changed, 146 insertions(+), 19 deletions(-) diff --git a/config/examples/mcxe247.config b/config/examples/mcxe247.config index 7c9984571e..ae633a665f 100644 --- a/config/examples/mcxe247.config +++ b/config/examples/mcxe247.config @@ -2,7 +2,7 @@ # # MCXE247: Cortex-M4F, 2MB flash (1.5MB Program Flash + 512KB FlexNVM), 256KB # SRAM. It is register compatible with the S32K148 and uses the s32k1xx HAL. -# Default: RUN mode at 48 MHz (FIRC - internal RC oscillator) +# Default: RUN mode at 80 MHz (crystal + SPLL); the wolfIP speed test uses HSRUN at 112 MHz # # Build: cp config/examples/mcxe247.config .config && make @@ -32,6 +32,7 @@ DUALBANK_SWAP?=0 # (0x1FFFC000-0x20002FFF) at reset so its ECC is valid. The rest of SRAM is the # application's to initialize. CFLAGS_EXTRA+=-DMCXE247 -DWOLFBOOT_RAM_ECC_INIT + # Word-at-a-time memcpy/memset in src/string.c (bootloader and test-app). The # Cortex-M4 loads unaligned words, so memcpy copies words even when source and # destination alignments differ; about doubles the wolfIP network test rates. @@ -43,6 +44,11 @@ CFLAGS_EXTRA+=-DFAST_MEMCPY # Remove to run from the 48 MHz internal oscillator. CFLAGS_EXTRA+=-DS32K1XX_CLOCK_80MHZ -DS32K1XX_CODE_CACHE +# The wolfIP speed test runs in HSRUN at 112 MHz (bus 56 MHz, flash 28 MHz) +# and returns to RUN at 80 MHz when it stops. Flash cannot be programmed in +# HSRUN, so the console commands that write flash run at 80 MHz. +CFLAGS_EXTRA+=-DS32K1XX_HSRUN_SPEED_TEST + # 4KB sectors WOLFBOOT_SECTOR_SIZE?=0x1000 diff --git a/docs/Targets.md b/docs/Targets.md index 779d67bb36..599db89dd8 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7598,6 +7598,7 @@ The following build options are available for the S32K1xx HAL: | `WATCHDOG_TIMEOUT_MS` | Watchdog timeout in milliseconds when `WATCHDOG` is enabled (default: 1000ms). | | `S32K1XX_CLOCK_HSRUN` | Enable HSRUN mode (112 MHz). Requires external crystal and SPLL (not fully implemented). | | `S32K1XX_CLOCK_80MHZ` | Run wolfBoot at 80 MHz (RUN mode) from the external crystal through the SPLL, instead of the 48 MHz FIRC. The crystal frequency is `S32K1XX_SOSC_FREQ` (default 8 MHz). The clock is switched back before the application starts; the s32k1xx test-app switches to 80 MHz again with `s32k1xx_clock_80mhz()`. Tested on the MCXE247 only. | +| `S32K1XX_HSRUN_SPEED_TEST` | With `S32K1XX_CLOCK_80MHZ` and the wolfIP speed test, the test-app `network` command runs in HSRUN at 112 MHz (bus 56 MHz, flash 28 MHz) with `s32k1xx_clock_hsrun()` and returns to RUN at 80 MHz with `s32k1xx_clock_run()` when the server stops, so flash writes from the console still work. Tested on the MCXE247 only. | | `S32K1XX_CODE_CACHE` | Enable the 4 KB LMEM code cache for flash while wolfBoot runs. It is invalidated after every flash erase and program command, and disabled before the application starts; the s32k1xx test-app enables it again with `s32k1xx_code_cache_enable()`. Tested on the MCXE247 only. | | `DEBUG_UART` | Enable LPUART debug output. | | `DEBUG_HARDFAULT` | Enable detailed hard fault debugging output. | @@ -7764,7 +7765,9 @@ with the S32K148 (NXP AN14731), so it uses the bare-metal `s32k1xx` HAL with the The 2 MB of flash is not contiguous: 1.5 MB of Program Flash is at `0x00000000` and the remaining 512 KB is FlexNVM at `0x10000000`. Only the Program Flash is -used. The system runs at 48 MHz (FIRC). Flash cannot be programmed in HSRUN. +used. wolfBoot runs at 80 MHz with `mcxe247.config` (48 MHz FIRC without +`S32K1XX_CLOCK_80MHZ`). Flash cannot be programmed in HSRUN, so only the +network speed test runs at 112 MHz. ### NXP MCXE247: Memory Layout @@ -7861,6 +7864,8 @@ it to find the highest rate without loss. Do not raise it above the link rate: a fast host (WSL can send 2 Gbit/s) queues the excess and keeps feeding it to the board long after the test, so the board stops answering. The board prints the same counters on the console after each test. +`mcxe247.config` sets `S32K1XX_HSRUN_SPEED_TEST`, so the server runs in +HSRUN at 112 MHz and the console returns to RUN at 80 MHz when it stops. Plain `nc 9` still works as a bidirectional TCP test. Press Ctrl-C on the console to stop the server and return to the `cmd>` prompt. diff --git a/hal/s32k1xx.c b/hal/s32k1xx.c index 00e276cff3..e884d05732 100644 --- a/hal/s32k1xx.c +++ b/hal/s32k1xx.c @@ -221,34 +221,69 @@ static void clock_init_firc(void) #error "S32K1XX_SOSC_FREQ cannot produce a 320 MHz VCO with PREDIV=0" #endif -/* RUN mode at 80 MHz (reference manual "Normal RUN" example): - * SOSC -> SPLL 160 MHz -> CORE/SYS 80 MHz (/2), BUS 40 MHz (/2 of core), - * FLASH 26.67 MHz (/3 of core, the RUN mode maximum). - */ -static void clock_init_spll(void) +/* HSRUN: VCO_CLK = 224 MHz, SPLL_CLK = 112 MHz (the FRDM-MCXE247 SDK + * BOARD_BootClockHSRUN configuration) */ +#define SPLL_VCO_HSRUN_FREQ 224000000UL +#define SPLL_MULT_HSRUN ((SPLL_VCO_HSRUN_FREQ / S32K1XX_SOSC_FREQ) - 16UL) +#if (SPLL_VCO_HSRUN_FREQ % S32K1XX_SOSC_FREQ) != 0 || \ + (SPLL_VCO_HSRUN_FREQ / S32K1XX_SOSC_FREQ) < 16 || \ + (SPLL_VCO_HSRUN_FREQ / S32K1XX_SOSC_FREQ) > 47 +#error "S32K1XX_SOSC_FREQ cannot produce a 224 MHz VCO with PREDIV=0" +#endif + +/* FIRC as system clock: 48 MHz core and bus, 24 MHz flash. Valid in RUN + * and in HSRUN, so the clock waits there while the SPLL is reprogrammed or + * the power mode changes. */ +#define SCG_xCCR_FIRC_48MHZ (SCG_xCCR_SCS_FIRC | \ + (0UL << SCG_xCCR_DIVCORE_SHIFT) | \ + (0UL << SCG_xCCR_DIVBUS_SHIFT) | \ + (1UL << SCG_xCCR_DIVSLOW_SHIFT)) + +static void sysclk_wait(uint32_t scs) +{ + while ((SCG_CSR & SCG_CSR_SCS_MASK) != scs) {} +} + +/* SOSC: crystal, high range (required when it feeds the SPLL) */ +static void sosc_start(void) { - /* SOSC: crystal, high range (required when it feeds the SPLL) */ + if ((SCG_SOSCCSR & SCG_SOSCCSR_SOSCVLD) != 0U) + return; SCG_SOSCCSR = 0; SCG_SOSCDIV = (1UL << 8) | (1UL << 0); /* SOSCDIV1=/1, SOSCDIV2=/1 */ SCG_SOSCCFG = SCG_SOSCCFG_RANGE_HIGH | SCG_SOSCCFG_EREFS; SCG_SOSCCSR = SCG_SOSCCSR_SOSCEN; while (!(SCG_SOSCCSR & SCG_SOSCCSR_SOSCVLD)) {} +} - /* SPLL: SPLLCFG can only be written while the SPLL is disabled */ +/* Program and lock the SPLL. SPLLCFG can only be written while the SPLL is + * disabled, so the system clock must not be running from it. */ +static void spll_start(uint32_t mult, uint32_t div1, uint32_t div2) +{ SCG_SPLLCSR = 0; - SCG_SPLLDIV = (2UL << SCG_SPLLDIV_SPLLDIV1_SHIFT) | /* /2: 80 MHz */ - (3UL << SCG_SPLLDIV_SPLLDIV2_SHIFT); /* /4: 40 MHz */ - SCG_SPLLCFG = (SPLL_MULT << SCG_SPLLCFG_MULT_SHIFT) | + SCG_SPLLDIV = (div1 << SCG_SPLLDIV_SPLLDIV1_SHIFT) | + (div2 << SCG_SPLLDIV_SPLLDIV2_SHIFT); + SCG_SPLLCFG = (mult << SCG_SPLLCFG_MULT_SHIFT) | (0UL << SCG_SPLLCFG_PREDIV_SHIFT); SCG_SPLLCSR = SCG_SPLLCSR_SPLLEN; while (!(SCG_SPLLCSR & SCG_SPLLCSR_SPLLVLD)) {} +} + +/* RUN mode at 80 MHz (reference manual "Normal RUN" example): + * SOSC -> SPLL 160 MHz -> CORE/SYS 80 MHz (/2), BUS 40 MHz (/2 of core), + * FLASH 26.67 MHz (/3 of core, the RUN mode maximum). + */ +static void clock_init_spll(void) +{ + sosc_start(); + spll_start(SPLL_MULT, 2UL, 3UL); /* SPLLDIV1 /2: 80, SPLLDIV2 /4: 40 */ /* Switch the system clock to the SPLL */ SCG_RCCR = SCG_xCCR_SCS_SPLL | (1UL << SCG_xCCR_DIVCORE_SHIFT) | (1UL << SCG_xCCR_DIVBUS_SHIFT) | (2UL << SCG_xCCR_DIVSLOW_SHIFT); - while ((SCG_CSR & SCG_CSR_SCS_MASK) != SCG_CSR_SCS_SPLL) {} + sysclk_wait(SCG_CSR_SCS_SPLL); } /* Stop the SPLL and SOSC once the system clock no longer uses them */ @@ -263,6 +298,55 @@ void s32k1xx_clock_80mhz(void) if ((SCG_CSR & SCG_CSR_SCS_MASK) != SCG_CSR_SCS_SPLL) clock_init_spll(); } + +/* HSRUN at 112 MHz: SOSC -> SPLL 112 MHz -> CORE/SYS 112 MHz (/1), BUS + * 56 MHz (/2), FLASH 28 MHz (/4), following the SDK sequence: enter HSRUN on + * the FIRC, then switch to the SPLL. Flash cannot be programmed or erased in + * HSRUN; call s32k1xx_clock_run() first. */ +int s32k1xx_clock_hsrun(void) +{ + if ((SMC_PMSTAT & 0xFFUL) == SMC_PMSTAT_HSRUN) + return 0; + /* PMPROT can be written once after reset: allow HSRUN unless already + * allowed, then check that it took */ + if ((SMC_PMPROT & SMC_PMPROT_AHSRUN) == 0U) + SMC_PMPROT = SMC_PMPROT_AHSRUN; + if ((SMC_PMPROT & SMC_PMPROT_AHSRUN) == 0U) + return -1; + + /* Leave the SPLL while its VCO changes */ + SCG_RCCR = SCG_xCCR_FIRC_48MHZ; + sysclk_wait(SCG_CSR_SCS_FIRC); + sosc_start(); + spll_start(SPLL_MULT_HSRUN, 1UL, 2UL); /* SPLLDIV1 /1: 112, DIV2 /2: 56 */ + + SCG_HCCR = SCG_xCCR_FIRC_48MHZ; + SMC_PMCTRL = (SMC_PMCTRL & ~(3UL << SMC_PMCTRL_RUNM_SHIFT)) | + SMC_PMCTRL_RUNM_HSRUN; + while ((SMC_PMSTAT & 0xFFUL) != SMC_PMSTAT_HSRUN) {} + + SCG_HCCR = SCG_xCCR_SCS_SPLL | + (0UL << SCG_xCCR_DIVCORE_SHIFT) | + (1UL << SCG_xCCR_DIVBUS_SHIFT) | + (3UL << SCG_xCCR_DIVSLOW_SHIFT); + sysclk_wait(SCG_CSR_SCS_SPLL); + return 0; +} + +/* Back from HSRUN to RUN at 80 MHz */ +void s32k1xx_clock_run(void) +{ + if ((SMC_PMSTAT & 0xFFUL) == SMC_PMSTAT_HSRUN) { + /* Drop to the FIRC before leaving HSRUN; RUN then takes RCCR, + * which s32k1xx_clock_hsrun() left on the FIRC */ + SCG_HCCR = SCG_xCCR_FIRC_48MHZ; + sysclk_wait(SCG_CSR_SCS_FIRC); + SMC_PMCTRL = (SMC_PMCTRL & ~(3UL << SMC_PMCTRL_RUNM_SHIFT)) | + SMC_PMCTRL_RUNM_RUN; + while ((SMC_PMSTAT & 0xFFUL) != SMC_PMSTAT_RUN) {} + } + s32k1xx_clock_80mhz(); +} #endif /* S32K1XX_CLOCK_80MHZ */ static void clock_init(void) diff --git a/hal/s32k1xx.h b/hal/s32k1xx.h index e047d49667..f126a74890 100644 --- a/hal/s32k1xx.h +++ b/hal/s32k1xx.h @@ -186,9 +186,9 @@ /* SMC - System Mode Controller */ #define SMC_BASE (0x4007E000UL) -#define SMC_PMPROT (*(volatile uint32_t *)(SMC_BASE + 0x000UL)) -#define SMC_PMCTRL (*(volatile uint32_t *)(SMC_BASE + 0x004UL)) -#define SMC_PMSTAT (*(volatile uint32_t *)(SMC_BASE + 0x008UL)) +#define SMC_PMPROT (*(volatile uint32_t *)(SMC_BASE + 0x008UL)) +#define SMC_PMCTRL (*(volatile uint32_t *)(SMC_BASE + 0x00CUL)) +#define SMC_PMSTAT (*(volatile uint32_t *)(SMC_BASE + 0x014UL)) #define SMC_PMPROT_AHSRUN (1UL << 7) /* Allow HSRUN */ #define SMC_PMCTRL_RUNM_SHIFT 5 @@ -693,6 +693,12 @@ * wolfBoot, which hands over on the SIRC or FIRC. The LPUART keeps its FIRC * clock. */ void s32k1xx_clock_80mhz(void); +/* Switch between HSRUN at 112 MHz and RUN at 80 MHz. Flash cannot be + * programmed or erased in HSRUN. s32k1xx_clock_hsrun() returns -1 if HSRUN + * cannot be allowed (SMC_PMPROT already written without AHSRUN). */ +#define S32K1XX_HSRUN_CLOCK_SPEED 112000000UL +int s32k1xx_clock_hsrun(void); +void s32k1xx_clock_run(void); #endif #ifdef S32K1XX_CODE_CACHE /* Enable the LMEM code cache for flash. The HAL flash erase and program diff --git a/test-app/app_s32k1xx.c b/test-app/app_s32k1xx.c index 09b96001c9..231a51c9cc 100644 --- a/test-app/app_s32k1xx.c +++ b/test-app/app_s32k1xx.c @@ -107,14 +107,19 @@ static void delay_ms(uint32_t ms) } } -static void systick_init(void) +/* 1 ms tick from the core clock running at core_hz */ +static void systick_set(uint32_t core_hz) { - /* Configure SysTick for 1ms tick */ - SYST_RVR = (CLOCK_SPEED / 1000) - 1; + SYST_RVR = (core_hz / 1000) - 1; SYST_CVR = 0; SYST_CSR = SYST_CSR_ENABLE | SYST_CSR_TICKINT | SYST_CSR_CLKSOURCE; } +static void systick_init(void) +{ + systick_set(CLOCK_SPEED); +} + /* ============== LED Functions ============== */ static void led_init(void) @@ -889,10 +894,31 @@ static int cmd_update(const char *args) } #ifdef ENABLE_WOLFIP +/* S32K1XX_HSRUN_SPEED_TEST runs the throughput server in HSRUN at 112 MHz + * and returns to RUN at 80 MHz after it, before anything can write flash. + * The ENET driver is started inside, so it times itself at 112 MHz. */ +#if defined(S32K1XX_HSRUN_SPEED_TEST) && defined(WOLFIP_SPEED_TEST) && \ + !defined(WOLFBOOT_TEST_TFTP) +#ifndef S32K1XX_CLOCK_80MHZ +#error "S32K1XX_HSRUN_SPEED_TEST needs S32K1XX_CLOCK_80MHZ" +#endif +#define NETWORK_TEST_HSRUN +#endif + static int cmd_network(const char *args) { (void)args; +#ifdef NETWORK_TEST_HSRUN + if (s32k1xx_clock_hsrun() == 0) + systick_set(S32K1XX_HSRUN_CLOCK_SPEED); + else + printf("HSRUN not allowed, staying at 80 MHz\r\n"); +#endif wolfip_tftp_test_report(); +#ifdef NETWORK_TEST_HSRUN + s32k1xx_clock_run(); + systick_set(CLOCK_SPEED); +#endif return 0; } From e5d300b916732fea57324ec774b08e49dc7e8c0a Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 16 Nov 2026 13:40:42 -0500 Subject: [PATCH 11/24] string: post-increment the FAST_MEMCPY word loop At -Os GCC compiled the unaligned-source word loop with both pointers recomputed from the byte count on every pass: 15 instructions per 16 bytes. Step word pointers instead and store through an aligned type, since the destination is aligned by then: 11 instructions per 16 bytes. Results match a byte copy for every length up to 300 and all source/destination offsets 0-7 (host test, ASan/UBSan). MCXE247 wolfIP speed test at 112 MHz: udp-tx 75.8 -> 77.5 Mbit/s, wolfIP cycles per frame down 2-4% for tcp-rx, udp-tx and udp-bidir. --- config/examples/mcxe247.config | 9 ++++--- docs/Targets.md | 4 +++ src/string.c | 45 ++++++++++++++++++++-------------- test-app/Makefile | 19 +++++--------- 4 files changed, 42 insertions(+), 35 deletions(-) diff --git a/config/examples/mcxe247.config b/config/examples/mcxe247.config index ae633a665f..d731bbbb9f 100644 --- a/config/examples/mcxe247.config +++ b/config/examples/mcxe247.config @@ -2,7 +2,8 @@ # # MCXE247: Cortex-M4F, 2MB flash (1.5MB Program Flash + 512KB FlexNVM), 256KB # SRAM. It is register compatible with the S32K148 and uses the s32k1xx HAL. -# Default: RUN mode at 80 MHz (crystal + SPLL); the wolfIP speed test uses HSRUN at 112 MHz +# Default: RUN mode at 80 MHz (crystal + SPLL); the wolfIP speed test uses HSRUN +# at 112 MHz. # # Build: cp config/examples/mcxe247.config .config && make @@ -30,7 +31,7 @@ DUALBANK_SWAP?=0 # Select the MCXE247 variant. SRAM is ECC protected and holds no valid ECC after # power-on. WOLFBOOT_RAM_ECC_INIT clears the SRAM the bootloader uses # (0x1FFFC000-0x20002FFF) at reset so its ECC is valid. The rest of SRAM is the -# application's to initialize. +# application's to initialize (see APP_RAM_ECC_INIT). CFLAGS_EXTRA+=-DMCXE247 -DWOLFBOOT_RAM_ECC_INIT # Word-at-a-time memcpy/memset in src/string.c (bootloader and test-app). The @@ -53,8 +54,8 @@ CFLAGS_EXTRA+=-DS32K1XX_HSRUN_SPEED_TEST WOLFBOOT_SECTOR_SIZE?=0x1000 # The application's vector table follows the image header and is used in -# place (VTOR). With 163 interrupts the table must be 1 KB aligned, or the -# core fetches the vectors of IRQ 48 and up from the wrong slots. +# place (VTOR). The table must be 1 KB aligned, or the core fetches the vectors +# of IRQ 48 and up from the wrong slots. IMAGE_HEADER_SIZE?=1024 # Memory layout (Program Flash 0x00000000 - 0x0017FFFF): diff --git a/docs/Targets.md b/docs/Targets.md index 599db89dd8..fdf509d80e 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7702,8 +7702,12 @@ The S32K1xx test application (`test-app/app_s32k1xx.c`) provides a feature-rich | `trigger` | Set update flag if update image is in flash | | `update` | Receive firmware via XMODEM and trigger update | | `timestamp` | Show current system time (ms) | +| `network` | Run the wolfIP network test | | `reboot` | Perform software reset | +Note: `network` requires `ENABLE_WOLFIP=1` and, optionally, `WOLFIP_SPEED_TEST=1` +or `WOLFBOOT_TEST_TFTP=1`. + **UART Configuration:** - LPUART1: PTC7 (TX), PTC6 (RX) - Baud rate: 115200, 8N1 diff --git a/src/string.c b/src/string.c index d93c6d1084..ec7ed3a605 100644 --- a/src/string.c +++ b/src/string.c @@ -307,12 +307,21 @@ size_t strlen(const char *s) /* A 32-bit word at any address. aligned(1) lets the compiler emit a plain * (unaligned) word access; may_alias lets it alias the byte buffers. */ typedef uint32_t __attribute__((aligned(1), may_alias)) wb_u32_unaligned; +/* An aligned 32-bit word that may alias the byte buffers */ +typedef uint32_t __attribute__((may_alias)) wb_u32_alias; #endif void RAMFUNCTION *memcpy(void *dst, const void *src, size_t n) { size_t i; const char *s = (const char *)src; char *d = (char *)dst; +#if defined(FAST_MEMCPY) && defined(__ARM_FEATURE_UNALIGNED) && \ + defined(__GNUC__) + const wb_u32_unaligned *sw; + wb_u32_alias *dw; + uint32_t w0, w1, w2, w3; + size_t blocks; +#endif #if defined(FAST_MEMCPY) && defined(__ARM_FEATURE_UNALIGNED) && \ defined(__GNUC__) @@ -326,26 +335,26 @@ void RAMFUNCTION *memcpy(void *dst, const void *src, size_t n) *d++ = *s++; n--; } - while (n >= 4 * sizeof(uint32_t)) { - uint32_t w0 = ((const wb_u32_unaligned *)s)[0]; - uint32_t w1 = ((const wb_u32_unaligned *)s)[1]; - uint32_t w2 = ((const wb_u32_unaligned *)s)[2]; - uint32_t w3 = ((const wb_u32_unaligned *)s)[3]; - - ((wb_u32_unaligned *)d)[0] = w0; - ((wb_u32_unaligned *)d)[1] = w1; - ((wb_u32_unaligned *)d)[2] = w2; - ((wb_u32_unaligned *)d)[3] = w3; - d += 4 * sizeof(uint32_t); - s += 4 * sizeof(uint32_t); - n -= 4 * sizeof(uint32_t); + sw = (const wb_u32_unaligned *)s; + dw = (wb_u32_alias *)d; + /* 16 bytes per pass with post-incremented pointers */ + for (blocks = n / (4 * sizeof(uint32_t)); blocks > 0; blocks--) { + w0 = *sw++; + w1 = *sw++; + w2 = *sw++; + w3 = *sw++; + *dw++ = w0; + *dw++ = w1; + *dw++ = w2; + *dw++ = w3; } - while (n >= sizeof(uint32_t)) { - *(wb_u32_unaligned *)d = *(const wb_u32_unaligned *)s; - d += sizeof(uint32_t); - s += sizeof(uint32_t); - n -= sizeof(uint32_t); + n %= 4 * sizeof(uint32_t); + for (blocks = n / sizeof(uint32_t); blocks > 0; blocks--) { + *dw++ = *sw++; } + n %= sizeof(uint32_t); + s = (const char *)sw; + d = (char *)dw; } #elif defined(FAST_MEMCPY) /* is 32-bit aligned pointer */ diff --git a/test-app/Makefile b/test-app/Makefile index 4eb2e85a02..c67b0c36bf 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1788,23 +1788,16 @@ ifeq ($(ENABLE_WOLFIP),1) CFLAGS+=-DAPP_RAM_ECC_INIT # Hot code in SRAM_L (.ramcode_l in ARM-s32k1xx-wolfip.ld) CFLAGS+=-DAPP_RAMCODE_L - # Standalone driver, interrupt driven: startup_arm.c routes ENET IRQs - # 73-75 to nxp_mcxe_enet_irq_handler() CFLAGS+=-DWOLFIP_PORT_MCXE_ENET -DNXP_MCXE_ENET_IRQ=1 - # The TFTP receive buffer shares the 124KB of SRAM_U CFLAGS+=-DTFTP_RAM_MAX=0xA000U # wolfIP state is in the 128KB of SRAM_L (ARM-s32k1xx-wolfip.ld): six # full segments of TCP buffering per socket CFLAGS+=-DRXBUF_SIZE=9216 -DTXBUF_SIZE=9216 - # Build wolfIP hosted: -ffreestanding turns every small fixed-size - # memcpy (checksum words, header fields) into a call to the byte-wise - # memcpy in src/string.c, which cost most of the stack's CPU time - WOLFIP_CFLAGS_OUT:=-ffreestanding - # The stack is CPU bound: -O2 (after the global -Os) is 10-18% faster for - # 12KB more flash. Take at most 8 frames per wolfIP_poll() so the app can - # drain a socket between batches; with the default 128 a line-rate UDP - # flood fills the 6-datagram socket buffer and most frames are processed - # only to be dropped + # remove -ffreestanding so small memcpy's can be inlined + WOLFIP_CFLAGS_FILTEROUT:=-ffreestanding + # -O2 for some network objects is 10-18% faster. + # Take at most 8 frames per wolfIP_poll() so the app can drain a socket + # between batches. WOLFIP_CFLAGS_ADD:=-O2 -DWOLFIP_POLL_BUDGET=8 # Driver cycle counters for the throughput test's CPU breakdown ifeq ($(WOLFIP_SPEED_TEST),1) @@ -1839,7 +1832,7 @@ ifeq ($(ENABLE_WOLFIP),1) # wolfIP TUs need the port headers first (so config.h resolves to the # port copy) and tolerate wolfIP's own style; drop -Werror/-Wstack-usage. WOLFIP_CFLAGS:=-I"$(WOLFIP_PORTDIR)" -I"$(WOLFBOOT_LIB_WOLFIP)" \ - $(filter-out -Werror -Wstack-usage=$(STACK_USAGE_LIMIT) $(WOLFIP_CFLAGS_OUT),$(CFLAGS)) \ + $(filter-out -Werror -Wstack-usage=$(STACK_USAGE_LIMIT) $(WOLFIP_CFLAGS_FILTEROUT),$(CFLAGS)) \ -DWOLFIP_ENABLE_TFTP=$(if $(filter 1,$(WOLFBOOT_TEST_TFTP)),1,0) \ -Wno-unused -Wno-sign-compare -Wno-missing-field-initializers $(WOLFIP_CFLAGS_ADD) endif From af3162c1afa7f47cddfadfb97a1ecadcf093700f Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 16 Nov 2026 22:01:29 -0500 Subject: [PATCH 12/24] wolfip speed test: fix review findings in the server and host script Board server: - Refuse a TCP client while a UDP test runs. Its speed_start() cleared the shared state and silently ended the UDP test. - A TCP client that sends no direction byte within 500 ms gets a bidir test. A plain "nc 9" that only reads never got any data. - End a UDP bidir test when the board's stream ends, as tx already did. It stayed open until the host's 'q', about 1 s later, so the window held an idle tail: an 8 s test was timed as 9 s and the board rx rate read about 11% low (udp-bidir rx 38.9 -> 43.8 Mbit/s at 112 MHz, same loss). wolfip_speed.py: - An error in a TCP worker thread (reset, sendall() timeout) now fails the test instead of reporting partial counts. The socket is closed in a finally block, and the receiver waits with select() so it no longer changes the timeout the sender's sendall() uses. - Send 'q' before every test, TCP too, so a UDP test left running cannot make the board refuse the TCP client. --- docs/Targets.md | 4 ++- test-app/wolfip_tftp_test.c | 28 +++++++++++------ tools/scripts/wolfip_speed.py | 57 +++++++++++++++++++++-------------- 3 files changed, 56 insertions(+), 33 deletions(-) diff --git a/docs/Targets.md b/docs/Targets.md index fdf509d80e..1ee89bb832 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7870,7 +7870,9 @@ the board long after the test, so the board stops answering. The board prints the same counters on the console after each test. `mcxe247.config` sets `S32K1XX_HSRUN_SPEED_TEST`, so the server runs in HSRUN at 112 MHz and the console returns to RUN at 80 MHz when it stops. -Plain `nc 9` still works as a bidirectional TCP test. +Plain `nc 9` still works as a bidirectional TCP test; if `nc` sends +nothing, the board starts sending 0.5 s after it connects. TCP clients are +refused while a UDP test runs. Press Ctrl-C on the console to stop the server and return to the `cmd>` prompt. diff --git a/test-app/wolfip_tftp_test.c b/test-app/wolfip_tftp_test.c index 4df764d8a2..3f2752b124 100644 --- a/test-app/wolfip_tftp_test.c +++ b/test-app/wolfip_tftp_test.c @@ -448,8 +448,10 @@ static int run_tftp_fetch(struct wolfIP *s) * bidir = both at once. * * TCP: the first byte the client sends picks the direction: 'r' rx, - * 't' tx, anything else bidir (so plain "nc 9" stays bidirectional). - * The test ends when the client closes. + * 't' tx, anything else bidir. A client that sends nothing for + * SPEED_TCP_MODE_MS gets bidir, so plain "nc 9" works whether or not + * it sends. The test ends when the client closes. TCP clients are refused + * while a UDP test runs. * * UDP: each datagram starts with a SPEED_HDR_LEN byte header, big-endian: * [0] SPEED_MAGIC [1] command [2..3] board datagram size @@ -460,7 +462,8 @@ static int run_tftp_fetch(struct wolfIP *s) * Commands to the board: * 'r' data to count (starts an rx test) * 'b' data to count; the first one starts a bidir test and the board - * sends to the client for the given duration + * sends to the client for the given duration, which also ends + * the test * 't' start a tx test: the board sends to the client for the duration * 'q' end the current UDP test and reply with an 'S' stats datagram * The board's own datagrams carry command 'd'. @@ -477,6 +480,9 @@ static int run_tftp_fetch(struct wolfIP *s) #define SPEED_PROTO_TCP 1U #define SPEED_PROTO_UDP 2U #define SPEED_REPLY_LEN 108 +/* A TCP client that sends no direction byte this long after it connects + * gets a bidir test */ +#define SPEED_TCP_MODE_MS 500U /* How often the server checks for Ctrl-C on the console */ #define SPEED_ABORT_POLL_MS 100U @@ -695,7 +701,8 @@ static void speed_cb(int fd, uint16_t event, void *arg) if ((event & CB_EVENT_READABLE) != 0U) { c = wolfIP_sock_accept(s, speed_listen_fd, NULL, NULL); if (c >= 0) { - if (speed_client_fd >= 0) { + if (speed_client_fd >= 0 || speed.active != 0U) { + /* one test at a time, TCP or UDP */ (void)wolfIP_sock_close(s, c); } else { @@ -714,7 +721,7 @@ static void speed_cb(int fd, uint16_t event, void *arg) } } -static void speed_tcp_pump(struct wolfIP *s) +static void speed_tcp_pump(struct wolfIP *s, uint64_t now) { int n; int k; @@ -737,6 +744,8 @@ static void speed_tcp_pump(struct wolfIP *s) } speed.rx_bytes += (uint32_t)n; } + if (speed.mode == 0U && now >= speed.start_ms + SPEED_TCP_MODE_MS) + speed.mode = 'b'; if (speed.mode != 't' && speed.mode != 'b') return; for (k = 0; k < SPEED_BURST; k++) { @@ -811,9 +820,10 @@ static void speed_udp_send(struct wolfIP *s, uint64_t now) if (speed.streaming == 0U) return; if (now >= speed.stream_end_ms) { - speed.streaming = 0U; - if (speed.mode == 't') - speed_stop(now); + /* The host sends for the same duration, from slightly earlier, so + * a bidir test ends here too: its window then holds no idle tail + * while the host collects the last datagrams before 'q'. */ + speed_stop(now); return; } speed_txbuf[0] = SPEED_MAGIC; @@ -903,7 +913,7 @@ static int run_speed_server(struct wolfIP *s) } c_poll = SPEED_CYCLES(); (void)wolfIP_poll(s, now); - speed_tcp_pump(s); + speed_tcp_pump(s, now); speed_udp_recv(s, now); speed_udp_send(s, now); c_done = SPEED_CYCLES(); diff --git a/tools/scripts/wolfip_speed.py b/tools/scripts/wolfip_speed.py index b15f46206d..9cc6a470f7 100644 --- a/tools/scripts/wolfip_speed.py +++ b/tools/scripts/wolfip_speed.py @@ -21,6 +21,7 @@ import argparse import random +import select import socket import struct import sys @@ -129,10 +130,9 @@ def wait(self, idle=None): def tcp_test(ip, port, mode, secs): """Returns (host bytes sent, host bytes received, host seconds).""" s = socket.create_connection((ip, port), timeout=5) - s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) - s.sendall(mode.encode()) sent = [0] recvd = [0] + errors = [] stop = time.monotonic() + secs buf = bytes(65536) @@ -142,28 +142,39 @@ def sender(): sent[0] += len(buf) def receiver(): - s.settimeout(0.5) + # select() rather than a socket timeout, which the sender shares while time.monotonic() < stop: - try: - n = len(s.recv(65536)) - except socket.timeout: + if not select.select([s], [], [], 0.5)[0]: continue + n = len(s.recv(65536)) if n == 0: - break + raise RuntimeError("the board closed the connection") recvd[0] += n - t0 = time.monotonic() - workers = [] - if mode in ("r", "b"): - workers.append(threading.Thread(target=sender)) - if mode in ("t", "b"): - workers.append(threading.Thread(target=receiver)) - for w in workers: - w.start() - for w in workers: - w.join() - elapsed = time.monotonic() - t0 - s.close() + def worker(fn): + try: + fn() + except (OSError, RuntimeError) as e: + errors.append(e) + + try: + s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + s.sendall(mode.encode()) + t0 = time.monotonic() + workers = [] + if mode in ("r", "b"): + workers.append(threading.Thread(target=worker, args=(sender,))) + if mode in ("t", "b"): + workers.append(threading.Thread(target=worker, args=(receiver,))) + for w in workers: + w.start() + for w in workers: + w.join() + elapsed = time.monotonic() - t0 + finally: + s.close() + if errors: + raise errors[0] return sent[0], recvd[0], elapsed @@ -258,6 +269,10 @@ def run_test(name, args): addr = (args.ip, args.port) ctl = udp_socket() try: + # End any UDP test left running, so this one starts fresh (the + # board refuses TCP clients while a UDP test runs) + ctl.sendto(HDR.pack(MAGIC, ord("q"), 0, 0, 0, 0), addr) + time.sleep(0.3) drain(ctl) if proto == "tcp": h_sent, h_recv, h_secs = tcp_test(args.ip, args.port, mode, args.time) @@ -265,10 +280,6 @@ def run_test(name, args): host_tx = mbps(h_recv, h_secs) loss_rx = loss_tx = None else: - # End any UDP test left running, so this one starts fresh - ctl.sendto(HDR.pack(MAGIC, ord("q"), 0, 0, 0, 0), addr) - time.sleep(0.3) - drain(ctl) sent, got, got_bytes, span = udp_test(ctl, addr, mode, args.time, args.size, args.rate) st = query(ctl, addr, 2) From 6f71bbb932d5e1871e8006090282da377dee2ad2 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Wed, 25 Nov 2026 14:50:16 -0500 Subject: [PATCH 13/24] fix xmodem issues --- test-app/app_s32k1xx.c | 55 ++++++++++++++++++++++++++++++++---------- 1 file changed, 42 insertions(+), 13 deletions(-) diff --git a/test-app/app_s32k1xx.c b/test-app/app_s32k1xx.c index 231a51c9cc..95bb1fb7d7 100644 --- a/test-app/app_s32k1xx.c +++ b/test-app/app_s32k1xx.c @@ -457,6 +457,9 @@ static void print_keystore_info(void) #define XMODEM_PAYLOAD_SIZE 128 #define XMODEM_PACKET_SIZE_CRC (3 + XMODEM_PAYLOAD_SIZE + 2) /* SOH + blk + ~blk + data + CRC16 */ #define XMODEM_TIMEOUT_MS 1000 +/* Space in the update partition below its trailer sectors */ +#define XMODEM_MAX_SIZE (WOLFBOOT_PARTITION_SIZE - \ + (WOLFBOOT_TRAILER_SECTORS * WOLFBOOT_SECTOR_SIZE)) /* CRC-16-CCITT for XMODEM-CRC mode */ static uint16_t APP_RAMFUNCTION crc16_ccitt(const uint8_t* data, int len) @@ -519,10 +522,12 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) uint8_t payload[XMODEM_PAYLOAD_SIZE]; uint8_t pkt_num = 0, pkt_num_expected = 0xFF; uint32_t t_size = 0; + uint32_t img_size; uint32_t now; uint32_t i = 0; int transfer_started = 0; int eot_expected = 0; + int dup; int ret = -1; state->dst_offset = 0; @@ -565,10 +570,6 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) led_red_on(); /* Indicate transfer complete */ ret = 0; break; - } else if (eot_expected) { - uart_tx(XNAK); - ret = -1; - break; } /* Validate SOH */ @@ -583,9 +584,14 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) if ((uint8_t)(~xpkt[2]) == pkt_num) { uint16_t recv_crc, calc_crc; + dup = 0; if (!transfer_started) { pkt_num_expected = pkt_num; transfer_started = 1; + } else if (state->dst_offset > 0U && + pkt_num == (uint8_t)(pkt_num_expected - 1U)) { + /* The last block again: the sender missed its ACK */ + dup = 1; } else if (pkt_num_expected != pkt_num) { uart_tx(XNAK); continue; @@ -603,7 +609,30 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) xpkt[XMODEM_PACKET_SIZE_CRC - 1]; calc_crc = crc16_ccitt(xpkt + 3, XMODEM_PAYLOAD_SIZE); - if (recv_crc == calc_crc) { + if (recv_crc == calc_crc && dup) { + /* Already written: only ACK it again */ + uart_tx(XACK); + } else if (recv_crc == calc_crc) { + /* A block past the end of the image, or one that would reach + * the trailer sectors of the update partition */ + if (eot_expected || + state->dst_offset + XMODEM_PAYLOAD_SIZE > XMODEM_MAX_SIZE) { + xmodem_cancel(); + ret = -1; + break; + } + /* The image size (header offset 4) must fit, checked before + * the first block is ACKed or written */ + if (state->dst_offset == 0U) { + ram_memcpy(&img_size, xpkt + 3 + 4, sizeof(img_size)); + if (img_size > XMODEM_MAX_SIZE - IMAGE_HEADER_SIZE) { + xmodem_cancel(); + ret = -1; + break; + } + t_size = img_size + IMAGE_HEADER_SIZE; + } + /* Copy payload using RAM-based memcpy */ ram_memcpy(payload, xpkt + 3, XMODEM_PAYLOAD_SIZE); @@ -624,12 +653,7 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) pkt_num_expected++; state->dst_offset += XMODEM_PAYLOAD_SIZE; - /* Get expected size from header (offset 4 = image size) */ - if (t_size == 0 && state->dst_offset >= 8) { - t_size = *(uint32_t*)(payload + 4) + IMAGE_HEADER_SIZE; - } - - if (t_size > 0 && state->dst_offset >= t_size) { + if (state->dst_offset >= t_size) { eot_expected = 1; } } else { @@ -681,8 +705,13 @@ static int cmd_update_xmodem(void) } #else (void)erase_addr; - (void)erase_ret; - hal_flash_erase(WOLFBOOT_PARTITION_UPDATE_ADDRESS, WOLFBOOT_PARTITION_SIZE); + erase_ret = hal_flash_erase(WOLFBOOT_PARTITION_UPDATE_ADDRESS, + WOLFBOOT_PARTITION_SIZE); + if (erase_ret != 0) { + printf("Erase FAILED (%d)\r\n", erase_ret); + hal_flash_lock(); + return -1; + } #endif printf("Done.\r\n"); From 9aedefc2042d7b41932c14fff63c1a1394d865e5 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Tue, 1 Dec 2026 00:44:59 -0500 Subject: [PATCH 14/24] Address pr comments --- .gitignore | 3 + config/examples/mcxe247.config | 4 +- config/examples/nxp-s32k142.config | 2 - config/examples/nxp-s32k144.config | 2 - config/examples/nxp-s32k146.config | 2 - config/examples/nxp-s32k148.config | 2 - docs/Targets.md | 50 +- hal/s32k1xx.c | 315 +++++--- hal/s32k1xx.h | 31 +- src/string.c | 27 +- test-app/ARM-s32k1xx-wolfip.ld | 4 +- test-app/Makefile | 2 +- test-app/app_s32k1xx.c | 289 ++------ test-app/startup_arm.c | 7 +- test-app/wolfip_tftp_test.c | 202 +++-- test-app/xmodem_rx.c | 248 +++++++ tools/scripts/wolfip_speed.py | 84 ++- tools/unit-tests/Makefile | 21 + tools/unit-tests/unit-string.c | 95 +++ tools/unit-tests/unit-wolfip-speed.c | 737 +++++++++++++++++++ tools/unit-tests/unit-xmodem-rx.c | 366 +++++++++ tools/unit-tests/wolfip_stub/nxp_mcxe_enet.h | 38 + tools/unit-tests/wolfip_stub/wolfip.h | 81 ++ 23 files changed, 2161 insertions(+), 451 deletions(-) create mode 100644 test-app/xmodem_rx.c create mode 100644 tools/unit-tests/unit-wolfip-speed.c create mode 100644 tools/unit-tests/unit-xmodem-rx.c create mode 100644 tools/unit-tests/wolfip_stub/nxp_mcxe_enet.h create mode 100644 tools/unit-tests/wolfip_stub/wolfip.h diff --git a/.gitignore b/.gitignore index 16949128f9..344d81de2b 100644 --- a/.gitignore +++ b/.gitignore @@ -185,6 +185,9 @@ tools/unit-tests/unit-pkcs11_store tools/unit-tests/unit-sectorflags tools/unit-tests/unit-spi-flash tools/unit-tests/unit-string +tools/unit-tests/unit-string-unaligned +tools/unit-tests/unit-wolfip-speed +tools/unit-tests/unit-xmodem-rx tools/unit-tests/unit-update-flash tools/unit-tests/unit-update-flash-enc tools/unit-tests/unit-update-flash-enc-cache diff --git a/config/examples/mcxe247.config b/config/examples/mcxe247.config index d731bbbb9f..09a21445da 100644 --- a/config/examples/mcxe247.config +++ b/config/examples/mcxe247.config @@ -76,8 +76,8 @@ CFLAGS_EXTRA+=-DDEBUG_UART_RX_PORT=S32K_PORT_D -DDEBUG_UART_RX_PIN=17 CFLAGS_EXTRA+=-DDEBUG_UART_RX_MUX=PORT_PCR_MUX_ALT3 # wolfIP network test in the test-app (optional) -# Adds the "network" console command. Needs a wolfIP checkout, which provides -# the interrupt-driven nxp_mcxe_enet driver. +# Adds the "network" console command. Needs a wolfIP checkout with the +# nxp_mcxe_enet driver. ENABLE_WOLFIP?=0 WOLFBOOT_LIB_WOLFIP?=../lib/wolfip # By default the command acquires a DHCP lease and runs a TCP and UDP diff --git a/config/examples/nxp-s32k142.config b/config/examples/nxp-s32k142.config index 7c8254afd1..c9ac39e8cb 100644 --- a/config/examples/nxp-s32k142.config +++ b/config/examples/nxp-s32k142.config @@ -42,8 +42,6 @@ WOLFBOOT_PARTITION_UPDATE_ADDRESS?=0x25000 WOLFBOOT_PARTITION_SWAP_ADDRESS?=0x3E000 # Clock mode: Default is RUN mode with FIRC (48 MHz internal RC) -# To enable HSRUN mode (112 MHz), uncomment below (requires SOSC + SPLL, not fully implemented): -#CFLAGS_EXTRA+=-DS32K1XX_CLOCK_HSRUN # Optionally enable watchdog #CFLAGS_EXTRA+=-DWATCHDOG diff --git a/config/examples/nxp-s32k144.config b/config/examples/nxp-s32k144.config index cd145539e6..0d90e36e7a 100644 --- a/config/examples/nxp-s32k144.config +++ b/config/examples/nxp-s32k144.config @@ -45,8 +45,6 @@ WOLFBOOT_PARTITION_UPDATE_ADDRESS?=0x44000 WOLFBOOT_PARTITION_SWAP_ADDRESS?=0x7C000 # Clock mode: Default is RUN mode with FIRC (48 MHz internal RC) -# To enable HSRUN mode (112 MHz), uncomment below (requires SOSC + SPLL, not fully implemented): -#CFLAGS_EXTRA+=-DS32K1XX_CLOCK_HSRUN # Optionally enable watchdog #CFLAGS_EXTRA+=-DWATCHDOG diff --git a/config/examples/nxp-s32k146.config b/config/examples/nxp-s32k146.config index e4f1597d42..42c3d35c07 100644 --- a/config/examples/nxp-s32k146.config +++ b/config/examples/nxp-s32k146.config @@ -45,8 +45,6 @@ WOLFBOOT_PARTITION_UPDATE_ADDRESS?=0x80000 WOLFBOOT_PARTITION_SWAP_ADDRESS?=0xF4000 # Clock mode: Default is RUN mode with FIRC (48 MHz internal RC) -# To enable HSRUN mode (112 MHz), uncomment below (requires SOSC + SPLL, not fully implemented): -#CFLAGS_EXTRA+=-DS32K1XX_CLOCK_HSRUN # Optionally enable watchdog #CFLAGS_EXTRA+=-DWATCHDOG diff --git a/config/examples/nxp-s32k148.config b/config/examples/nxp-s32k148.config index 574be8da52..73f8207e4e 100644 --- a/config/examples/nxp-s32k148.config +++ b/config/examples/nxp-s32k148.config @@ -45,8 +45,6 @@ WOLFBOOT_PARTITION_UPDATE_ADDRESS?=0xC4000 WOLFBOOT_PARTITION_SWAP_ADDRESS?=0x17C000 # Clock mode: Default is RUN mode with FIRC (48 MHz internal RC) -# To enable HSRUN mode (112 MHz), uncomment below (requires SOSC + SPLL, not fully implemented): -#CFLAGS_EXTRA+=-DS32K1XX_CLOCK_HSRUN # Optionally enable watchdog #CFLAGS_EXTRA+=-DWATCHDOG diff --git a/docs/Targets.md b/docs/Targets.md index 1ee89bb832..30ffe53a31 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7596,10 +7596,10 @@ The following build options are available for the S32K1xx HAL: | `WOLFBOOT_DISABLE_WATCHDOG_ON_BOOT` | Keep watchdog disabled when jumping to application. By default, the watchdog is re-enabled before boot since it is enabled out of reset. | | `WATCHDOG` | Enable the watchdog during wolfBoot operation. wolfBoot calls `wolfBoot_watchdog_feed()` from its hash and copy/erase loops -- a weak no-op a port overrides to service its watchdog (e.g. external MAX6316-MAX6322, see `hal/renesas-rx.c`). | | `WATCHDOG_TIMEOUT_MS` | Watchdog timeout in milliseconds when `WATCHDOG` is enabled (default: 1000ms). | -| `S32K1XX_CLOCK_HSRUN` | Enable HSRUN mode (112 MHz). Requires external crystal and SPLL (not fully implemented). | -| `S32K1XX_CLOCK_80MHZ` | Run wolfBoot at 80 MHz (RUN mode) from the external crystal through the SPLL, instead of the 48 MHz FIRC. The crystal frequency is `S32K1XX_SOSC_FREQ` (default 8 MHz). The clock is switched back before the application starts; the s32k1xx test-app switches to 80 MHz again with `s32k1xx_clock_80mhz()`. Tested on the MCXE247 only. | +| `S32K1XX_CLOCK_HSRUN` | Removed: the build stops with an error. wolfBoot does not run in HSRUN, because flash cannot be programmed or erased there. An application enters HSRUN at 112 MHz with `s32k1xx_clock_hsrun()` (see `S32K1XX_HSRUN_SPEED_TEST`). | +| `S32K1XX_CLOCK_80MHZ` | Run wolfBoot at 80 MHz (RUN mode) from the external crystal through the SPLL, instead of the 48 MHz FIRC. The crystal frequency is `S32K1XX_SOSC_FREQ` (default 8 MHz). The clock is switched back before the application starts; the s32k1xx test-app switches to 80 MHz again with `s32k1xx_clock_80mhz()`. Each wait for the crystal, the SPLL lock, the clock switch and the power mode is bounded (`S32K1XX_WAIT_LOOPS` status reads, at least about 60 ms); if one times out, wolfBoot prints a message and carries on at 48 MHz on the FIRC, and the clock functions return an error. Tested on the MCXE247 only. | | `S32K1XX_HSRUN_SPEED_TEST` | With `S32K1XX_CLOCK_80MHZ` and the wolfIP speed test, the test-app `network` command runs in HSRUN at 112 MHz (bus 56 MHz, flash 28 MHz) with `s32k1xx_clock_hsrun()` and returns to RUN at 80 MHz with `s32k1xx_clock_run()` when the server stops, so flash writes from the console still work. Tested on the MCXE247 only. | -| `S32K1XX_CODE_CACHE` | Enable the 4 KB LMEM code cache for flash while wolfBoot runs. It is invalidated after every flash erase and program command, and disabled before the application starts; the s32k1xx test-app enables it again with `s32k1xx_code_cache_enable()`. Tested on the MCXE247 only. | +| `S32K1XX_CODE_CACHE` | Enable the 4 KB LMEM code cache for flash while wolfBoot runs. It is invalidated after every flash erase and program command, and disabled before the application starts; the s32k1xx test-app enables it again with `s32k1xx_code_cache_enable()`. The waits for the cache commands are bounded like the clock waits: a cache that does not finish its invalidate stays off at start-up, and fails the flash command that needed it. Tested on the MCXE247 only. | | `DEBUG_UART` | Enable LPUART debug output. | | `DEBUG_HARDFAULT` | Enable detailed hard fault debugging output. | | `S32K144`, `S32K146`, `S32K148` | Select variant (default is S32K142). Affects flash/SRAM size definitions. | @@ -7807,8 +7807,8 @@ apply to the MCXE247, with these differences: clears the SRAM it uses (the S32K142 layout of `hal/s32k1xx.ld`) at reset, so the ECC of that RAM is valid. It does not clear the rest of the 252 KB, so an application that enables ERM interrupts must - write its RAM before reading it. The network test app clears all of SRAM_U at - reset (`APP_RAM_ECC_INIT`). + write its RAM before reading it. The network test app clears all of SRAM_L + and SRAM_U at reset (`APP_RAM_ECC_INIT`). - `mcxe247.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 163 interrupts it must be 1 KB aligned: with the default 256-byte @@ -7828,10 +7828,14 @@ apply to the MCXE247, with these differences: ### NXP MCXE247: Network test The test application can run a wolfIP throughput test or a DHCP and TFTP test -over the board's Ethernet port. This is optional and needs a wolfIP checkout, whose -`nxp_mcxe_enet` port is a standalone ENET and LAN8741 driver (no vendor SDK). -The test app builds it interrupt driven (`NXP_MCXE_ENET_IRQ=1`, with ENET IRQs -73-75 routed in `test-app/startup_arm.c`). The wolfIP stack state, with 9 KB +over the board's Ethernet port. This is optional and needs a wolfIP checkout +with the `nxp_mcxe_enet` port, a standalone ENET driver with a generic +clause-22 PHY bring-up (no vendor SDK). The port is not in a wolfIP release +yet: it is in [wolfIP pull request 196](https://github.com/wolfSSL/wolfip/pull/196), +tested at commit `e139371`. Check that out in `lib/wolfip`, or point +`WOLFBOOT_LIB_WOLFIP` at it. +The test app builds it interrupt driven (`NXP_MCXE_ENET_IRQ=1`, with the ENET +receive and error IRQs, 74 and 75, routed in `test-app/startup_arm.c`). The wolfIP stack state, with 9 KB TCP receive and transmit buffers per socket, is placed in SRAM_L by `test-app/ARM-s32k1xx-wolfip.ld`, together with the hottest code (`memcpy` and wolfIP's checksum loop), which the core then fetches over its code bus in @@ -7859,6 +7863,12 @@ python3 tools/scripts/wolfip_speed.py The script runs six tests of 10 s each: TCP and UDP, each with the board only receiving (`rx`), only sending (`tx`) and both at once (`bidir`). +Each UDP test starts with an open request carrying a session id the host +picks; the board only counts data of the open session, so datagrams still on +the way from an earlier test cannot start or disturb another one. The board +limits a UDP test to 60 s (`--time` at most 60) and ends one the host +abandons 2 s after its duration. The server has no authentication and sends +to whoever opens a test, so run it on a trusted network only. It prints a table of the rates and UDP loss. With this build the driver also counts its own core cycles (`NXP_MCXE_ENET_STATS=1`), so the table also shows how the CPU time divides between the driver, the frame copies, wolfIP and the @@ -7871,8 +7881,11 @@ the same counters on the console after each test. `mcxe247.config` sets `S32K1XX_HSRUN_SPEED_TEST`, so the server runs in HSRUN at 112 MHz and the console returns to RUN at 80 MHz when it stops. Plain `nc 9` still works as a bidirectional TCP test; if `nc` sends -nothing, the board starts sending 0.5 s after it connects. TCP clients are -refused while a UDP test runs. +nothing, the board starts sending 0.5 s after it connects. A TCP test ends +when the client closes, or after 5 s with no data either way, so a client +that disappears without closing does not block the server. TCP clients are +refused while a UDP test runs. `tools/unit-tests/unit-wolfip-speed` tests the +server's protocol handling on the host. Press Ctrl-C on the console to stop the server and return to the `cmd>` prompt. @@ -7891,6 +7904,21 @@ priority: with both options set to 1, the command runs the TFTP fetch and the speed server is never started. With both set to 0 it only acquires a DHCP lease. +### NXP MCXE247: Programming with pyOCD + +The onboard MCU-Link (JP4 open) programs the board with +[pyOCD](https://pyocd.io): + +```sh +pyocd pack install mcxe247vlq +pyocd flash -t mcxe247vlq --base-address 0 factory.bin +``` + +`pyocd flash` erases only the sectors it programs. Do not use +`pyocd erase --chip` on its own: it also erases the Flash Configuration +Field, so the part comes back secured after the next reset (see the security +byte below). Program `factory.bin` after a chip erase, before any reset. + ### NXP MCXE247: Programming with Lauterbach TRACE32 Connect the 10-pin debug cable to J14 and short JP4 to disable the onboard diff --git a/hal/s32k1xx.c b/hal/s32k1xx.c index e884d05732..206109fbd8 100644 --- a/hal/s32k1xx.c +++ b/hal/s32k1xx.c @@ -191,6 +191,33 @@ static void clock_restore_sirc(void) } #endif /* WOLFBOOT_RESTORE_CLOCK */ +#if defined(S32K1XX_CLOCK_80MHZ) || defined(S32K1XX_CODE_CACHE) +/* Bound for the SOSC, SPLL, system clock, power mode and code cache waits, + * in reads of the status register: at least about 60 ms at 112 MHz, where + * the slowest of them, the crystal start, takes a few ms. */ +#ifndef S32K1XX_WAIT_LOOPS +#define S32K1XX_WAIT_LOOPS 1000000UL +#endif + +/* Wait until (*reg & mask) == val. Returns 0, or -1 after + * S32K1XX_WAIT_LOOPS reads. In RAM, as the cache helpers run during flash + * commands. */ +static int RAMFUNCTION reg_wait(volatile uint32_t *reg, uint32_t mask, + uint32_t val) +{ + uint32_t n; + int ret = -1; + + for (n = 0; n < S32K1XX_WAIT_LOOPS; n++) { + if ((*reg & mask) == val) { + ret = 0; + break; + } + } + return ret; +} +#endif + static void clock_init_firc(void) { /* Enable FIRC (48 MHz) */ @@ -202,11 +229,14 @@ static void clock_init_firc(void) while (!(SCG_FIRCCSR & SCG_FIRCCSR_FIRCVLD)) {} } -#ifdef S32K1XX_CLOCK_80MHZ -#if defined(S32K1XX_CLOCK_HSRUN) -#error "S32K1XX_CLOCK_80MHZ and S32K1XX_CLOCK_HSRUN are mutually exclusive" +/* wolfBoot never runs in HSRUN, where flash cannot be programmed or erased. + * An application enters it with s32k1xx_clock_hsrun() (S32K1XX_CLOCK_80MHZ). */ +#ifdef S32K1XX_CLOCK_HSRUN +#error "S32K1XX_CLOCK_HSRUN is removed: use s32k1xx_clock_hsrun()" #endif +#ifdef S32K1XX_CLOCK_80MHZ + /* Crystal on the SOSC (EXTAL/XTAL) pins */ #ifndef S32K1XX_SOSC_FREQ #define S32K1XX_SOSC_FREQ 8000000UL @@ -239,26 +269,35 @@ static void clock_init_firc(void) (0UL << SCG_xCCR_DIVBUS_SHIFT) | \ (1UL << SCG_xCCR_DIVSLOW_SHIFT)) -static void sysclk_wait(uint32_t scs) +/* Wait for the system clock switch to scs. Returns 0, or -1 on timeout. */ +static int sysclk_wait(uint32_t scs) { - while ((SCG_CSR & SCG_CSR_SCS_MASK) != scs) {} + return reg_wait(&SCG_CSR, SCG_CSR_SCS_MASK, scs); } -/* SOSC: crystal, high range (required when it feeds the SPLL) */ -static void sosc_start(void) +/* Wait for the power mode in SMC_PMSTAT. Returns 0, or -1 on timeout. */ +static int pmstat_wait(uint32_t mode) +{ + return reg_wait(&SMC_PMSTAT, 0xFFUL, mode); +} + +/* SOSC: crystal, high range (required when it feeds the SPLL). Returns 0, + * or -1 when the crystal does not start. */ +static int sosc_start(void) { if ((SCG_SOSCCSR & SCG_SOSCCSR_SOSCVLD) != 0U) - return; + return 0; SCG_SOSCCSR = 0; SCG_SOSCDIV = (1UL << 8) | (1UL << 0); /* SOSCDIV1=/1, SOSCDIV2=/1 */ SCG_SOSCCFG = SCG_SOSCCFG_RANGE_HIGH | SCG_SOSCCFG_EREFS; SCG_SOSCCSR = SCG_SOSCCSR_SOSCEN; - while (!(SCG_SOSCCSR & SCG_SOSCCSR_SOSCVLD)) {} + return reg_wait(&SCG_SOSCCSR, SCG_SOSCCSR_SOSCVLD, SCG_SOSCCSR_SOSCVLD); } /* Program and lock the SPLL. SPLLCFG can only be written while the SPLL is - * disabled, so the system clock must not be running from it. */ -static void spll_start(uint32_t mult, uint32_t div1, uint32_t div2) + * disabled, so the system clock must not be running from it. Returns 0, or + * -1 when the SPLL does not lock. */ +static int spll_start(uint32_t mult, uint32_t div1, uint32_t div2) { SCG_SPLLCSR = 0; SCG_SPLLDIV = (div1 << SCG_SPLLDIV_SPLLDIV1_SHIFT) | @@ -266,24 +305,7 @@ static void spll_start(uint32_t mult, uint32_t div1, uint32_t div2) SCG_SPLLCFG = (mult << SCG_SPLLCFG_MULT_SHIFT) | (0UL << SCG_SPLLCFG_PREDIV_SHIFT); SCG_SPLLCSR = SCG_SPLLCSR_SPLLEN; - while (!(SCG_SPLLCSR & SCG_SPLLCSR_SPLLVLD)) {} -} - -/* RUN mode at 80 MHz (reference manual "Normal RUN" example): - * SOSC -> SPLL 160 MHz -> CORE/SYS 80 MHz (/2), BUS 40 MHz (/2 of core), - * FLASH 26.67 MHz (/3 of core, the RUN mode maximum). - */ -static void clock_init_spll(void) -{ - sosc_start(); - spll_start(SPLL_MULT, 2UL, 3UL); /* SPLLDIV1 /2: 80, SPLLDIV2 /4: 40 */ - - /* Switch the system clock to the SPLL */ - SCG_RCCR = SCG_xCCR_SCS_SPLL | - (1UL << SCG_xCCR_DIVCORE_SHIFT) | - (1UL << SCG_xCCR_DIVBUS_SHIFT) | - (2UL << SCG_xCCR_DIVSLOW_SHIFT); - sysclk_wait(SCG_CSR_SCS_SPLL); + return reg_wait(&SCG_SPLLCSR, SCG_SPLLCSR_SPLLVLD, SCG_SPLLCSR_SPLLVLD); } /* Stop the SPLL and SOSC once the system clock no longer uses them */ @@ -293,10 +315,74 @@ static void clock_stop_spll(void) SCG_SOSCCSR = 0; } -void s32k1xx_clock_80mhz(void) +/* Fall back to RUN mode on the FIRC at 48 MHz, from RUN or HSRUN on any + * clock, and stop the SPLL. The FIRC is started first if it is off (wolfBoot + * stops it before the application with WOLFBOOT_RESTORE_CLOCK). Returns 0, + * or -1 when the FIRC, the clock or the power mode does not switch; the SPLL + * then stays on. */ +static int clock_run_firc(void) +{ + int ret = 0; + + if ((SCG_FIRCCSR & SCG_FIRCCSR_FIRCVLD) == 0U) { + SCG_FIRCDIV = (1UL << 8) | (1UL << 0); /* FIRCDIV1=/1, FIRCDIV2=/1 */ + SCG_FIRCCFG = 0; /* Range 0: 48 MHz */ + SCG_FIRCCSR = SCG_FIRCCSR_FIRCEN; + ret = reg_wait(&SCG_FIRCCSR, SCG_FIRCCSR_FIRCVLD, + SCG_FIRCCSR_FIRCVLD); + } + if (ret == 0) { + /* HSRUN takes HCCR and RUN takes RCCR: put both on the FIRC */ + SCG_HCCR = SCG_xCCR_FIRC_48MHZ; + SCG_RCCR = SCG_xCCR_FIRC_48MHZ; + ret = sysclk_wait(SCG_CSR_SCS_FIRC); + } + if (ret == 0 && (SMC_PMSTAT & 0xFFUL) != SMC_PMSTAT_RUN) { + SMC_PMCTRL = (SMC_PMCTRL & ~(3UL << SMC_PMCTRL_RUNM_SHIFT)) | + SMC_PMCTRL_RUNM_RUN; + ret = pmstat_wait(SMC_PMSTAT_RUN); + } + if (ret == 0) + clock_stop_spll(); + return ret; +} + +/* RUN mode at 80 MHz (reference manual "Normal RUN" example): + * SOSC -> SPLL 160 MHz -> CORE/SYS 80 MHz (/2), BUS 40 MHz (/2 of core), + * FLASH 26.67 MHz (/3 of core, the RUN mode maximum). Called in RUN mode. + * Returns 0; -1 when the crystal, the SPLL or the switch fails, with the + * core back on the FIRC at 48 MHz; or -2 when even that switch fails. + */ +static int clock_init_spll(void) { - if ((SCG_CSR & SCG_CSR_SCS_MASK) != SCG_CSR_SCS_SPLL) - clock_init_spll(); + int ret; + + ret = sosc_start(); + if (ret == 0) + ret = spll_start(SPLL_MULT, 2UL, 3UL); /* DIV1 /2: 80, DIV2 /4: 40 */ + if (ret == 0) { + /* Switch the system clock to the SPLL */ + SCG_RCCR = SCG_xCCR_SCS_SPLL | + (1UL << SCG_xCCR_DIVCORE_SHIFT) | + (1UL << SCG_xCCR_DIVBUS_SHIFT) | + (2UL << SCG_xCCR_DIVSLOW_SHIFT); + ret = sysclk_wait(SCG_CSR_SCS_SPLL); + } + if (ret != 0 && clock_run_firc() != 0) + ret = -2; + return ret; +} + +int s32k1xx_clock_80mhz(void) +{ + int ret = 0; + + /* The SPLL also runs the core in HSRUN at 112 MHz: leave HSRUN first */ + if ((SMC_PMSTAT & 0xFFUL) != SMC_PMSTAT_RUN && clock_run_firc() != 0) + ret = -2; + else if ((SCG_CSR & SCG_CSR_SCS_MASK) != SCG_CSR_SCS_SPLL) + ret = clock_init_spll(); + return ret; } /* HSRUN at 112 MHz: SOSC -> SPLL 112 MHz -> CORE/SYS 112 MHz (/1), BUS @@ -305,6 +391,8 @@ void s32k1xx_clock_80mhz(void) * HSRUN; call s32k1xx_clock_run() first. */ int s32k1xx_clock_hsrun(void) { + int ret; + if ((SMC_PMSTAT & 0xFFUL) == SMC_PMSTAT_HSRUN) return 0; /* PMPROT can be written once after reset: allow HSRUN unless already @@ -316,39 +404,44 @@ int s32k1xx_clock_hsrun(void) /* Leave the SPLL while its VCO changes */ SCG_RCCR = SCG_xCCR_FIRC_48MHZ; - sysclk_wait(SCG_CSR_SCS_FIRC); - sosc_start(); - spll_start(SPLL_MULT_HSRUN, 1UL, 2UL); /* SPLLDIV1 /1: 112, DIV2 /2: 56 */ - - SCG_HCCR = SCG_xCCR_FIRC_48MHZ; - SMC_PMCTRL = (SMC_PMCTRL & ~(3UL << SMC_PMCTRL_RUNM_SHIFT)) | - SMC_PMCTRL_RUNM_HSRUN; - while ((SMC_PMSTAT & 0xFFUL) != SMC_PMSTAT_HSRUN) {} - - SCG_HCCR = SCG_xCCR_SCS_SPLL | - (0UL << SCG_xCCR_DIVCORE_SHIFT) | - (1UL << SCG_xCCR_DIVBUS_SHIFT) | - (3UL << SCG_xCCR_DIVSLOW_SHIFT); - sysclk_wait(SCG_CSR_SCS_SPLL); - return 0; + ret = sysclk_wait(SCG_CSR_SCS_FIRC); + if (ret == 0) + ret = sosc_start(); + if (ret == 0) + ret = spll_start(SPLL_MULT_HSRUN, 1UL, 2UL); /* /1: 112, /2: 56 */ + if (ret == 0) { + SCG_HCCR = SCG_xCCR_FIRC_48MHZ; + SMC_PMCTRL = (SMC_PMCTRL & ~(3UL << SMC_PMCTRL_RUNM_SHIFT)) | + SMC_PMCTRL_RUNM_HSRUN; + ret = pmstat_wait(SMC_PMSTAT_HSRUN); + } + if (ret == 0) { + SCG_HCCR = SCG_xCCR_SCS_SPLL | + (0UL << SCG_xCCR_DIVCORE_SHIFT) | + (1UL << SCG_xCCR_DIVBUS_SHIFT) | + (3UL << SCG_xCCR_DIVSLOW_SHIFT); + ret = sysclk_wait(SCG_CSR_SCS_SPLL); + } + if (ret != 0 && clock_run_firc() != 0) + ret = -2; + return ret; } /* Back from HSRUN to RUN at 80 MHz */ -void s32k1xx_clock_run(void) +int s32k1xx_clock_run(void) { - if ((SMC_PMSTAT & 0xFFUL) == SMC_PMSTAT_HSRUN) { - /* Drop to the FIRC before leaving HSRUN; RUN then takes RCCR, - * which s32k1xx_clock_hsrun() left on the FIRC */ - SCG_HCCR = SCG_xCCR_FIRC_48MHZ; - sysclk_wait(SCG_CSR_SCS_FIRC); - SMC_PMCTRL = (SMC_PMCTRL & ~(3UL << SMC_PMCTRL_RUNM_SHIFT)) | - SMC_PMCTRL_RUNM_RUN; - while ((SMC_PMSTAT & 0xFFUL) != SMC_PMSTAT_RUN) {} - } - s32k1xx_clock_80mhz(); + /* s32k1xx_clock_80mhz() drops to RUN on the FIRC first */ + return s32k1xx_clock_80mhz(); } #endif /* S32K1XX_CLOCK_80MHZ */ +#ifdef S32K1XX_CLOCK_80MHZ +static int clock_err; +#endif +#ifdef S32K1XX_CODE_CACHE +static int cache_err; +#endif + static void clock_init(void) { /* Initialize FIRC to 48 MHz */ @@ -369,29 +462,8 @@ static void clock_init(void) while ((SCG_CSR & SCG_CSR_SCS_MASK) != SCG_CSR_SCS_FIRC) {} #ifdef S32K1XX_CLOCK_80MHZ - clock_init_spll(); -#endif - -#ifdef S32K1XX_CLOCK_HSRUN - /* HSRUN mode (112 MHz) - requires SOSC + SPLL (not fully implemented yet) - * TODO: Add SOSC initialization and SPLL configuration for true 112 MHz - * Currently this enters HSRUN mode but still uses FIRC at 48 MHz - */ - - /* Enable HSRUN mode */ - SMC_PMPROT = SMC_PMPROT_AHSRUN; - - /* Configure HSRUN clock control (same as RUN for now with FIRC) */ - SCG_HCCR = SCG_xCCR_SCS_FIRC | - (0UL << SCG_xCCR_DIVCORE_SHIFT) | - (0UL << SCG_xCCR_DIVBUS_SHIFT) | - (1UL << SCG_xCCR_DIVSLOW_SHIFT); - - /* Enter HSRUN mode */ - SMC_PMCTRL = (SMC_PMCTRL & ~(3UL << SMC_PMCTRL_RUNM_SHIFT)) | SMC_PMCTRL_RUNM_HSRUN; - - /* Wait for HSRUN */ - while ((SMC_PMSTAT & 0xFF) != SMC_PMSTAT_HSRUN) {} + /* On failure wolfBoot carries on at 48 MHz on the FIRC */ + clock_err = clock_init_spll(); #endif } @@ -400,44 +472,60 @@ static void clock_init(void) #ifdef S32K1XX_CODE_CACHE /* The cache is write-through for Program Flash (region 0). Flash erase and * program commands bypass it, so it is invalidated after each command. */ -static void RAMFUNCTION cache_invalidate(void) +/* Returns 0, or -1 when the invalidate does not finish. PCCCR must not be + * written while a command runs: on the MCXE247 that stalls the code bus + * (flash and SRAM_L) until reset. */ +static int RAMFUNCTION cache_invalidate(void) { + int ret = 0; + if (LMEM_PCCCR & LMEM_PCCCR_ENCACHE) { LMEM_PCCCR |= LMEM_PCCCR_INVW0 | LMEM_PCCCR_INVW1 | LMEM_PCCCR_GO; - while (LMEM_PCCCR & LMEM_PCCCR_GO) {} + ret = reg_wait(&LMEM_PCCCR, LMEM_PCCCR_GO, 0U); } + return ret; } -static void cache_enable(void) +/* Returns 0, or -1 with the cache left off when the invalidate does not + * finish */ +static int cache_enable(void) { + int ret; + /* FlexNVM (region 2) must not be cached on MCXE247. A region can only * be demoted, until the next reset. */ LMEM_PCCRMR &= ~LMEM_PCCRMR_R2_MASK; /* The tags are not cleared at reset: invalidate, then enable */ LMEM_PCCCR = LMEM_PCCCR_INVW0 | LMEM_PCCCR_INVW1 | LMEM_PCCCR_GO; - while (LMEM_PCCCR & LMEM_PCCCR_GO) {} - LMEM_PCCCR = LMEM_PCCCR_ENCACHE; + ret = reg_wait(&LMEM_PCCCR, LMEM_PCCCR_GO, 0U); + if (ret == 0) + LMEM_PCCCR = LMEM_PCCCR_ENCACHE; DSB(); ISB(); + return ret; } +/* Leaves the cache on when its invalidate does not finish (see + * cache_invalidate()) */ static void cache_disable(void) { - cache_invalidate(); - LMEM_PCCCR = 0; - DSB(); - ISB(); + if (cache_invalidate() == 0) { + LMEM_PCCCR = 0; + DSB(); + ISB(); + } } #else -#define cache_invalidate() do {} while (0) +#define cache_invalidate() (0) #endif /* S32K1XX_CODE_CACHE */ #ifdef S32K1XX_CODE_CACHE -void s32k1xx_code_cache_enable(void) +int s32k1xx_code_cache_enable(void) { - if ((LMEM_PCCCR & LMEM_PCCCR_ENCACHE) == 0U) - cache_enable(); + if ((LMEM_PCCCR & LMEM_PCCCR_ENCACHE) != 0U) + return 0; + return cache_enable(); } #endif @@ -552,6 +640,8 @@ static void RAMFUNCTION flash_clear_errors(void) static int RAMFUNCTION flash_program_phrase(uint32_t address, const uint8_t *data) { + int ret; + /* Skip if phrase is all 0xFF (erased) */ if (data[0] == 0xFF && data[1] == 0xFF && data[2] == 0xFF && data[3] == 0xFF && data[4] == 0xFF && data[5] == 0xFF && data[6] == 0xFF && data[7] == 0xFF) { @@ -586,7 +676,7 @@ static int RAMFUNCTION flash_program_phrase(uint32_t address, const uint8_t *dat /* Wait for completion */ flash_wait_complete(); - cache_invalidate(); + ret = cache_invalidate(); #ifdef WATCHDOG /* Refresh watchdog after flash operation */ @@ -595,15 +685,16 @@ static int RAMFUNCTION flash_program_phrase(uint32_t address, const uint8_t *dat /* Check for errors */ if (FTFC_FSTAT & (FTFC_FSTAT_ACCERR | FTFC_FSTAT_FPVIOL | FTFC_FSTAT_MGSTAT0)) { - return -1; + ret = -1; } - return 0; + return ret; } static int RAMFUNCTION flash_erase_sector_internal(uint32_t address) { uint32_t primask; + int ret; /* Wait for previous command to complete */ flash_wait_complete(); @@ -627,7 +718,7 @@ static int RAMFUNCTION flash_erase_sector_internal(uint32_t address) /* Wait for completion */ flash_wait_complete(); - cache_invalidate(); + ret = cache_invalidate(); /* Re-enable interrupts */ __set_PRIMASK(primask); @@ -639,10 +730,10 @@ static int RAMFUNCTION flash_erase_sector_internal(uint32_t address) /* Check for errors */ if (FTFC_FSTAT & (FTFC_FSTAT_ACCERR | FTFC_FSTAT_FPVIOL | FTFC_FSTAT_MGSTAT0)) { - return -1; + ret = -1; } - return 0; + return ret; } /* ============== HAL Interface Functions ============== */ @@ -656,7 +747,7 @@ void hal_init(void) clock_init(); #ifdef S32K1XX_CODE_CACHE - cache_enable(); + cache_err = cache_enable(); #endif /* Enable clock to flash controller */ @@ -672,6 +763,14 @@ void hal_init(void) wolfBoot_printf("wolfBoot Version: %s (%s %s)\n", LIBWOLFBOOT_VERSION_STRING,__DATE__, __TIME__); #endif +#ifdef S32K1XX_CLOCK_80MHZ + if (clock_err != 0) + wolfBoot_printf("SPLL failed (%d), running at 48 MHz\n", clock_err); +#endif +#ifdef S32K1XX_CODE_CACHE + if (cache_err != 0) + wolfBoot_printf("Code cache invalidate failed, cache off\n"); +#endif #endif #endif @@ -703,17 +802,15 @@ void hal_prepare_boot(void) * This gives the application a known clock state to start from. */ clock_restore_sirc(); -#elif defined(S32K1XX_CLOCK_80MHZ) - /* Return to the default FIRC 48 MHz RUN configuration */ - SCG_RCCR = SCG_xCCR_SCS_FIRC | - (0UL << SCG_xCCR_DIVCORE_SHIFT) | - (0UL << SCG_xCCR_DIVBUS_SHIFT) | - (1UL << SCG_xCCR_DIVSLOW_SHIFT); - while ((SCG_CSR & SCG_CSR_SCS_MASK) != SCG_CSR_SCS_FIRC) {} -#endif #ifdef S32K1XX_CLOCK_80MHZ clock_stop_spll(); #endif +#elif defined(S32K1XX_CLOCK_80MHZ) + /* Return to the default FIRC 48 MHz RUN configuration and stop the + * SPLL. If the clock does not switch, nothing more can be done here: + * the SPLL stays on and the application starts on it. */ + (void)clock_run_firc(); +#endif /* Re-enable watchdog before booting application. * The watchdog is enabled by default after reset, so the application diff --git a/hal/s32k1xx.h b/hal/s32k1xx.h index f126a74890..7de6cc09a9 100644 --- a/hal/s32k1xx.h +++ b/hal/s32k1xx.h @@ -36,13 +36,13 @@ * * Run modes: * - RUN: Up to 80 MHz core clock (requires SOSC + SPLL) - * - HSRUN: Up to 112 MHz core clock (requires SOSC + SPLL, not implemented yet) + * - HSRUN: Up to 112 MHz core clock (requires SOSC + SPLL); no flash + * program or erase. s32k1xx_clock_hsrun() enters it from an application. * * Default: RUN mode with FIRC at 48 MHz (no external crystal required) * S32K1XX_CLOCK_80MHZ: RUN mode at 80 MHz from SOSC + SPLL. The crystal * frequency is S32K1XX_SOSC_FREQ (default 8 MHz). * S32K1XX_CODE_CACHE: enable the LMEM code cache for flash. - * To enable HSRUN mode (112 MHz), define S32K1XX_CLOCK_HSRUN (requires SOSC + SPLL) */ /* ============== ARM Cortex-M4 System Registers ============== */ @@ -689,21 +689,30 @@ */ #ifdef S32K1XX_CLOCK_80MHZ -/* Switch the core to 80 MHz (SOSC + SPLL). For an application started by - * wolfBoot, which hands over on the SIRC or FIRC. The LPUART keeps its FIRC - * clock. */ -void s32k1xx_clock_80mhz(void); +/* Switch the core to RUN at 80 MHz (SOSC + SPLL), from RUN on any clock or + * from HSRUN. For an application started by wolfBoot, which hands over on + * the SIRC or FIRC. The LPUART keeps its FIRC clock. + * + * These calls bound each wait for the crystal, the SPLL, the clock switch + * and the power mode (S32K1XX_WAIT_LOOPS). They return 0 on success; -1 + * when a step fails, with the core back in RUN on the FIRC at + * S32K1XX_FIRC_CLOCK_SPEED (started if it was off); or -2 when even that + * fallback fails and the clock is unknown. s32k1xx_clock_hsrun() also + * returns -1, with the clock unchanged, if HSRUN cannot be allowed + * (SMC_PMPROT already written without AHSRUN). */ +#define S32K1XX_FIRC_CLOCK_SPEED 48000000UL +int s32k1xx_clock_80mhz(void); /* Switch between HSRUN at 112 MHz and RUN at 80 MHz. Flash cannot be - * programmed or erased in HSRUN. s32k1xx_clock_hsrun() returns -1 if HSRUN - * cannot be allowed (SMC_PMPROT already written without AHSRUN). */ + * programmed or erased in HSRUN. */ #define S32K1XX_HSRUN_CLOCK_SPEED 112000000UL int s32k1xx_clock_hsrun(void); -void s32k1xx_clock_run(void); +int s32k1xx_clock_run(void); #endif #ifdef S32K1XX_CODE_CACHE /* Enable the LMEM code cache for flash. The HAL flash erase and program - * functions invalidate it. */ -void s32k1xx_code_cache_enable(void); + * functions invalidate it. Returns 0, or -1 with the cache off when its + * invalidate does not finish. */ +int s32k1xx_code_cache_enable(void); #endif #ifdef DEBUG_UART diff --git a/src/string.c b/src/string.c index ec7ed3a605..3ad2895a8f 100644 --- a/src/string.c +++ b/src/string.c @@ -302,8 +302,16 @@ size_t strlen(const char *s) #undef RAMFUNCTION #define RAMFUNCTION #endif -#if defined(FAST_MEMCPY) && defined(__ARM_FEATURE_UNALIGNED) && \ - defined(__GNUC__) +/* Word copies from unaligned sources: M-profile only. Its cores load words + * from any Normal memory address (CCR.UNALIGN_TRP clear at reset); an + * A-profile core with the MMU off faults on any unaligned access, and + * AArch64 defines __ARM_FEATURE_UNALIGNED without -mstrict-align. */ +#if defined(FAST_MEMCPY) && defined(__GNUC__) && \ + defined(__ARM_FEATURE_UNALIGNED) && defined(__ARM_ARCH_PROFILE) && \ + (__ARM_ARCH_PROFILE == 'M') + #define WOLFBOOT_MEMCPY_UNALIGNED +#endif +#ifdef WOLFBOOT_MEMCPY_UNALIGNED /* A 32-bit word at any address. aligned(1) lets the compiler emit a plain * (unaligned) word access; may_alias lets it alias the byte buffers. */ typedef uint32_t __attribute__((aligned(1), may_alias)) wb_u32_unaligned; @@ -315,21 +323,18 @@ void RAMFUNCTION *memcpy(void *dst, const void *src, size_t n) size_t i; const char *s = (const char *)src; char *d = (char *)dst; -#if defined(FAST_MEMCPY) && defined(__ARM_FEATURE_UNALIGNED) && \ - defined(__GNUC__) +#ifdef WOLFBOOT_MEMCPY_UNALIGNED const wb_u32_unaligned *sw; wb_u32_alias *dw; uint32_t w0, w1, w2, w3; size_t blocks; #endif -#if defined(FAST_MEMCPY) && defined(__ARM_FEATURE_UNALIGNED) && \ - defined(__GNUC__) - /* The core loads words from any address (e.g. ARMv7-M with - * CCR.UNALIGN_TRP clear), so the source alignment does not matter: - * align the destination, then copy words. Network stacks copy payloads - * at 2 mod 4 offsets, which the aligned-only path below never speeds - * up. Normal memory only, as for any word access. */ +#ifdef WOLFBOOT_MEMCPY_UNALIGNED + /* The core loads words from any address, so the source alignment does + * not matter: align the destination, then copy words. Network stacks + * copy payloads at 2 mod 4 offsets, which the aligned-only path below + * never speeds up. Normal memory only, as for any word access. */ if (n >= 2 * sizeof(uint32_t)) { while (((size_t)d & (sizeof(uint32_t) - 1)) != 0) { *d++ = *s++; diff --git a/test-app/ARM-s32k1xx-wolfip.ld b/test-app/ARM-s32k1xx-wolfip.ld index 859a12962e..cebd325faf 100644 --- a/test-app/ARM-s32k1xx-wolfip.ld +++ b/test-app/ARM-s32k1xx-wolfip.ld @@ -4,8 +4,8 @@ * The application runs from the boot partition after the wolfBoot header. * RAM is SRAM_U. The wolfIP stack state (wolfip.o .bss: sockets and their * buffers) goes in SRAM_L, which the ENET DMA and eDMA reach through its - * backdoor port. Both are outside the code cache while it is disabled (the - * default); enabling the cache for SRAM_L would break the DMA coherency. + * backdoor port. Neither is cached, even with the LMEM code cache on: it + * caches only Program Flash (region 0), so the DMA stays coherent. * The hottest code (memcpy and wolfIP's checksum loop) runs from SRAM_L too * (.ramcode_l), so the core fetches it over the code bus while its data * accesses use the system bus. diff --git a/test-app/Makefile b/test-app/Makefile index c67b0c36bf..0aa4a40d0c 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1784,7 +1784,7 @@ ifeq ($(ENABLE_WOLFIP),1) WOLFIP_PORT:=nxp_mcxe_enet WOLFIP_PORT_OBJ:=nxp_mcxe_enet.o LSCRIPT_TEMPLATE=ARM-s32k1xx-wolfip.ld - # Clear all of SRAM_U at reset, before the stack is used (ECC) + # Clear all of SRAM_L and SRAM_U at reset, before the stack is used (ECC) CFLAGS+=-DAPP_RAM_ECC_INIT # Hot code in SRAM_L (.ramcode_l in ARM-s32k1xx-wolfip.ld) CFLAGS+=-DAPP_RAMCODE_L diff --git a/test-app/app_s32k1xx.c b/test-app/app_s32k1xx.c index 95bb1fb7d7..1a6aeaa6c0 100644 --- a/test-app/app_s32k1xx.c +++ b/test-app/app_s32k1xx.c @@ -107,6 +107,10 @@ static void delay_ms(uint32_t ms) } } +/* Core clock in RUN mode: CLOCK_SPEED, or the FIRC when the 80 MHz SPLL + * setup failed */ +static uint32_t run_clock_hz = CLOCK_SPEED; + /* 1 ms tick from the core clock running at core_hz */ static void systick_set(uint32_t core_hz) { @@ -117,7 +121,7 @@ static void systick_set(uint32_t core_hz) static void systick_init(void) { - systick_set(CLOCK_SPEED); + systick_set(run_clock_hz); } /* ============== LED Functions ============== */ @@ -447,228 +451,7 @@ static void print_keystore_info(void) /* ============== XMODEM Transfer ============== */ -#define XSOH 0x01 -#define XEOT 0x04 -#define XACK 0x06 -#define XNAK 0x15 -#define XCAN 0x18 -#define XCRC 'C' /* Request CRC mode */ - -#define XMODEM_PAYLOAD_SIZE 128 -#define XMODEM_PACKET_SIZE_CRC (3 + XMODEM_PAYLOAD_SIZE + 2) /* SOH + blk + ~blk + data + CRC16 */ -#define XMODEM_TIMEOUT_MS 1000 -/* Space in the update partition below its trailer sectors */ -#define XMODEM_MAX_SIZE (WOLFBOOT_PARTITION_SIZE - \ - (WOLFBOOT_TRAILER_SECTORS * WOLFBOOT_SECTOR_SIZE)) - -/* CRC-16-CCITT for XMODEM-CRC mode */ -static uint16_t APP_RAMFUNCTION crc16_ccitt(const uint8_t* data, int len) -{ - uint16_t crc = 0; - int i, j; - for (i = 0; i < len; i++) { - crc ^= ((uint16_t)data[i] << 8); - for (j = 0; j < 8; j++) { - if (crc & 0x8000) { - crc = (crc << 1) ^ 0x1021; - } else { - crc <<= 1; - } - } - } - return crc; -} - -/* Raw byte transmit for XMODEM (declared in hal, runs from RAM) */ -extern void uart_tx(uint8_t byte); - -/* RAM-based memory copy for use during flash operations */ -static void APP_RAMFUNCTION ram_memcpy(void *dst, const void *src, uint32_t len) -{ - uint8_t *d = (uint8_t *)dst; - const uint8_t *s = (const uint8_t *)src; - while (len--) { - *d++ = *s++; - } -} - -static void APP_RAMFUNCTION xmodem_cancel(void) -{ - int i; - for (i = 0; i < 10; i++) { - uart_tx(XCAN); - } -} - -/* XMODEM receive state - passed to RAM function */ -typedef struct { - uint32_t dst_offset; - int result; - /* Debug counters */ - uint32_t pkts_received; - uint32_t pkts_crc_fail; - uint32_t pkts_num_fail; - uint32_t pkts_soh_fail; - uint32_t timeouts; -} xmodem_state_t; - -/* Core XMODEM-CRC receive loop - runs entirely from RAM during flash operations - * Uses XMODEM-CRC mode (133-byte packets with 16-bit CRC) - * Returns: 0 on success, -1 on error - */ -static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) -{ - uint8_t xpkt[XMODEM_PACKET_SIZE_CRC]; - uint8_t payload[XMODEM_PAYLOAD_SIZE]; - uint8_t pkt_num = 0, pkt_num_expected = 0xFF; - uint32_t t_size = 0; - uint32_t img_size; - uint32_t now; - uint32_t i = 0; - int transfer_started = 0; - int eot_expected = 0; - int dup; - int ret = -1; - - state->dst_offset = 0; - state->result = -1; - state->pkts_received = 0; - state->pkts_crc_fail = 0; - state->pkts_num_fail = 0; - state->pkts_soh_fail = 0; - state->timeouts = 0; - - /* Send 'C' to request CRC mode (XMODEM-CRC) */ - uart_tx(XCRC); - - while (1) { - now = jiffies; /* Direct access to volatile - faster than function call */ - i = 0; - - /* Receive packet - uses interrupt-buffered RX to avoid FIFO overflow */ - while (i < XMODEM_PACKET_SIZE_CRC) { - int r = uart_rx_isr(&xpkt[i], XMODEM_PACKET_SIZE_CRC - i); - if (r > 0) { - i += r; - now = jiffies; - if (i >= 1 && xpkt[0] == XEOT) { - break; /* End of transmission */ - } - } else if (jiffies > (now + XMODEM_TIMEOUT_MS)) { - now = jiffies; - state->timeouts++; - if (i == 0) { - uart_tx(XCRC); /* Request CRC mode again */ - } - i = 0; - } - } - - /* Check for EOT */ - if (xpkt[0] == XEOT) { - uart_tx(XACK); - led_red_on(); /* Indicate transfer complete */ - ret = 0; - break; - } - - /* Validate SOH */ - if (xpkt[0] != XSOH) { - state->pkts_soh_fail++; - continue; - } - state->pkts_received++; - - /* Validate packet number */ - pkt_num = xpkt[1]; - if ((uint8_t)(~xpkt[2]) == pkt_num) { - uint16_t recv_crc, calc_crc; - - dup = 0; - if (!transfer_started) { - pkt_num_expected = pkt_num; - transfer_started = 1; - } else if (state->dst_offset > 0U && - pkt_num == (uint8_t)(pkt_num_expected - 1U)) { - /* The last block again: the sender missed its ACK */ - dup = 1; - } else if (pkt_num_expected != pkt_num) { - uart_tx(XNAK); - continue; - } - - /* Toggle LED to show activity */ - if ((pkt_num & 0x0F) == 0) { - led_red_on(); - } else if ((pkt_num & 0x0F) == 8) { - led_red_off(); - } - - /* Validate CRC-16 - XMODEM-CRC uses CRC over DATA bytes only */ - recv_crc = ((uint16_t)xpkt[XMODEM_PACKET_SIZE_CRC - 2] << 8) | - xpkt[XMODEM_PACKET_SIZE_CRC - 1]; - calc_crc = crc16_ccitt(xpkt + 3, XMODEM_PAYLOAD_SIZE); - - if (recv_crc == calc_crc && dup) { - /* Already written: only ACK it again */ - uart_tx(XACK); - } else if (recv_crc == calc_crc) { - /* A block past the end of the image, or one that would reach - * the trailer sectors of the update partition */ - if (eot_expected || - state->dst_offset + XMODEM_PAYLOAD_SIZE > XMODEM_MAX_SIZE) { - xmodem_cancel(); - ret = -1; - break; - } - /* The image size (header offset 4) must fit, checked before - * the first block is ACKed or written */ - if (state->dst_offset == 0U) { - ram_memcpy(&img_size, xpkt + 3 + 4, sizeof(img_size)); - if (img_size > XMODEM_MAX_SIZE - IMAGE_HEADER_SIZE) { - xmodem_cancel(); - ret = -1; - break; - } - t_size = img_size + IMAGE_HEADER_SIZE; - } - - /* Copy payload using RAM-based memcpy */ - ram_memcpy(payload, xpkt + 3, XMODEM_PAYLOAD_SIZE); - - /* Send ACK first, then write to flash. - * This allows sender to prepare next packet while we write. - * Risk: if write fails, we've already ACKed - but that's rare. - */ - uart_tx(XACK); - - /* Write to flash */ - ret = hal_flash_write(WOLFBOOT_PARTITION_UPDATE_ADDRESS + state->dst_offset, - payload, XMODEM_PAYLOAD_SIZE); - if (ret != 0) { - xmodem_cancel(); - /* No printf here - we're in RAM */ - break; - } - pkt_num_expected++; - state->dst_offset += XMODEM_PAYLOAD_SIZE; - - if (state->dst_offset >= t_size) { - eot_expected = 1; - } - } else { - state->pkts_crc_fail++; - uart_tx(XNAK); - } - } else { - state->pkts_num_fail++; - uart_tx(XNAK); - } - } - - state->result = ret; - return ret; -} +#include "xmodem_rx.c" static int cmd_update_xmodem(void) { @@ -934,19 +717,44 @@ static int cmd_update(const char *args) #define NETWORK_TEST_HSRUN #endif +#ifdef NETWORK_TEST_HSRUN +/* Back to RUN at 80 MHz, or the FIRC if the SPLL fails */ +static void network_clock_run(void) +{ + int ret = s32k1xx_clock_run(); + + if (ret == 0) { + run_clock_hz = CLOCK_SPEED; + } + else { + run_clock_hz = S32K1XX_FIRC_CLOCK_SPEED; + printf("80 MHz clock failed (%d), running at 48 MHz\r\n", ret); + } + systick_set(run_clock_hz); +} +#endif + static int cmd_network(const char *args) { +#ifdef NETWORK_TEST_HSRUN + int ret; +#endif + (void)args; #ifdef NETWORK_TEST_HSRUN - if (s32k1xx_clock_hsrun() == 0) + ret = s32k1xx_clock_hsrun(); + if (ret == 0) { systick_set(S32K1XX_HSRUN_CLOCK_SPEED); - else - printf("HSRUN not allowed, staying at 80 MHz\r\n"); + } + else { + printf("HSRUN failed (%d), running the test in RUN mode\r\n", ret); + network_clock_run(); + } #endif wolfip_tftp_test_report(); #ifdef NETWORK_TEST_HSRUN - s32k1xx_clock_run(); - systick_set(CLOCK_SPEED); + if (ret == 0) + network_clock_run(); #endif return 0; } @@ -1053,6 +861,12 @@ static void clock_ensure_firc(void) void main(void) { uint32_t version; +#ifdef S32K1XX_CLOCK_80MHZ + int clock_ret; +#endif +#ifdef S32K1XX_CODE_CACHE + int cache_ret; +#endif /* Disable watchdog - bootloader may have enabled it */ WDOG_CNT = WDOG_CNT_UNLOCK; @@ -1064,12 +878,15 @@ void main(void) /* Ensure FIRC clock is running at 48 MHz for UART */ clock_ensure_firc(); #ifdef S32K1XX_CLOCK_80MHZ - /* wolfBoot hands over on SIRC or FIRC: run the core at 80 MHz. The UART - * stays on FIRC; SysTick follows CLOCK_SPEED. */ - s32k1xx_clock_80mhz(); + /* wolfBoot hands over on SIRC or FIRC: run the core at 80 MHz, or stay + * on the FIRC if that fails. The UART stays on FIRC; SysTick follows + * run_clock_hz. */ + clock_ret = s32k1xx_clock_80mhz(); + if (clock_ret != 0) + run_clock_hz = S32K1XX_FIRC_CLOCK_SPEED; #endif #ifdef S32K1XX_CODE_CACHE - s32k1xx_code_cache_enable(); + cache_ret = s32k1xx_code_cache_enable(); #endif #ifdef DEBUG_UART @@ -1105,6 +922,14 @@ void main(void) printf("Copyright 2025-2026 wolfSSL Inc.\r\n"); printf("========================================\r\n"); printf("Firmware Version: %lu\r\n", (unsigned long)version); +#ifdef S32K1XX_CLOCK_80MHZ + if (clock_ret != 0) + printf("80 MHz clock failed (%d), running at 48 MHz\r\n", clock_ret); +#endif +#ifdef S32K1XX_CODE_CACHE + if (cache_ret != 0) + printf("Code cache invalidate failed, cache off\r\n"); +#endif /* Auto-mark success for testing if version > 1 */ if (version > 1) { diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index 9c2bc607a2..1b90d98258 100644 --- a/test-app/startup_arm.c +++ b/test-app/startup_arm.c @@ -61,14 +61,13 @@ extern void isr_debug_uart(void); #define isr_lpuart1 isr_debug_uart #define isr_lpuart2 isr_empty #endif -/* MCXE247 ENET transmit, receive and error interrupts (IRQ 73-75) */ +/* MCXE247 ENET receive and error interrupts (IRQ 74 and 75); the driver + * does not use the transmit interrupt (73) */ #if defined(MCXE247) && defined(NXP_MCXE_ENET_IRQ) && (NXP_MCXE_ENET_IRQ == 1) extern void nxp_mcxe_enet_irq_handler(void); -#define isr_irq73 nxp_mcxe_enet_irq_handler #define isr_irq74 nxp_mcxe_enet_irq_handler #define isr_irq75 nxp_mcxe_enet_irq_handler #else -#define isr_irq73 isr_empty #define isr_irq74 isr_empty #define isr_irq75 isr_empty #endif @@ -586,7 +585,7 @@ void (* const IV[])(void) = isr_empty, // CAN0_MB16_31 70 isr_empty, // FTM0_Ch0_Ch1 71 isr_empty, // FTM0_Ch2_Ch3 72 - isr_irq73, // FTM0_Ch4_Ch5 73 (MCXE247: ENET_Transmit) + isr_empty, // FTM0_Ch4_Ch5 73 (MCXE247: ENET_Transmit) isr_irq74, // FTM0_Ch6_Ch7 74 (MCXE247: ENET_Receive) isr_irq75, // FTM0_Fault 75 (MCXE247: ENET_Error) isr_empty, // FTM0_Ovf_Reload 76 diff --git a/test-app/wolfip_tftp_test.c b/test-app/wolfip_tftp_test.c index 3f2752b124..a13edfac73 100644 --- a/test-app/wolfip_tftp_test.c +++ b/test-app/wolfip_tftp_test.c @@ -450,24 +450,38 @@ static int run_tftp_fetch(struct wolfIP *s) * TCP: the first byte the client sends picks the direction: 'r' rx, * 't' tx, anything else bidir. A client that sends nothing for * SPEED_TCP_MODE_MS gets bidir, so plain "nc 9" works whether or not - * it sends. The test ends when the client closes. TCP clients are refused - * while a UDP test runs. + * it sends. The test ends when the client closes, or when no data moves + * either way for SPEED_TCP_IDLE_MS (a client gone without a FIN or RST). + * TCP clients are refused while a UDP test runs. * * UDP: each datagram starts with a SPEED_HDR_LEN byte header, big-endian: * [0] SPEED_MAGIC [1] command [2..3] board datagram size - * [4..7] sequence [8..11] board send duration in ms - * [12..15] session: a non-zero id the host picks for each test. Data of - * a test that has ended is ignored, so datagrams still queued - * on the way cannot start a new test. + * [4..7] sequence, or the test mode for 'o' + * [8..11] test duration in ms, at most SPEED_MAX_MS + * [12..15] session: a non-zero id the host picks for each test * Commands to the board: - * 'r' data to count (starts an rx test) - * 'b' data to count; the first one starts a bidir test and the board - * sends to the client for the given duration, which also ends - * the test - * 't' start a tx test: the board sends to the client for the duration - * 'q' end the current UDP test and reply with an 'S' stats datagram + * 'o' open a test of mode [7] ('r' rx, 't' tx, 'b' bidir). The board + * replies 'O' (also to a repeated 'o' of the open test), or 'B' + * while another test runs. A tx test starts here: the board sends + * to the client for the duration, which ends the test. + * 'r' rx data to count; the first one starts the test window + * 'b' bidir data to count; the first one starts the test window and + * the board sends to the client for the duration, which ends the + * test + * 'q' reply with an 'S' stats datagram, after ending the UDP test of + * this session if it runs (session 0 ends nothing) * The board's own datagrams carry command 'd'. * + * Only an 'o' starts a test, and data and 'q' only act on the test of + * their session, so datagrams still queued from an earlier test cannot + * start, end or feed another one. An 'o' of one of the last + * SPEED_ENDED_NUM tests is ignored too. A test the host abandons ends + * SPEED_GRACE_MS after its duration. + * + * The server has no authentication: anyone who reaches port 9 can start + * a test, and a tx or bidir test sends to the address the 'o' came from + * for up to SPEED_MAX_MS. Run it on a trusted lab network only. + * * The 'S' reply describes the last test, TCP or UDP, so the host can fetch * the board's counters after a TCP test too. Each finished test is also * printed on the console. Ctrl-C on the console stops the server. */ @@ -480,9 +494,18 @@ static int run_tftp_fetch(struct wolfIP *s) #define SPEED_PROTO_TCP 1U #define SPEED_PROTO_UDP 2U #define SPEED_REPLY_LEN 108 +/* Longest UDP test the board runs, whatever the host asks for */ +#define SPEED_MAX_MS 60000U +/* A UDP test whose host stops sending or asking ends this long after its + * duration */ +#define SPEED_GRACE_MS 2000U +/* Finished UDP sessions whose late 'o' is ignored */ +#define SPEED_ENDED_NUM 4 /* A TCP client that sends no direction byte this long after it connects * gets a bidir test */ #define SPEED_TCP_MODE_MS 500U +/* A TCP test in which no data moves either way for this long ends */ +#define SPEED_TCP_IDLE_MS 5000U /* How often the server checks for Ctrl-C on the console */ #define SPEED_ABORT_POLL_MS 100U @@ -509,6 +532,9 @@ struct speed_state { uint64_t start_ms; uint64_t end_ms; uint64_t stream_end_ms; + uint64_t deadline_ms; /* a UDP test ends here at the latest */ + uint64_t last_io_ms; /* a TCP test last moved data here */ + uint32_t dur_ms; /* UDP test duration */ uint32_t rx_pkts; uint32_t tx_pkts; uint32_t tx_seq; @@ -518,6 +544,7 @@ struct speed_state { uint8_t proto; uint8_t mode; /* 'r', 't', 'b'; 0 until a TCP client sends */ uint8_t active; + uint8_t started; /* the test window runs */ uint8_t streaming; }; @@ -525,7 +552,8 @@ static int speed_listen_fd = -1; static int speed_client_fd = -1; static int speed_udp_fd = -1; static struct speed_state speed; -static uint32_t speed_ended_session; /* last UDP test that ended */ +static uint32_t speed_ended[SPEED_ENDED_NUM]; /* last UDP tests that ended */ +static uint32_t speed_ended_idx; static struct wolfIP_sockaddr_in speed_peer; static uint8_t speed_rxbuf[SPEED_UDP_MAX]; static uint8_t speed_txbuf[SPEED_UDP_MAX]; @@ -627,16 +655,38 @@ static void speed_print(void) #endif } +/* Start the test window: TCP and UDP tx tests when they open, UDP rx and + * bidir tests at their first data. */ +static void speed_window_start(uint64_t now) +{ + speed.start_ms = now; + speed.started = 1U; +#if SPEED_PROFILE + nxp_mcxe_enet_stats_reset(); +#endif +} + static void speed_start(uint8_t proto, uint8_t mode, uint64_t now) { zmem(&speed, sizeof(speed)); speed.proto = proto; speed.mode = mode; speed.start_ms = now; + speed.last_io_ms = now; speed.active = 1U; -#if SPEED_PROFILE - nxp_mcxe_enet_stats_reset(); -#endif + if (proto == SPEED_PROTO_TCP || mode == 't') + speed_window_start(now); +} + +static int speed_session_ended(uint32_t session) +{ + int i; + + for (i = 0; i < SPEED_ENDED_NUM; i++) { + if (speed_ended[i] == session) + return 1; + } + return 0; } static void speed_stop(uint64_t now) @@ -646,7 +696,10 @@ static void speed_stop(uint64_t now) speed.active = 0U; speed.streaming = 0U; speed.end_ms = now; - speed_ended_session = speed.session; + if (speed.proto == SPEED_PROTO_UDP) { + speed_ended[speed_ended_idx] = speed.session; + speed_ended_idx = (speed_ended_idx + 1U) % SPEED_ENDED_NUM; + } #if SPEED_PROFILE nxp_mcxe_enet_stats_get(&speed_drv); #endif @@ -725,9 +778,19 @@ static void speed_tcp_pump(struct wolfIP *s, uint64_t now) { int n; int k; + int fd; if (speed_client_fd < 0) return; + if (now >= speed.last_io_ms + SPEED_TCP_IDLE_MS) { + /* the client is gone: wolfIP has no keepalive, and an rx test + * never sends, so no retransmission timeout would end it */ + fd = speed_client_fd; + speed_client_fd = -1; + speed_stop(speed.last_io_ms); + (void)wolfIP_sock_close(s, fd); + return; + } for (k = 0; k < SPEED_BURST; k++) { n = wolfIP_sock_recvfrom(s, speed_client_fd, speed_rxbuf, SPEED_TCP_CHUNK, 0, NULL, NULL); @@ -743,6 +806,7 @@ static void speed_tcp_pump(struct wolfIP *s, uint64_t now) } } speed.rx_bytes += (uint32_t)n; + speed.last_io_ms = now; } if (speed.mode == 0U && now >= speed.start_ms + SPEED_TCP_MODE_MS) speed.mode = 'b'; @@ -754,14 +818,69 @@ static void speed_tcp_pump(struct wolfIP *s, uint64_t now) if (n <= 0) break; speed.tx_bytes += (uint32_t)n; + speed.last_io_ms = now; + } +} + +/* Answer an 'o' or a refused one with a header-only datagram */ +static void speed_ack(struct wolfIP *s, const struct wolfIP_sockaddr_in *to, + uint8_t cmd, uint32_t session) +{ + uint8_t r[SPEED_HDR_LEN]; + + zmem(r, sizeof(r)); + r[0] = SPEED_MAGIC; + r[1] = cmd; + r[2] = (uint8_t)(speed.stream_len >> 8); + r[3] = (uint8_t)speed.stream_len; + speed_put32(r + 8, speed.dur_ms); + speed_put32(r + 12, session); + (void)wolfIP_sock_sendto(s, speed_udp_fd, r, sizeof(r), 0, + (const struct wolfIP_sockaddr *)to, sizeof(*to)); +} + +/* 'o': open a UDP test, unless one runs */ +static void speed_udp_open(struct wolfIP *s, + const struct wolfIP_sockaddr_in *from, + uint32_t session, uint64_t now) +{ + uint8_t mode = speed_rxbuf[7]; + uint8_t reply = 'O'; + uint32_t len; + uint32_t dur; + + if (session == 0U || (mode != 'r' && mode != 't' && mode != 'b') || + speed_session_ended(session)) + return; /* invalid, or a late copy of an old 'o' */ + if (speed.active != 0U) { + if (speed.proto != SPEED_PROTO_UDP || session != speed.session) + reply = 'B'; /* another test runs */ + } + else { + dur = speed_get32(speed_rxbuf + 8); + if (dur > SPEED_MAX_MS) + dur = SPEED_MAX_MS; + len = ((uint32_t)speed_rxbuf[2] << 8) | speed_rxbuf[3]; + if (len < (uint32_t)SPEED_HDR_LEN || len > SPEED_UDP_MAX) + len = SPEED_UDP_MAX; + speed_start(SPEED_PROTO_UDP, mode, now); + speed.session = session; + speed.dur_ms = dur; + speed.stream_len = len; + speed.deadline_ms = now + dur + SPEED_GRACE_MS; + speed_peer = *from; + if (mode == 't') { + speed.stream_end_ms = now + dur; + speed.streaming = 1U; + } } + speed_ack(s, from, reply, session); } static void speed_udp_recv(struct wolfIP *s, uint64_t now) { struct wolfIP_sockaddr_in from; socklen_t from_len; - uint32_t len; uint32_t session; uint8_t cmd; int n; @@ -777,38 +896,32 @@ static void speed_udp_recv(struct wolfIP *s, uint64_t now) if (n < SPEED_HDR_LEN || speed_rxbuf[0] != SPEED_MAGIC) continue; cmd = speed_rxbuf[1]; + session = speed_get32(speed_rxbuf + 12); if (cmd == 'q') { - if (speed.proto == SPEED_PROTO_UDP) + if (speed.active != 0U && speed.proto == SPEED_PROTO_UDP && + session == speed.session) speed_stop(now); speed_reply(s, &from, now); continue; } - if (cmd != 'r' && cmd != 'b' && cmd != 't') + if (cmd == 'o') { + speed_udp_open(s, &from, session, now); continue; - if (speed.active != 0U && speed.proto == SPEED_PROTO_TCP) - continue; /* a TCP test is running */ - session = speed_get32(speed_rxbuf + 12); - if (session == 0U || session == speed_ended_session) - continue; /* left over from a finished test */ - if (speed.active != 0U && session != speed.session) - speed_stop(now); /* the host started a new test */ - if (speed.active == 0U) { - speed_start(SPEED_PROTO_UDP, cmd, now); - speed.session = session; - speed_peer = from; - if (cmd != 'r') { - len = ((uint32_t)speed_rxbuf[2] << 8) | speed_rxbuf[3]; - if (len < (uint32_t)SPEED_HDR_LEN || len > SPEED_UDP_MAX) - len = SPEED_UDP_MAX; - speed.stream_len = len; - speed.stream_end_ms = now + speed_get32(speed_rxbuf + 8); + } + if ((cmd != 'r' && cmd != 'b') || speed.active == 0U || + speed.proto != SPEED_PROTO_UDP || session != speed.session || + cmd != speed.mode) + continue; /* not data of the running test */ + if (speed.started == 0U) { + speed_window_start(now); + speed.deadline_ms = now + speed.dur_ms + SPEED_GRACE_MS; + if (cmd == 'b') { + speed.stream_end_ms = now + speed.dur_ms; speed.streaming = 1U; } } - if (cmd != 't') { - speed.rx_bytes += (uint32_t)n; - speed.rx_pkts++; - } + speed.rx_bytes += (uint32_t)n; + speed.rx_pkts++; } } @@ -817,6 +930,11 @@ static void speed_udp_send(struct wolfIP *s, uint64_t now) int n; int k; + if (speed.active != 0U && speed.proto == SPEED_PROTO_UDP && + now >= speed.deadline_ms) { + speed_stop(now); /* the host stopped sending and asking */ + return; + } if (speed.streaming == 0U) return; if (now >= speed.stream_end_ms) { @@ -917,7 +1035,7 @@ static int run_speed_server(struct wolfIP *s) speed_udp_recv(s, now); speed_udp_send(s, now); c_done = SPEED_CYCLES(); - if (speed.active != 0U) { + if (speed.started != 0U && speed.active != 0U) { speed.cyc_busy += c_done - c_poll; speed.cyc_total += c_done - c_prev; speed.polls++; diff --git a/test-app/xmodem_rx.c b/test-app/xmodem_rx.c new file mode 100644 index 0000000000..109eee5e0f --- /dev/null +++ b/test-app/xmodem_rx.c @@ -0,0 +1,248 @@ +/* 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. + * + * 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 + */ + +#define XSOH 0x01 +#define XEOT 0x04 +#define XACK 0x06 +#define XNAK 0x15 +#define XCAN 0x18 +#define XCRC 'C' /* Request CRC mode */ + +#define XMODEM_PAYLOAD_SIZE 128 +#define XMODEM_PACKET_SIZE_CRC (3 + XMODEM_PAYLOAD_SIZE + 2) /* SOH + blk + ~blk + data + CRC16 */ +#define XMODEM_TIMEOUT_MS 1000 +/* Space in the update partition below its trailer sectors */ +#define XMODEM_MAX_SIZE (WOLFBOOT_PARTITION_SIZE - \ + (WOLFBOOT_TRAILER_SECTORS * WOLFBOOT_SECTOR_SIZE)) + +/* CRC-16-CCITT for XMODEM-CRC mode */ +static uint16_t APP_RAMFUNCTION crc16_ccitt(const uint8_t* data, int len) +{ + uint16_t crc = 0; + int i, j; + for (i = 0; i < len; i++) { + crc ^= ((uint16_t)data[i] << 8); + for (j = 0; j < 8; j++) { + if (crc & 0x8000) { + crc = (crc << 1) ^ 0x1021; + } else { + crc <<= 1; + } + } + } + return crc; +} + +/* Raw byte transmit for XMODEM (declared in hal, runs from RAM) */ +extern void uart_tx(uint8_t byte); + +/* RAM-based memory copy for use during flash operations */ +static void APP_RAMFUNCTION ram_memcpy(void *dst, const void *src, uint32_t len) +{ + uint8_t *d = (uint8_t *)dst; + const uint8_t *s = (const uint8_t *)src; + while (len--) { + *d++ = *s++; + } +} + +static void APP_RAMFUNCTION xmodem_cancel(void) +{ + int i; + for (i = 0; i < 10; i++) { + uart_tx(XCAN); + } +} + +/* XMODEM receive state - passed to RAM function */ +typedef struct { + uint32_t dst_offset; + int result; + /* Debug counters */ + uint32_t pkts_received; + uint32_t pkts_crc_fail; + uint32_t pkts_num_fail; + uint32_t pkts_soh_fail; + uint32_t timeouts; +} xmodem_state_t; + +/* Core XMODEM-CRC receive loop - runs entirely from RAM during flash operations + * Uses XMODEM-CRC mode (133-byte packets with 16-bit CRC) + * Returns: 0 on success, -1 on error + */ +static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) +{ + uint8_t xpkt[XMODEM_PACKET_SIZE_CRC]; + uint8_t payload[XMODEM_PAYLOAD_SIZE]; + uint8_t pkt_num = 0, pkt_num_expected = 0xFF; + uint32_t t_size = 0; + uint32_t img_size; + uint32_t now; + uint32_t i = 0; + int transfer_started = 0; + int eot_expected = 0; + int dup; + int ret = -1; + + state->dst_offset = 0; + state->result = -1; + state->pkts_received = 0; + state->pkts_crc_fail = 0; + state->pkts_num_fail = 0; + state->pkts_soh_fail = 0; + state->timeouts = 0; + + /* Send 'C' to request CRC mode (XMODEM-CRC) */ + uart_tx(XCRC); + + while (1) { + now = jiffies; /* Direct access to volatile - faster than function call */ + i = 0; + + /* Receive packet - uses interrupt-buffered RX to avoid FIFO overflow */ + while (i < XMODEM_PACKET_SIZE_CRC) { + int r = uart_rx_isr(&xpkt[i], XMODEM_PACKET_SIZE_CRC - i); + if (r > 0) { + i += r; + now = jiffies; + if (i >= 1 && xpkt[0] == XEOT) { + break; /* End of transmission */ + } + } else if (jiffies > (now + XMODEM_TIMEOUT_MS)) { + now = jiffies; + state->timeouts++; + if (i == 0) { + uart_tx(XCRC); /* Request CRC mode again */ + } + i = 0; + } + } + + /* Check for EOT */ + if (xpkt[0] == XEOT) { + uart_tx(XACK); + led_red_on(); /* Indicate transfer complete */ + ret = 0; + break; + } + + /* Validate SOH */ + if (xpkt[0] != XSOH) { + state->pkts_soh_fail++; + continue; + } + state->pkts_received++; + + /* Validate packet number */ + pkt_num = xpkt[1]; + if ((uint8_t)(~xpkt[2]) == pkt_num) { + uint16_t recv_crc, calc_crc; + + dup = 0; + if (!transfer_started) { + pkt_num_expected = pkt_num; + transfer_started = 1; + } else if (state->dst_offset > 0U && + pkt_num == (uint8_t)(pkt_num_expected - 1U)) { + /* The last block again: the sender missed its ACK */ + dup = 1; + } else if (pkt_num_expected != pkt_num) { + uart_tx(XNAK); + continue; + } + + /* Toggle LED to show activity */ + if ((pkt_num & 0x0F) == 0) { + led_red_on(); + } else if ((pkt_num & 0x0F) == 8) { + led_red_off(); + } + + /* Validate CRC-16 - XMODEM-CRC uses CRC over DATA bytes only */ + recv_crc = ((uint16_t)xpkt[XMODEM_PACKET_SIZE_CRC - 2] << 8) | + xpkt[XMODEM_PACKET_SIZE_CRC - 1]; + calc_crc = crc16_ccitt(xpkt + 3, XMODEM_PAYLOAD_SIZE); + + if (recv_crc == calc_crc && dup) { + /* Already written: only ACK it again */ + uart_tx(XACK); + } else if (recv_crc == calc_crc) { + /* A block past the end of the image, or one that would reach + * the trailer sectors of the update partition */ + if (eot_expected || + state->dst_offset + XMODEM_PAYLOAD_SIZE > XMODEM_MAX_SIZE) { + xmodem_cancel(); + ret = -1; + break; + } + /* The image size (header offset 4) must fit, checked before + * the first block is ACKed or written */ + if (state->dst_offset == 0U) { + ram_memcpy(&img_size, xpkt + 3 + 4, sizeof(img_size)); + if (img_size > XMODEM_MAX_SIZE - IMAGE_HEADER_SIZE) { + xmodem_cancel(); + ret = -1; + break; + } + t_size = img_size + IMAGE_HEADER_SIZE; + } + + /* Copy payload using RAM-based memcpy */ + ram_memcpy(payload, xpkt + 3, XMODEM_PAYLOAD_SIZE); + + /* Send ACK first, then write to flash. + * This allows sender to prepare next packet while we write. + * Risk: if write fails, we've already ACKed - but that's rare. + */ + uart_tx(XACK); + + /* Write to flash */ + ret = hal_flash_write(WOLFBOOT_PARTITION_UPDATE_ADDRESS + state->dst_offset, + payload, XMODEM_PAYLOAD_SIZE); + if (ret != 0) { + xmodem_cancel(); + /* No printf here - we're in RAM */ + break; + } + pkt_num_expected++; + state->dst_offset += XMODEM_PAYLOAD_SIZE; + + if (state->dst_offset >= t_size) { + eot_expected = 1; + } + } else { + state->pkts_crc_fail++; + uart_tx(XNAK); + } + } else { + state->pkts_num_fail++; + uart_tx(XNAK); + } + } + + state->result = ret; + return ret; +} diff --git a/tools/scripts/wolfip_speed.py b/tools/scripts/wolfip_speed.py index 9cc6a470f7..27e7634e3e 100644 --- a/tools/scripts/wolfip_speed.py +++ b/tools/scripts/wolfip_speed.py @@ -16,6 +16,8 @@ is what this host received from the board, timed by the host. UDP loss is datagrams sent but not received, per direction. +The board's server has no authentication; use it on a trusted network. + Standard library only; runs on Linux, macOS and Windows. """ @@ -35,6 +37,8 @@ # datagram costs on the wire beyond its payload WIRE_OVERHEAD = 8 + 14 + 4 + 12 + 20 + 8 TESTS = ["tcp-rx", "tcp-tx", "tcp-bidir", "udp-rx", "udp-tx", "udp-bidir"] +MAX_SECS = 60.0 # longest UDP test the board runs (SPEED_MAX_MS) +GRACE_SECS = 2.0 # an abandoned UDP test ends this long after it class Stats: @@ -79,12 +83,13 @@ def udp_socket(): return s -def query(sock, addr, want_proto, timeout=5.0): - """Send 'q' until the board reports the finished test of want_proto.""" +def query(sock, addr, want_proto, session=0, timeout=5.0): + """Send 'q' until the board reports the finished test of want_proto. + The 'q' also ends the UDP test of session, if it still runs.""" deadline = time.monotonic() + timeout sock.settimeout(0.3) while time.monotonic() < deadline: - sock.sendto(HDR.pack(MAGIC, ord("q"), 0, 0, 0, 0), addr) + sock.sendto(HDR.pack(MAGIC, ord("q"), 0, 0, 0, session), addr) end = time.monotonic() + 0.3 while time.monotonic() < end: try: @@ -98,6 +103,47 @@ def query(sock, addr, want_proto, timeout=5.0): raise RuntimeError("no stats reply from the board") +def open_test(sock, addr, mode, size, dur_ms, session, on_data): + """Send 'o' until the board opens the UDP test. on_data gets the + board's datagrams that arrive meanwhile (a tx test starts at the 'o'). + While the board is busy with another test, keep asking until that one + must have ended.""" + start = time.monotonic() + deadline = start + 5.0 + waiting = False + sock.settimeout(0.3) + while time.monotonic() < deadline: + sock.sendto(HDR.pack(MAGIC, ord("o"), size, ord(mode), dur_ms, + session), addr) + end = time.monotonic() + 0.3 + busy = False + while time.monotonic() < end and not busy: + try: + data, _ = sock.recvfrom(2048) + except socket.timeout: + break + if len(data) < HDR.size or data[0] != MAGIC: + continue + fields = HDR.unpack_from(data) + if fields[5] != session: + continue + if fields[1] == ord("O"): + return + if fields[1] == ord("B"): + busy = True + else: + on_data(data) + if busy: + if not waiting: + print(" the board runs another test, waiting for it to end", + file=sys.stderr, flush=True) + waiting = True + deadline = min(time.monotonic() + 5.0, + start + MAX_SECS + GRACE_SECS + 5.0) + time.sleep(0.5) + raise RuntimeError("the board did not open the test") + + def drain(sock): sock.settimeout(0) try: @@ -178,10 +224,9 @@ def worker(fn): return sent[0], recvd[0], elapsed -def udp_test(sock, addr, mode, secs, size, rate): +def udp_test(sock, addr, mode, secs, size, rate, session): """Returns (datagrams sent, datagrams received, bytes received, secs).""" dur_ms = int(secs * 1000) - session = random.randint(1, 0xFFFFFFFF) sent = [0] got = [0, 0] # datagrams, bytes first = [None] @@ -221,17 +266,12 @@ def drain_rx(): pass payload = bytearray(size) - t0 = time.monotonic() rx = None + open_test(sock, addr, mode, size, dur_ms, session, count) + t0 = time.monotonic() # after any wait for a busy board if mode == "t": rx = threading.Thread(target=receiver) rx.start() - if mode == "t": - sock.sendto(HDR.pack(MAGIC, ord("t"), size, 0, dur_ms, session), addr) - time.sleep(1.0) - if got[0] == 0: # start lost: try once more - sock.sendto(HDR.pack(MAGIC, ord("t"), size, 0, dur_ms, session), - addr) else: # bidir receives in this thread, between sends: a receiver thread # would wait for the GIL after every recvfrom() while the pacer @@ -267,12 +307,10 @@ def run_test(name, args): proto, direction = name.split("-") mode = {"rx": "r", "tx": "t", "bidir": "b"}[direction] addr = (args.ip, args.port) + session = random.randint(1, 0xFFFFFFFF) ctl = udp_socket() + done = False try: - # End any UDP test left running, so this one starts fresh (the - # board refuses TCP clients while a UDP test runs) - ctl.sendto(HDR.pack(MAGIC, ord("q"), 0, 0, 0, 0), addr) - time.sleep(0.3) drain(ctl) if proto == "tcp": h_sent, h_recv, h_secs = tcp_test(args.ip, args.port, mode, args.time) @@ -281,12 +319,20 @@ def run_test(name, args): loss_rx = loss_tx = None else: sent, got, got_bytes, span = udp_test(ctl, addr, mode, args.time, - args.size, args.rate) - st = query(ctl, addr, 2) + args.size, args.rate, + session) + st = query(ctl, addr, 2, session) host_tx = mbps(got_bytes, span) loss_rx = (100.0 * (sent - st.rx_pkts) / sent) if sent else None loss_tx = (100.0 * (st.tx_pkts - got) / st.tx_pkts) if st.tx_pkts else None + done = True finally: + if not done and proto == "udp": + # End the board's test now rather than at its deadline + try: + ctl.sendto(HDR.pack(MAGIC, ord("q"), 0, 0, 0, session), addr) + except OSError: + pass ctl.close() board_secs = st.ms / 1000.0 return { @@ -357,6 +403,8 @@ def main(): help="seconds between tests") args = p.parse_args() + if not 0 < args.time <= MAX_SECS: + p.error("--time must be more than 0 and at most {:g}".format(MAX_SECS)) if not HDR.size <= args.size <= 1472: p.error("--size must be {}..1472".format(HDR.size)) names = [t.strip() for t in args.tests.split(",") if t.strip()] diff --git a/tools/unit-tests/Makefile b/tools/unit-tests/Makefile index 06da97f7aa..ffe3cbc7db 100644 --- a/tools/unit-tests/Makefile +++ b/tools/unit-tests/Makefile @@ -74,6 +74,7 @@ endif TESTS:=unit-parser unit-parser-large-header unit-fdt unit-extflash unit-string \ + unit-string-unaligned unit-wolfip-speed unit-xmodem-rx \ unit-spi-flash unit-aes128 \ unit-uart-flash \ unit-aes256 unit-chacha20 unit-pci unit-pci-4gib unit-mock-state \ @@ -705,6 +706,7 @@ unit-image-elf-scatter:CFLAGS+=-DMOCK_PARTITIONS -DWOLFBOOT_NO_SIGN -DUNIT_TEST_ -DWOLFBOOT_HASH_SHA256 -DPRINTF_ENABLED -DWOLFBOOT_ELF_FLASH_SCATTER -DWOLFBOOT_ELF \ -DIMAGE_HEADER_SIZE=256 unit-string:CFLAGS+=-fno-builtin +unit-string-unaligned:CFLAGS+=-fno-builtin WOLFCRYPT_CFLAGS+=-DWOLFBOOT_SIGN_ECC256 -DWOLFBOOT_SIGN_ECC256 -DHAVE_ECC_KEY_IMPORT -D__WOLFBOOT @@ -924,6 +926,25 @@ unit-string: ../../include/target.h unit-string.c unit-psci: ../../include/target.h unit-psci.c ../../src/psci.c gcc -o $@ unit-psci.c $(CFLAGS) $(LDFLAGS) +# The test-app wolfIP throughput server, against wolfIP mocks +unit-wolfip-speed: ../../include/target.h unit-wolfip-speed.c \ + ../../test-app/wolfip_tftp_test.c wolfip_stub/wolfip.h \ + wolfip_stub/nxp_mcxe_enet.h + gcc -o $@ unit-wolfip-speed.c $(CFLAGS) -Iwolfip_stub -Wall -Wextra \ + $(LDFLAGS) + +# The S32K1xx / MCX E247 test-app XMODEM receiver, against UART and flash +# mocks +unit-xmodem-rx: ../../include/target.h unit-xmodem-rx.c \ + ../../test-app/xmodem_rx.c + gcc -o $@ unit-xmodem-rx.c $(CFLAGS) -Wall -Wextra $(LDFLAGS) + +# The FAST_MEMCPY path for M-profile cores, which load words from any +# address, built on the host, whose CPU does the same +unit-string-unaligned: ../../include/target.h unit-string.c + gcc -o $@ $^ $(CFLAGS) -DDEBUG_UART -DPRINTF_ENABLED \ + -D__ARM_FEATURE_UNALIGNED=1 "-D__ARM_ARCH_PROFILE='M'" $(LDFLAGS) + unit-arm-tee-psa-ipc: ../../include/target.h unit-arm-tee-psa-ipc.c ../../src/arm_tee_psa_ipc.c gcc -o $@ unit-arm-tee-psa-ipc.c $(CFLAGS) -I$(WOLFBOOT_LIB_WOLFPSA)/wolfpsa \ -ffunction-sections -fdata-sections \ diff --git a/tools/unit-tests/unit-string.c b/tools/unit-tests/unit-string.c index d94d695ac3..18afe5a3a9 100644 --- a/tools/unit-tests/unit-string.c +++ b/tools/unit-tests/unit-string.c @@ -382,6 +382,99 @@ START_TEST(test_memcpy_aligned_buffers) } END_TEST +/* Every source and destination offset 0-3 against an aligned base, for + * lengths around the 4-byte word and 16-byte block sizes, with guard bytes + * on both sides of the destination and a source left untouched. Covers the + * byte prologue, the 16-byte loop, the word remainder and the byte tail of + * the FAST_MEMCPY paths (the unaligned one in unit-string-unaligned). */ +#define MEMCPY_GUARD 8 +#define MEMCPY_MAX_LEN 72 +START_TEST(test_memcpy_offsets_lengths) +{ + union { + unsigned long align; + unsigned char buf[MEMCPY_MAX_LEN + 2 * MEMCPY_GUARD + 4]; + } src_mem, dst_mem; + unsigned char ref[sizeof(src_mem.buf)]; + unsigned char *src; + unsigned char *dst; + size_t so, doff, len, i; + void *ret; + + for (i = 0; i < sizeof(src_mem.buf); i++) { + src_mem.buf[i] = (unsigned char)(0x5A ^ (i * 7U)); + ref[i] = src_mem.buf[i]; /* not memcpy: it is under test */ + } + for (so = 0; so < 4; so++) { + for (doff = 0; doff < 4; doff++) { + for (len = 0; len <= MEMCPY_MAX_LEN; len++) { + src = src_mem.buf + MEMCPY_GUARD + so; + dst = dst_mem.buf + MEMCPY_GUARD + doff; + for (i = 0; i < sizeof(dst_mem.buf); i++) + dst_mem.buf[i] = 0xEE; + ret = memcpy(dst, src, len); + ck_assert_ptr_eq(ret, dst); + for (i = 0; i < sizeof(dst_mem.buf); i++) { + if (&dst_mem.buf[i] >= dst && &dst_mem.buf[i] < dst + len) + ck_assert_uint_eq(dst_mem.buf[i], + src[&dst_mem.buf[i] - dst]); + else + ck_assert_uint_eq(dst_mem.buf[i], 0xEE); + } + ck_assert_int_eq(memcmp(src_mem.buf, ref, sizeof(ref)), 0); + } + } + } +} +END_TEST + +/* Overlapping moves both ways, gaps 1-17 (inside and past one 16-byte + * block), destination offsets 0-3: a forward move (source above the + * destination) goes through memcpy and its word loops. The whole buffer is + * compared, so bytes outside the destination must not change. */ +#define MEMMOVE_MAX_GAP 17 +START_TEST(test_memmove_overlap_offsets) +{ + union { + unsigned long align; + unsigned char buf[MEMCPY_MAX_LEN + MEMMOVE_MAX_GAP + + 2 * MEMCPY_GUARD + 4]; + } mem; + unsigned char ref[sizeof(mem.buf)]; + unsigned char tmp[MEMCPY_MAX_LEN]; + unsigned char *src; + unsigned char *dst; + size_t fwd, gap, doff, len, i, so, dof; + void *ret; + + for (fwd = 0; fwd < 2; fwd++) { + for (gap = 1; gap <= MEMMOVE_MAX_GAP; gap++) { + for (doff = 0; doff < 4; doff++) { + for (len = 0; len <= MEMCPY_MAX_LEN; len++) { + so = MEMCPY_GUARD + doff + ((fwd != 0) ? gap : 0); + dof = MEMCPY_GUARD + doff + ((fwd != 0) ? 0 : gap); + for (i = 0; i < sizeof(mem.buf); i++) { + mem.buf[i] = (unsigned char)(0x3C ^ (i * 13U)); + ref[i] = mem.buf[i]; + } + /* reference move through a separate buffer */ + for (i = 0; i < len; i++) + tmp[i] = ref[so + i]; + for (i = 0; i < len; i++) + ref[dof + i] = tmp[i]; + src = mem.buf + so; + dst = mem.buf + dof; + ret = memmove(dst, src, len); + ck_assert_ptr_eq(ret, dst); + for (i = 0; i < sizeof(mem.buf); i++) + ck_assert_uint_eq(mem.buf[i], ref[i]); + } + } + } + } +} +END_TEST + START_TEST(test_write_num_basic) { reset_uart_buf(); @@ -553,6 +646,8 @@ Suite *string_suite(void) #endif #endif tcase_add_test(tcase_misc, test_memcpy_aligned_buffers); + tcase_add_test(tcase_misc, test_memcpy_offsets_lengths); + tcase_add_test(tcase_misc, test_memmove_overlap_offsets); tcase_add_test(tcase_misc, test_write_num_basic); tcase_add_test(tcase_misc, test_log_printf_formats); tcase_add_test(tcase_misc, test_log_printf_64bit_args); diff --git a/tools/unit-tests/unit-wolfip-speed.c b/tools/unit-tests/unit-wolfip-speed.c new file mode 100644 index 0000000000..28cb094295 --- /dev/null +++ b/tools/unit-tests/unit-wolfip-speed.c @@ -0,0 +1,737 @@ +/* unit-wolfip-speed.c + * + * Unit tests for the wolfIP throughput server in test-app/wolfip_tftp_test.c + * (WOLFIP_SPEED_TEST): the UDP test lifecycle, late datagrams of finished + * tests, busy and TCP-during-UDP refusals, 'q' handling and the duration + * limits. wolfIP is replaced by mocks (wolfip_stub/), and the tests drive + * the server's handlers directly with a mock clock. + * + * 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 + */ + +#define WOLFIP_SPEED_TEST +#define WOLFIP_PORT_MCXE_ENET + +#include +#include +#include + +#include "../../test-app/wolfip_tftp_test.c" + +#define MOCK_LISTEN_FD 1 +#define MOCK_UDP_FD 2 +#define MOCK_CLIENT_FD 3 +#define MOCK_FDS 4 +#define MOCK_RXQ 8 + +#define SESSION_A 0x11111111U +#define SESSION_B 0x22222222U + +struct mock_dgram { + uint8_t data[SPEED_HDR_LEN]; + int len; +}; + +static struct mock_dgram mock_rxq[MOCK_RXQ]; +static int mock_rx_head; +static int mock_rx_tail; +static int mock_accept_pending; +static int mock_closed[MOCK_FDS]; +static uint64_t mock_now; +static int mock_tx_data; /* 'd' datagrams the board sent */ +static int mock_tx_ctl; /* other datagrams the board sent */ +static uint8_t mock_last_ctl[SPEED_REPLY_LEN]; /* the last of those */ +static uint8_t mock_tcp_in[128]; /* what the TCP client sent */ +static size_t mock_tcp_in_len; +static size_t mock_tcp_in_pos; +static int mock_tcp_sends; /* send() calls on the TCP client */ + +/* ---- wolfIP and driver mocks ---- */ + +void wolfIP_init_static(struct wolfIP **s) +{ + *s = NULL; +} + +struct wolfIP_ll_dev *wolfIP_getdev(struct wolfIP *s) +{ + (void)s; + return NULL; +} + +int wolfIP_poll(struct wolfIP *s, uint64_t now) +{ + (void)s; + (void)now; + return 0; +} + +int dhcp_client_init(struct wolfIP *s) +{ + (void)s; + return -1; +} + +int dhcp_bound(struct wolfIP *s) +{ + (void)s; + return 0; +} + +void wolfIP_ipconfig_get(struct wolfIP *s, ip4 *ip, ip4 *mask, ip4 *gw) +{ + (void)s; + *ip = 0; + *mask = 0; + *gw = 0; +} + +int wolfIP_sock_socket(struct wolfIP *s, int domain, int type, int protocol) +{ + (void)s; + (void)domain; + (void)protocol; + return (type == IPSTACK_SOCK_STREAM) ? MOCK_LISTEN_FD : MOCK_UDP_FD; +} + +int wolfIP_sock_bind(struct wolfIP *s, int sockfd, + const struct wolfIP_sockaddr *addr, socklen_t addrlen) +{ + (void)s; + (void)sockfd; + (void)addr; + (void)addrlen; + return 0; +} + +int wolfIP_sock_listen(struct wolfIP *s, int sockfd, int backlog) +{ + (void)s; + (void)sockfd; + (void)backlog; + return 0; +} + +int wolfIP_sock_accept(struct wolfIP *s, int sockfd, + struct wolfIP_sockaddr *addr, socklen_t *addrlen) +{ + (void)s; + (void)sockfd; + (void)addr; + (void)addrlen; + if (mock_accept_pending == 0) + return -1; + mock_accept_pending = 0; + return MOCK_CLIENT_FD; +} + +int wolfIP_sock_sendto(struct wolfIP *s, int sockfd, const void *buf, + size_t len, int flags, + const struct wolfIP_sockaddr *dest_addr, + socklen_t addrlen) +{ + const uint8_t *p = (const uint8_t *)buf; + + (void)s; + (void)flags; + (void)dest_addr; + (void)addrlen; + ck_assert_int_eq(sockfd, MOCK_UDP_FD); + if (p[1] == 'd') { + mock_tx_data++; + } + else { + mock_tx_ctl++; + memset(mock_last_ctl, 0, sizeof(mock_last_ctl)); + memcpy(mock_last_ctl, p, + (len < sizeof(mock_last_ctl)) ? len : sizeof(mock_last_ctl)); + } + return (int)len; +} + +int wolfIP_sock_send(struct wolfIP *s, int sockfd, const void *buf, + size_t len, int flags) +{ + (void)s; + (void)buf; + (void)flags; + ck_assert_int_eq(sockfd, MOCK_CLIENT_FD); + mock_tcp_sends++; + return (int)len; +} + +int wolfIP_sock_recvfrom(struct wolfIP *s, int sockfd, void *buf, size_t len, + int flags, struct wolfIP_sockaddr *src_addr, + socklen_t *addrlen) +{ + struct mock_dgram *d; + struct wolfIP_sockaddr_in *from = (struct wolfIP_sockaddr_in *)src_addr; + + (void)s; + (void)flags; + if (sockfd == MOCK_CLIENT_FD) { + if (mock_tcp_in_pos >= mock_tcp_in_len) + return -1; + if (len > mock_tcp_in_len - mock_tcp_in_pos) + len = mock_tcp_in_len - mock_tcp_in_pos; + memcpy(buf, mock_tcp_in + mock_tcp_in_pos, len); + mock_tcp_in_pos += len; + return (int)len; + } + if (sockfd != MOCK_UDP_FD || mock_rx_head == mock_rx_tail) + return -1; + d = &mock_rxq[mock_rx_head]; + mock_rx_head = (mock_rx_head + 1) % MOCK_RXQ; + ck_assert_uint_ge(len, (size_t)d->len); + memcpy(buf, d->data, (size_t)d->len); + if (from != NULL) { + memset(from, 0, sizeof(*from)); + from->sin_family = AF_INET; + from->sin_addr.s_addr = 0x0A000001U; + *addrlen = sizeof(*from); + } + return d->len; +} + +int wolfIP_sock_close(struct wolfIP *s, int sockfd) +{ + (void)s; + if (sockfd >= 0 && sockfd < MOCK_FDS) + mock_closed[sockfd]++; + return 0; +} + +void wolfIP_register_callback(struct wolfIP *s, int sock_fd, tsocket_cb cb, + void *arg) +{ + (void)s; + (void)sock_fd; + (void)cb; + (void)arg; +} + +int nxp_mcxe_enet_init(struct wolfIP_ll_dev *ll, const uint8_t *mac) +{ + (void)ll; + (void)mac; + return -1; +} + +int nxp_mcxe_enet_phy_addr(void) +{ + return 0; +} + +uint16_t nxp_mcxe_enet_phy_read(uint8_t reg) +{ + (void)reg; + return 0xFFFFU; +} + +uint32_t nxp_mcxe_enet_link_up(void) +{ + return 0; +} + +uint64_t wolfip_test_get_ms(void) +{ + return mock_now; +} + +int wolfip_test_abort(void) +{ + return 0; +} + +/* ---- helpers ---- */ + +static void setup(void) +{ + memset(&speed, 0, sizeof(speed)); + memset(speed_ended, 0, sizeof(speed_ended)); + speed_ended_idx = 0; + speed_listen_fd = MOCK_LISTEN_FD; + speed_udp_fd = MOCK_UDP_FD; + speed_client_fd = -1; + mock_rx_head = 0; + mock_rx_tail = 0; + mock_accept_pending = 0; + memset(mock_closed, 0, sizeof(mock_closed)); + mock_now = 1000; + mock_tx_data = 0; + mock_tx_ctl = 0; + memset(mock_last_ctl, 0, sizeof(mock_last_ctl)); + mock_tcp_in_len = 0; + mock_tcp_in_pos = 0; + mock_tcp_sends = 0; +} + +/* Hand the board one header-only datagram and let it read it */ +static void udp_in(uint8_t cmd, uint32_t seq, uint32_t dur_ms, + uint32_t session) +{ + struct mock_dgram *d = &mock_rxq[mock_rx_tail]; + + memset(d, 0, sizeof(*d)); + d->data[0] = SPEED_MAGIC; + d->data[1] = cmd; + d->data[2] = (uint8_t)(SPEED_UDP_MAX >> 8); + d->data[3] = (uint8_t)SPEED_UDP_MAX; + speed_put32(d->data + 4, seq); + speed_put32(d->data + 8, dur_ms); + speed_put32(d->data + 12, session); + d->len = SPEED_HDR_LEN; + mock_rx_tail = (mock_rx_tail + 1) % MOCK_RXQ; + speed_udp_recv(NULL, mock_now); +} + +static void udp_open(uint8_t mode, uint32_t dur_ms, uint32_t session) +{ + udp_in('o', mode, dur_ms, session); +} + +/* The board's reply to the last control datagram */ +static uint8_t last_cmd(void) +{ + return mock_last_ctl[1]; +} + +static uint32_t last_session(void) +{ + return speed_get32(mock_last_ctl + 12); +} + +/* Run a whole UDP rx test of session: open, three datagrams, 'q' */ +static void udp_rx_test(uint32_t session) +{ + udp_open('r', 1000, session); + ck_assert_int_eq(last_cmd(), 'O'); + udp_in('r', 0, 1000, session); + udp_in('r', 1, 1000, session); + udp_in('r', 2, 1000, session); + udp_in('q', 0, 0, session); + ck_assert_int_eq(last_cmd(), 'S'); + ck_assert_uint_eq(speed.active, 0); + ck_assert_uint_eq(speed.rx_pkts, 3); +} + +/* ---- tests ---- */ + +START_TEST(test_udp_rx_lifecycle) +{ + setup(); + udp_open('r', 1000, SESSION_A); + ck_assert_int_eq(last_cmd(), 'O'); + ck_assert_uint_eq(last_session(), SESSION_A); + ck_assert_uint_eq(speed.active, 1); + ck_assert_uint_eq(speed.started, 0); /* window waits for data */ + + mock_now += 5; + udp_in('r', 0, 1000, SESSION_A); + ck_assert_uint_eq(speed.started, 1); + ck_assert_uint_eq(speed.start_ms, mock_now); + udp_in('r', 1, 1000, SESSION_A); + ck_assert_uint_eq(speed.rx_pkts, 2); + + mock_now += 1000; + udp_in('q', 0, 0, SESSION_A); + ck_assert_uint_eq(speed.active, 0); + ck_assert_int_eq(last_cmd(), 'S'); + ck_assert_uint_eq(mock_last_ctl[3], SPEED_PROTO_UDP); + ck_assert_uint_eq(mock_last_ctl[5], 0); /* not active */ + ck_assert_uint_eq(speed_get32(mock_last_ctl + 8), 1000); +} +END_TEST + +/* Data and a repeated 'o' of a finished test start nothing */ +START_TEST(test_late_datagrams_after_end) +{ + int ctl; + + setup(); + udp_rx_test(SESSION_A); + udp_in('r', 3, 1000, SESSION_A); + ck_assert_uint_eq(speed.active, 0); + ck_assert_uint_eq(speed.rx_pkts, 3); + + ctl = mock_tx_ctl; + udp_open('r', 1000, SESSION_A); + ck_assert_uint_eq(speed.active, 0); + ck_assert_int_eq(mock_tx_ctl, ctl); /* no reply */ +} +END_TEST + +/* UDP A, then B, then late A datagrams: B is not fed, ended or replaced */ +START_TEST(test_late_datagrams_during_next_test) +{ + setup(); + udp_rx_test(SESSION_A); + udp_open('r', 1000, SESSION_B); + ck_assert_int_eq(last_cmd(), 'O'); + udp_in('r', 0, 1000, SESSION_B); + + udp_in('r', 3, 1000, SESSION_A); + udp_in('q', 0, 0, SESSION_A); + udp_open('r', 1000, SESSION_A); + ck_assert_uint_eq(speed.active, 1); + ck_assert_uint_eq(speed.session, SESSION_B); + ck_assert_uint_eq(speed.rx_pkts, 1); +} +END_TEST + +/* UDP A, a TCP test, then late A datagrams: the TCP test does not make the + * server forget A */ +START_TEST(test_late_udp_after_tcp) +{ + setup(); + udp_rx_test(SESSION_A); + + mock_accept_pending = 1; + speed_cb(MOCK_LISTEN_FD, CB_EVENT_READABLE, NULL); + ck_assert_int_eq(speed_client_fd, MOCK_CLIENT_FD); + ck_assert_uint_eq(speed.proto, SPEED_PROTO_TCP); + speed_cb(MOCK_CLIENT_FD, CB_EVENT_CLOSED, NULL); + ck_assert_uint_eq(speed.active, 0); + + udp_open('r', 1000, SESSION_A); + udp_in('r', 3, 1000, SESSION_A); + ck_assert_uint_eq(speed.active, 0); + ck_assert_uint_eq(speed.proto, SPEED_PROTO_TCP); +} +END_TEST + +/* The last SPEED_ENDED_NUM sessions are remembered */ +START_TEST(test_ended_sessions_remembered) +{ + uint32_t i; + + setup(); + for (i = 1; i <= SPEED_ENDED_NUM; i++) + udp_rx_test(i); + for (i = 1; i <= SPEED_ENDED_NUM; i++) { + udp_open('r', 1000, i); + ck_assert_uint_eq(speed.active, 0); + } + udp_open('r', 1000, SPEED_ENDED_NUM + 1U); + ck_assert_uint_eq(speed.active, 1); +} +END_TEST + +/* An 'o' of another session while a test runs is refused; a repeated 'o' + * of the running one is answered again */ +START_TEST(test_open_while_busy) +{ + setup(); + udp_open('r', 1000, SESSION_A); + udp_in('r', 0, 1000, SESSION_A); + + udp_open('t', 1000, SESSION_B); + ck_assert_int_eq(last_cmd(), 'B'); + ck_assert_uint_eq(last_session(), SESSION_B); + ck_assert_uint_eq(speed.session, SESSION_A); + ck_assert_uint_eq(speed.mode, 'r'); + ck_assert_uint_eq(speed.streaming, 0); + + udp_open('r', 1000, SESSION_A); + ck_assert_int_eq(last_cmd(), 'O'); + ck_assert_uint_eq(speed.rx_pkts, 1); /* not restarted */ +} +END_TEST + +/* Invalid opens are ignored */ +START_TEST(test_open_invalid) +{ + setup(); + udp_open('r', 1000, 0); + udp_open('x', 1000, SESSION_A); + ck_assert_uint_eq(speed.active, 0); + ck_assert_int_eq(mock_tx_ctl, 0); +} +END_TEST + +/* Data that does not match the open test is ignored */ +START_TEST(test_data_mismatch) +{ + setup(); + udp_in('r', 0, 1000, SESSION_A); /* no open */ + ck_assert_uint_eq(speed.active, 0); + + udp_open('r', 1000, SESSION_A); + udp_in('b', 0, 1000, SESSION_A); /* wrong mode */ + udp_in('r', 0, 1000, SESSION_B); /* wrong session */ + ck_assert_uint_eq(speed.started, 0); + ck_assert_uint_eq(speed.rx_pkts, 0); +} +END_TEST + +/* 'q' of session 0 or another session only reports */ +START_TEST(test_query_other_session) +{ + setup(); + udp_open('r', 1000, SESSION_A); + udp_in('r', 0, 1000, SESSION_A); + + udp_in('q', 0, 0, 0); + ck_assert_int_eq(last_cmd(), 'S'); + ck_assert_uint_eq(mock_last_ctl[5], 1); /* still active */ + udp_in('q', 0, 0, SESSION_B); + ck_assert_uint_eq(speed.active, 1); +} +END_TEST + +/* A TCP client is refused while a UDP test is open */ +START_TEST(test_tcp_refused_during_udp) +{ + setup(); + udp_open('r', 1000, SESSION_A); + mock_accept_pending = 1; + speed_cb(MOCK_LISTEN_FD, CB_EVENT_READABLE, NULL); + ck_assert_int_eq(mock_closed[MOCK_CLIENT_FD], 1); + ck_assert_int_eq(speed_client_fd, -1); + ck_assert_uint_eq(speed.proto, SPEED_PROTO_UDP); + ck_assert_uint_eq(speed.active, 1); +} +END_TEST + +/* A tx test starts at the 'o', is limited to SPEED_MAX_MS and ends at its + * duration */ +START_TEST(test_tx_duration_clamped) +{ + uint64_t t0; + + setup(); + t0 = mock_now; + udp_open('t', 0xFFFFFFFFU, SESSION_A); + ck_assert_int_eq(last_cmd(), 'O'); + ck_assert_uint_eq(speed_get32(mock_last_ctl + 8), SPEED_MAX_MS); + ck_assert_uint_eq(speed.dur_ms, SPEED_MAX_MS); + ck_assert_uint_eq(speed.started, 1); + ck_assert_uint_eq(speed.streaming, 1); + + speed_udp_send(NULL, t0 + 1); + ck_assert_int_eq(mock_tx_data, SPEED_BURST); + speed_udp_send(NULL, t0 + SPEED_MAX_MS - 1); + ck_assert_uint_eq(speed.active, 1); + speed_udp_send(NULL, t0 + SPEED_MAX_MS); + ck_assert_uint_eq(speed.active, 0); + ck_assert_int_eq(mock_tx_data, 2 * SPEED_BURST); +} +END_TEST + +/* A bidir test sends from its first data, for its duration from there */ +START_TEST(test_bidir_streams_from_first_data) +{ + uint64_t t1; + + setup(); + udp_open('b', 2000, SESSION_A); + speed_udp_send(NULL, mock_now); + ck_assert_int_eq(mock_tx_data, 0); + + mock_now += 50; + t1 = mock_now; + udp_in('b', 0, 2000, SESSION_A); + ck_assert_uint_eq(speed.streaming, 1); + speed_udp_send(NULL, t1 + 1999); + ck_assert_int_eq(mock_tx_data, SPEED_BURST); + speed_udp_send(NULL, t1 + 2000); + ck_assert_uint_eq(speed.active, 0); +} +END_TEST + +/* A test the host abandons ends SPEED_GRACE_MS after its duration */ +START_TEST(test_abandoned_tests_expire) +{ + uint64_t t0; + uint64_t t1; + + setup(); + t0 = mock_now; + udp_open('r', 1000, SESSION_A); /* never any data */ + speed_udp_send(NULL, t0 + 1000 + SPEED_GRACE_MS - 1); + ck_assert_uint_eq(speed.active, 1); + speed_udp_send(NULL, t0 + 1000 + SPEED_GRACE_MS); + ck_assert_uint_eq(speed.active, 0); + + /* With data, the deadline counts from the first datagram */ + mock_now = t0 + 10000; + udp_open('r', 1000, SESSION_B); + mock_now += 500; + t1 = mock_now; + udp_in('r', 0, 1000, SESSION_B); + speed_udp_send(NULL, t1 + 1000 + SPEED_GRACE_MS - 1); + ck_assert_uint_eq(speed.active, 1); + speed_udp_send(NULL, t1 + 1000 + SPEED_GRACE_MS); + ck_assert_uint_eq(speed.active, 0); +} +END_TEST + +/* A TCP client that sends no direction byte gets bidir */ +START_TEST(test_tcp_default_bidir) +{ + setup(); + mock_accept_pending = 1; + speed_cb(MOCK_LISTEN_FD, CB_EVENT_READABLE, NULL); + ck_assert_uint_eq(speed.mode, 0); + speed_tcp_pump(NULL, mock_now + SPEED_TCP_MODE_MS); + ck_assert_uint_eq(speed.mode, 'b'); + ck_assert_uint_eq(speed.tx_bytes, (uint64_t)SPEED_BURST * SPEED_TCP_CHUNK); +} +END_TEST + +/* Accept a TCP client that sent first, then len bytes of payload */ +static void tcp_client(uint8_t first, size_t len) +{ + size_t i; + + ck_assert_uint_le(len + 1U, sizeof(mock_tcp_in)); + mock_tcp_in[0] = first; + for (i = 1; i <= len; i++) + mock_tcp_in[i] = (uint8_t)i; + mock_tcp_in_len = len + 1U; + mock_tcp_in_pos = 0; + mock_accept_pending = 1; + speed_cb(MOCK_LISTEN_FD, CB_EVENT_READABLE, NULL); + ck_assert_int_eq(speed_client_fd, MOCK_CLIENT_FD); + ck_assert_uint_eq(speed.mode, 0); + speed_tcp_pump(NULL, mock_now); +} + +/* 'r': the host sends, the board only receives; the direction byte is not + * counted */ +START_TEST(test_tcp_direction_rx) +{ + setup(); + tcp_client('r', 99); + ck_assert_uint_eq(speed.mode, 'r'); + ck_assert_uint_eq(speed.rx_bytes, 99); + ck_assert_int_eq(mock_tcp_sends, 0); + ck_assert_uint_eq(speed.tx_bytes, 0); + speed_tcp_pump(NULL, mock_now + SPEED_TCP_MODE_MS); + ck_assert_uint_eq(speed.mode, 'r'); + ck_assert_int_eq(mock_tcp_sends, 0); +} +END_TEST + +/* 't': the board sends */ +START_TEST(test_tcp_direction_tx) +{ + setup(); + tcp_client('t', 0); + ck_assert_uint_eq(speed.mode, 't'); + ck_assert_uint_eq(speed.rx_bytes, 0); + ck_assert_int_eq(mock_tcp_sends, SPEED_BURST); + ck_assert_uint_eq(speed.tx_bytes, (uint64_t)SPEED_BURST * SPEED_TCP_CHUNK); +} +END_TEST + +/* Any other first byte: bidir, and the byte is data */ +START_TEST(test_tcp_first_byte_data) +{ + setup(); + tcp_client('x', 9); + ck_assert_uint_eq(speed.mode, 'b'); + ck_assert_uint_eq(speed.rx_bytes, 10); + ck_assert_int_eq(mock_tcp_sends, SPEED_BURST); +} +END_TEST + +/* A TCP client that goes away without closing: the test ends after + * SPEED_TCP_IDLE_MS with no data, timed to its last data, and frees the + * server for the next test */ +START_TEST(test_tcp_idle_client_expires) +{ + uint64_t t_data; + + setup(); + tcp_client('r', 20); + t_data = mock_now; + ck_assert_uint_eq(speed.active, 1); + speed_tcp_pump(NULL, t_data + SPEED_TCP_IDLE_MS - 1U); + ck_assert_uint_eq(speed.active, 1); + ck_assert_int_eq(mock_closed[MOCK_CLIENT_FD], 0); + speed_tcp_pump(NULL, t_data + SPEED_TCP_IDLE_MS); + ck_assert_uint_eq(speed.active, 0); + ck_assert_int_eq(speed_client_fd, -1); + ck_assert_int_eq(mock_closed[MOCK_CLIENT_FD], 1); + ck_assert_uint_eq(speed.end_ms, t_data); + ck_assert_uint_eq(speed.rx_bytes, 20); + /* a late close event for the old socket changes nothing */ + speed_cb(MOCK_CLIENT_FD, CB_EVENT_CLOSED, NULL); + ck_assert_int_eq(mock_closed[MOCK_CLIENT_FD], 1); + + mock_now = t_data + SPEED_TCP_IDLE_MS + 1U; + udp_open('r', 1000, SESSION_A); + ck_assert_int_eq(last_cmd(), 'O'); +} +END_TEST + +/* Data moving either way keeps a TCP test alive */ +START_TEST(test_tcp_active_client_stays) +{ + uint64_t t; + + setup(); + tcp_client('t', 0); + for (t = 1; t <= 4U; t++) + speed_tcp_pump(NULL, mock_now + t * (SPEED_TCP_IDLE_MS - 1U)); + ck_assert_uint_eq(speed.active, 1); + ck_assert_int_eq(mock_closed[MOCK_CLIENT_FD], 0); +} +END_TEST + +static Suite *speed_suite(void) +{ + Suite *s = suite_create("wolfIP speed server"); + TCase *tc = tcase_create("udp-tcp"); + + tcase_add_test(tc, test_udp_rx_lifecycle); + tcase_add_test(tc, test_late_datagrams_after_end); + tcase_add_test(tc, test_late_datagrams_during_next_test); + tcase_add_test(tc, test_late_udp_after_tcp); + tcase_add_test(tc, test_ended_sessions_remembered); + tcase_add_test(tc, test_open_while_busy); + tcase_add_test(tc, test_open_invalid); + tcase_add_test(tc, test_data_mismatch); + tcase_add_test(tc, test_query_other_session); + tcase_add_test(tc, test_tcp_refused_during_udp); + tcase_add_test(tc, test_tx_duration_clamped); + tcase_add_test(tc, test_bidir_streams_from_first_data); + tcase_add_test(tc, test_abandoned_tests_expire); + tcase_add_test(tc, test_tcp_default_bidir); + tcase_add_test(tc, test_tcp_direction_rx); + tcase_add_test(tc, test_tcp_direction_tx); + tcase_add_test(tc, test_tcp_first_byte_data); + tcase_add_test(tc, test_tcp_idle_client_expires); + tcase_add_test(tc, test_tcp_active_client_stays); + suite_add_tcase(s, tc); + return s; +} + +int main(void) +{ + int fails; + Suite *s = speed_suite(); + SRunner *sr = srunner_create(s); + + srunner_run_all(sr, CK_NORMAL); + fails = srunner_ntests_failed(sr); + srunner_free(sr); + return fails; +} diff --git a/tools/unit-tests/unit-xmodem-rx.c b/tools/unit-tests/unit-xmodem-rx.c new file mode 100644 index 0000000000..a08d232303 --- /dev/null +++ b/tools/unit-tests/unit-xmodem-rx.c @@ -0,0 +1,366 @@ +/* unit-xmodem-rx.c + * + * Unit tests for the XMODEM-CRC receiver of the S32K1xx / MCX E247 test-app + * (test-app/xmodem_rx.c): image size limits, blocks past the image, + * duplicate blocks after a lost ACK, CRC errors and flash write failures. + * The UART, the LED, the tick counter and the flash are mocks; each test + * queues what the sender transmits and checks the receiver's answers and + * what it wrote. + * + * 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 + +/* A small update partition: 8 KB, its last 1 KB sector for the trailer, + * so images up to 7 KB (56 blocks) fit */ +#define WOLFBOOT_PARTITION_SIZE 0x2000U +#define WOLFBOOT_SECTOR_SIZE 0x400U +#define WOLFBOOT_TRAILER_SECTORS 1U +#define WOLFBOOT_PARTITION_UPDATE_ADDRESS 0x10000U +#define IMAGE_HEADER_SIZE 256U +#define APP_RAMFUNCTION + +#define MAX_BLOCKS ((WOLFBOOT_PARTITION_SIZE - \ + WOLFBOOT_TRAILER_SECTORS * WOLFBOOT_SECTOR_SIZE) / 128U) + +static volatile uint32_t jiffies; + +static uint8_t mock_in[(MAX_BLOCKS + 8U) * 133U]; +static uint32_t mock_in_len; +static uint32_t mock_in_pos; +static int mock_idle; /* reads in a row with no data */ +static uint8_t mock_out[1024]; +static uint32_t mock_out_len; +static uint8_t mock_flash[WOLFBOOT_PARTITION_SIZE]; +static int mock_writes; +static int mock_fail_write; /* fail this write (1-based), 0 never */ + +static void APP_RAMFUNCTION led_red_on(void) +{ +} + +static void APP_RAMFUNCTION led_red_off(void) +{ +} + +void uart_tx(uint8_t byte) +{ + if (mock_out_len < sizeof(mock_out)) + mock_out[mock_out_len++] = byte; +} + +/* What the sender transmitted, at most 17 bytes per read like a UART FIFO. + * With nothing left, time out: the tick jumps past the receiver's timeout. */ +static int uart_rx_isr(uint8_t *buf, int max_len) +{ + int n = 0; + + if (mock_in_pos >= mock_in_len) { + mock_idle++; + ck_assert_msg(mock_idle < 4, "receiver waits for more input"); + jiffies += 1001U; + return 0; + } + mock_idle = 0; + while (n < max_len && n < 17 && mock_in_pos < mock_in_len) + buf[n++] = mock_in[mock_in_pos++]; + return n; +} + +int hal_flash_write(uint32_t address, const uint8_t *data, int len) +{ + mock_writes++; + if (mock_writes == mock_fail_write) + return -1; + ck_assert_uint_ge(address, WOLFBOOT_PARTITION_UPDATE_ADDRESS); + ck_assert_uint_le(address - WOLFBOOT_PARTITION_UPDATE_ADDRESS + (uint32_t)len, + WOLFBOOT_PARTITION_SIZE); + memcpy(mock_flash + (address - WOLFBOOT_PARTITION_UPDATE_ADDRESS), data, + (size_t)len); + return 0; +} + +#include "../../test-app/xmodem_rx.c" + +/* ---- helpers ---- */ + +static void setup(void) +{ + jiffies = 0; + mock_in_len = 0; + mock_in_pos = 0; + mock_idle = 0; + mock_out_len = 0; + memset(mock_flash, 0xFF, sizeof(mock_flash)); + mock_writes = 0; + mock_fail_write = 0; +} + +/* Content of block n (1-based) of an image of img_size bytes after its + * header */ +static void block_data(uint8_t *d, uint32_t n, uint32_t img_size) +{ + uint32_t i; + + for (i = 0; i < 128U; i++) + d[i] = (uint8_t)(n * 31U + i); + if (n == 1U) + memcpy(d + 4, &img_size, sizeof(img_size)); /* header size field */ +} + +/* Queue block n as the sender transmits it */ +static void send_block(uint32_t n, uint32_t img_size, int bad_crc) +{ + uint8_t *p = mock_in + mock_in_len; + uint16_t crc; + + ck_assert_uint_le(mock_in_len + 133U, sizeof(mock_in)); + p[0] = XSOH; + p[1] = (uint8_t)n; + p[2] = (uint8_t)~n; + block_data(p + 3, n, img_size); + crc = crc16_ccitt(p + 3, 128); + if (bad_crc) + crc ^= 1U; + p[131] = (uint8_t)(crc >> 8); + p[132] = (uint8_t)crc; + mock_in_len += 133U; +} + +static void send_eot(void) +{ + mock_in[mock_in_len++] = XEOT; +} + +static int count_out(uint8_t c) +{ + uint32_t i; + int n = 0; + + for (i = 0; i < mock_out_len; i++) { + if (mock_out[i] == c) + n++; + } + return n; +} + +/* Blocks 1..blocks are in flash */ +static void check_flash(uint32_t blocks, uint32_t img_size) +{ + uint8_t d[128]; + uint32_t n; + + for (n = 1; n <= blocks; n++) { + block_data(d, n, img_size); + ck_assert_int_eq(memcmp(mock_flash + (n - 1U) * 128U, d, 128), 0); + } + for (n = blocks * 128U; n < sizeof(mock_flash); n++) + ck_assert_uint_eq(mock_flash[n], 0xFF); +} + +static int run(xmodem_state_t *st) +{ + int ret = xmodem_receive_ram(st); + + ck_assert_int_eq(st->result, ret); + return ret; +} + +/* ---- tests ---- */ + +/* An image that fills the partition up to its trailer */ +START_TEST(test_image_at_max_size) +{ + xmodem_state_t st; + uint32_t img = MAX_BLOCKS * 128U - IMAGE_HEADER_SIZE; + uint32_t n; + + setup(); + for (n = 1; n <= MAX_BLOCKS; n++) + send_block(n, img, 0); + send_eot(); + ck_assert_int_eq(run(&st), 0); + ck_assert_uint_eq(st.dst_offset, MAX_BLOCKS * 128U); + ck_assert_int_eq(count_out(XACK), (int)MAX_BLOCKS + 1); + ck_assert_int_eq(count_out(XCAN), 0); + check_flash(MAX_BLOCKS, img); +} +END_TEST + +/* A header one byte too large is refused before anything is written */ +START_TEST(test_oversized_header) +{ + xmodem_state_t st; + uint32_t img = MAX_BLOCKS * 128U - IMAGE_HEADER_SIZE + 1U; + + setup(); + send_block(1, img, 0); + send_eot(); + ck_assert_int_eq(run(&st), -1); + ck_assert_int_eq(mock_writes, 0); + ck_assert_int_eq(count_out(XACK), 0); + ck_assert_int_eq(count_out(XCAN), 10); +} +END_TEST + +/* A block after the last one of the image is refused */ +START_TEST(test_block_past_image) +{ + xmodem_state_t st; + uint32_t img = 2U * 128U - IMAGE_HEADER_SIZE + 100U; /* 3 blocks */ + + setup(); + send_block(1, img, 0); + send_block(2, img, 0); + send_block(3, img, 0); + send_block(4, img, 0); + send_eot(); + ck_assert_int_eq(run(&st), -1); + ck_assert_uint_eq(st.dst_offset, 3U * 128U); + ck_assert_int_eq(count_out(XCAN), 10); + check_flash(3, img); +} +END_TEST + +/* A block repeated after a lost ACK is ACKed again, not written again */ +START_TEST(test_duplicate_block) +{ + xmodem_state_t st; + uint32_t img = 4U * 128U - IMAGE_HEADER_SIZE; + + setup(); + send_block(1, img, 0); + send_block(2, img, 0); + send_block(2, img, 0); + send_block(3, img, 0); + send_block(4, img, 0); + send_eot(); + ck_assert_int_eq(run(&st), 0); + ck_assert_int_eq(mock_writes, 4); + ck_assert_uint_eq(st.dst_offset, 4U * 128U); + ck_assert_int_eq(count_out(XACK), 6); + check_flash(4, img); +} +END_TEST + +/* The last block repeated once the image is complete: ACKed, not refused */ +START_TEST(test_duplicate_final_block) +{ + xmodem_state_t st; + uint32_t img = 3U * 128U - IMAGE_HEADER_SIZE; + + setup(); + send_block(1, img, 0); + send_block(2, img, 0); + send_block(3, img, 0); + send_block(3, img, 0); + send_eot(); + ck_assert_int_eq(run(&st), 0); + ck_assert_int_eq(mock_writes, 3); + ck_assert_int_eq(count_out(XCAN), 0); + ck_assert_int_eq(count_out(XACK), 5); + check_flash(3, img); +} +END_TEST + +/* A repeat with a bad CRC is NAKed and changes nothing */ +START_TEST(test_bad_crc_duplicate) +{ + xmodem_state_t st; + uint32_t img = 2U * 128U - IMAGE_HEADER_SIZE; + + setup(); + send_block(1, img, 0); + send_block(1, img, 1); + send_block(2, img, 0); + send_eot(); + ck_assert_int_eq(run(&st), 0); + ck_assert_uint_eq(st.pkts_crc_fail, 1); + ck_assert_int_eq(count_out(XNAK), 1); + ck_assert_int_eq(mock_writes, 2); + check_flash(2, img); +} +END_TEST + +/* A block out of sequence is NAKed */ +START_TEST(test_out_of_sequence) +{ + xmodem_state_t st; + uint32_t img = 2U * 128U - IMAGE_HEADER_SIZE; + + setup(); + send_block(1, img, 0); + send_block(3, img, 0); + send_block(2, img, 0); + send_eot(); + ck_assert_int_eq(run(&st), 0); + ck_assert_int_eq(count_out(XNAK), 1); + check_flash(2, img); +} +END_TEST + +/* A failed flash write cancels the transfer */ +START_TEST(test_flash_write_failure) +{ + xmodem_state_t st; + uint32_t img = 4U * 128U - IMAGE_HEADER_SIZE; + + setup(); + mock_fail_write = 2; + send_block(1, img, 0); + send_block(2, img, 0); + send_block(3, img, 0); + send_eot(); + ck_assert_int_ne(run(&st), 0); + ck_assert_uint_eq(st.dst_offset, 128U); + ck_assert_int_eq(count_out(XCAN), 10); +} +END_TEST + +static Suite *xmodem_suite(void) +{ + Suite *s = suite_create("XMODEM receiver"); + TCase *tc = tcase_create("xmodem"); + + tcase_add_test(tc, test_image_at_max_size); + tcase_add_test(tc, test_oversized_header); + tcase_add_test(tc, test_block_past_image); + tcase_add_test(tc, test_duplicate_block); + tcase_add_test(tc, test_duplicate_final_block); + tcase_add_test(tc, test_bad_crc_duplicate); + tcase_add_test(tc, test_out_of_sequence); + tcase_add_test(tc, test_flash_write_failure); + suite_add_tcase(s, tc); + return s; +} + +int main(void) +{ + int fails; + Suite *s = xmodem_suite(); + SRunner *sr = srunner_create(s); + + srunner_run_all(sr, CK_NORMAL); + fails = srunner_ntests_failed(sr); + srunner_free(sr); + return fails; +} diff --git a/tools/unit-tests/wolfip_stub/nxp_mcxe_enet.h b/tools/unit-tests/wolfip_stub/nxp_mcxe_enet.h new file mode 100644 index 0000000000..2e74d86af6 --- /dev/null +++ b/tools/unit-tests/wolfip_stub/nxp_mcxe_enet.h @@ -0,0 +1,38 @@ +/* nxp_mcxe_enet.h + * + * Minimal stand-in for the wolfIP MCX E247 driver header, for + * unit-wolfip-speed (see wolfip.h here). Statistics are off, so the speed + * server builds without the driver's cycle counters. + * + * 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 + */ +#ifndef UNIT_NXP_MCXE_ENET_STUB_H +#define UNIT_NXP_MCXE_ENET_STUB_H + +#include +#include "wolfip.h" + +#define NXP_MCXE_ENET_STATS 0 + +int nxp_mcxe_enet_init(struct wolfIP_ll_dev *ll, const uint8_t *mac); +int nxp_mcxe_enet_phy_addr(void); +uint16_t nxp_mcxe_enet_phy_read(uint8_t reg); +uint32_t nxp_mcxe_enet_link_up(void); + +#endif /* UNIT_NXP_MCXE_ENET_STUB_H */ diff --git a/tools/unit-tests/wolfip_stub/wolfip.h b/tools/unit-tests/wolfip_stub/wolfip.h new file mode 100644 index 0000000000..10e91fb1e2 --- /dev/null +++ b/tools/unit-tests/wolfip_stub/wolfip.h @@ -0,0 +1,81 @@ +/* wolfip.h + * + * Minimal stand-in for the wolfIP API used by test-app/wolfip_tftp_test.c, + * so unit-wolfip-speed can test its throughput server without a wolfIP + * checkout. The declarations match wolfIP; unit-wolfip-speed.c implements + * them as mocks. + * + * 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 + */ +#ifndef UNIT_WOLFIP_STUB_H +#define UNIT_WOLFIP_STUB_H + +#include +#include + +typedef uint32_t ip4; +typedef uint32_t socklen_t; + +struct wolfIP; +struct wolfIP_ll_dev; + +struct wolfIP_sockaddr_in { + uint16_t sin_family; + uint16_t sin_port; + struct sin_addr { uint32_t s_addr; } sin_addr; +}; +struct wolfIP_sockaddr { uint16_t sa_family; }; + +#define AF_INET 2 +#define IPSTACK_SOCK_STREAM 1 +#define IPSTACK_SOCK_DGRAM 2 +#define CB_EVENT_READABLE 0x01 +#define CB_EVENT_CLOSED 0x10 + +#define ee16(x) ((uint16_t)(((uint16_t)(x) >> 8) | ((uint16_t)(x) << 8))) + +typedef void (*tsocket_cb)(int sock_fd, uint16_t events, void *arg); + +void wolfIP_init_static(struct wolfIP **s); +struct wolfIP_ll_dev *wolfIP_getdev(struct wolfIP *s); +int wolfIP_poll(struct wolfIP *s, uint64_t now); +int dhcp_client_init(struct wolfIP *s); +int dhcp_bound(struct wolfIP *s); +void wolfIP_ipconfig_get(struct wolfIP *s, ip4 *ip, ip4 *mask, ip4 *gw); +int wolfIP_sock_socket(struct wolfIP *s, int domain, int type, int protocol); +int wolfIP_sock_bind(struct wolfIP *s, int sockfd, + const struct wolfIP_sockaddr *addr, socklen_t addrlen); +int wolfIP_sock_listen(struct wolfIP *s, int sockfd, int backlog); +int wolfIP_sock_accept(struct wolfIP *s, int sockfd, + struct wolfIP_sockaddr *addr, socklen_t *addrlen); +int wolfIP_sock_sendto(struct wolfIP *s, int sockfd, const void *buf, + size_t len, int flags, + const struct wolfIP_sockaddr *dest_addr, + socklen_t addrlen); +int wolfIP_sock_send(struct wolfIP *s, int sockfd, const void *buf, + size_t len, int flags); +int wolfIP_sock_recvfrom(struct wolfIP *s, int sockfd, void *buf, size_t len, + int flags, struct wolfIP_sockaddr *src_addr, + socklen_t *addrlen); +int wolfIP_sock_close(struct wolfIP *s, int sockfd); +void wolfIP_register_callback(struct wolfIP *s, int sock_fd, tsocket_cb cb, + void *arg); +uint32_t wolfIP_getrandom(void); + +#endif /* UNIT_WOLFIP_STUB_H */ From 03718e4ac9b8c56761c5542c80c30593cd8fcd6e Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Tue, 1 Dec 2026 01:18:43 -0500 Subject: [PATCH 15/24] mcxe247: make the unaligned memcpy opt-in, fix review nits - The unaligned-source word path in memcpy now also needs FAST_MEMCPY_UNALIGNED, set only in mcxe247.config. The M-profile check still let it into other FAST_MEMCPY builds: max32666 with MAX3266X_TPU=1 memcpy's the hash digest out of the TPU registers, and unaligned loads from Device memory are not allowed. Other targets get the old aligned-only path back. Documented in Targets.md. - Document that the code cache stays on at handover when its last invalidate times out (PCCCR must not be written while a command runs). - The speed server prints byte counts in KiB: a long TCP test passes 4 GiB, and the 32-bit cast wrapped. MCXE247 speed test unchanged (tcp-rx 45.4, udp-rx 95.6 Mbit/s), unit tests pass. --- config/examples/mcxe247.config | 11 +++++++---- docs/Targets.md | 3 ++- src/string.c | 17 ++++++++++------- test-app/wolfip_tftp_test.c | 10 +++++++--- tools/unit-tests/Makefile | 3 ++- 5 files changed, 28 insertions(+), 16 deletions(-) diff --git a/config/examples/mcxe247.config b/config/examples/mcxe247.config index 09a21445da..5c5a9572cb 100644 --- a/config/examples/mcxe247.config +++ b/config/examples/mcxe247.config @@ -35,13 +35,16 @@ DUALBANK_SWAP?=0 CFLAGS_EXTRA+=-DMCXE247 -DWOLFBOOT_RAM_ECC_INIT # Word-at-a-time memcpy/memset in src/string.c (bootloader and test-app). The -# Cortex-M4 loads unaligned words, so memcpy copies words even when source and -# destination alignments differ; about doubles the wolfIP network test rates. -CFLAGS_EXTRA+=-DFAST_MEMCPY +# Cortex-M4 loads unaligned words from RAM and flash, so with +# FAST_MEMCPY_UNALIGNED memcpy copies words even when source and destination +# alignments differ; about doubles the wolfIP network test rates. Nothing on +# this target copies from peripheral registers with memcpy. +CFLAGS_EXTRA+=-DFAST_MEMCPY -DFAST_MEMCPY_UNALIGNED # Run at 80 MHz from the 8 MHz crystal (SOSC + SPLL) with the 4 KB flash code # cache on. wolfBoot returns clock and cache to their reset state before it -# starts the application; the test-app then switches both on again. +# starts the application (the cache stays on only if its invalidate times +# out); the test-app then switches both on again. # Remove to run from the 48 MHz internal oscillator. CFLAGS_EXTRA+=-DS32K1XX_CLOCK_80MHZ -DS32K1XX_CODE_CACHE diff --git a/docs/Targets.md b/docs/Targets.md index 30ffe53a31..eba58c04d4 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7599,7 +7599,8 @@ The following build options are available for the S32K1xx HAL: | `S32K1XX_CLOCK_HSRUN` | Removed: the build stops with an error. wolfBoot does not run in HSRUN, because flash cannot be programmed or erased there. An application enters HSRUN at 112 MHz with `s32k1xx_clock_hsrun()` (see `S32K1XX_HSRUN_SPEED_TEST`). | | `S32K1XX_CLOCK_80MHZ` | Run wolfBoot at 80 MHz (RUN mode) from the external crystal through the SPLL, instead of the 48 MHz FIRC. The crystal frequency is `S32K1XX_SOSC_FREQ` (default 8 MHz). The clock is switched back before the application starts; the s32k1xx test-app switches to 80 MHz again with `s32k1xx_clock_80mhz()`. Each wait for the crystal, the SPLL lock, the clock switch and the power mode is bounded (`S32K1XX_WAIT_LOOPS` status reads, at least about 60 ms); if one times out, wolfBoot prints a message and carries on at 48 MHz on the FIRC, and the clock functions return an error. Tested on the MCXE247 only. | | `S32K1XX_HSRUN_SPEED_TEST` | With `S32K1XX_CLOCK_80MHZ` and the wolfIP speed test, the test-app `network` command runs in HSRUN at 112 MHz (bus 56 MHz, flash 28 MHz) with `s32k1xx_clock_hsrun()` and returns to RUN at 80 MHz with `s32k1xx_clock_run()` when the server stops, so flash writes from the console still work. Tested on the MCXE247 only. | -| `S32K1XX_CODE_CACHE` | Enable the 4 KB LMEM code cache for flash while wolfBoot runs. It is invalidated after every flash erase and program command, and disabled before the application starts; the s32k1xx test-app enables it again with `s32k1xx_code_cache_enable()`. The waits for the cache commands are bounded like the clock waits: a cache that does not finish its invalidate stays off at start-up, and fails the flash command that needed it. Tested on the MCXE247 only. | +| `S32K1XX_CODE_CACHE` | Enable the 4 KB LMEM code cache for flash while wolfBoot runs. It is invalidated after every flash erase and program command, and disabled before the application starts (unless that last invalidate times out: PCCCR must not be written while a cache command runs, so the cache is then left on); the s32k1xx test-app enables it again with `s32k1xx_code_cache_enable()`. The waits for the cache commands are bounded like the clock waits: a cache that does not finish its invalidate stays off at start-up, and fails the flash command that needed it. Tested on the MCXE247 only. | +| `FAST_MEMCPY_UNALIGNED` | With `FAST_MEMCPY` on a Cortex-M (GCC), `memcpy` copies words even when the source and destination alignments differ, using unaligned word loads. Only for targets that never `memcpy` from peripheral registers, where unaligned loads are not allowed. `mcxe247.config` sets it; it about doubles the wolfIP test rates. | | `DEBUG_UART` | Enable LPUART debug output. | | `DEBUG_HARDFAULT` | Enable detailed hard fault debugging output. | | `S32K144`, `S32K146`, `S32K148` | Select variant (default is S32K142). Affects flash/SRAM size definitions. | diff --git a/src/string.c b/src/string.c index 3ad2895a8f..e6d18428f4 100644 --- a/src/string.c +++ b/src/string.c @@ -302,13 +302,16 @@ size_t strlen(const char *s) #undef RAMFUNCTION #define RAMFUNCTION #endif -/* Word copies from unaligned sources: M-profile only. Its cores load words - * from any Normal memory address (CCR.UNALIGN_TRP clear at reset); an - * A-profile core with the MMU off faults on any unaligned access, and - * AArch64 defines __ARM_FEATURE_UNALIGNED without -mstrict-align. */ -#if defined(FAST_MEMCPY) && defined(__GNUC__) && \ - defined(__ARM_FEATURE_UNALIGNED) && defined(__ARM_ARCH_PROFILE) && \ - (__ARM_ARCH_PROFILE == 'M') +/* Word copies from unaligned sources, opt-in with FAST_MEMCPY_UNALIGNED and + * M-profile only. Its cores load words from any Normal memory address + * (CCR.UNALIGN_TRP clear at reset); an A-profile core with the MMU off + * faults on any unaligned access, and AArch64 defines + * __ARM_FEATURE_UNALIGNED without -mstrict-align. Unaligned loads from + * Device memory (peripheral registers) are not allowed either, so a port + * that copies from peripherals with memcpy must not set it. */ +#if defined(FAST_MEMCPY) && defined(FAST_MEMCPY_UNALIGNED) && \ + defined(__GNUC__) && defined(__ARM_FEATURE_UNALIGNED) && \ + defined(__ARM_ARCH_PROFILE) && (__ARM_ARCH_PROFILE == 'M') #define WOLFBOOT_MEMCPY_UNALIGNED #endif #ifdef WOLFBOOT_MEMCPY_UNALIGNED diff --git a/test-app/wolfip_tftp_test.c b/test-app/wolfip_tftp_test.c index a13edfac73..e9a58f7c1f 100644 --- a/test-app/wolfip_tftp_test.c +++ b/test-app/wolfip_tftp_test.c @@ -627,11 +627,15 @@ static void speed_print(void) if (ms == 0U) ms = 1U; - wolfBoot_printf("SPEED %s %s: %u ms rx %u B %u kbit/s tx %u B %u kbit/s\r\n", + /* KiB: a long TCP test passes 4 GiB */ + wolfBoot_printf("SPEED %s %s: %u ms rx %u KiB %u kbit/s " + "tx %u KiB %u kbit/s\r\n", (speed.proto == SPEED_PROTO_TCP) ? "tcp" : "udp", speed_mode_name(speed.mode), (unsigned)ms, - (unsigned)speed.rx_bytes, (unsigned)speed_kbps(speed.rx_bytes, ms), - (unsigned)speed.tx_bytes, (unsigned)speed_kbps(speed.tx_bytes, ms)); + (unsigned)(speed.rx_bytes >> 10), + (unsigned)speed_kbps(speed.rx_bytes, ms), + (unsigned)(speed.tx_bytes >> 10), + (unsigned)speed_kbps(speed.tx_bytes, ms)); if (speed.proto == SPEED_PROTO_UDP) { wolfBoot_printf(" datagrams rx %u tx %u\r\n", (unsigned)speed.rx_pkts, (unsigned)speed.tx_pkts); diff --git a/tools/unit-tests/Makefile b/tools/unit-tests/Makefile index ffe3cbc7db..6d779c5eaf 100644 --- a/tools/unit-tests/Makefile +++ b/tools/unit-tests/Makefile @@ -943,7 +943,8 @@ unit-xmodem-rx: ../../include/target.h unit-xmodem-rx.c \ # address, built on the host, whose CPU does the same unit-string-unaligned: ../../include/target.h unit-string.c gcc -o $@ $^ $(CFLAGS) -DDEBUG_UART -DPRINTF_ENABLED \ - -D__ARM_FEATURE_UNALIGNED=1 "-D__ARM_ARCH_PROFILE='M'" $(LDFLAGS) + -DFAST_MEMCPY_UNALIGNED -D__ARM_FEATURE_UNALIGNED=1 \ + "-D__ARM_ARCH_PROFILE='M'" $(LDFLAGS) unit-arm-tee-psa-ipc: ../../include/target.h unit-arm-tee-psa-ipc.c ../../src/arm_tee_psa_ipc.c gcc -o $@ unit-arm-tee-psa-ipc.c $(CFLAGS) -I$(WOLFBOOT_LIB_WOLFPSA)/wolfpsa \ From b22cdab2e0ded7d9f5db7a8a9f73cbeb881213b6 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Tue, 1 Dec 2026 01:45:55 -0500 Subject: [PATCH 16/24] minor fix --- docs/Targets.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/Targets.md b/docs/Targets.md index eba58c04d4..2046012092 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7831,10 +7831,8 @@ apply to the MCXE247, with these differences: The test application can run a wolfIP throughput test or a DHCP and TFTP test over the board's Ethernet port. This is optional and needs a wolfIP checkout with the `nxp_mcxe_enet` port, a standalone ENET driver with a generic -clause-22 PHY bring-up (no vendor SDK). The port is not in a wolfIP release -yet: it is in [wolfIP pull request 196](https://github.com/wolfSSL/wolfip/pull/196), -tested at commit `e139371`. Check that out in `lib/wolfip`, or point -`WOLFBOOT_LIB_WOLFIP` at it. +clause-22 PHY bring-up (no vendor SDK). The port requires wolfIP. +Check that out in `lib/wolfip`, or point `WOLFBOOT_LIB_WOLFIP` at it. The test app builds it interrupt driven (`NXP_MCXE_ENET_IRQ=1`, with the ENET receive and error IRQs, 74 and 75, routed in `test-app/startup_arm.c`). The wolfIP stack state, with 9 KB TCP receive and transmit buffers per socket, is placed in SRAM_L by From 33de392c0368eb51a3a511c2d5c7a01b12a155c3 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Tue, 1 Dec 2026 09:34:16 -0500 Subject: [PATCH 17/24] fix xmodem eot issue --- test-app/xmodem_rx.c | 7 ++++++- tools/unit-tests/unit-xmodem-rx.c | 33 +++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/test-app/xmodem_rx.c b/test-app/xmodem_rx.c index 109eee5e0f..c7acc8c914 100644 --- a/test-app/xmodem_rx.c +++ b/test-app/xmodem_rx.c @@ -141,8 +141,13 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) } } - /* Check for EOT */ + /* Check for EOT: refused until the whole image is in flash */ if (xpkt[0] == XEOT) { + if (!eot_expected) { + xmodem_cancel(); + ret = -1; + break; + } uart_tx(XACK); led_red_on(); /* Indicate transfer complete */ ret = 0; diff --git a/tools/unit-tests/unit-xmodem-rx.c b/tools/unit-tests/unit-xmodem-rx.c index a08d232303..aaa545280e 100644 --- a/tools/unit-tests/unit-xmodem-rx.c +++ b/tools/unit-tests/unit-xmodem-rx.c @@ -336,6 +336,37 @@ START_TEST(test_flash_write_failure) } END_TEST +/* EOT before the image size in the header has been received is refused */ +START_TEST(test_early_eot) +{ + xmodem_state_t st; + uint32_t img = 3U * 128U - IMAGE_HEADER_SIZE; + + setup(); + send_block(1, img, 0); + send_block(2, img, 0); + send_eot(); + ck_assert_int_eq(run(&st), -1); + ck_assert_uint_eq(st.dst_offset, 2U * 128U); + ck_assert_int_eq(count_out(XACK), 2); + ck_assert_int_eq(count_out(XCAN), 10); +} +END_TEST + +/* EOT before any block is refused */ +START_TEST(test_eot_without_blocks) +{ + xmodem_state_t st; + + setup(); + send_eot(); + ck_assert_int_eq(run(&st), -1); + ck_assert_int_eq(mock_writes, 0); + ck_assert_int_eq(count_out(XACK), 0); + ck_assert_int_eq(count_out(XCAN), 10); +} +END_TEST + static Suite *xmodem_suite(void) { Suite *s = suite_create("XMODEM receiver"); @@ -349,6 +380,8 @@ static Suite *xmodem_suite(void) tcase_add_test(tc, test_bad_crc_duplicate); tcase_add_test(tc, test_out_of_sequence); tcase_add_test(tc, test_flash_write_failure); + tcase_add_test(tc, test_early_eot); + tcase_add_test(tc, test_eot_without_blocks); suite_add_tcase(s, tc); return s; } From 27dd4f874b50c2184f026a55fd8316c693a0b13a Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Wed, 18 Nov 2026 12:16:32 -0500 Subject: [PATCH 18/24] initial commit --- .github/workflows/test-configs.yml | 6 + arch.mk | 4 + config/examples/mcxe31b.config | 55 + docs/Targets.md | 110 ++ hal/mcxe31b.c | 586 +++++++++ hal/mcxe31b.h | 288 +++++ hal/mcxe31b.ld | 80 ++ test-app/ARM-mcxe31b.ld | 70 ++ test-app/Makefile | 9 + test-app/app_mcxe31b.c | 1046 +++++++++++++++++ test-app/startup_arm.c | 9 + tools/scripts/mcxe31b/e31b_debug.cmm | 101 ++ .../mcxe31b/e31b_flash_factory_bin.cmm | 106 ++ tools/scripts/mcxe31b/e31b_flash_update.cmm | 92 ++ 14 files changed, 2562 insertions(+) create mode 100644 config/examples/mcxe31b.config create mode 100644 hal/mcxe31b.c create mode 100644 hal/mcxe31b.h create mode 100644 hal/mcxe31b.ld create mode 100644 test-app/ARM-mcxe31b.ld create mode 100644 test-app/app_mcxe31b.c create mode 100644 tools/scripts/mcxe31b/e31b_debug.cmm create mode 100644 tools/scripts/mcxe31b/e31b_flash_factory_bin.cmm create mode 100644 tools/scripts/mcxe31b/e31b_flash_update.cmm diff --git a/.github/workflows/test-configs.yml b/.github/workflows/test-configs.yml index 859e1c8004..0c12ede1e3 100644 --- a/.github/workflows/test-configs.yml +++ b/.github/workflows/test-configs.yml @@ -644,6 +644,12 @@ jobs: arch: arm config-file: ./config/examples/mcxe247.config + nxp_mcxe31b_test: + uses: ./.github/workflows/test-build.yml + with: + arch: arm + config-file: ./config/examples/mcxe31b.config + max32666_test: uses: ./.github/workflows/test-build.yml with: diff --git a/arch.mk b/arch.mk index 40df366382..da7db1ab78 100644 --- a/arch.mk +++ b/arch.mk @@ -571,6 +571,10 @@ ifeq ($(ARCH),ARM) ifeq ($(TARGET),imx95_m7) CORTEX_M7=1 endif + ifeq ($(TARGET),mcxe31b) + CORTEX_M7=1 + ARCH_FLASH_OFFSET=0x00400000 + endif ifeq ($(TARGET),stm32l0) CORTEX_M0=1 SPI_TARGET=stm32 diff --git a/config/examples/mcxe31b.config b/config/examples/mcxe31b.config new file mode 100644 index 0000000000..e5e80d9221 --- /dev/null +++ b/config/examples/mcxe31b.config @@ -0,0 +1,55 @@ +# wolfBoot configuration for NXP MCX E31B (FRDM-MCXE31B) +# +# MCXE31B: Cortex-M7, 4 MB code flash (four 1 MB blocks) + 128 KB data flash, +# 8 KB sectors. wolfBoot switches the core from FIRC 48 MHz to the PLL +# (160 MHz) and enables the caches. It runs from flash, with data, bss and the +# RAM_CODE flash routines in the 64 KB CM7_0 DTCM. +# +# Build: cp config/examples/mcxe31b.config .config && make + +ARCH?=ARM +TARGET?=mcxe31b +SIGN?=ECC256 +HASH?=SHA256 +VTOR?=1 +NO_ASM?=0 +NO_MPU=1 +EXT_FLASH?=0 +SPI_FLASH?=0 +ALLOW_DOWNGRADE?=0 + +# Each 64-bit ECC segment of the flash can be programmed only once between +# erases +NVM_FLASH_WRITEONCE?=1 + +WOLFBOOT_VERSION?=0 +V?=0 +SPMATH?=1 +RAM_CODE?=1 +DUALBANK_SWAP?=0 + +# The CM7 DTCM is ECC protected and must be written before it is read +CFLAGS_EXTRA+=-DWOLFBOOT_RAM_ECC_INIT + +# 8KB sectors +WOLFBOOT_SECTOR_SIZE?=0x2000 + +# Memory layout (code flash 0x00400000 - 0x007FFFFF): +# IVT + Bootloader: 0x00400000 - 0x0040FFFF (64 KB) +# Boot Partition: 0x00410000 - 0x005EFFFF (1920 KB) +# Update Partition: 0x005F0000 - 0x007CFFFF (1920 KB) +# Swap Sector: 0x007D0000 - 0x007D1FFF (8 KB) +# 0x007D4000 - 0x007FFFFF is left free: it holds the Secure BAF and, when the +# security firmware feature flag is set, the security firmware. +WOLFBOOT_PARTITION_SIZE?=0x1E0000 +WOLFBOOT_PARTITION_BOOT_ADDRESS?=0x410000 +WOLFBOOT_PARTITION_UPDATE_ADDRESS?=0x5F0000 +WOLFBOOT_PARTITION_SWAP_ADDRESS?=0x7D0000 + +# Console on the MCU-Link VCOM port: LPUART5, PTE14 (TX) and PTE3 (RX), +# 115200 8N1 + +# Debugging options +DEBUG?=0 +DEBUG_SYMBOLS?=0 +DEBUG_UART?=1 diff --git a/docs/Targets.md b/docs/Targets.md index 2046012092..9bf440d15a 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -47,6 +47,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) @@ -7945,6 +7946,115 @@ Detach with `SYStem.Down` before testing an update, which relies on a software reset. +## NXP MCXE31B + +The NXP MCX E31B is a Cortex-M7 microcontroller with 4 MB of code flash (four +1 MB blocks), 128 KB of data flash and 512 KB of SRAM. It has its own +bare-metal `mcxe31b` HAL. No SDK is needed. The port targets the FRDM-MCXE31B +board. + +- The boot ROM (Secure BAF) starts wolfBoot through the Image Vector Table + (IVT) that the HAL places at `0x00400000`. +- Flash (C40ASF): 8 KB sectors. Each 64-bit ECC segment can be programmed once + between erases, and a program operation writes up to 128 bytes. +- wolfBoot and the test application use the 64 KB CM7_0 DTCM for data, stack + and the `RAM_CODE` flash routines. The DTCM is ECC protected; the reset + handler clears it before use (`WOLFBOOT_RAM_ECC_INIT`, set by `arch.mk`). +- `hal_init()` switches from the boot ROM's FIRC 48 MHz to the PLL (16 MHz + crystal, reference manual clock "Option A"): core 160 MHz, AIPS_PLAT 80 MHz, + AIPS_SLOW 40 MHz. It first enables the last mile regulator, which the + FRDM-MCXE31B feeds through the Q1 ballast on VRC_CTRL. If a step fails, + wolfBoot stays on FIRC and prints a warning. +- The I-cache and D-cache are on while wolfBoot runs; flash program and erase + invalidate the D-cache over the modified range. Both caches are cleaned and + turned off before the jump to the application. The clocks stay at 160 MHz. + +### NXP MCXE31B: Memory Layout + +| Region | Address Range | Size | +|--------|---------------|------| +| IVT + Bootloader | 0x00400000 - 0x0040FFFF | 64 KB | +| Boot Partition | 0x00410000 - 0x005EFFFF | 1920 KB | +| Update Partition | 0x005F0000 - 0x007CFFFF | 1920 KB | +| Swap Sector | 0x007D0000 - 0x007D1FFF | 8 KB | + +`0x007D4000 - 0x007FFFFF` is not used: the Secure BAF occupies the last 48 KB, +and the security firmware uses the 128 KB below it when its feature flag is +set. The boot ROM uses the lowest valid IVT, so the IVT of wolfBoot at +`0x00400000` always wins. + +### NXP MCXE31B: Building + +```sh +cp config/examples/mcxe31b.config .config +make +``` + +`factory.bin` (wolfBoot plus the signed version 1 test application) must be +programmed at `0x00400000`. + +The console is on the MCU-Link VCOM port (LPUART5, PTE14 TX, PTE3 RX, 115200 +8N1). The test application shows green on the RGB LED for version 1 and blue +for later versions, and has the same console as the +[S32K1xx test application](#nxp-s32k1xx-test-application). + +### NXP MCXE31B: Configuration Options + +| Option | Description | +|--------|-------------| +| `NVM_FLASH_WRITEONCE` | **Required.** A 64-bit ECC segment can be programmed once between erases, so trailer updates erase and rewrite the sector. | +| `RAM_CODE` | **Required.** The flash program and erase routines run from DTCM, so the block being written is not read. The linker script checks this. | +| `DEBUG_UART` | Console output on LPUART5 (MCU-Link VCOM). | + +### NXP MCXE31B: Programming with Lauterbach TRACE32 + +Connect the 10-pin debug cable to J14 and short JP5 to disable the onboard +MCU-Link SWD. TRACE32 R2024.09 has no MCXE31B entry. The S32K314 has the same +debug architecture (AHB-AP 4 = CM7_0, MDM-AP 6, SDA-AP 7) and flash +controller, so use `SYStem.CPU S32K314-M7` with SWD (JTAG on J14 does not +work). Program `factory.bin` at `0x00400000`. + +Scripts for this are in `tools/scripts/mcxe31b`. They find the build output +relative to their own location, so run them from the wolfBoot checkout, for +example `DO /tools/scripts/mcxe31b/e31b_flash_factory_bin.cmm`: + +| Script | Purpose | +|--------|---------| +| `e31b_debug.cmm` | Reset and halt the CPU, then load the `wolfboot.elf` and `test-app/image.elf` symbols | +| `e31b_flash_factory_bin.cmm` | Program `factory.bin`, erase the update partition and swap sector, then reset and detach | +| `e31b_flash_update.cmm` | Program `test-app/image_v2_signed.bin` into the update partition, then reset and detach | + +Each script writes a log to the TRACE32 system directory (`~~`). + +The flash scripts run the TRACE32 S32K3 flash algorithm (`s32k3x4.bin`) from +the DTCM, which they clear first so its ECC is valid. They leave the data +flash and the Secure BAF area untouched. The factory script refuses a file +without the IVT marker at offset 0. + +`SYStem.Up` sometimes reports a debug port time-out while the boot ROM runs. +`e31b_debug.cmm` then attaches, and finds the core halted at the reset vector. + +While TRACE32 is attached, it halts the CPU at the reset vector on every reset. +Detach with `SYStem.Down` before testing an update, which relies on a software +reset. + +### NXP MCXE31B: Testing an update + +Tested on the FRDM-MCXE31B: + +1. Program `factory.bin` with `e31b_flash_factory_bin.cmm`. wolfBoot boots + version 1 and the RGB LED is green. +2. Sign version 2 and program it with `e31b_flash_update.cmm`: + ```sh + tools/keytools/sign --ecc256 --sha256 test-app/image.bin wolfboot_signing_private_key.der 2 + ``` +3. On the console, `status` shows the update. `trigger` then `reboot` swaps + the partitions. Version 2 boots, finds the TESTING state and marks itself + successful. The RGB LED is blue. + +The console `update` command receives a signed image over XMODEM-CRC into the +update partition instead, and triggers it. + ## TI Hercules TMS570LC435 See [/config/examples/ti-tms570lc435.config](/config/examples/ti-tms570lc435.config) for example configuration. diff --git a/hal/mcxe31b.c b/hal/mcxe31b.c new file mode 100644 index 0000000000..c0ac77d773 --- /dev/null +++ b/hal/mcxe31b.c @@ -0,0 +1,586 @@ +/* mcxe31b.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + * + * HAL for NXP MCXE31B (Cortex-M7, 4MB C40ASF code flash + 128KB data flash) + * Tested on FRDM-MCXE31B. + */ + +#include +#include +#include "image.h" +#include "hal.h" +#include "printf.h" + +/* Override RAMFUNCTION for test-app: when RAM_CODE is set but not __WOLFBOOT, + * we still need flash functions to run from RAM for self-programming. */ +#if defined(RAM_CODE) && !defined(__WOLFBOOT) + #undef RAMFUNCTION + #define RAMFUNCTION __attribute__((used,section(".ramcode"),long_call)) +#endif + +#define DSB() __asm__ volatile ("dsb") +#define ISB() __asm__ volatile ("isb") + +#define __get_PRIMASK() ({ \ + uint32_t primask; \ + __asm__ volatile ("mrs %0, primask" : "=r" (primask)); \ + primask; \ +}) + +#define __set_PRIMASK(primask) \ + __asm__ volatile ("msr primask, %0" :: "r" (primask) : "memory") + +#define __disable_irq() \ + __asm__ volatile ("cpsid i" ::: "memory") + +#include "mcxe31b.h" + +/* ============== Image Vector Table (IVT) ============== */ +/* The Secure BAF boot ROM scans for this 256-byte structure at the start of + * each code flash block (0x00400000 first) and starts CM7_0 at the vector + * table it points to. */ + +#ifdef __WOLFBOOT + +extern uint32_t _start_vector; + +const uint32_t __attribute__((section(".ivt"))) mcxe31b_ivt[64] = { + IVT_MARKER, /* 0x00: IVT marker */ + IVT_BCW_CM7_0_ENABLE, /* 0x04: boot config: start CM7_0, no SWT0 */ + 0, /* 0x08: reserved */ + (uint32_t)&_start_vector, /* 0x0C: CM7_0 start address */ + 0, /* 0x10: reserved */ + 0, /* 0x14: CM7_1 start address (n/a) */ + 0, /* 0x18: reserved */ + 0, /* 0x1C: CM7_2 start address (n/a) */ + 0, /* 0x20: reserved */ + 0, /* 0x24: LC configuration word address */ + /* 0x28 - 0xFF: reserved (zero) */ +}; + +#endif /* __WOLFBOOT */ + +/* ============== Clocks ============== */ + +#define CLOCK_TIMEOUT 1000000 + +/* Enable a partition 1 peripheral clock by its MC_ME clock request number */ +static void mc_me_clock_enable(uint32_t req) +{ + uint32_t cofb = req / 32; + uint32_t bit = 1UL << (req % 32); + + if (MC_ME_PRTN1_COFB_STAT(cofb) & bit) + return; + MC_ME_PRTN1_COFB_CLKEN(cofb) |= bit; + MC_ME_PRTN1_PUPD = MC_ME_PRTN_PUPD_PCUD; + MC_ME_CTL_KEY = MC_ME_CTL_KEY_KEY; + MC_ME_CTL_KEY = MC_ME_CTL_KEY_INVKEY; + while (!(MC_ME_PRTN1_COFB_STAT(cofb) & bit)) {} +} + +/* Busy wait for at least n core cycles */ +static void delay_cycles(uint32_t n) +{ + volatile uint32_t i; + for (i = 0; i < n; i++) {} +} + +/* Switch the system clocks from FIRC 48 MHz to the PLL using the RM + * "Option A" (high performance) configuration: FXOSC 16 MHz -> PLL VCO + * 960 MHz -> ODIV2 480 MHz -> PHI0 160 MHz. On failure the system stays + * on FIRC. */ +static int clock_init(void) +{ + /* MUX_0 dividers (DIV + 1): CORE 160, AIPS_PLAT 80, AIPS_SLOW 40, + * HSE 80, DCM 40, LBIST 40, QSPI_MEM 160 MHz */ + static const uint8_t mux0_div[MC_CGM_MUX0_NUM_DIV] = { + 0, 1, 3, 1, 3, 3, 0 + }; + uint32_t timeout; + int i; + + /* Already running from the PLL, e.g. the test-app started by wolfBoot */ + if (MC_CGM_CSS_SELSTAT(MC_CGM_MUX0_CSS) == MC_CGM_SEL_PLL_PHI0) + return 0; + + mc_me_clock_enable(MC_ME_REQ_FXOSC); + mc_me_clock_enable(MC_ME_REQ_PLL); + + /* Last mile regulator: it supplies the core above FIRC speed. Start the + * V15 ballast, wait for its soft start and for V15, then hand over. */ + if (!(PMC_CONFIG & PMC_CONFIG_LMEN)) { + PMC_CONFIG |= PMC_CONFIG_LMBCTLEN; + delay_cycles(FIRC_FREQ / 20000); /* 50 us */ + timeout = CLOCK_TIMEOUT; + while ((PMC_LVSC & PMC_LVSC_LVD15S) && --timeout) {} + if (timeout == 0) + return -1; + PMC_LVSC = PMC_LVSC_LVD15F; + PMC_CONFIG |= PMC_CONFIG_LMEN; + delay_cycles(FIRC_FREQ / 500000); /* 2 us before a clock change */ + } + + /* FXOSC: crystal mode with the reset end-of-count and gain values */ + if (!(FXOSC_STAT & FXOSC_STAT_OSC_STAT)) { + FXOSC_CTRL = FXOSC_CTRL_COMP_EN | FXOSC_CTRL_EOCV(0x9D) | + FXOSC_CTRL_GM_SEL(0xC) | FXOSC_CTRL_OSCON; + timeout = CLOCK_TIMEOUT; + while (!(FXOSC_STAT & FXOSC_STAT_OSC_STAT) && --timeout) {} + if (timeout == 0) + return -1; + } + + /* PLL: 16 MHz / 1 * 60 = 960 MHz VCO, / 2 = 480 MHz, PHI0 / 3 */ + PLL_PLLODIV(0) = 0; + PLL_PLLODIV(1) = 0; + PLL_PLLCR = PLL_PLLCR_PLLPD; + PLL_PLLDV = PLL_PLLDV_RESERVED | PLL_PLLDV_ODIV2(2) | PLL_PLLDV_RDIV(1) | + PLL_PLLDV_MFI(60); + PLL_PLLFM = PLL_PLLFM_SSCGBYP; + PLL_PLLFD = 0; + PLL_PLLODIV(0) = PLL_PLLODIV_DIV(2); + PLL_PLLCR = 0; + timeout = CLOCK_TIMEOUT; + while (!(PLL_PLLSR & PLL_PLLSR_LOCK) && --timeout) {} + if (timeout == 0) { + PLL_PLLCR = PLL_PLLCR_PLLPD; + return -1; + } + PLL_PLLODIV(0) = PLL_PLLODIV_DE | PLL_PLLODIV_DIV(2); + + /* SRAM0 needs a read wait state above 120 MHz. Nothing runs from SRAM0 + * here, so it can be changed safely. */ + PRAMC0_PRCR1 |= PRAMC_PRCR1_FT_DIS; + + /* Program all MUX_0 dividers together, with the crossbar halt + * handshake, then switch the mux to PHI0 */ + MC_CGM_MUX0_DIV_TRIG_CTRL = MC_CGM_DIV_TRIG_CTRL_TCTL | + MC_CGM_DIV_TRIG_CTRL_HHEN; + for (i = 0; i < MC_CGM_MUX0_NUM_DIV; i++) + MC_CGM_MUX0_DC(i) = MC_CGM_DC_DE | MC_CGM_DC_DIV(mux0_div[i]); + MC_CGM_MUX0_DIV_TRIG = 0xFFFFFFFFUL; + while (MC_CGM_MUX0_DIV_UPD_STAT & MC_CGM_DIV_UPD_STAT_DIV_STAT) {} + + MC_CGM_MUX0_CSC = MC_CGM_CSC_SELCTL(MC_CGM_SEL_PLL_PHI0) | + MC_CGM_CSC_CLK_SW; + timeout = CLOCK_TIMEOUT; + while (((MC_CGM_MUX0_CSS & MC_CGM_CSS_SWIP) || + MC_CGM_CSS_SELSTAT(MC_CGM_MUX0_CSS) != MC_CGM_SEL_PLL_PHI0) && + --timeout) {} + if (timeout == 0) + return -1; + return 0; +} + +/* ============== Caches ============== */ + +/* Code and data flash are in the Cortex-M7 "Code" region (normal memory, + * write-through cacheable with the default memory map), so the D-cache can + * hold flash contents that a program or erase has changed. The TCMs are not + * cached. */ +static void RAMFUNCTION dcache_invalidate_range(uint32_t addr, uint32_t len) +{ + uint32_t line; + + if (!(SCB_CCR & SCB_CCR_DC)) + return; + DSB(); + for (line = addr & ~(CACHE_LINE_SIZE - 1); line < addr + len; + line += CACHE_LINE_SIZE) { + SCB_DCIMVAC = line; + } + DSB(); + ISB(); +} + +/* Operate on every D-cache line by set/way: DCISW invalidates, DCCISW cleans + * and invalidates */ +static void dcache_setway(volatile uint32_t *op) +{ + uint32_t sets, ways, ccsidr; + + SCB_CSSELR = 0; /* L1 data cache */ + DSB(); + ccsidr = SCB_CCSIDR; + sets = (ccsidr >> 13) & 0x7FFF; + do { + ways = (ccsidr >> 3) & 0x3FF; + do { + *op = ((sets & 0x1FF) << 5) | ((ways & 0x3) << 30); + } while (ways-- != 0); + } while (sets-- != 0); + DSB(); +} + +static void cache_enable(void) +{ + if (!(SCB_CCR & SCB_CCR_IC)) { + DSB(); + ISB(); + SCB_ICIALLU = 0; + DSB(); + ISB(); + SCB_CCR |= SCB_CCR_IC; + DSB(); + ISB(); + } + if (!(SCB_CCR & SCB_CCR_DC)) { + dcache_setway(&SCB_DCISW); + SCB_CCR |= SCB_CCR_DC; + DSB(); + ISB(); + } +} + +/* Hand over with both caches off and empty */ +static void cache_disable(void) +{ + if (SCB_CCR & SCB_CCR_DC) { + dcache_setway(&SCB_DCCISW); + SCB_CCR &= ~SCB_CCR_DC; + DSB(); + ISB(); + } + if (SCB_CCR & SCB_CCR_IC) { + DSB(); + ISB(); + SCB_CCR &= ~SCB_CCR_IC; + SCB_ICIALLU = 0; + DSB(); + ISB(); + } +} + +#ifdef DEBUG_UART + +#ifndef UART_BAUDRATE +#define UART_BAUDRATE 115200 +#endif + +/* LPUART5 functional clock, from the clock configuration actually in use + * (the PLL setup may have failed and left the system on FIRC) */ +static uint32_t aips_slow_clk(void) +{ + uint32_t src = FIRC_FREQ; + + if (MC_CGM_CSS_SELSTAT(MC_CGM_MUX0_CSS) == MC_CGM_SEL_PLL_PHI0) + src = PLL_PHI0_FREQ; + return src / (MC_CGM_DC_GET_DIV(MC_CGM_MUX0_DC(MC_CGM_DIV_AIPS_SLOW)) + 1); +} + +void uart_init(void) +{ + uint32_t clk = aips_slow_clk(); + uint32_t osr, sbr, err; + uint32_t best_osr = 16, best_sbr = 1, best_err = 0xFFFFFFFFUL; + + /* Pick the oversampling ratio (8..32) with the smallest baud error */ + for (osr = 8; osr <= 32; osr++) { + sbr = (clk + (UART_BAUDRATE * osr / 2)) / (UART_BAUDRATE * osr); + if (sbr == 0 || sbr > 0x1FFF) + continue; + err = clk / (osr * sbr); + err = (err > UART_BAUDRATE) ? err - UART_BAUDRATE : + UART_BAUDRATE - err; + if (err < best_err) { + best_err = err; + best_osr = osr; + best_sbr = sbr; + } + } + + mc_me_clock_enable(MC_ME_REQ_LPUART5); + + /* Pin mux: TX output, RX input routed through IMCR */ + SIUL2_MSCR(UART_TX_PAD) = SIUL2_MSCR_OBE | SIUL2_MSCR_SSS(UART_TX_SSS); + SIUL2_MSCR(UART_RX_PAD) = SIUL2_MSCR_IBE; + SIUL2_IMCR(UART_RX_IMCR) = UART_RX_IMCR_SSS; + + LPUART_CTRL = 0; + LPUART_BAUD = ((best_osr - 1) << LPUART_BAUD_OSR_SHIFT) | + (best_sbr << LPUART_BAUD_SBR_SHIFT); + LPUART_CTRL = LPUART_CTRL_TE | LPUART_CTRL_RE; +} + +void RAMFUNCTION uart_tx(uint8_t byte) +{ + while (!(LPUART_STAT & LPUART_STAT_TDRE)) {} + LPUART_DATA = byte; +} + +void uart_write(const char* buf, unsigned int sz) +{ + unsigned int i; + for (i = 0; i < sz; i++) { + if (buf[i] == '\n') { + uart_tx('\r'); + } + uart_tx(buf[i]); + } + while (!(LPUART_STAT & LPUART_STAT_TC)) {} +} + +/* Non-blocking read: returns 1 if a character was read, 0 otherwise */ +int RAMFUNCTION uart_read(char* c) +{ + uint32_t stat = LPUART_STAT; + + if (stat & (LPUART_STAT_OR | LPUART_STAT_NF | LPUART_STAT_FE | + LPUART_STAT_PF)) { + LPUART_STAT = stat; /* write 1 to clear */ + } + if (stat & LPUART_STAT_RDRF) { + *c = (char)(LPUART_DATA & 0xFF); + return 1; + } + return 0; +} + +#endif /* DEBUG_UART */ + +/* Return the PFLASH lock register and bit covering a flash address. The first + * 768 KB of each code block is locked per 64 KB super sector, the last 256 KB + * (and the data flash) per 8 KB sector. */ +static volatile uint32_t* RAMFUNCTION flash_lock_reg(uint32_t address, + uint32_t *bit) +{ + uint32_t blk, off; + + if (address >= FLASH_DATA_BASE) { + *bit = 1UL << ((address - FLASH_DATA_BASE) / FLASH_SECTOR_SIZE); + return &PFLASH_SPELOCK(4); + } + blk = (address - FLASH_BASE) / FLASH_BLOCK_SIZE; + off = (address - FLASH_BASE) % FLASH_BLOCK_SIZE; + if (off < FLASH_SUPER_SECTOR_AREA) { + *bit = 1UL << (off / FLASH_SUPER_SECTOR_SIZE); + return &PFLASH_SSPELOCK(blk); + } + *bit = 1UL << ((off - FLASH_SUPER_SECTOR_AREA) / FLASH_SECTOR_SIZE); + return &PFLASH_SPELOCK(blk); +} + +/* Clearing and restoring the line buffer invalidates stale reads of + * the flash array after a program or erase */ +static void RAMFUNCTION flash_invalidate_buffers(void) +{ + uint32_t pfcr0 = PFLASH_PFCR0; + uint32_t pfcr1 = PFLASH_PFCR1; + uint32_t mask = PFLASH_PFCR_CBFEN | PFLASH_PFCR_DBFEN; + + PFLASH_PFCR0 = pfcr0 & ~mask; + PFLASH_PFCR1 = pfcr1 & ~mask; + DSB(); + PFLASH_PFCR0 = pfcr0; + PFLASH_PFCR1 = pfcr1; + DSB(); + ISB(); +} + +/* Run the high voltage step of a program (PGM) or erase (ERS) sequence whose + * interlock writes (PEADR_L and DATA) are already done. addr/len is the + * flash range that the operation modifies. */ +static int RAMFUNCTION flash_hv_operation(uint32_t op, uint32_t addr, + uint32_t len) +{ + int ret = 0; + uint32_t primask; + + /* No flash fetches (e.g. interrupt handlers) while the controller is + * busy: reading the block being modified is a read-while-write error */ + primask = __get_PRIMASK(); + __disable_irq(); + + C40ASF_MCR = op; + C40ASF_MCR = op | C40ASF_MCR_EHV; + while (!(C40ASF_MCRS & C40ASF_MCRS_DONE)) {} + if (!(C40ASF_MCRS & C40ASF_MCRS_PEG) || + (C40ASF_MCRS & C40ASF_MCRS_ERR_MASK)) { + ret = -1; + } + C40ASF_MCR = op; + C40ASF_MCR = 0; + + flash_invalidate_buffers(); + dcache_invalidate_range(addr, len); + __set_PRIMASK(primask); + return ret; +} + +static void RAMFUNCTION flash_prepare(void) +{ + while (!(C40ASF_MCRS & C40ASF_MCRS_DONE)) {} + /* Clear sticky errors from earlier operations (write 1 to clear) */ + C40ASF_MCRS = C40ASF_MCRS_ERR_MASK; +} + +/* Program up to one quad page (128 bytes). words[] holds the whole quad page + * image; only words whose bit is set in mask are written to DATAn, the + * others receive no program pulses. */ +static int RAMFUNCTION flash_program_qpage(uint32_t qpage, + const uint32_t *words, uint32_t mask) +{ + volatile uint32_t *lock; + uint32_t bit; + int i, ret; + int first = 1; + + flash_prepare(); + lock = flash_lock_reg(qpage, &bit); + *lock &= ~bit; + + for (i = 0; i < (FLASH_QUAD_PAGE_SIZE / 4); i++) { + if (!(mask & (1UL << i))) + continue; + if (first) { + /* Interlock write: selects the quad page to program */ + PFLASH_PEADR_L = qpage + (i * 4); + first = 0; + } + C40ASF_DATA(i) = words[i]; + } + ret = flash_hv_operation(C40ASF_MCR_PGM, qpage, FLASH_QUAD_PAGE_SIZE); + *lock |= bit; + return ret; +} + +static int RAMFUNCTION flash_erase_sector(uint32_t address) +{ + volatile uint32_t *lock; + uint32_t bit; + int ret; + + flash_prepare(); + lock = flash_lock_reg(address, &bit); + *lock &= ~bit; + + /* Erase interlock write: sector address plus one DATA write */ + PFLASH_PEADR_L = address; + C40ASF_DATA(0) = 0; + ret = flash_hv_operation(C40ASF_MCR_ERS, address, FLASH_SECTOR_SIZE); + *lock |= bit; + return ret; +} + +void hal_init(void) +{ + /* SWT0 is disabled because the IVT boot configuration word does not + * request it */ + int clk_ret = clock_init(); + + cache_enable(); + +#ifdef DEBUG_UART + uart_init(); +#endif + +#if defined(DEBUG_UART) && defined(__WOLFBOOT) +#ifdef WOLFBOOT_REPRODUCIBLE_BUILD + wolfBoot_printf("wolfBoot Version: %s\n", LIBWOLFBOOT_VERSION_STRING); +#else + wolfBoot_printf("wolfBoot Version: %s (%s %s)\n", + LIBWOLFBOOT_VERSION_STRING, __DATE__, __TIME__); +#endif + if (clk_ret != 0) + wolfBoot_printf("PLL setup failed: running from FIRC 48 MHz\n"); +#else + (void)clk_ret; +#endif +} + +void hal_prepare_boot(void) +{ +#ifdef DEBUG_UART + /* Leave the UART idle so the application can reinitialize it */ + while (!(LPUART_STAT & LPUART_STAT_TC)) {} + LPUART_CTRL = 0; +#endif + /* The application starts with the clocks left at 160 MHz and with both + * caches off */ + cache_disable(); +} + +/* Program any length at any address. Writes are split per quad page; each + * 64-bit ECC segment that changes is merged with the current flash contents + * and programmed once. Segments that are unchanged are skipped, because the + * C40ASF allows only one program per ECC segment between erases. */ +int RAMFUNCTION hal_flash_write(uint32_t address, const uint8_t *data, int len) +{ + uint32_t words[FLASH_QUAD_PAGE_SIZE / 4]; + uint8_t *buf = (uint8_t *)words; + uint32_t qpage, start, end, off, mask; + int ret; + + while (len > 0) { + qpage = address & ~(FLASH_QUAD_PAGE_SIZE - 1); + start = address - qpage; + end = start + (uint32_t)len; + if (end > FLASH_QUAD_PAGE_SIZE) + end = FLASH_QUAD_PAGE_SIZE; + + memcpy(buf, (const void *)qpage, FLASH_QUAD_PAGE_SIZE); + memcpy(buf + start, data, end - start); + + mask = 0; + for (off = start & ~(FLASH_DWORD_SIZE - 1); off < end; + off += FLASH_DWORD_SIZE) { + if (memcmp(buf + off, (const void *)(qpage + off), + FLASH_DWORD_SIZE) != 0) { + mask |= 3UL << (off / 4); + } + } + if (mask != 0) { + ret = flash_program_qpage(qpage, words, mask); + if (ret != 0) + return ret; + } + data += end - start; + address += end - start; + len -= (int)(end - start); + } + return 0; +} + +int RAMFUNCTION hal_flash_erase(uint32_t address, int len) +{ + int ret; + + if (len <= 0) + return -1; + + address &= ~(FLASH_SECTOR_SIZE - 1); + while (len > 0) { + ret = flash_erase_sector(address); + if (ret != 0) + return ret; + address += FLASH_SECTOR_SIZE; + len -= FLASH_SECTOR_SIZE; + } + return 0; +} + +void RAMFUNCTION hal_flash_unlock(void) +{ +} + +void RAMFUNCTION hal_flash_lock(void) +{ +} diff --git a/hal/mcxe31b.h b/hal/mcxe31b.h new file mode 100644 index 0000000000..743b4d6331 --- /dev/null +++ b/hal/mcxe31b.h @@ -0,0 +1,288 @@ +/* mcxe31b.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + * + * Register definitions for NXP MCXE31B (Cortex-M7, 4MB C40ASF flash). + * Register offsets and fields from the MCXE31x Reference Manual Rev. 3. + */ + +#ifndef MCXE31B_H +#define MCXE31B_H + +#include + +/* ============== Clock ============== */ + +/* The boot ROM (Secure BAF) leaves the core on FIRC 48 MHz. hal_init() + * switches to the PLL with the RM "Option A" (high performance) dividers: + * CORE_CLK 160 MHz, AIPS_PLAT_CLK 80 MHz, AIPS_SLOW_CLK 40 MHz (LPUART1..7 + * functional clock), HSE_CLK 80 MHz. */ +#define FIRC_FREQ 48000000UL +#define FXOSC_FREQ 16000000UL /* FRDM-MCXE31B Y1 crystal */ +#define PLL_PHI0_FREQ 160000000UL +#ifndef CLOCK_SPEED +#define CLOCK_SPEED PLL_PHI0_FREQ +#endif + +/* MC_CGM clock mux 0 (system clocks) */ +#define MC_CGM_BASE 0x402D8000UL +#define MC_CGM_MUX0_CSC (*(volatile uint32_t *)(MC_CGM_BASE + 0x300)) +#define MC_CGM_MUX0_CSS (*(volatile uint32_t *)(MC_CGM_BASE + 0x304)) +#define MC_CGM_MUX0_DC(n) (*(volatile uint32_t *)(MC_CGM_BASE + 0x308 + ((n) * 4))) +#define MC_CGM_MUX0_DIV_TRIG_CTRL (*(volatile uint32_t *)(MC_CGM_BASE + 0x334)) +#define MC_CGM_MUX0_DIV_TRIG (*(volatile uint32_t *)(MC_CGM_BASE + 0x338)) +#define MC_CGM_MUX0_DIV_UPD_STAT (*(volatile uint32_t *)(MC_CGM_BASE + 0x33C)) + +#define MC_CGM_CSC_SELCTL(x) (((x) & 0xFUL) << 24) +#define MC_CGM_CSC_CLK_SW (1UL << 2) +#define MC_CGM_CSS_SELSTAT(r) (((r) >> 24) & 0xFUL) +#define MC_CGM_CSS_SWIP (1UL << 16) +#define MC_CGM_SEL_FIRC 0x0 +#define MC_CGM_SEL_PLL_PHI0 0x8 +#define MC_CGM_DC_DE (1UL << 31) +#define MC_CGM_DC_DIV(x) (((x) & 0x7UL) << 16) +#define MC_CGM_DC_GET_DIV(r) (((r) >> 16) & 0x7UL) +#define MC_CGM_DIV_TRIG_CTRL_TCTL (1UL << 0) +#define MC_CGM_DIV_TRIG_CTRL_HHEN (1UL << 31) +#define MC_CGM_DIV_UPD_STAT_DIV_STAT (1UL << 0) + +/* MUX_0 dividers: CORE, AIPS_PLAT, AIPS_SLOW, HSE, DCM, LBIST, QSPI_MEM */ +#define MC_CGM_DIV_CORE_CLK 0 +#define MC_CGM_DIV_AIPS_PLAT 1 +#define MC_CGM_DIV_AIPS_SLOW 2 +#define MC_CGM_DIV_HSE 3 +#define MC_CGM_DIV_DCM 4 +#define MC_CGM_DIV_LBIST 5 +#define MC_CGM_DIV_QSPI_MEM 6 +#define MC_CGM_MUX0_NUM_DIV 7 + +/* FXOSC (fast crystal oscillator) */ +#define FXOSC_BASE 0x402D4000UL +#define FXOSC_CTRL (*(volatile uint32_t *)(FXOSC_BASE + 0x0)) +#define FXOSC_STAT (*(volatile uint32_t *)(FXOSC_BASE + 0x4)) +#define FXOSC_CTRL_OSCON (1UL << 0) +#define FXOSC_CTRL_GM_SEL(x) (((x) & 0xFUL) << 4) +#define FXOSC_CTRL_EOCV(x) (((x) & 0xFFUL) << 16) +#define FXOSC_CTRL_COMP_EN (1UL << 24) +#define FXOSC_STAT_OSC_STAT (1UL << 31) + +/* PLLDIG */ +#define PLL_BASE 0x402E0000UL +#define PLL_PLLCR (*(volatile uint32_t *)(PLL_BASE + 0x00)) +#define PLL_PLLSR (*(volatile uint32_t *)(PLL_BASE + 0x04)) +#define PLL_PLLDV (*(volatile uint32_t *)(PLL_BASE + 0x08)) +#define PLL_PLLFM (*(volatile uint32_t *)(PLL_BASE + 0x0C)) +#define PLL_PLLFD (*(volatile uint32_t *)(PLL_BASE + 0x10)) +#define PLL_PLLODIV(n) (*(volatile uint32_t *)(PLL_BASE + 0x80 + ((n) * 4))) +#define PLL_PLLCR_PLLPD (1UL << 31) +#define PLL_PLLSR_LOCK (1UL << 2) +#define PLL_PLLDV_MFI(x) ((x) & 0xFFUL) +#define PLL_PLLDV_RDIV(x) (((x) & 0x7UL) << 12) +#define PLL_PLLDV_ODIV2(x) (((x) & 0x3FUL) << 25) +#define PLL_PLLDV_RESERVED 0x003F0000UL /* keep at reset value */ +#define PLL_PLLFM_SSCGBYP (1UL << 30) +#define PLL_PLLODIV_DE (1UL << 31) +#define PLL_PLLODIV_DIV(x) (((x) & 0xFUL) << 16) + +/* PMC: the last mile regulator must be on to run above FIRC. On the + * FRDM-MCXE31B it builds V15 through an external NPN (Q1) driven by + * VRC_CTRL. */ +#define PMC_BASE 0x402E8000UL +#define PMC_LVSC (*(volatile uint32_t *)(PMC_BASE + 0x0)) +#define PMC_CONFIG (*(volatile uint32_t *)(PMC_BASE + 0x4)) +#define PMC_LVSC_LVD15F (1UL << 5) +#define PMC_LVSC_LVD15S (1UL << 13) +#define PMC_CONFIG_LMEN (1UL << 0) +#define PMC_CONFIG_LMBCTLEN (1UL << 1) + +/* PRAMC_0 (SRAM0 controller): one read wait state above 120 MHz */ +#define PRAMC0_PRCR1 (*(volatile uint32_t *)0x40264000UL) +#define PRAMC_PRCR1_FT_DIS (1UL << 0) + +/* ============== Flash memory map ============== */ + +#define FLASH_BASE 0x00400000UL +#define FLASH_BLOCK_SIZE 0x00100000UL /* 4 x 1 MB code flash blocks */ +#define FLASH_NUM_BLOCKS 4 +#define FLASH_DATA_BASE 0x10000000UL /* Data flash = block 4 */ +#define FLASH_DATA_SIZE 0x00020000UL /* 128 KB */ +#define FLASH_SECTOR_SIZE 0x2000UL /* 8 KB */ +#define FLASH_SUPER_SECTOR_SIZE 0x10000UL /* 64 KB */ +/* Each 1 MB block: first 768 KB locked per super sector, last 256 KB per + * sector */ +#define FLASH_SUPER_SECTOR_AREA 0x000C0000UL +#define FLASH_QUAD_PAGE_SIZE 128 /* Max bytes per program op */ +#define FLASH_DWORD_SIZE 8 /* ECC granularity */ + +/* ============== Image Vector Table (IVT) ============== */ + +#define IVT_MARKER 0x5AA55AA5UL +#define IVT_BCW_CM7_0_ENABLE (1UL << 0) +#define IVT_BCW_APP_SWT_INIT (1UL << 5) + +/* ============== C40ASF flash controller ============== */ + +#define C40ASF_BASE 0x402EC000UL +#define C40ASF_MCR (*(volatile uint32_t *)(C40ASF_BASE + 0x000)) +#define C40ASF_MCRS (*(volatile uint32_t *)(C40ASF_BASE + 0x004)) +#define C40ASF_DATA(n) (*(volatile uint32_t *)(C40ASF_BASE + 0x100 + ((n) * 4))) + +#define C40ASF_MCR_EHV (1UL << 0) +#define C40ASF_MCR_ERS (1UL << 4) +#define C40ASF_MCR_ESS (1UL << 5) +#define C40ASF_MCR_PGM (1UL << 8) + +#define C40ASF_MCRS_PES (1UL << 16) +#define C40ASF_MCRS_PEP (1UL << 17) +#define C40ASF_MCRS_RWE (1UL << 20) +#define C40ASF_MCRS_PEG (1UL << 14) +#define C40ASF_MCRS_DONE (1UL << 15) +#define C40ASF_MCRS_ERR_MASK (C40ASF_MCRS_PES | C40ASF_MCRS_PEP | \ + C40ASF_MCRS_RWE) + +/* ============== PFLASH controller ============== */ + +#define PFLASH_BASE 0x40268000UL +#define PFLASH_PFCR0 (*(volatile uint32_t *)(PFLASH_BASE + 0x000)) +#define PFLASH_PFCR1 (*(volatile uint32_t *)(PFLASH_BASE + 0x004)) +#define PFLASH_PEADR_L (*(volatile uint32_t *)(PFLASH_BASE + 0x300)) +/* Sector lock: blocks 0-3 = code flash, 4 = data flash */ +#define PFLASH_SPELOCK(blk) (*(volatile uint32_t *)(PFLASH_BASE + 0x340 + ((blk) * 4))) +/* Super sector lock: blocks 0-3 only */ +#define PFLASH_SSPELOCK(blk) (*(volatile uint32_t *)(PFLASH_BASE + 0x35C + ((blk) * 4))) + +/* Line buffer enables; clearing them also invalidates the buffers */ +#define PFLASH_PFCR_CBFEN (1UL << 0) +#define PFLASH_PFCR_DBFEN (1UL << 1) + +/* ============== MC_ME (mode entry / clock gating) ============== */ + +#define MC_ME_BASE 0x402DC000UL +#define MC_ME_CTL_KEY (*(volatile uint32_t *)(MC_ME_BASE + 0x000)) +#define MC_ME_MODE_CONF (*(volatile uint32_t *)(MC_ME_BASE + 0x004)) +#define MC_ME_MODE_UPD (*(volatile uint32_t *)(MC_ME_BASE + 0x008)) +#define MC_ME_PRTN1_PUPD (*(volatile uint32_t *)(MC_ME_BASE + 0x304)) +#define MC_ME_PRTN1_COFB_STAT(n) (*(volatile uint32_t *)(MC_ME_BASE + 0x310 + ((n) * 4))) +#define MC_ME_PRTN1_COFB_CLKEN(n) (*(volatile uint32_t *)(MC_ME_BASE + 0x330 + ((n) * 4))) + +#define MC_ME_CTL_KEY_KEY 0x00005AF0UL +#define MC_ME_CTL_KEY_INVKEY 0x0000A50FUL +#define MC_ME_MODE_CONF_FUNC_RST (1UL << 1) +#define MC_ME_MODE_UPD_MODE_UPD (1UL << 0) +#define MC_ME_PRTN_PUPD_PCUD (1UL << 0) + +/* Partition 1 clock requests: REQn = COFB(n / 32) bit (n % 32) */ +#define MC_ME_REQ_FXOSC 53 +#define MC_ME_REQ_PLL 56 +#define MC_ME_REQ_LPUART5 79 + +/* ============== SIUL2 (pin mux and GPIO) ============== */ + +#define SIUL2_BASE 0x40290000UL +#define SIUL2_MSCR(n) (*(volatile uint32_t *)(SIUL2_BASE + 0x240 + ((n) * 4))) +/* IMCR numbers as listed in the IOMUX file (512 and up) */ +#define SIUL2_IMCR(n) (*(volatile uint32_t *)(SIUL2_BASE + 0xA40 + (((n) - 512) * 4))) +/* 8-bit GPIO data registers, byte-swapped within each 32-bit word */ +#define SIUL2_GPDO(n) (*(volatile uint8_t *)(SIUL2_BASE + 0x1300 + ((n) + 3 - 2 * ((n) % 4)))) +#define SIUL2_GPDI(n) (*(volatile uint8_t *)(SIUL2_BASE + 0x1500 + ((n) + 3 - 2 * ((n) % 4)))) + +#define SIUL2_MSCR_OBE (1UL << 21) +#define SIUL2_MSCR_IBE (1UL << 19) +#define SIUL2_MSCR_SSS(x) ((x) & 0xFUL) + +/* Pad numbers: port * 32 + pin */ +#define PAD_PTB22 54 +#define PAD_PTC14 78 +#define PAD_PTC16 80 +#define PAD_PTE3 131 +#define PAD_PTE14 142 + +/* FRDM-MCXE31B: MCU-Link VCOM is LPUART5 on PTE14 (TX) / PTE3 (RX) */ +#define UART_TX_PAD PAD_PTE14 +#define UART_TX_SSS 4 +#define UART_RX_PAD PAD_PTE3 +#define UART_RX_IMCR 704 +#define UART_RX_IMCR_SSS 1 + +/* FRDM-MCXE31B: RGB LED D1 */ +#define LED_RED_PAD PAD_PTC16 +#define LED_GREEN_PAD PAD_PTB22 +#define LED_BLUE_PAD PAD_PTC14 + +/* ============== LPUART ============== */ + +#define LPUART5_BASE 0x4033C000UL +#define LPUART_BAUD (*(volatile uint32_t *)(LPUART5_BASE + 0x10)) +#define LPUART_STAT (*(volatile uint32_t *)(LPUART5_BASE + 0x14)) +#define LPUART_CTRL (*(volatile uint32_t *)(LPUART5_BASE + 0x18)) +#define LPUART_DATA (*(volatile uint32_t *)(LPUART5_BASE + 0x1C)) + +#define LPUART_BAUD_SBR_SHIFT 0 +#define LPUART_BAUD_OSR_SHIFT 24 +#define LPUART_STAT_RDRF (1UL << 21) +#define LPUART_STAT_TC (1UL << 22) +#define LPUART_STAT_TDRE (1UL << 23) +#define LPUART_STAT_OR (1UL << 19) +#define LPUART_STAT_NF (1UL << 18) +#define LPUART_STAT_FE (1UL << 17) +#define LPUART_STAT_PF (1UL << 16) +#define LPUART_CTRL_RE (1UL << 18) +#define LPUART_CTRL_TE (1UL << 19) +#define LPUART_CTRL_RIE (1UL << 21) +#define LPUART_IRQn 146 /* LPUART5 */ + +/* ============== Cortex-M7 caches ============== */ + +#define SCB_CCR (*(volatile uint32_t *)0xE000ED14UL) +#define SCB_CCR_DC (1UL << 16) +#define SCB_CCR_IC (1UL << 17) +#define SCB_CCSIDR (*(volatile uint32_t *)0xE000ED80UL) +#define SCB_CSSELR (*(volatile uint32_t *)0xE000ED84UL) +#define SCB_ICIALLU (*(volatile uint32_t *)0xE000EF50UL) +#define SCB_DCIMVAC (*(volatile uint32_t *)0xE000EF5CUL) +#define SCB_DCISW (*(volatile uint32_t *)0xE000EF60UL) +#define SCB_DCCISW (*(volatile uint32_t *)0xE000EF74UL) +#define CACHE_LINE_SIZE 32 + +/* ============== NVIC ============== */ + +#define NVIC_ISER(n) (*(volatile uint32_t *)(0xE000E100UL + ((n) * 4))) +#define NVIC_IPR(n) (*(volatile uint8_t *)(0xE000E400UL + (n))) +#define NVIC_PRIO_BITS 4 +#define NVIC_EnableIRQ(irq) (NVIC_ISER((irq) >> 5) = (1UL << ((irq) & 0x1F))) +#define NVIC_SetPriority(irq, prio) \ + (NVIC_IPR(irq) = (uint8_t)(((prio) << (8 - NVIC_PRIO_BITS)) & 0xFF)) + +/* ============== SysTick ============== */ + +#define SYST_CSR (*(volatile uint32_t *)0xE000E010) +#define SYST_RVR (*(volatile uint32_t *)0xE000E014) +#define SYST_CVR (*(volatile uint32_t *)0xE000E018) +#define SYST_CSR_ENABLE (1UL << 0) +#define SYST_CSR_TICKINT (1UL << 1) +#define SYST_CSR_CLKSOURCE (1UL << 2) + +#ifdef DEBUG_UART +void uart_init(void); +void uart_tx(uint8_t byte); +void uart_write(const char* buf, unsigned int sz); +int uart_read(char* c); +#endif + +#endif /* MCXE31B_H */ diff --git a/hal/mcxe31b.ld b/hal/mcxe31b.ld new file mode 100644 index 0000000000..57b3d0f846 --- /dev/null +++ b/hal/mcxe31b.ld @@ -0,0 +1,80 @@ +/* + * Linker script for wolfBoot on NXP MCXE31B + * + * Flash: the boot ROM reads the Image Vector Table (IVT) at 0x00400000 and + * starts CM7_0 at the vector table it points to (0x00400400 here). + * + * RAM: wolfBoot uses only the 64 KB CM7_0 DTCM (0x20000000). DTCM is ECC + * protected and must be written before it is read; the reset handler clears + * [_start_ecc_ram, _end_ecc_ram) first (WOLFBOOT_RAM_ECC_INIT). Unlike system + * SRAM, DTCM accepts 32-bit writes for ECC init and can execute code, so it + * also holds the RAM_CODE flash routines. + */ + +MEMORY +{ + FLASH (rx) : ORIGIN = @ARCH_FLASH_OFFSET@, LENGTH = @BOOTLOADER_PARTITION_SIZE@ + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x10000 /* 64 KB DTCM */ +} + +SECTIONS +{ + .text : + { + _start_text = .; + KEEP(*(.ivt)) + . = 0x400; + _start_vector = .; + KEEP(*(.isr_vector)) + *(.text*) + *(.rodata*) + *(.init*) + *(.fini*) + . = ALIGN(4); + _end_text = .; + } > FLASH + + .edidx : + { + . = ALIGN(4); + *(.ARM.exidx*) + } > FLASH + + _stored_data = .; + + .data : AT (_stored_data) + { + _start_data = .; + KEEP(*(.data*)) + . = ALIGN(4); + KEEP(*(.ramcode)) + . = ALIGN(4); + _end_data = .; + } > RAM + + .bss (NOLOAD) : + { + _start_bss = .; + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + _end_bss = .; + __bss_end__ = .; + _end = .; + } > RAM + . = ALIGN(4); +} + +END_STACK = ORIGIN(RAM) + LENGTH(RAM); + +ASSERT(hal_flash_write >= ORIGIN(RAM) && hal_flash_erase >= ORIGIN(RAM), + "MCXE31B flash routines must run from RAM (RAM_CODE=1)") + +_start_ecc_ram = ORIGIN(RAM); +_end_ecc_ram = ORIGIN(RAM) + LENGTH(RAM); + +_wolfboot_partition_boot_address = @WOLFBOOT_PARTITION_BOOT_ADDRESS@; +_wolfboot_partition_size = @WOLFBOOT_PARTITION_SIZE@; +_wolfboot_partition_update_address = @WOLFBOOT_PARTITION_UPDATE_ADDRESS@; +_wolfboot_partition_swap_address = @WOLFBOOT_PARTITION_SWAP_ADDRESS@; diff --git a/test-app/ARM-mcxe31b.ld b/test-app/ARM-mcxe31b.ld new file mode 100644 index 0000000000..412244103b --- /dev/null +++ b/test-app/ARM-mcxe31b.ld @@ -0,0 +1,70 @@ +/* + * Linker script for wolfBoot test application on NXP MCXE31B + * + * Application runs from boot partition after wolfBoot header + * + * RAM: the 64 KB CM7_0 DTCM (0x20000000), which wolfBoot has already + * ECC-initialized. It also holds the RAM_CODE flash routines. + */ + +MEMORY +{ + FLASH (rx) : ORIGIN = @WOLFBOOT_TEST_APP_ADDRESS@, LENGTH = @WOLFBOOT_TEST_APP_SIZE@ + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x10000 /* 64 KB DTCM */ +} + +SECTIONS +{ + .text : + { + _start_text = .; + KEEP(*(.isr_vector)) + *(.text*) + *(.rodata*) + *(.init*) + *(.fini*) + . = ALIGN(4); + _end_text = .; + } > FLASH + + .edidx : + { + . = ALIGN(4); + *(.ARM.exidx*) + } > FLASH + + _stored_data = .; + + .data : AT (_stored_data) + { + _start_data = .; + KEEP(*(.data*)) + . = ALIGN(4); + KEEP(*(.ramcode)) + . = ALIGN(4); + _end_data = .; + } > RAM + + .bss (NOLOAD) : + { + _start_bss = .; + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + _end_bss = .; + __bss_end__ = .; + _end = .; + } > RAM + . = ALIGN(4); +} + +/* Partition info for libwolfboot */ +_wolfboot_partition_boot_address = @WOLFBOOT_PARTITION_BOOT_ADDRESS@; +_wolfboot_partition_size = @WOLFBOOT_PARTITION_SIZE@; +_wolfboot_partition_update_address = @WOLFBOOT_PARTITION_UPDATE_ADDRESS@; +_wolfboot_partition_swap_address = @WOLFBOOT_PARTITION_SWAP_ADDRESS@; + +/* Stack and heap indicators */ +_start_heap = _end; +_end_stack = ORIGIN(RAM) + LENGTH(RAM); diff --git a/test-app/Makefile b/test-app/Makefile index 0aa4a40d0c..f78f99fb59 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1130,6 +1130,15 @@ ifeq ($(TARGET),s32k1xx) CFLAGS+=-DRAM_CODE -DDEBUG_UART endif +ifeq ($(TARGET),mcxe31b) + LSCRIPT_TEMPLATE=ARM-mcxe31b.ld + ifneq ($(SIGN),NONE) + APP_OBJS+=../src/keystore.o + endif + CFLAGS+=-DAPP_HAS_SYSTICK + CFLAGS+=-DRAM_CODE -DDEBUG_UART +endif + ifeq ($(TARGET),stm32n6) CFLAGS+=-DRAM_CODE -DDEBUG_UART APP_OBJS+=syscalls.o diff --git a/test-app/app_mcxe31b.c b/test-app/app_mcxe31b.c new file mode 100644 index 0000000000..abfd8671df --- /dev/null +++ b/test-app/app_mcxe31b.c @@ -0,0 +1,1046 @@ +/* app_mcxe31b.c + * + * Test bare-metal application for NXP MCXE31B + * Features: + * - LED indicator based on firmware version (Green=v1, Blue=v>1) + * - Interactive console with commands + * - XMODEM firmware update support + * - Partition and keystore information display + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include +#include +#include +#include +#include +#include "hal.h" +#include "../hal/mcxe31b.h" +#include "wolfboot/wolfboot.h" +#include "keystore.h" +#include "target.h" +#include "image.h" + +#ifdef TARGET_mcxe31b + +/* RAMFUNCTION for test-app: code that runs during flash operations must be in RAM */ +#ifdef RAM_CODE + #define APP_RAMFUNCTION __attribute__((used,section(".ramcode"),long_call)) +#else + #define APP_RAMFUNCTION +#endif + +/* ============== SysTick Timer ============== */ + +static volatile uint32_t jiffies = 0; + +/* SysTick interrupt handler - called isr_systick to match startup_arm.c */ +void isr_systick(void) +{ + jiffies++; +} + +static void delay_ms(uint32_t ms) +{ + uint32_t start = jiffies; + while ((jiffies - start) < ms) { + __asm__ volatile ("wfi"); + } +} + +static void systick_init(void) +{ + /* Configure SysTick for 1ms tick */ + SYST_RVR = (CLOCK_SPEED / 1000) - 1; + SYST_CVR = 0; + SYST_CSR = SYST_CSR_ENABLE | SYST_CSR_TICKINT | SYST_CSR_CLKSOURCE; +} + +/* ============== LED Functions ============== */ + +/* FRDM-MCXE31B RGB LED D1, active low */ +static void led_init(void) +{ + SIUL2_GPDO(LED_RED_PAD) = 1; + SIUL2_GPDO(LED_GREEN_PAD) = 1; + SIUL2_GPDO(LED_BLUE_PAD) = 1; + SIUL2_MSCR(LED_RED_PAD) = SIUL2_MSCR_OBE; + SIUL2_MSCR(LED_GREEN_PAD) = SIUL2_MSCR_OBE; + SIUL2_MSCR(LED_BLUE_PAD) = SIUL2_MSCR_OBE; +} + +static void led_green_on(void) +{ + SIUL2_GPDO(LED_GREEN_PAD) = 0; +} + +static void led_green_off(void) +{ + SIUL2_GPDO(LED_GREEN_PAD) = 1; +} + +static void led_blue_on(void) +{ + SIUL2_GPDO(LED_BLUE_PAD) = 0; +} + +static void led_blue_off(void) +{ + SIUL2_GPDO(LED_BLUE_PAD) = 1; +} + +static void APP_RAMFUNCTION led_red_on(void) +{ + SIUL2_GPDO(LED_RED_PAD) = 0; +} + +static void APP_RAMFUNCTION led_red_off(void) +{ + SIUL2_GPDO(LED_RED_PAD) = 1; +} + +static void led_toggle_version(uint32_t version) +{ + if (version == 1) { + SIUL2_GPDO(LED_GREEN_PAD) ^= 1; + } else { + SIUL2_GPDO(LED_BLUE_PAD) ^= 1; + } +} + +/* Set LED based on version: Green for v1, Blue for v>1 */ +static void led_set_version(uint32_t version) +{ + /* Turn off both first */ + led_green_off(); + led_blue_off(); + + if (version == 1) { + led_green_on(); + } else if (version > 1) { + led_blue_on(); + } +} + +/* ============== System Control ============== */ + +/* Functional reset through MC_ME */ +void arch_reboot(void) +{ + MC_ME_MODE_CONF = MC_ME_MODE_CONF_FUNC_RST; + MC_ME_MODE_UPD = MC_ME_MODE_UPD_MODE_UPD; + MC_ME_CTL_KEY = MC_ME_CTL_KEY_KEY; + MC_ME_CTL_KEY = MC_ME_CTL_KEY_INVKEY; + while (1) { + __asm__ volatile ("wfi"); + } +} + +/* ============== UART / Printf Support ============== */ + +#ifdef DEBUG_UART +/* UART functions are declared in mcxe31b.h and implemented in hal/mcxe31b.c */ + +/* Flag to block text output during XMODEM transfer */ +static volatile int xmodem_active = 0; + +/* ============== UART RX Interrupt Buffering ============== */ +#define UART_RX_BUF_SIZE 512 +static volatile uint8_t uart_rx_buf[UART_RX_BUF_SIZE]; +static volatile uint32_t uart_rx_head = 0; /* Write index (ISR writes here) */ +static volatile uint32_t uart_rx_tail = 0; /* Read index (app reads from here) */ + +/* Console LPUART RX Interrupt Handler */ +void isr_debug_uart(void) +{ + uint32_t stat = LPUART_STAT; + + /* Clear only the error flags (write 1 to clear) - do NOT write other bits */ + uint32_t errors = stat & (LPUART_STAT_OR | LPUART_STAT_NF | LPUART_STAT_FE | LPUART_STAT_PF); + if (errors) { + LPUART_STAT = errors; /* Write 1 to clear only error flags */ + } + + /* Read all available bytes from FIFO */ + while (LPUART_STAT & LPUART_STAT_RDRF) { + uint8_t c = (uint8_t)(LPUART_DATA & 0xFF); + uint32_t next_head = (uart_rx_head + 1) % UART_RX_BUF_SIZE; + + /* Store byte if buffer not full */ + if (next_head != uart_rx_tail) { + uart_rx_buf[uart_rx_head] = c; + uart_rx_head = next_head; + } + /* else: buffer full, discard byte */ + } +} + +/* Read from RX buffer (for XMODEM) - returns number of bytes read + * Must be RAMFUNCTION since it's called during flash operations */ +static int APP_RAMFUNCTION uart_rx_isr(uint8_t *buf, int max_len) +{ + int count = 0; + + while (count < max_len && uart_rx_tail != uart_rx_head) { + buf[count++] = uart_rx_buf[uart_rx_tail]; + uart_rx_tail = (uart_rx_tail + 1) % UART_RX_BUF_SIZE; + } + + return count; +} + +/* Check if RX data available */ +static int uart_rx_available(void) +{ + return (uart_rx_head != uart_rx_tail) ? 1 : 0; +} + +/* Read single character from RX buffer (for console) - returns 1 if char read, 0 if none */ +static int uart_getc(char *c) +{ + if (uart_rx_tail != uart_rx_head) { + *c = uart_rx_buf[uart_rx_tail]; + uart_rx_tail = (uart_rx_tail + 1) % UART_RX_BUF_SIZE; + return 1; + } + return 0; +} + +/* Enable LPUART RX interrupt */ +static void uart_rx_irq_enable(void) +{ + /* Set interrupt priority lower than SysTick (higher number = lower priority) + * SysTick defaults to priority 0, so set LPUART to 2 to ensure + * jiffies keeps incrementing even during heavy UART traffic. */ + NVIC_SetPriority(LPUART_IRQn, 2); + + /* Enable LPUART interrupt in NVIC */ + NVIC_EnableIRQ(LPUART_IRQn); + + /* Enable Receiver Interrupt in LPUART */ + LPUART_CTRL |= LPUART_CTRL_RIE; +} + +/* Print hex buffer (similar to stm32h5 style) */ +#define LINE_LEN 16 +static void print_hex(const uint8_t* buffer, uint32_t length, int dumpChars) +{ + uint32_t i, sz; + + if (buffer == NULL) { + printf("\tNULL\r\n"); + return; + } + + while (length > 0) { + sz = length; + if (sz > LINE_LEN) + sz = LINE_LEN; + + printf("\t"); + for (i = 0; i < LINE_LEN; i++) { + if (i < length) + printf("%02x ", buffer[i]); + else + printf(" "); + } + if (dumpChars) { + printf("| "); + for (i = 0; i < sz; i++) { + if (buffer[i] > 31 && buffer[i] < 127) + printf("%c", buffer[i]); + else + printf("."); + } + } + printf("\r\n"); + + buffer += sz; + length -= sz; + } +} +#endif /* DEBUG_UART */ + +/* ============== Partition State Names ============== */ + +static const char* part_state_name(uint8_t state, int state_retval) +{ + /* wolfBoot_get_partition_state() returns 0 when it read a state */ + if (state_retval != 0) { + return "(no trailer)"; + } + switch (state) { + case IMG_STATE_NEW: return "NEW"; + case IMG_STATE_UPDATING: return "UPDATING"; + case IMG_STATE_TESTING: return "TESTING"; + case IMG_STATE_SUCCESS: return "SUCCESS"; + default: return "UNKNOWN"; + } +} + +/* ============== Key Type Names ============== */ + +static const char* key_type_name(uint32_t type) +{ + switch (type) { + case AUTH_KEY_ECC256: return "ECDSA P-256 (secp256r1)"; + case AUTH_KEY_ECC384: return "ECDSA P-384 (secp384r1)"; + case AUTH_KEY_ECC521: return "ECDSA P-521 (secp521r1)"; + case AUTH_KEY_RSA2048: return "RSA-2048"; + case AUTH_KEY_RSA3072: return "RSA-3072"; + case AUTH_KEY_RSA4096: return "RSA-4096"; + case AUTH_KEY_ED25519: return "Ed25519"; + case AUTH_KEY_ED448: return "Ed448"; + case AUTH_KEY_LMS: return "LMS"; + case AUTH_KEY_XMSS: return "XMSS"; + case AUTH_KEY_ML_DSA: return "ML-DSA"; + default: return "Unknown"; + } +} + +static const char* hash_type_name(void) +{ +#ifdef WOLFBOOT_HASH_SHA256 + return "SHA-256"; +#elif defined(WOLFBOOT_HASH_SHA384) + return "SHA-384"; +#elif defined(WOLFBOOT_HASH_SHA512) + return "SHA-512"; +#elif defined(WOLFBOOT_HASH_SHA3_384) + return "SHA3-384"; +#endif + return "Unknown"; +} + +/* ============== Information Display ============== */ + +#ifdef DEBUG_UART +static void print_partition_info(void) +{ + uint32_t boot_ver, update_ver; + uint8_t boot_state = 0, update_state = 0; + int boot_state_valid, update_state_valid; + + boot_ver = wolfBoot_current_firmware_version(); + update_ver = wolfBoot_update_firmware_version(); + + boot_state_valid = wolfBoot_get_partition_state(PART_BOOT, &boot_state); + update_state_valid = wolfBoot_get_partition_state(PART_UPDATE, &update_state); + + printf("\r\n=== Partition Information ===\r\n"); + + printf("Boot Partition:\r\n"); + printf(" Address: 0x%08lX\r\n", (unsigned long)WOLFBOOT_PARTITION_BOOT_ADDRESS); + printf(" Version: %lu\r\n", (unsigned long)boot_ver); + printf(" State: %s\r\n", part_state_name(boot_state, boot_state_valid)); + + printf("Update Partition:\r\n"); + printf(" Address: 0x%08lX\r\n", (unsigned long)WOLFBOOT_PARTITION_UPDATE_ADDRESS); + printf(" Version: %lu\r\n", (unsigned long)update_ver); + printf(" State: %s\r\n", part_state_name(update_state, update_state_valid)); + + printf("Swap Partition:\r\n"); + printf(" Address: 0x%08lX\r\n", (unsigned long)WOLFBOOT_PARTITION_SWAP_ADDRESS); + printf(" Size: %lu bytes\r\n", (unsigned long)WOLFBOOT_SECTOR_SIZE); +} + +static void print_keystore_info(void) +{ +#ifndef WOLFBOOT_NO_SIGN + uint32_t n_keys; + int i; + + printf("\r\n=== Keystore Information ===\r\n"); + + n_keys = keystore_num_pubkeys(); + printf("Number of public keys: %lu\r\n", (unsigned long)n_keys); + printf("Hash: %s\r\n", hash_type_name()); + + for (i = 0; i < (int)n_keys; i++) { + uint32_t size = keystore_get_size(i); + uint32_t type = keystore_get_key_type(i); + uint8_t* keybuf = keystore_get_buffer(i); + + printf("\r\nKey #%d:\r\n", i); + printf(" Algorithm: %s\r\n", key_type_name(type)); + printf(" Size: %lu bytes\r\n", (unsigned long)size); + printf(" Data:\r\n"); + print_hex(keybuf, size, 0); + } +#else + printf("\r\n=== Keystore Information ===\r\n"); + printf("Signing disabled (SIGN=NONE)\r\n"); +#endif /* !WOLFBOOT_NO_SIGN */ +} + +/* ============== XMODEM Transfer ============== */ + +#define XSOH 0x01 +#define XEOT 0x04 +#define XACK 0x06 +#define XNAK 0x15 +#define XCAN 0x18 +#define XCRC 'C' /* Request CRC mode */ + +#define XMODEM_PAYLOAD_SIZE 128 +#define XMODEM_PACKET_SIZE_CRC (3 + XMODEM_PAYLOAD_SIZE + 2) /* SOH + blk + ~blk + data + CRC16 */ +#define XMODEM_TIMEOUT_MS 1000 + +/* CRC-16-CCITT for XMODEM-CRC mode */ +static uint16_t APP_RAMFUNCTION crc16_ccitt(const uint8_t* data, int len) +{ + uint16_t crc = 0; + int i, j; + for (i = 0; i < len; i++) { + crc ^= ((uint16_t)data[i] << 8); + for (j = 0; j < 8; j++) { + if (crc & 0x8000) { + crc = (crc << 1) ^ 0x1021; + } else { + crc <<= 1; + } + } + } + return crc; +} + +/* Raw byte transmit for XMODEM (declared in hal, runs from RAM) */ +extern void uart_tx(uint8_t byte); + +/* RAM-based memory copy for use during flash operations */ +static void APP_RAMFUNCTION ram_memcpy(void *dst, const void *src, uint32_t len) +{ + uint8_t *d = (uint8_t *)dst; + const uint8_t *s = (const uint8_t *)src; + while (len--) { + *d++ = *s++; + } +} + +static void APP_RAMFUNCTION xmodem_cancel(void) +{ + int i; + for (i = 0; i < 10; i++) { + uart_tx(XCAN); + } +} + +/* XMODEM receive state - passed to RAM function */ +typedef struct { + uint32_t dst_offset; + int result; + /* Debug counters */ + uint32_t pkts_received; + uint32_t pkts_crc_fail; + uint32_t pkts_num_fail; + uint32_t pkts_soh_fail; + uint32_t timeouts; +} xmodem_state_t; + +/* Core XMODEM-CRC receive loop - runs entirely from RAM during flash operations + * Uses XMODEM-CRC mode (133-byte packets with 16-bit CRC) + * Returns: 0 on success, -1 on error + */ +static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) +{ + uint8_t xpkt[XMODEM_PACKET_SIZE_CRC]; + uint8_t payload[XMODEM_PAYLOAD_SIZE]; + uint8_t pkt_num = 0, pkt_num_expected = 0xFF; + uint32_t t_size = 0; + uint32_t now; + uint32_t i = 0; + int transfer_started = 0; + int eot_expected = 0; + int ret = -1; + + state->dst_offset = 0; + state->result = -1; + state->pkts_received = 0; + state->pkts_crc_fail = 0; + state->pkts_num_fail = 0; + state->pkts_soh_fail = 0; + state->timeouts = 0; + + /* Send 'C' to request CRC mode (XMODEM-CRC) */ + uart_tx(XCRC); + + while (1) { + now = jiffies; /* Direct access to volatile - faster than function call */ + i = 0; + + /* Receive packet - uses interrupt-buffered RX to avoid FIFO overflow */ + while (i < XMODEM_PACKET_SIZE_CRC) { + int r = uart_rx_isr(&xpkt[i], XMODEM_PACKET_SIZE_CRC - i); + if (r > 0) { + i += r; + now = jiffies; + if (i >= 1 && xpkt[0] == XEOT) { + break; /* End of transmission */ + } + } else if (jiffies > (now + XMODEM_TIMEOUT_MS)) { + now = jiffies; + state->timeouts++; + if (i == 0) { + uart_tx(XCRC); /* Request CRC mode again */ + } + i = 0; + } + } + + /* Check for EOT */ + if (xpkt[0] == XEOT) { + uart_tx(XACK); + led_red_on(); /* Indicate transfer complete */ + ret = 0; + break; + } else if (eot_expected) { + uart_tx(XNAK); + ret = -1; + break; + } + + /* Validate SOH */ + if (xpkt[0] != XSOH) { + state->pkts_soh_fail++; + continue; + } + state->pkts_received++; + + /* Validate packet number */ + pkt_num = xpkt[1]; + if ((uint8_t)(~xpkt[2]) == pkt_num) { + uint16_t recv_crc, calc_crc; + + if (!transfer_started) { + pkt_num_expected = pkt_num; + transfer_started = 1; + } else if (pkt_num_expected != pkt_num) { + uart_tx(XNAK); + continue; + } + + /* Toggle LED to show activity */ + if ((pkt_num & 0x0F) == 0) { + led_red_on(); + } else if ((pkt_num & 0x0F) == 8) { + led_red_off(); + } + + /* Validate CRC-16 - XMODEM-CRC uses CRC over DATA bytes only */ + recv_crc = ((uint16_t)xpkt[XMODEM_PACKET_SIZE_CRC - 2] << 8) | + xpkt[XMODEM_PACKET_SIZE_CRC - 1]; + calc_crc = crc16_ccitt(xpkt + 3, XMODEM_PAYLOAD_SIZE); + + if (recv_crc == calc_crc) { + /* Copy payload using RAM-based memcpy */ + ram_memcpy(payload, xpkt + 3, XMODEM_PAYLOAD_SIZE); + + /* Send ACK first, then write to flash. + * This allows sender to prepare next packet while we write. + * Risk: if write fails, we've already ACKed - but that's rare. + */ + uart_tx(XACK); + + /* Write to flash */ + ret = hal_flash_write(WOLFBOOT_PARTITION_UPDATE_ADDRESS + state->dst_offset, + payload, XMODEM_PAYLOAD_SIZE); + if (ret != 0) { + xmodem_cancel(); + /* No printf here - we're in RAM */ + break; + } + pkt_num_expected++; + state->dst_offset += XMODEM_PAYLOAD_SIZE; + + /* Get expected size from header (offset 4 = image size) */ + if (t_size == 0 && state->dst_offset >= 8) { + t_size = *(uint32_t*)(payload + 4) + IMAGE_HEADER_SIZE; + } + + if (t_size > 0 && state->dst_offset >= t_size) { + eot_expected = 1; + } + } else { + state->pkts_crc_fail++; + uart_tx(XNAK); + } + } else { + state->pkts_num_fail++; + uart_tx(XNAK); + } + } + + state->result = ret; + return ret; +} + +static int cmd_update_xmodem(void) +{ + xmodem_state_t state; + int ret; + uint32_t erase_addr; + int erase_ret; + char c; + + printf("Erasing update partition...\r\n"); +#ifdef DEBUG_FLASH + printf(" Address: 0x%08lX\r\n", (unsigned long)WOLFBOOT_PARTITION_UPDATE_ADDRESS); + printf(" Size: 0x%08lX (%lu bytes)\r\n", + (unsigned long)WOLFBOOT_PARTITION_SIZE, + (unsigned long)WOLFBOOT_PARTITION_SIZE); +#endif + + hal_flash_unlock(); + +#ifdef DEBUG_FLASH + /* Erase sector by sector with debug output */ + erase_addr = WOLFBOOT_PARTITION_UPDATE_ADDRESS; + while (erase_addr < WOLFBOOT_PARTITION_UPDATE_ADDRESS + WOLFBOOT_PARTITION_SIZE) { + printf(" Erasing sector at 0x%08lX...", (unsigned long)erase_addr); + fflush(stdout); + + erase_ret = hal_flash_erase(erase_addr, WOLFBOOT_SECTOR_SIZE); + if (erase_ret != 0) { + printf(" FAILED (%d)\r\n", erase_ret); + hal_flash_lock(); + return -1; + } + printf(" OK\r\n"); + erase_addr += WOLFBOOT_SECTOR_SIZE; + } +#else + (void)erase_addr; + (void)erase_ret; + hal_flash_erase(WOLFBOOT_PARTITION_UPDATE_ADDRESS, WOLFBOOT_PARTITION_SIZE); +#endif + + printf("Done.\r\n"); + printf("Waiting for XMODEM transfer...\r\n"); + printf("(Send file now using XMODEM-CRC protocol)\r\n"); + + /* Flush all printf output before starting XMODEM */ + fflush(stdout); + /* Wait for UART TX to complete */ + while (!(LPUART_STAT & LPUART_STAT_TC)) {} + + /* Drain any pending RX data before starting XMODEM */ + while (uart_getc(&c) > 0) {} /* Use ISR buffer, not hardware */ + + /* Small delay to ensure clean start */ + delay_ms(100); + + /* Block all printf output during XMODEM */ + xmodem_active = 1; + + /* Run the receive loop from RAM */ + ret = xmodem_receive_ram(&state); + + /* Re-enable printf output */ + xmodem_active = 0; + + hal_flash_lock(); + + /* Wait for sender to finish and drain any pending RX data. + * This prevents printf output from mixing with XMODEM retransmits. */ + delay_ms(3000); /* Wait for sender to give up */ + while (uart_read(&c) > 0) {} /* Drain RX buffer */ + + printf("\r\nTransfer %s\r\n", (ret == 0) ? "complete!" : "failed."); + printf("XMODEM stats: recv=%lu, crc_fail=%lu, num_fail=%lu, soh_fail=%lu, timeouts=%lu\r\n", + (unsigned long)state.pkts_received, (unsigned long)state.pkts_crc_fail, + (unsigned long)state.pkts_num_fail, (unsigned long)state.pkts_soh_fail, + (unsigned long)state.timeouts); + + if (ret == 0) { + uint32_t update_ver = wolfBoot_update_firmware_version(); + if (update_ver != 0) { + printf("New firmware version: %lu\r\n", (unsigned long)update_ver); + printf("Triggering update...\r\n"); + wolfBoot_update_trigger(); + printf("Reboot to apply update.\r\n"); + } else { + printf("Warning: No valid image detected\r\n"); + } + } + + led_red_off(); + return ret; +} + +/* ============== Console Commands ============== */ + +static int cmd_help(const char *args); +static int cmd_info(const char *args); +static int cmd_success(const char *args); +static int cmd_reboot(const char *args); +static int cmd_update(const char *args); +static int cmd_timestamp(const char *args); +static int cmd_trigger(const char *args); +static int cmd_status(const char *args); + +typedef struct { + int (*fn)(const char *args); + const char* name; + const char* help; +} console_cmd_t; + +static const console_cmd_t commands[] = { + {cmd_help, "help", "Show this help message"}, + {cmd_info, "info", "Display partition and key info"}, + {cmd_status, "status", "Show partition versions and states"}, + {cmd_success, "success", "Mark firmware as successful"}, + {cmd_trigger, "trigger", "Trigger update (if update image in flash)"}, + {cmd_update, "update", "Update firmware via XMODEM"}, + {cmd_timestamp, "timestamp", "Show current system time"}, + {cmd_reboot, "reboot", "Reboot the system"}, + {NULL, NULL, NULL} +}; + +static int cmd_help(const char *args) +{ + int i; + (void)args; + printf("\r\nAvailable commands:\r\n"); + for (i = 0; commands[i].name != NULL; i++) { + printf(" %s - %s\r\n", commands[i].name, commands[i].help); + } + return 0; +} + +static int cmd_info(const char *args) +{ + (void)args; + print_partition_info(); + print_keystore_info(); + return 0; +} + +static int cmd_success(const char *args) +{ + (void)args; + wolfBoot_success(); + printf("Firmware marked as successful.\r\n"); + return 0; +} + +static int cmd_timestamp(const char *args) +{ + (void)args; + printf("Current systick: %lu ms\r\n", (unsigned long)jiffies); + return 0; +} + +static int cmd_status(const char *args) +{ + uint32_t boot_ver, update_ver; + uint8_t boot_state, update_state; + int ret; + (void)args; + + boot_ver = wolfBoot_current_firmware_version(); + update_ver = wolfBoot_update_firmware_version(); + + printf("\r\n=== Partition Status ===\r\n"); + printf("Boot Partition: v%lu @ 0x%lX\r\n", + (unsigned long)boot_ver, (unsigned long)WOLFBOOT_PARTITION_BOOT_ADDRESS); + + ret = wolfBoot_get_partition_state(PART_BOOT, &boot_state); + if (ret == 0) { + printf(" State: %s (0x%02X)\r\n", + (boot_state == IMG_STATE_SUCCESS) ? "SUCCESS" : + (boot_state == IMG_STATE_TESTING) ? "TESTING" : + (boot_state == IMG_STATE_UPDATING) ? "UPDATING" : "NEW", + boot_state); + } else { + printf(" State: (no trailer)\r\n"); + } + + printf("Update Partition: v%lu @ 0x%lX\r\n", + (unsigned long)update_ver, (unsigned long)WOLFBOOT_PARTITION_UPDATE_ADDRESS); + + ret = wolfBoot_get_partition_state(PART_UPDATE, &update_state); + if (ret == 0) { + printf(" State: %s (0x%02X)\r\n", + (update_state == IMG_STATE_SUCCESS) ? "SUCCESS" : + (update_state == IMG_STATE_TESTING) ? "TESTING" : + (update_state == IMG_STATE_UPDATING) ? "UPDATING" : "NEW", + update_state); + } else { + printf(" State: (no trailer)\r\n"); + } + + if (update_ver > 0 && update_ver > boot_ver) { + printf("\r\nUpdate available! Use 'trigger' command to start update.\r\n"); + } + + return 0; +} + +static int cmd_trigger(const char *args) +{ + uint32_t update_ver; + (void)args; + + update_ver = wolfBoot_update_firmware_version(); + if (update_ver == 0) { + printf("No update image found in update partition.\r\n"); + return -1; + } + + printf("Update image version: %lu\r\n", (unsigned long)update_ver); + printf("Triggering update...\r\n"); + wolfBoot_update_trigger(); + printf("Update triggered. Use 'reboot' to start update.\r\n"); + return 0; +} + +static int cmd_reboot(const char *args) +{ + (void)args; + printf("Rebooting...\r\n"); + fflush(stdout); + delay_ms(100); /* Allow UART to flush */ + arch_reboot(); + return 0; +} + +static int cmd_update(const char *args) +{ + (void)args; + return cmd_update_xmodem(); +} + +static int parse_command(const char* cmd) +{ + int i; + for (i = 0; commands[i].name != NULL; i++) { + if (strcmp(cmd, commands[i].name) == 0) { + return commands[i].fn(NULL); + } + } + printf("Unknown command: %s\r\n", cmd); + printf("Type 'help' for available commands.\r\n"); + return -1; +} + +#define CMD_BUF_SIZE 64 + +static void console_loop(void) +{ + char cmd[CMD_BUF_SIZE]; + int idx; + char c; + + while (1) { + printf("\r\ncmd> "); + fflush(stdout); + idx = 0; + + while (idx < CMD_BUF_SIZE - 1) { + int ret = uart_getc(&c); + if (ret > 0) { + if (c == '\r' || c == '\n') { + printf("\r\n"); + break; + } else if (c == 0x08 || c == 0x7F) { /* Backspace */ + if (idx > 0) { + printf("\b \b"); + fflush(stdout); + idx--; + } + } else if (c >= 32 && c < 127) { + printf("%c", c); + fflush(stdout); + cmd[idx++] = c; + } + } + /* No delay - tight polling loop for responsive input */ + } + + cmd[idx] = '\0'; + if (idx > 0) { + parse_command(cmd); + } + } +} +#endif /* DEBUG_UART */ + +/* ============== Main Entry Point ============== */ + +void main(void) +{ + uint32_t version; + + /* Clocks (kept at 160 MHz when started by wolfBoot), caches and UART. + * SWT0 stays off: the IVT boot configuration word does not enable it. */ + hal_init(); + +#ifdef DEBUG_UART + /* Enable interrupt-based RX buffering for reliable XMODEM transfers */ + uart_rx_irq_enable(); + /* Disable stdout buffering to prevent delayed output during XMODEM */ + setvbuf(stdout, NULL, _IONBF, 0); +#endif + + /* Initialize test-app hardware */ + systick_init(); + led_init(); + + /* Enable interrupts */ + __asm__ volatile ("cpsie i"); + + /* Get current firmware version */ + version = wolfBoot_current_firmware_version(); + + /* Set LED based on version: Green for v1, Blue for v>1 */ + led_set_version(version); + +#ifdef DEBUG_UART + printf("\r\n"); + printf("========================================\r\n"); + printf("MCXE31B wolfBoot Test Application\r\n"); + printf("Copyright 2025-2026 wolfSSL Inc.\r\n"); + printf("========================================\r\n"); + printf("Firmware Version: %lu\r\n", (unsigned long)version); + + /* Auto-mark success for testing if version > 1 */ + if (version > 1) { + uint8_t state = 0; + wolfBoot_get_partition_state(PART_BOOT, &state); + if (state == IMG_STATE_TESTING) { + printf("Testing state detected, marking success...\r\n"); + wolfBoot_success(); + } + } + + /* Show initial info */ + print_partition_info(); + + printf("\r\nType 'help' for available commands.\r\n"); + + /* Enter interactive console */ + console_loop(); +#else + /* No UART - just blink LED */ + while (1) { + led_toggle_version(version); + delay_ms(500); + } +#endif +} + +/* ============== Syscalls for printf support ============== */ + +int _getpid(void) +{ + return 1; +} + +int _kill(int pid, int sig) +{ + (void)pid; + (void)sig; + return -1; +} + +void _exit(int status) +{ + _kill(status, -1); + while (1) {} +} + +int _read(int file, char *ptr, int len) +{ + (void)file; + (void)ptr; + (void)len; + return -1; +} + +int _write(int file, char *ptr, int len) +{ + (void)file; +#ifdef DEBUG_UART + /* Block text output during XMODEM to prevent protocol interference */ + if (!xmodem_active) { + uart_write(ptr, len); + } +#else + (void)ptr; +#endif + return len; +} + +int _close(int file) +{ + (void)file; + return -1; +} + +int _isatty(int file) +{ + (void)file; + return 1; +} + +int _lseek(int file, int ptr, int dir) +{ + (void)file; + (void)ptr; + (void)dir; + return 0; +} + +int _fstat(int file, struct stat *st) +{ + (void)file; + st->st_mode = S_IFCHR; + return 0; +} + +/* Back-end for malloc, used for printf */ +extern unsigned int _end; /* From linker script: end of BSS */ +extern unsigned int _end_stack; /* From linker script: end of RAM */ + +void *_sbrk(int incr) +{ + static unsigned char *heap = NULL; + unsigned char *prev_heap; + + if (heap == NULL) { + heap = (unsigned char *)&_end; + } + + prev_heap = heap; + + /* Align increment to 4 bytes */ + if (((incr >> 2) << 2) != incr) + incr = ((incr >> 2) + 1) << 2; + + /* Check we don't overflow into the stack */ + if ((heap + incr) > (unsigned char *)&_end_stack) { + return (void *)-1; + } + + heap += incr; + return prev_heap; +} + +#endif /* TARGET_mcxe31b */ diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index 1b90d98258..3c87871b81 100644 --- a/test-app/startup_arm.c +++ b/test-app/startup_arm.c @@ -73,6 +73,10 @@ extern void nxp_mcxe_enet_irq_handler(void); #endif #endif +#ifdef TARGET_mcxe31b +extern void isr_debug_uart(void); +#endif + #if defined(TARGET_va416x0) || defined(TARGET_lpc55s69) #define isr_systick SysTick_Handler #elif !defined(APP_HAS_SYSTICK) @@ -653,6 +657,11 @@ void (* const IV[])(void) = isr_empty, // DMA1_STREAM7_IRQ 47 +#elif defined(TARGET_mcxe31b) /* For NXP MCXE31B */ + /* IRQs 0-145 unused, 146 = LPUART5 (console) */ + [16 ... (16 + 145)] = isr_empty, + [16 + 146] = isr_debug_uart, + #elif defined(TARGET_va416x0) /* For Vorago VA416xx */ /* IRQ 0 through TXEV_IRQn (195), for 212 entries. wolfBoot points VTOR * at this table; see docs/Targets.md for the alignment it needs. */ diff --git a/tools/scripts/mcxe31b/e31b_debug.cmm b/tools/scripts/mcxe31b/e31b_debug.cmm new file mode 100644 index 0000000000..27254c03bf --- /dev/null +++ b/tools/scripts/mcxe31b/e31b_debug.cmm @@ -0,0 +1,101 @@ +;; e31b_debug.cmm +;; +;; Connect TRACE32 to the NXP MCXE31B (FRDM-MCXE31B) and halt the CPU at the +;; reset vector, then load the wolfBoot and test-app symbols. +;; No arguments: DO e31b_debug.cmm +;; +;; Board setup (UM12330): +;; - Lauterbach 10-pin cable on J14 (SWD/JTAG 2x5 header) +;; - JP5 SHORTED: disables the onboard MCU-Link SWD so it does not fight +;; the external probe on SWDIO/SWCLK +;; - The MCU-Link VCOM console (LPUART5, 115200 8N1) stays available +;; +;; Notes: +;; - TRACE32 R2024.09 has no MCXE31B entry. The S32K314 has the same debug +;; architecture (AHB-AP 4 = CM7_0, MDM-AP 6, SDA-AP 7) and flash +;; controller. Only SWD works on J14. +;; - SYStem.Up resets the chip and halts it at the reset vector, but often +;; reports a debug port time-out while the boot ROM runs. Attaching +;; afterwards finds the core halted. +;; - All output, including errors, is logged to ~~/e31b_debug.log +;; - The ELF files are loaded from the wolfBoot checkout this script is in. + +; wolfBoot root: three levels above this script +&basedir=OS.PPD()+"\..\..\.." + +AREA.OPEN A000 "~~/e31b_debug.log" /Create /NoFileCache +PRINT "e31b_debug.cmm " DATE.DATE() " " DATE.TIME() + +RESet +SYStem.RESet +SYStem.CPU S32K314-M7 +SYStem.CONFIG.DEBUGPORTTYPE SWD +SYStem.Option DUALPORT ON +SYStem.MemAccess DAP +Trace.DISable + +; reset and halt at the reset vector, retrying with a slow debug clock +SYStem.JtagClock 10MHz +PRINT "[1] SYStem.Up @ 10MHz" +ON ERROR CONTinue +SYStem.Up +ON ERROR inherit + +IF !SYStem.Up() +( + PRINT "[2] SYStem.Mode Attach @ 10MHz" + ON ERROR CONTinue + SYStem.Mode Attach + ON ERROR inherit +) + +IF !SYStem.Up() +( + PRINT "[3] SYStem.Up @ 1MHz" + SYStem.Down + SYStem.JtagClock 1MHz + ON ERROR CONTinue + SYStem.Up + ON ERROR inherit +) + +IF !SYStem.Up() +( + PRINT %ERROR "MCXE31B: connection failed (check JP5 shorted, cable on J14, board powered)" + AREA.CLOSE A000 + ENDDO +) + +IF STATE.RUN() +( + ON ERROR CONTinue + Break + ON ERROR inherit +) + +IF STATE.RUN() +( + PRINT %ERROR "MCXE31B: connected but CPU did not halt" + AREA.CLOSE A000 + ENDDO +) + +PRINT "MCXE31B halted, PC=0x"+FORMAT.HEX(8.,Register(PC))+" SP=0x"+FORMAT.HEX(8.,Register(SP)) +AREA.CLOSE A000 + +mode.hll + +IF OS.FILE("&basedir\wolfboot.elf") + data.load.elf "&basedir\wolfboot.elf" /nocode +IF OS.FILE("&basedir\test-app\image.elf") + data.load.elf "&basedir\test-app\image.elf" /nocode /noclear +; The ELF files hold the paths of the build machine. Look the sources up in +; this checkout instead, so it also works when TRACE32 runs on another host +; (e.g. Windows with the checkout in WSL). +; Sources are found by file name in these directories. +sYmbol.SourcePATH.SetBaseDir "&basedir" +&srcdirs="""&basedir"" ""&basedir\src"" ""&basedir\hal"" ""&basedir\test-app""" +&srcdirs="&srcdirs ""&basedir\lib\wolfssl\wolfcrypt\src""" +sYmbol.SourcePATH.Set &srcdirs + +ENDDO diff --git a/tools/scripts/mcxe31b/e31b_flash_factory_bin.cmm b/tools/scripts/mcxe31b/e31b_flash_factory_bin.cmm new file mode 100644 index 0000000000..8f67fb149d --- /dev/null +++ b/tools/scripts/mcxe31b/e31b_flash_factory_bin.cmm @@ -0,0 +1,106 @@ +;; e31b_flash_factory_bin.cmm +;; +;; Program factory.bin (wolfBoot + signed test app) into the NXP MCXE31B +;; (FRDM-MCXE31B) and erase the update partition and swap sector. +;; No arguments: DO e31b_flash_factory_bin.cmm +;; +;; Connects with e31b_debug.cmm (reset and halt), programs the image with the +;; TRACE32 S32K3 flash algorithm, verifies it, resets the board to boot and +;; detaches the debugger. +;; Range erased and programmed: 0x00400000--0x007D1FFF (IVT + bootloader, +;; boot partition, update partition, swap sector). factory.bin must fit in the +;; bootloader + boot partition without the partition's last two sectors +;; (0x00400000--0x005EBFFF): with NVM_FLASH_WRITEONCE wolfBoot keeps the boot +;; state there and erases those sectors when it updates it. The data flash at +;; 0x10000000 and the Secure BAF area from 0x007D4000 are left as is. +;; The addresses match config/examples/mcxe31b.config. Update them here if the +;; partition layout is changed. +;; +;; factory.bin starts with the Image Vector Table that the boot ROM looks for +;; at 0x00400000. Without its marker the boot ROM does not start wolfBoot, so +;; the marker is checked in the file before anything is erased. +;; Output is logged to ~~/e31b_flash_factory_bin.log +;; factory.bin is taken from the wolfBoot checkout this script is in. + +; This script's directory, and the wolfBoot root three levels above it +&scriptdir=OS.PPD() +&basedir="&scriptdir\..\..\.." +&file="&basedir\factory.bin" +&start=0x00400000 +&end=0x007D1FFF +; factory.bin (bootloader + boot partition) must end before the boot +; partition's two trailer sectors (0x5EC000--0x5EFFFF) +&maxsize=0x1EC000 +&ivt_marker=0x5AA55AA5 + +DO "&scriptdir\e31b_debug.cmm" + +AREA.OPEN A000 "~~/e31b_flash_factory_bin.log" /Create /NoFileCache +PRINT "e31b_flash_factory_bin.cmm " DATE.DATE() " " DATE.TIME() + +IF !SYStem.Up()||STATE.RUN() +( + PRINT %ERROR "not connected or CPU not halted, see ~~/e31b_debug.log" + AREA.CLOSE A000 + ENDDO +) +IF !OS.FILE("&file") +( + PRINT %ERROR "&file not found" + AREA.CLOSE A000 + ENDDO +) +&size=OS.FILE.SIZE("&file") +IF &size>&maxsize +( + PRINT %ERROR "&file does not fit before the boot partition trailer (0x5EC000)" + AREA.CLOSE A000 + ENDDO +) + +; Refuse an image the boot ROM would not start +Data.LOAD.Binary "&file" VM:&start +IF Data.Long(VM:&start)!=&ivt_marker +( + PRINT %ERROR "&file: no IVT marker at 0x00400000, not programming" + AREA.CLOSE A000 + ENDDO +) + +; The flash algorithm runs from the CM7_0 DTCM, which is ECC protected and +; must be written before it is read +Data.Set SD:0x20000000++0xFFFF %Long 0 + +; S32K3 flash algorithm, code flash without the Secure BAF area +FLASH.RESet +FLASH.Create 1. 0x00400000--0x007D3FFF 0x2000 TARGET Long +FLASH.TARGET 0x20000000 0x20002000 0x1000 ~~/demo/arm/flash/long/s32k3x4.bin + +; Sectors in range not covered by the file are erased +PRINT "programming &file (" FORMAT.Decimal(0.,&size) " bytes) at "+FORMAT.HEX(8.,&start) +FLASH.ReProgram &start--&end /Erase +Data.LOAD.Binary "&file" &start +FLASH.ReProgram OFF + +Data.LOAD.Binary "&file" &start /DIFF +IF FOUND() +( + PRINT %ERROR "verify FAILED, not resetting" + AREA.CLOSE A000 + ENDDO +) +PRINT "verify OK" +FLASH.RESet + +; Reset and boot +AREA.CLOSE A000 +DO "&scriptdir\e31b_debug.cmm" +AREA.OPEN A000 "~~/e31b_flash_factory_bin.log" /Append /NoFileCache +Go +; Detach: while attached, TRACE32 catches every reset at the reset vector, so +; a software reset (e.g. to start a firmware update) would leave the CPU halted +SYStem.Down +PRINT "done, board running, debugger detached" +AREA.CLOSE A000 + +ENDDO diff --git a/tools/scripts/mcxe31b/e31b_flash_update.cmm b/tools/scripts/mcxe31b/e31b_flash_update.cmm new file mode 100644 index 0000000000..cd90964d59 --- /dev/null +++ b/tools/scripts/mcxe31b/e31b_flash_update.cmm @@ -0,0 +1,92 @@ +;; e31b_flash_update.cmm +;; +;; Program the signed update image into the update partition of the NXP +;; MCXE31B (FRDM-MCXE31B). +;; No arguments: DO e31b_flash_update.cmm +;; +;; Connects with e31b_debug.cmm (reset and halt), programs the image with the +;; TRACE32 S32K3 flash algorithm, verifies it, resets the board to boot and +;; detaches the debugger. +;; Range erased and programmed: 0x005F0000--0x007CFFFF. Every other flash area +;; is left as is. The update is not triggered: use the test-app console +;; command "trigger" followed by "reboot". +;; The image must not reach the partition's last two sectors +;; (0x007CC000--0x007CFFFF): with NVM_FLASH_WRITEONCE wolfBoot keeps the update +;; state there and erases those sectors when the update is triggered, so the +;; image may be at most 0x1DC000 bytes. +;; The addresses match config/examples/mcxe31b.config. Update them here if the +;; partition layout is changed. +;; Output is logged to ~~/e31b_flash_update.log +;; The image is taken from the wolfBoot checkout this script is in. + +; This script's directory, and the wolfBoot root three levels above it +&scriptdir=OS.PPD() +&basedir="&scriptdir\..\..\.." +&file="&basedir\test-app\image_v2_signed.bin" +&start=0x005F0000 +&end=0x007CFFFF +; Partition size less the two trailer sectors +&maxsize=0x1DC000 + +DO "&scriptdir\e31b_debug.cmm" + +AREA.OPEN A000 "~~/e31b_flash_update.log" /Create /NoFileCache +PRINT "e31b_flash_update.cmm " DATE.DATE() " " DATE.TIME() + +IF !SYStem.Up()||STATE.RUN() +( + PRINT %ERROR "not connected or CPU not halted, see ~~/e31b_debug.log" + AREA.CLOSE A000 + ENDDO +) +IF !OS.FILE("&file") +( + PRINT %ERROR "&file not found" + AREA.CLOSE A000 + ENDDO +) +&size=OS.FILE.SIZE("&file") +IF &size>&maxsize +( + PRINT %ERROR "&file does not fit before the update partition trailer (0x1DC000 bytes)" + AREA.CLOSE A000 + ENDDO +) + +; The flash algorithm runs from the CM7_0 DTCM, which is ECC protected and +; must be written before it is read +Data.Set SD:0x20000000++0xFFFF %Long 0 + +; S32K3 flash algorithm, code flash without the Secure BAF area +FLASH.RESet +FLASH.Create 1. 0x00400000--0x007D3FFF 0x2000 TARGET Long +FLASH.TARGET 0x20000000 0x20002000 0x1000 ~~/demo/arm/flash/long/s32k3x4.bin + +; Sectors in range not covered by the file are erased +PRINT "programming &file (" FORMAT.Decimal(0.,&size) " bytes) at "+FORMAT.HEX(8.,&start) +FLASH.ReProgram &start--&end /Erase +Data.LOAD.Binary "&file" &start +FLASH.ReProgram OFF + +Data.LOAD.Binary "&file" &start /DIFF +IF FOUND() +( + PRINT %ERROR "verify FAILED" + AREA.CLOSE A000 + ENDDO +) +PRINT "verify OK" +FLASH.RESet + +; Reset and boot +AREA.CLOSE A000 +DO "&scriptdir\e31b_debug.cmm" +AREA.OPEN A000 "~~/e31b_flash_update.log" /Append /NoFileCache +Go +; Detach: while attached, TRACE32 catches every reset at the reset vector, so +; the software reset that starts the update would leave the CPU halted +SYStem.Down +PRINT "done, board running, debugger detached" +AREA.CLOSE A000 + +ENDDO From 42f8973b14ee8f32f386152ebdde78f1f902b7f3 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Wed, 18 Nov 2026 14:39:44 -0500 Subject: [PATCH 19/24] add wolfip support --- config/examples/mcxe31b.config | 27 +++++++ docs/Targets.md | 56 +++++++++++++- test-app/ARM-mcxe31b-wolfip.ld | 109 +++++++++++++++++++++++++++ test-app/Makefile | 23 ++++++ test-app/app_mcxe31b.c | 67 ++++++++++++++++ test-app/startup_arm.c | 18 ++++- test-app/wolfip_tftp_test.c | 32 ++++++-- test-app/wolfip_tftp_test.h | 8 +- tools/scripts/mcxe31b/e31b_debug.cmm | 3 + 9 files changed, 332 insertions(+), 11 deletions(-) create mode 100644 test-app/ARM-mcxe31b-wolfip.ld diff --git a/config/examples/mcxe31b.config b/config/examples/mcxe31b.config index e5e80d9221..35e5e51e59 100644 --- a/config/examples/mcxe31b.config +++ b/config/examples/mcxe31b.config @@ -34,6 +34,16 @@ CFLAGS_EXTRA+=-DWOLFBOOT_RAM_ECC_INIT # 8KB sectors WOLFBOOT_SECTOR_SIZE?=0x2000 +# Word-at-a-time memcpy/memset in src/string.c (bootloader and test-app). The +# Cortex-M7 loads unaligned words, so memcpy copies words even when source and +# destination alignments differ. +CFLAGS_EXTRA+=-DFAST_MEMCPY + +# The application's vector table follows the image header and is used in +# place (VTOR). The table must be 1 KB aligned, or the core fetches the vectors +# of some IRQs (e.g. EMAC, 105) from the wrong slots. +IMAGE_HEADER_SIZE?=1024 + # Memory layout (code flash 0x00400000 - 0x007FFFFF): # IVT + Bootloader: 0x00400000 - 0x0040FFFF (64 KB) # Boot Partition: 0x00410000 - 0x005EFFFF (1920 KB) @@ -49,6 +59,23 @@ WOLFBOOT_PARTITION_SWAP_ADDRESS?=0x7D0000 # Console on the MCU-Link VCOM port: LPUART5, PTE14 (TX) and PTE3 (RX), # 115200 8N1 +# wolfIP network test in the test-app (optional) +# Adds the "network" console command. Needs a wolfIP checkout, which provides +# the nxp_mcxe31b_emac driver (EMAC, RMII to the LAN8741 PHY). The driver is +# interrupt driven; NXP_MCXE31B_EMAC_IRQ=0 makes it poll the EMAC instead. +ENABLE_WOLFIP?=0 +WOLFBOOT_LIB_WOLFIP?=../lib/wolfip +NXP_MCXE31B_EMAC_IRQ?=1 +# By default the command acquires a DHCP lease and runs a TCP and UDP +# throughput server on port 9, driven from the host by +# tools/scripts/wolfip_speed.py. +WOLFIP_SPEED_TEST?=1 +# WOLFBOOT_TEST_TFTP=1 makes the command fetch a file over TFTP instead (it +# overrides WOLFIP_SPEED_TEST). The file must fit the 128 KB receive buffer. +# With both set to 0 the command only acquires a DHCP lease. +WOLFBOOT_TEST_TFTP?=0 +CFLAGS_EXTRA+=-DHOST_IP_STR='"192.168.50.1"' -DTFTP_FILENAME='"wolfip_test.bin"' + # Debugging options DEBUG?=0 DEBUG_SYMBOLS?=0 diff --git a/docs/Targets.md b/docs/Targets.md index 9bf440d15a..ac91583df6 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7968,6 +7968,13 @@ board. - The I-cache and D-cache are on while wolfBoot runs; flash program and erase invalidate the D-cache over the modified range. Both caches are cleaned and turned off before the jump to the application. The clocks stay at 160 MHz. +- `mcxe31b.config` sets `IMAGE_HEADER_SIZE=1024`, so the application starts + 1 KB into the boot partition. The application's vector table is used in + place, and with up to 163 entries it must be 1 KB aligned: with the default + 256-byte header the core fetches the vectors of some interrupts (the EMAC, + IRQ 105, among them) from the wrong slots. +- `mcxe31b.config` sets `FAST_MEMCPY`, the word-at-a-time `memcpy` and + `memset` of `src/string.c`, for wolfBoot and the test application. ### NXP MCXE31B: Memory Layout @@ -8006,6 +8013,50 @@ for later versions, and has the same console as the | `RAM_CODE` | **Required.** The flash program and erase routines run from DTCM, so the block being written is not read. The linker script checks this. | | `DEBUG_UART` | Console output on LPUART5 (MCU-Link VCOM). | +### NXP MCXE31B: Network test + +The test application can run a wolfIP throughput test or a DHCP and TFTP test +over the board's Ethernet port (RMII to a LAN8741A PHY, 50 MHz reference clock +from the board oscillator). This is optional and needs a wolfIP checkout, whose +`nxp_mcxe31b_emac` port is a standalone driver for the EMAC (Synopsys Ethernet +QoS), its clocks and pins, and the PHY (no vendor SDK). The test app builds it +interrupt driven (`NXP_MCXE31B_EMAC_IRQ=1`, EMAC IRQ 105 routed in +`test-app/startup_arm.c`); `NXP_MCXE31B_EMAC_IRQ=0` makes it poll the EMAC +instead. `test-app/ARM-mcxe31b-wolfip.ld` keeps the driver's descriptor rings +and frame buffers in the DTCM, which the core does not cache and the EMAC DMA +reaches through its backdoor port, and places the wolfIP stack state, with +9 KB TCP receive and transmit buffers per socket, and the TFTP receive buffer +in SRAM. SRAM is ECC protected: the reset handler clears all 320 KB of it +with 64-bit stores (`APP_RAM_ECC_INIT`) before it is used. Set +`ENABLE_WOLFIP=1` in `mcxe31b.config` and check the wolfIP path: + +```sh +ENABLE_WOLFIP?=1 +WOLFBOOT_LIB_WOLFIP?=../lib/wolfip +NXP_MCXE31B_EMAC_IRQ?=1 +WOLFIP_SPEED_TEST?=1 +WOLFBOOT_TEST_TFTP?=0 +``` + +Type `network` on the console to run the test. It works the same way as the +[MCXE247 network test](#nxp-mcxe247-network-test): by default it acquires a +DHCP lease and runs a TCP and UDP throughput server on port 9, driven from a +PC on the same network with `python3 tools/scripts/wolfip_speed.py `. +Ctrl-C on the console stops the server. Measured on the FRDM-MCXE31B at +160 MHz, 100 Mbit/s full duplex, interrupt driven, 10 s per test: + +| Test | Board receives | Board sends | +|------|----------------|-------------| +| TCP, one direction | 92.3 Mbit/s | 72.5 Mbit/s | +| TCP, both directions | 38.2 Mbit/s | 30.6 Mbit/s | +| UDP, one direction | 95.7 Mbit/s (no loss) | 78.5 Mbit/s | +| UDP, both directions | 71.8 Mbit/s | 71.8 Mbit/s | + +With `WOLFBOOT_TEST_TFTP=1` the command fetches `TFTP_FILENAME` from +`HOST_IP_STR` instead (128 KB at most) and prints its size and checksum +followed by `WOLFIP_TEST: PASS` or `WOLFIP_TEST: FAIL`. Both the interrupt +driven and the polled build pass this test. + ### NXP MCXE31B: Programming with Lauterbach TRACE32 Connect the 10-pin debug cable to J14 and short JP5 to disable the onboard @@ -8044,9 +8095,10 @@ Tested on the FRDM-MCXE31B: 1. Program `factory.bin` with `e31b_flash_factory_bin.cmm`. wolfBoot boots version 1 and the RGB LED is green. -2. Sign version 2 and program it with `e31b_flash_update.cmm`: +2. Sign version 2 with the configured 1 KB header and program it with + `e31b_flash_update.cmm`: ```sh - tools/keytools/sign --ecc256 --sha256 test-app/image.bin wolfboot_signing_private_key.der 2 + IMAGE_HEADER_SIZE=1024 tools/keytools/sign --ecc256 --sha256 test-app/image.bin wolfboot_signing_private_key.der 2 ``` 3. On the console, `status` shows the update. `trigger` then `reboot` swaps the partitions. Version 2 boots, finds the TESTING state and marks itself diff --git a/test-app/ARM-mcxe31b-wolfip.ld b/test-app/ARM-mcxe31b-wolfip.ld new file mode 100644 index 0000000000..6748917a63 --- /dev/null +++ b/test-app/ARM-mcxe31b-wolfip.ld @@ -0,0 +1,109 @@ +/* + * Linker script for the wolfBoot test application on NXP MCXE31B with wolfIP + * + * The application runs from the boot partition after the wolfBoot header. + * + * RAM is the 64 KB CM7_0 DTCM (0x20000000), which wolfBoot has already + * ECC-initialized: data, the RAM_CODE flash routines, .bss, heap and stack. + * The core does not cache the DTCM and the EMAC DMA reaches it through its + * backdoor port, so the EMAC driver's descriptor rings and frame buffers + * (its .bss) live there with no cache maintenance. + * + * The wolfIP stack state (sockets and their buffers) and the TFTP receive + * buffer go in the 320 KB SRAM (0x20400000), which the core caches and only + * the core uses. SRAM is ECC protected and holds no valid ECC after + * power-on. With APP_RAM_ECC_INIT the reset handler clears + * [_start_ecc_ram, _end_ecc_ram) with 64-bit stores (SRAM ECC words are 64 + * bits) before anything reads it; that clear is also what zeroes the SRAM + * section: it is not part of .bss. + */ + +MEMORY +{ + FLASH (rx) : ORIGIN = @WOLFBOOT_TEST_APP_ADDRESS@, LENGTH = @WOLFBOOT_TEST_APP_SIZE@ + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x10000 /* 64 KB DTCM */ + SRAM (rw) : ORIGIN = 0x20400000, LENGTH = 0x50000 /* 320 KB SRAM */ +} + +SECTIONS +{ + .text : + { + _start_text = .; + KEEP(*(.isr_vector)) + *(.text*) + *(.rodata*) + *(.init*) + *(.fini*) + . = ALIGN(4); + _end_text = .; + } > FLASH + + .keystore : + { + . = ALIGN(4); + KEEP(*(.keystore*)) + } > FLASH + + .edidx : + { + . = ALIGN(4); + *(.ARM.exidx*) + } > FLASH + + _stored_data = .; + + .data : AT (_stored_data) + { + _start_data = .; + KEEP(*(.data*)) + . = ALIGN(4); + KEEP(*(.ramcode)) + . = ALIGN(4); + _end_data = .; + } > RAM + + /* wolfIP and network test state, zero-filled by the APP_RAM_ECC_INIT + * clear. It comes before .bss so that these input sections are taken + * before the .bss* rule below. */ + .bss_sram (NOLOAD) : + { + . = ALIGN(8); + *wolfip.o(.bss .bss.* COMMON) + *wolftftp.o(.bss .bss.* COMMON) + *wolfip_tftp_test.o(.bss .bss.* COMMON) + . = ALIGN(8); + } > SRAM + + .bss (NOLOAD) : + { + _start_bss = .; + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + _end_bss = .; + __bss_end__ = .; + _end = .; + } > RAM + . = ALIGN(4); +} + +/* Partition info for libwolfboot */ +_wolfboot_partition_boot_address = @WOLFBOOT_PARTITION_BOOT_ADDRESS@; +_wolfboot_partition_size = @WOLFBOOT_PARTITION_SIZE@; +_wolfboot_partition_update_address = @WOLFBOOT_PARTITION_UPDATE_ADDRESS@; +_wolfboot_partition_swap_address = @WOLFBOOT_PARTITION_SWAP_ADDRESS@; + +/* Stack and heap indicators */ +_start_heap = _end; +_end_stack = ORIGIN(RAM) + LENGTH(RAM); + +/* SRAM cleared at reset with APP_RAM_ECC_INIT */ +_start_ecc_ram = ORIGIN(SRAM); +_end_ecc_ram = ORIGIN(SRAM) + LENGTH(SRAM); + +/* The EMAC driver's buffers must be in the DTCM */ +ASSERT(_end_bss <= ORIGIN(RAM) + LENGTH(RAM), "DTCM overflow") +/* Keep room above .bss for the stack and the heap used by printf */ +ASSERT(_end_stack - _end >= 0x2000, "not enough RAM left for the stack") diff --git a/test-app/Makefile b/test-app/Makefile index f78f99fb59..21522b073b 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1812,6 +1812,29 @@ ifeq ($(ENABLE_WOLFIP),1) ifeq ($(WOLFIP_SPEED_TEST),1) CFLAGS+=-DNXP_MCXE_ENET_STATS=1 endif + else ifeq ($(TARGET),mcxe31b) + WOLFIP_PORT:=nxp_mcxe31b_emac + WOLFIP_PORT_OBJ:=nxp_mcxe31b_emac.o + # wolfIP state in SRAM, EMAC rings in the DTCM (ARM-mcxe31b-wolfip.ld) + LSCRIPT_TEMPLATE=ARM-mcxe31b-wolfip.ld + # Clear all of SRAM at reset, before it is read (ECC) + CFLAGS+=-DAPP_RAM_ECC_INIT + # NXP_MCXE31B_EMAC_IRQ=0 polls the EMAC instead of using its interrupt + NXP_MCXE31B_EMAC_IRQ?=1 + CFLAGS+=-DWOLFIP_PORT_MCXE31B_EMAC + CFLAGS+=-DNXP_MCXE31B_EMAC_IRQ=$(NXP_MCXE31B_EMAC_IRQ) + CFLAGS+=-DTFTP_RAM_MAX=0x20000U + # Six full segments of TCP buffering per socket + CFLAGS+=-DRXBUF_SIZE=9216 -DTXBUF_SIZE=9216 + # remove -ffreestanding so small memcpy's can be inlined + WOLFIP_CFLAGS_FILTEROUT:=-ffreestanding + # Take at most 8 frames per wolfIP_poll() so the app can drain a socket + # between batches + WOLFIP_CFLAGS_ADD:=-O2 -DWOLFIP_POLL_BUDGET=8 + # Driver cycle counters for the throughput test's CPU breakdown + ifeq ($(WOLFIP_SPEED_TEST),1) + CFLAGS+=-DNXP_MCXE31B_EMAC_STATS=1 + endif else WOLFIP_PORT:=nxp_fman WOLFIP_PORT_OBJ:=nxp_fman.o diff --git a/test-app/app_mcxe31b.c b/test-app/app_mcxe31b.c index abfd8671df..c42903e6da 100644 --- a/test-app/app_mcxe31b.c +++ b/test-app/app_mcxe31b.c @@ -37,6 +37,9 @@ #include "keystore.h" #include "target.h" #include "image.h" +#ifdef ENABLE_WOLFIP +#include "wolfip_tftp_test.h" +#endif #ifdef TARGET_mcxe31b @@ -50,12 +53,46 @@ /* ============== SysTick Timer ============== */ static volatile uint32_t jiffies = 0; +#ifdef ENABLE_WOLFIP +/* Upper 32 bits of the ms count, so the network timebase does not wrap */ +static volatile uint32_t jiffies_hi = 0; +#endif /* SysTick interrupt handler - called isr_systick to match startup_arm.c */ void isr_systick(void) { jiffies++; +#ifdef ENABLE_WOLFIP + if (jiffies == 0U) { + jiffies_hi++; + } +#endif +} + +#ifdef ENABLE_WOLFIP +/* Millisecond timebase for wolfip_tftp_test.c. 64 bits, so it is monotonic + * across the 32-bit wrap of jiffies. */ +uint64_t wolfip_test_get_ms(void) +{ + uint32_t hi, lo; + + /* Read again if SysTick carried into the upper word in between */ + do { + hi = jiffies_hi; + lo = jiffies; + } while (hi != jiffies_hi); + + return ((uint64_t)hi << 32) | lo; +} + +#ifndef DEBUG_UART +/* No console: the network test cannot be cancelled */ +int wolfip_test_abort(void) +{ + return 0; } +#endif +#endif static void delay_ms(uint32_t ms) { @@ -694,6 +731,9 @@ static int cmd_update(const char *args); static int cmd_timestamp(const char *args); static int cmd_trigger(const char *args); static int cmd_status(const char *args); +#ifdef ENABLE_WOLFIP +static int cmd_network(const char *args); +#endif typedef struct { int (*fn)(const char *args); @@ -709,6 +749,9 @@ static const console_cmd_t commands[] = { {cmd_trigger, "trigger", "Trigger update (if update image in flash)"}, {cmd_update, "update", "Update firmware via XMODEM"}, {cmd_timestamp, "timestamp", "Show current system time"}, +#ifdef ENABLE_WOLFIP + {cmd_network, "network", "Run the wolfIP network test"}, +#endif {cmd_reboot, "reboot", "Reboot the system"}, {NULL, NULL, NULL} }; @@ -827,6 +870,30 @@ static int cmd_update(const char *args) return cmd_update_xmodem(); } +#ifdef ENABLE_WOLFIP +static int cmd_network(const char *args) +{ + (void)args; + wolfip_tftp_test_report(); + return 0; +} + +#ifdef DEBUG_UART +/* Non-zero when Ctrl-C arrived on the console. Other input is discarded. */ +int wolfip_test_abort(void) +{ + char c; + int abort = 0; + + while (uart_getc(&c) > 0) { + if (c == 0x03) + abort = 1; + } + return abort; +} +#endif +#endif + static int parse_command(const char* cmd) { int i; diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index 3c87871b81..08eaeacb8e 100644 --- a/test-app/startup_arm.c +++ b/test-app/startup_arm.c @@ -75,6 +75,13 @@ extern void nxp_mcxe_enet_irq_handler(void); #ifdef TARGET_mcxe31b extern void isr_debug_uart(void); +/* MCXE31B EMAC common interrupt (IRQ 105) */ +#if defined(NXP_MCXE31B_EMAC_IRQ) && (NXP_MCXE31B_EMAC_IRQ == 1) +extern void nxp_mcxe31b_emac_irq_handler(void); +#define isr_emac nxp_mcxe31b_emac_irq_handler +#else +#define isr_emac isr_empty +#endif #endif #if defined(TARGET_va416x0) || defined(TARGET_lpc55s69) @@ -106,10 +113,18 @@ void isr_reset(void) "ldr r0, =_start_ecc_ram\n\t" "ldr r1, =_end_ecc_ram\n\t" "movs r2, #0\n\t" +#ifdef TARGET_mcxe31b + /* SRAM ECC words are 64 bits: [_start, _end) is 8-byte aligned */ + "movs r3, #0\n\t" +#endif "1:\n\t" "cmp r0, r1\n\t" "bhs 2f\n\t" +#ifdef TARGET_mcxe31b + "strd r2, r3, [r0], #8\n\t" +#else "str r2, [r0], #4\n\t" +#endif "b 1b\n\t" "2:\n\t" "b isr_reset_c\n\t" @@ -658,8 +673,9 @@ void (* const IV[])(void) = #elif defined(TARGET_mcxe31b) /* For NXP MCXE31B */ - /* IRQs 0-145 unused, 146 = LPUART5 (console) */ + /* IRQs 0-145 unused except 105 = EMAC, 146 = LPUART5 (console) */ [16 ... (16 + 145)] = isr_empty, + [16 + 105] = isr_emac, [16 + 146] = isr_debug_uart, #elif defined(TARGET_va416x0) /* For Vorago VA416xx */ diff --git a/test-app/wolfip_tftp_test.c b/test-app/wolfip_tftp_test.c index e9a58f7c1f..6c3948d425 100644 --- a/test-app/wolfip_tftp_test.c +++ b/test-app/wolfip_tftp_test.c @@ -42,6 +42,7 @@ /* Port selection: * WOLFIP_PORT_ENETC -> LS1028A ENETC * WOLFIP_PORT_MCXE_ENET -> MCXE247 ENET + * WOLFIP_PORT_MCXE31B_EMAC -> MCXE31B EMAC * else QorIQ FMan * Driver entry points are wrapped so the bring-up code below is port-agnostic. */ #if defined(WOLFIP_PORT_ENETC) @@ -59,6 +60,23 @@ #define WOLFIP_NETDEV_PHY_READ nxp_mcxe_enet_phy_read #define WOLFIP_NETDEV_LINK_UP nxp_mcxe_enet_link_up #define WOLFIP_NETDEV_NAME "MCXE247 ENET" +#if NXP_MCXE_ENET_STATS +#define WOLFIP_NETDEV_STATS struct nxp_mcxe_enet_stats +#define WOLFIP_NETDEV_STATS_GET nxp_mcxe_enet_stats_get +#define WOLFIP_NETDEV_STATS_RESET nxp_mcxe_enet_stats_reset +#endif +#elif defined(WOLFIP_PORT_MCXE31B_EMAC) +#include "nxp_mcxe31b_emac.h" +#define WOLFIP_NETDEV_INIT nxp_mcxe31b_emac_init +#define WOLFIP_NETDEV_PHY_ADDR nxp_mcxe31b_emac_phy_addr +#define WOLFIP_NETDEV_PHY_READ nxp_mcxe31b_emac_phy_read +#define WOLFIP_NETDEV_LINK_UP nxp_mcxe31b_emac_link_up +#define WOLFIP_NETDEV_NAME "MCXE31B EMAC" +#if NXP_MCXE31B_EMAC_STATS +#define WOLFIP_NETDEV_STATS struct nxp_mcxe31b_emac_stats +#define WOLFIP_NETDEV_STATS_GET nxp_mcxe31b_emac_stats_get +#define WOLFIP_NETDEV_STATS_RESET nxp_mcxe31b_emac_stats_reset +#endif #else #include "nxp_fman.h" #define WOLFIP_NETDEV_INIT nxp_fman_init @@ -113,7 +131,7 @@ static uint64_t now_ms(void) { return read_tb() / (tb_hz() / 1000ULL); } -#elif defined(WOLFIP_PORT_MCXE_ENET) +#elif defined(WOLFIP_TEST_APP_TIMEBASE) /* 1 ms SysTick count, kept by the target app. */ #define SYST_CVR_REG (*(volatile uint32_t *)0xE000E018UL) @@ -509,13 +527,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) @@ -558,7 +576,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) @@ -666,7 +684,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 } @@ -705,7 +723,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(); } @@ -734,7 +752,7 @@ static void speed_reply(struct wolfIP *s, const struct wolfIP_sockaddr_in *to, speed_put32(r + 104, speed.polls); #if SPEED_PROFILE if (speed.active != 0U) - nxp_mcxe_enet_stats_get(&speed_drv); + WOLFIP_NETDEV_STATS_GET(&speed_drv); speed_put32(r + 12, speed_drv.core_hz); speed_put32(r + 24, speed_drv.rx_frames); speed_put32(r + 28, speed_drv.tx_frames); diff --git a/test-app/wolfip_tftp_test.h b/test-app/wolfip_tftp_test.h index 4816205fbf..ab23844035 100644 --- a/test-app/wolfip_tftp_test.h +++ b/test-app/wolfip_tftp_test.h @@ -34,7 +34,13 @@ int wolfip_tftp_test_run(void); * Convenience wrapper so each target app's main() is a single call. */ void wolfip_tftp_test_report(void); -#ifdef WOLFIP_PORT_MCXE_ENET +/* Cortex-M ports without a free-running timer of their own take the time + * and the stop request from the target app */ +#if defined(WOLFIP_PORT_MCXE_ENET) || defined(WOLFIP_PORT_MCXE31B_EMAC) +#define WOLFIP_TEST_APP_TIMEBASE +#endif + +#ifdef WOLFIP_TEST_APP_TIMEBASE /* Milliseconds since start, monotonic. Provided by the target app. */ uint64_t wolfip_test_get_ms(void); diff --git a/tools/scripts/mcxe31b/e31b_debug.cmm b/tools/scripts/mcxe31b/e31b_debug.cmm index 27254c03bf..67df602835 100644 --- a/tools/scripts/mcxe31b/e31b_debug.cmm +++ b/tools/scripts/mcxe31b/e31b_debug.cmm @@ -96,6 +96,9 @@ IF OS.FILE("&basedir\test-app\image.elf") sYmbol.SourcePATH.SetBaseDir "&basedir" &srcdirs="""&basedir"" ""&basedir\src"" ""&basedir\hal"" ""&basedir\test-app""" &srcdirs="&srcdirs ""&basedir\lib\wolfssl\wolfcrypt\src""" +; wolfIP and its MCXE31B port (test-app built with ENABLE_WOLFIP=1) +&srcdirs="&srcdirs ""&basedir\lib\wolfip\src"" ""&basedir\lib\wolfip\src\tftp""" +&srcdirs="&srcdirs ""&basedir\lib\wolfip\src\port\nxp_mcxe31b_emac""" sYmbol.SourcePATH.Set &srcdirs ENDDO From 71739567523cbb022aaa534b5d755564cb1abd2f Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 23 Nov 2026 13:23:17 -0500 Subject: [PATCH 20/24] wolfip perf improvements --- docs/Targets.md | 25 ++++++++++++------ test-app/ARM-mcxe31b-wolfip.ld | 48 +++++++++++++++++++++++++++++----- test-app/Makefile | 9 ++++--- test-app/startup_arm.c | 28 ++++++++++++++++++++ 4 files changed, 91 insertions(+), 19 deletions(-) diff --git a/docs/Targets.md b/docs/Targets.md index ac91583df6..39bbbb38c7 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -8025,10 +8025,15 @@ interrupt driven (`NXP_MCXE31B_EMAC_IRQ=1`, EMAC IRQ 105 routed in instead. `test-app/ARM-mcxe31b-wolfip.ld` keeps the driver's descriptor rings and frame buffers in the DTCM, which the core does not cache and the EMAC DMA reaches through its backdoor port, and places the wolfIP stack state, with -9 KB TCP receive and transmit buffers per socket, and the TFTP receive buffer -in SRAM. SRAM is ECC protected: the reset handler clears all 320 KB of it -with 64-bit stores (`APP_RAM_ECC_INIT`) before it is used. Set -`ENABLE_WOLFIP=1` in `mcxe31b.config` and check the wolfIP path: +9 KB TCP receive and transmit buffers per socket, the TFTP receive buffer and +libwolfboot's 8 KB flash sector buffer (`NVM_CACHE`) in SRAM. SRAM is ECC +protected: the reset handler clears all 320 KB of it with 64-bit stores +(`APP_RAM_ECC_INIT`) before it is used. The hottest network code (8.7 KB: +runs from the ITCM: the reset handler clears the ITCM and copies it there +(`APP_RAMCODE_ITCM`). wolfIP takes at most 16 frames per `wolfIP_poll()` +(`WOLFIP_POLL_BUDGET=16`). The driver uses 8 transmit and 4 receive +descriptors (19 KB of DTCM). +Set `ENABLE_WOLFIP=1` in `mcxe31b.config` and check the wolfIP path: ```sh ENABLE_WOLFIP?=1 @@ -8047,10 +8052,14 @@ Ctrl-C on the console stops the server. Measured on the FRDM-MCXE31B at | Test | Board receives | Board sends | |------|----------------|-------------| -| TCP, one direction | 92.3 Mbit/s | 72.5 Mbit/s | -| TCP, both directions | 38.2 Mbit/s | 30.6 Mbit/s | -| UDP, one direction | 95.7 Mbit/s (no loss) | 78.5 Mbit/s | -| UDP, both directions | 71.8 Mbit/s | 71.8 Mbit/s | +| TCP, one direction | 83-89 Mbit/s | 86.1 Mbit/s | +| TCP, both directions | 52.4-53.0 Mbit/s | 39.5 Mbit/s | +| UDP, one direction | 95.7 Mbit/s (no loss) | 95.7 Mbit/s | +| UDP, both directions | 93.5-95.3 Mbit/s | 95.7 Mbit/s | + +UDP in one direction runs at the line rate, and both directions at once come +close to it: the board drops 0.4-2.4% of what it receives. TCP is limited by the +CPU. With `WOLFBOOT_TEST_TFTP=1` the command fetches `TFTP_FILENAME` from `HOST_IP_STR` instead (128 KB at most) and prints its size and checksum diff --git a/test-app/ARM-mcxe31b-wolfip.ld b/test-app/ARM-mcxe31b-wolfip.ld index 6748917a63..49dc707548 100644 --- a/test-app/ARM-mcxe31b-wolfip.ld +++ b/test-app/ARM-mcxe31b-wolfip.ld @@ -9,24 +9,51 @@ * backdoor port, so the EMAC driver's descriptor rings and frame buffers * (its .bss) live there with no cache maintenance. * - * The wolfIP stack state (sockets and their buffers) and the TFTP receive - * buffer go in the 320 KB SRAM (0x20400000), which the core caches and only - * the core uses. SRAM is ECC protected and holds no valid ECC after + * The wolfIP stack state (sockets and their buffers), the TFTP receive + * buffer and libwolfboot's flash sector buffer (NVM_CACHE) go in the 320 KB + * SRAM (0x20400000), which the core caches and only the core uses. SRAM is + * ECC protected and holds no valid ECC after * power-on. With APP_RAM_ECC_INIT the reset handler clears * [_start_ecc_ram, _end_ecc_ram) with 64-bit stores (SRAM ECC words are 64 * bits) before anything reads it; that clear is also what zeroes the SRAM * section: it is not part of .bss. + * + * The hottest code runs from the 32 KB ITCM (.ramcode_itcm). The first + * 1 KB of the ITCM is left unused, so that writes through a NULL pointer do + * not land on code. */ MEMORY { FLASH (rx) : ORIGIN = @WOLFBOOT_TEST_APP_ADDRESS@, LENGTH = @WOLFBOOT_TEST_APP_SIZE@ + ITCM (rx) : ORIGIN = 0x00000400, LENGTH = 0x7C00 /* 31 KB ITCM */ RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x10000 /* 64 KB DTCM */ SRAM (rw) : ORIGIN = 0x20400000, LENGTH = 0x50000 /* 320 KB SRAM */ } SECTIONS { + /* Hot code run from the ITCM. It comes first so that these input + * sections are taken before the .text* rule below. */ + .ramcode_itcm : AT (_stored_ramcode_itcm) + { + . = ALIGN(8); + _start_ramcode_itcm = .; + KEEP(*string.o(.ramcode)) + *string.o(.text.memset .text.memcmp) + *wolfip.o(.text.csum_add .text.transport_checksum) + *wolfip.o(.text.iphdr_set_checksum .text.wolfIP_poll) + *wolfip.o(.text.fifo_next .text.fifo_peek .text.fifo_push) + *wolfip.o(.text.fifo_pop .text.fifo_can_push_len) + *wolfip.o(.text.tcp_snd_nxt .text.tcp_calc_win .text.wolfIP_sock_send) + *wolfip.o(.text.wolfIP_route_lookup_internal .text.arp_neighbor_index) + *nxp_mcxe31b_emac.o(.text.eth_poll .text.eth_send) + *nxp_mcxe31b_emac.o(.text.eth_poll_stats .text.eth_send_stats) + *nxp_mcxe31b_emac.o(.text.nxp_mcxe31b_emac_irq_handler) + . = ALIGN(8); + _end_ramcode_itcm = .; + } > ITCM + .text : { _start_text = .; @@ -51,7 +78,9 @@ SECTIONS *(.ARM.exidx*) } > FLASH - _stored_data = .; + _stored_ramcode_itcm = ALIGN(8); + + _stored_data = _stored_ramcode_itcm + SIZEOF(.ramcode_itcm); .data : AT (_stored_data) { @@ -63,15 +92,16 @@ SECTIONS _end_data = .; } > RAM - /* wolfIP and network test state, zero-filled by the APP_RAM_ECC_INIT - * clear. It comes before .bss so that these input sections are taken - * before the .bss* rule below. */ + /* wolfIP and network test state and the libwolfboot sector buffer, + * zero-filled by the APP_RAM_ECC_INIT clear. It comes before .bss so + * that these input sections are taken before the .bss* rule below. */ .bss_sram (NOLOAD) : { . = ALIGN(8); *wolfip.o(.bss .bss.* COMMON) *wolftftp.o(.bss .bss.* COMMON) *wolfip_tftp_test.o(.bss .bss.* COMMON) + *libwolfboot.o(.bss.NVM_CACHE) . = ALIGN(8); } > SRAM @@ -99,6 +129,10 @@ _wolfboot_partition_swap_address = @WOLFBOOT_PARTITION_SWAP_ADDRESS@; _start_heap = _end; _end_stack = ORIGIN(RAM) + LENGTH(RAM); +/* ITCM cleared at reset with APP_RAMCODE_ITCM, before the code is copied */ +_start_ecc_itcm = 0x00000000; +_end_ecc_itcm = 0x00008000; + /* SRAM cleared at reset with APP_RAM_ECC_INIT */ _start_ecc_ram = ORIGIN(SRAM); _end_ecc_ram = ORIGIN(SRAM) + LENGTH(SRAM); diff --git a/test-app/Makefile b/test-app/Makefile index 21522b073b..1f8bf03bd9 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1819,18 +1819,19 @@ ifeq ($(ENABLE_WOLFIP),1) LSCRIPT_TEMPLATE=ARM-mcxe31b-wolfip.ld # Clear all of SRAM at reset, before it is read (ECC) CFLAGS+=-DAPP_RAM_ECC_INIT + # Hot code in the ITCM (.ramcode_itcm in ARM-mcxe31b-wolfip.ld) + CFLAGS+=-DAPP_RAMCODE_ITCM # NXP_MCXE31B_EMAC_IRQ=0 polls the EMAC instead of using its interrupt NXP_MCXE31B_EMAC_IRQ?=1 CFLAGS+=-DWOLFIP_PORT_MCXE31B_EMAC CFLAGS+=-DNXP_MCXE31B_EMAC_IRQ=$(NXP_MCXE31B_EMAC_IRQ) CFLAGS+=-DTFTP_RAM_MAX=0x20000U - # Six full segments of TCP buffering per socket + # Six full segments of TCP buffering per socket. CFLAGS+=-DRXBUF_SIZE=9216 -DTXBUF_SIZE=9216 # remove -ffreestanding so small memcpy's can be inlined WOLFIP_CFLAGS_FILTEROUT:=-ffreestanding - # Take at most 8 frames per wolfIP_poll() so the app can drain a socket - # between batches - WOLFIP_CFLAGS_ADD:=-O2 -DWOLFIP_POLL_BUDGET=8 + # Take at most 16 frames per wolfIP_poll() + WOLFIP_CFLAGS_ADD:=-O2 -DWOLFIP_POLL_BUDGET=16 # Driver cycle counters for the throughput test's CPU breakdown ifeq ($(WOLFIP_SPEED_TEST),1) CFLAGS+=-DNXP_MCXE31B_EMAC_STATS=1 diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index 08eaeacb8e..698d2669e7 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 */ extern unsigned int _stored_ramcode_l; @@ -127,6 +133,18 @@ void isr_reset(void) #endif "b 1b\n\t" "2:\n\t" +#ifdef APP_RAMCODE_ITCM + /* The ITCM holds no valid ECC either: clear it before the hot + * code is copied in, also with 64-bit stores */ + "ldr r0, =_start_ecc_itcm\n\t" + "ldr r1, =_end_ecc_itcm\n\t" + "3:\n\t" + "cmp r0, r1\n\t" + "bhs 4f\n\t" + "strd r2, r3, [r0], #8\n\t" + "b 3b\n\t" + "4:\n\t" +#endif "b isr_reset_c\n\t" ); } @@ -150,6 +168,16 @@ void isr_reset(void) dst++; src++; } +#ifdef APP_RAMCODE_ITCM + src = (unsigned int *) &_stored_ramcode_itcm; + dst = (unsigned int *) &_start_ramcode_itcm; + while (dst < (unsigned int *)&_end_ramcode_itcm) { + *dst = *src; + dst++; + src++; + } + __asm__ volatile ("dsb\n\tisb" ::: "memory"); +#endif #ifdef APP_RAMCODE_L src = (unsigned int *) &_stored_ramcode_l; dst = (unsigned int *) &_start_ramcode_l; From a21007050ac42a58729455df009dec0bd39fc515 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 23 Nov 2026 14:07:01 -0500 Subject: [PATCH 21/24] rename from e31b_emac to mcxe_emac for more general use --- config/examples/mcxe31b.config | 6 +++--- docs/Targets.md | 15 ++++++++------- hal/mcxe31b.c | 6 +++--- hal/mcxe31b.h | 6 ++++-- test-app/ARM-mcxe31b-wolfip.ld | 6 +++--- test-app/Makefile | 16 ++++++++-------- test-app/startup_arm.c | 6 +++--- test-app/wolfip_tftp_test.c | 22 +++++++++++----------- test-app/wolfip_tftp_test.h | 2 +- tools/scripts/mcxe31b/e31b_debug.cmm | 2 +- 10 files changed, 45 insertions(+), 42 deletions(-) diff --git a/config/examples/mcxe31b.config b/config/examples/mcxe31b.config index 35e5e51e59..8849fb0a32 100644 --- a/config/examples/mcxe31b.config +++ b/config/examples/mcxe31b.config @@ -61,11 +61,11 @@ WOLFBOOT_PARTITION_SWAP_ADDRESS?=0x7D0000 # wolfIP network test in the test-app (optional) # Adds the "network" console command. Needs a wolfIP checkout, which provides -# the nxp_mcxe31b_emac driver (EMAC, RMII to the LAN8741 PHY). The driver is -# interrupt driven; NXP_MCXE31B_EMAC_IRQ=0 makes it poll the EMAC instead. +# the nxp_mcxe_emac driver (EMAC, RMII to the LAN8741 PHY). The driver is +# interrupt driven; NXP_MCXE_EMAC_IRQ=0 makes it poll the EMAC instead. ENABLE_WOLFIP?=0 WOLFBOOT_LIB_WOLFIP?=../lib/wolfip -NXP_MCXE31B_EMAC_IRQ?=1 +NXP_MCXE_EMAC_IRQ?=1 # By default the command acquires a DHCP lease and runs a TCP and UDP # throughput server on port 9, driven from the host by # tools/scripts/wolfip_speed.py. diff --git a/docs/Targets.md b/docs/Targets.md index 39bbbb38c7..9a799ff438 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -8018,10 +8018,10 @@ for later versions, and has the same console as the The test application can run a wolfIP throughput test or a DHCP and TFTP test over the board's Ethernet port (RMII to a LAN8741A PHY, 50 MHz reference clock from the board oscillator). This is optional and needs a wolfIP checkout, whose -`nxp_mcxe31b_emac` port is a standalone driver for the EMAC (Synopsys Ethernet +`nxp_mcxe_emac` port is a standalone driver for the EMAC (Synopsys Ethernet QoS), its clocks and pins, and the PHY (no vendor SDK). The test app builds it -interrupt driven (`NXP_MCXE31B_EMAC_IRQ=1`, EMAC IRQ 105 routed in -`test-app/startup_arm.c`); `NXP_MCXE31B_EMAC_IRQ=0` makes it poll the EMAC +interrupt driven (`NXP_MCXE_EMAC_IRQ=1`, EMAC IRQ 105 routed in +`test-app/startup_arm.c`); `NXP_MCXE_EMAC_IRQ=0` makes it poll the EMAC instead. `test-app/ARM-mcxe31b-wolfip.ld` keeps the driver's descriptor rings and frame buffers in the DTCM, which the core does not cache and the EMAC DMA reaches through its backdoor port, and places the wolfIP stack state, with @@ -8038,7 +8038,7 @@ Set `ENABLE_WOLFIP=1` in `mcxe31b.config` and check the wolfIP path: ```sh ENABLE_WOLFIP?=1 WOLFBOOT_LIB_WOLFIP?=../lib/wolfip -NXP_MCXE31B_EMAC_IRQ?=1 +NXP_MCXE_EMAC_IRQ?=1 WOLFIP_SPEED_TEST?=1 WOLFBOOT_TEST_TFTP?=0 ``` @@ -8048,11 +8048,12 @@ Type `network` on the console to run the test. It works the same way as the DHCP lease and runs a TCP and UDP throughput server on port 9, driven from a PC on the same network with `python3 tools/scripts/wolfip_speed.py `. Ctrl-C on the console stops the server. Measured on the FRDM-MCXE31B at -160 MHz, 100 Mbit/s full duplex, interrupt driven, 10 s per test: +160 MHz, 100 Mbit/s full duplex, interrupt driven, 10 s per test, with the +script run by Windows Python on a Windows PC on an otherwise idle network: | Test | Board receives | Board sends | |------|----------------|-------------| -| TCP, one direction | 83-89 Mbit/s | 86.1 Mbit/s | +| TCP, one direction | 88-90 Mbit/s | 86 Mbit/s | | TCP, both directions | 52.4-53.0 Mbit/s | 39.5 Mbit/s | | UDP, one direction | 95.7 Mbit/s (no loss) | 95.7 Mbit/s | | UDP, both directions | 93.5-95.3 Mbit/s | 95.7 Mbit/s | @@ -8062,7 +8063,7 @@ close to it: the board drops 0.4-2.4% of what it receives. TCP is limited by the CPU. With `WOLFBOOT_TEST_TFTP=1` the command fetches `TFTP_FILENAME` from -`HOST_IP_STR` instead (128 KB at most) and prints its size and checksum +`HOST_IP_STR` instead (40 KB at most) and prints its size and checksum followed by `WOLFIP_TEST: PASS` or `WOLFIP_TEST: FAIL`. Both the interrupt driven and the polled build pass this test. diff --git a/hal/mcxe31b.c b/hal/mcxe31b.c index c0ac77d773..028db819b6 100644 --- a/hal/mcxe31b.c +++ b/hal/mcxe31b.c @@ -104,9 +104,9 @@ static void delay_cycles(uint32_t n) } /* Switch the system clocks from FIRC 48 MHz to the PLL using the RM - * "Option A" (high performance) configuration: FXOSC 16 MHz -> PLL VCO - * 960 MHz -> ODIV2 480 MHz -> PHI0 160 MHz. On failure the system stays - * on FIRC. */ + * "Option A" (high performance) configuration (MCXEP172M160FB0RM Rev. 5, + * Table 134): FXOSC 16 MHz -> PLL VCO 960 MHz -> ODIV2 480 MHz -> PHI0 + * 160 MHz. On failure the system stays on FIRC. */ static int clock_init(void) { /* MUX_0 dividers (DIV + 1): CORE 160, AIPS_PLAT 80, AIPS_SLOW 40, diff --git a/hal/mcxe31b.h b/hal/mcxe31b.h index 743b4d6331..2e0e6f4b21 100644 --- a/hal/mcxe31b.h +++ b/hal/mcxe31b.h @@ -19,7 +19,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA * * Register definitions for NXP MCXE31B (Cortex-M7, 4MB C40ASF flash). - * Register offsets and fields from the MCXE31x Reference Manual Rev. 3. + * Register offsets and fields from the MCX E3 Reference Manual + * (MCXEP172M160FB0RM, Rev. 5). */ #ifndef MCXE31B_H @@ -30,7 +31,8 @@ /* ============== Clock ============== */ /* The boot ROM (Secure BAF) leaves the core on FIRC 48 MHz. hal_init() - * switches to the PLL with the RM "Option A" (high performance) dividers: + * switches to the PLL with the RM "Option A" (high performance) dividers + * (MCXEP172M160FB0RM Rev. 5, 23.7.2.1, Table 134): * CORE_CLK 160 MHz, AIPS_PLAT_CLK 80 MHz, AIPS_SLOW_CLK 40 MHz (LPUART1..7 * functional clock), HSE_CLK 80 MHz. */ #define FIRC_FREQ 48000000UL diff --git a/test-app/ARM-mcxe31b-wolfip.ld b/test-app/ARM-mcxe31b-wolfip.ld index 49dc707548..f4c041a11d 100644 --- a/test-app/ARM-mcxe31b-wolfip.ld +++ b/test-app/ARM-mcxe31b-wolfip.ld @@ -47,9 +47,9 @@ SECTIONS *wolfip.o(.text.fifo_pop .text.fifo_can_push_len) *wolfip.o(.text.tcp_snd_nxt .text.tcp_calc_win .text.wolfIP_sock_send) *wolfip.o(.text.wolfIP_route_lookup_internal .text.arp_neighbor_index) - *nxp_mcxe31b_emac.o(.text.eth_poll .text.eth_send) - *nxp_mcxe31b_emac.o(.text.eth_poll_stats .text.eth_send_stats) - *nxp_mcxe31b_emac.o(.text.nxp_mcxe31b_emac_irq_handler) + *nxp_mcxe_emac.o(.text.eth_poll .text.eth_send) + *nxp_mcxe_emac.o(.text.eth_poll_stats .text.eth_send_stats) + *nxp_mcxe_emac.o(.text.nxp_mcxe_emac_irq_handler) . = ALIGN(8); _end_ramcode_itcm = .; } > ITCM diff --git a/test-app/Makefile b/test-app/Makefile index 1f8bf03bd9..1a6353c9aa 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1813,19 +1813,19 @@ ifeq ($(ENABLE_WOLFIP),1) CFLAGS+=-DNXP_MCXE_ENET_STATS=1 endif else ifeq ($(TARGET),mcxe31b) - WOLFIP_PORT:=nxp_mcxe31b_emac - WOLFIP_PORT_OBJ:=nxp_mcxe31b_emac.o + WOLFIP_PORT:=nxp_mcxe_emac + WOLFIP_PORT_OBJ:=nxp_mcxe_emac.o # wolfIP state in SRAM, EMAC rings in the DTCM (ARM-mcxe31b-wolfip.ld) LSCRIPT_TEMPLATE=ARM-mcxe31b-wolfip.ld # Clear all of SRAM at reset, before it is read (ECC) CFLAGS+=-DAPP_RAM_ECC_INIT # Hot code in the ITCM (.ramcode_itcm in ARM-mcxe31b-wolfip.ld) CFLAGS+=-DAPP_RAMCODE_ITCM - # NXP_MCXE31B_EMAC_IRQ=0 polls the EMAC instead of using its interrupt - NXP_MCXE31B_EMAC_IRQ?=1 - CFLAGS+=-DWOLFIP_PORT_MCXE31B_EMAC - CFLAGS+=-DNXP_MCXE31B_EMAC_IRQ=$(NXP_MCXE31B_EMAC_IRQ) - CFLAGS+=-DTFTP_RAM_MAX=0x20000U + # NXP_MCXE_EMAC_IRQ=0 polls the EMAC instead of using its interrupt + NXP_MCXE_EMAC_IRQ?=1 + CFLAGS+=-DWOLFIP_PORT_MCXE_EMAC + CFLAGS+=-DNXP_MCXE_EMAC_IRQ=$(NXP_MCXE_EMAC_IRQ) + CFLAGS+=-DTFTP_RAM_MAX=0xA000U # Six full segments of TCP buffering per socket. CFLAGS+=-DRXBUF_SIZE=9216 -DTXBUF_SIZE=9216 # remove -ffreestanding so small memcpy's can be inlined @@ -1834,7 +1834,7 @@ ifeq ($(ENABLE_WOLFIP),1) WOLFIP_CFLAGS_ADD:=-O2 -DWOLFIP_POLL_BUDGET=16 # Driver cycle counters for the throughput test's CPU breakdown ifeq ($(WOLFIP_SPEED_TEST),1) - CFLAGS+=-DNXP_MCXE31B_EMAC_STATS=1 + CFLAGS+=-DNXP_MCXE_EMAC_STATS=1 endif else WOLFIP_PORT:=nxp_fman diff --git a/test-app/startup_arm.c b/test-app/startup_arm.c index 698d2669e7..9762d44748 100644 --- a/test-app/startup_arm.c +++ b/test-app/startup_arm.c @@ -82,9 +82,9 @@ extern void nxp_mcxe_enet_irq_handler(void); #ifdef TARGET_mcxe31b extern void isr_debug_uart(void); /* MCXE31B EMAC common interrupt (IRQ 105) */ -#if defined(NXP_MCXE31B_EMAC_IRQ) && (NXP_MCXE31B_EMAC_IRQ == 1) -extern void nxp_mcxe31b_emac_irq_handler(void); -#define isr_emac nxp_mcxe31b_emac_irq_handler +#if defined(NXP_MCXE_EMAC_IRQ) && (NXP_MCXE_EMAC_IRQ == 1) +extern void nxp_mcxe_emac_irq_handler(void); +#define isr_emac nxp_mcxe_emac_irq_handler #else #define isr_emac isr_empty #endif diff --git a/test-app/wolfip_tftp_test.c b/test-app/wolfip_tftp_test.c index 6c3948d425..8656eded72 100644 --- a/test-app/wolfip_tftp_test.c +++ b/test-app/wolfip_tftp_test.c @@ -42,7 +42,7 @@ /* Port selection: * WOLFIP_PORT_ENETC -> LS1028A ENETC * WOLFIP_PORT_MCXE_ENET -> MCXE247 ENET - * WOLFIP_PORT_MCXE31B_EMAC -> MCXE31B EMAC + * WOLFIP_PORT_MCXE_EMAC -> MCX E EMAC (MCXE31B) * else QorIQ FMan * Driver entry points are wrapped so the bring-up code below is port-agnostic. */ #if defined(WOLFIP_PORT_ENETC) @@ -65,17 +65,17 @@ #define WOLFIP_NETDEV_STATS_GET nxp_mcxe_enet_stats_get #define WOLFIP_NETDEV_STATS_RESET nxp_mcxe_enet_stats_reset #endif -#elif defined(WOLFIP_PORT_MCXE31B_EMAC) -#include "nxp_mcxe31b_emac.h" -#define WOLFIP_NETDEV_INIT nxp_mcxe31b_emac_init -#define WOLFIP_NETDEV_PHY_ADDR nxp_mcxe31b_emac_phy_addr -#define WOLFIP_NETDEV_PHY_READ nxp_mcxe31b_emac_phy_read -#define WOLFIP_NETDEV_LINK_UP nxp_mcxe31b_emac_link_up +#elif defined(WOLFIP_PORT_MCXE_EMAC) +#include "nxp_mcxe_emac.h" +#define WOLFIP_NETDEV_INIT nxp_mcxe_emac_init +#define WOLFIP_NETDEV_PHY_ADDR nxp_mcxe_emac_phy_addr +#define WOLFIP_NETDEV_PHY_READ nxp_mcxe_emac_phy_read +#define WOLFIP_NETDEV_LINK_UP nxp_mcxe_emac_link_up #define WOLFIP_NETDEV_NAME "MCXE31B EMAC" -#if NXP_MCXE31B_EMAC_STATS -#define WOLFIP_NETDEV_STATS struct nxp_mcxe31b_emac_stats -#define WOLFIP_NETDEV_STATS_GET nxp_mcxe31b_emac_stats_get -#define WOLFIP_NETDEV_STATS_RESET nxp_mcxe31b_emac_stats_reset +#if NXP_MCXE_EMAC_STATS +#define WOLFIP_NETDEV_STATS struct nxp_mcxe_emac_stats +#define WOLFIP_NETDEV_STATS_GET nxp_mcxe_emac_stats_get +#define WOLFIP_NETDEV_STATS_RESET nxp_mcxe_emac_stats_reset #endif #else #include "nxp_fman.h" diff --git a/test-app/wolfip_tftp_test.h b/test-app/wolfip_tftp_test.h index ab23844035..0bbcd0e1a9 100644 --- a/test-app/wolfip_tftp_test.h +++ b/test-app/wolfip_tftp_test.h @@ -36,7 +36,7 @@ void wolfip_tftp_test_report(void); /* Cortex-M ports without a free-running timer of their own take the time * and the stop request from the target app */ -#if defined(WOLFIP_PORT_MCXE_ENET) || defined(WOLFIP_PORT_MCXE31B_EMAC) +#if defined(WOLFIP_PORT_MCXE_ENET) || defined(WOLFIP_PORT_MCXE_EMAC) #define WOLFIP_TEST_APP_TIMEBASE #endif diff --git a/tools/scripts/mcxe31b/e31b_debug.cmm b/tools/scripts/mcxe31b/e31b_debug.cmm index 67df602835..32502b2510 100644 --- a/tools/scripts/mcxe31b/e31b_debug.cmm +++ b/tools/scripts/mcxe31b/e31b_debug.cmm @@ -98,7 +98,7 @@ sYmbol.SourcePATH.SetBaseDir "&basedir" &srcdirs="&srcdirs ""&basedir\lib\wolfssl\wolfcrypt\src""" ; wolfIP and its MCXE31B port (test-app built with ENABLE_WOLFIP=1) &srcdirs="&srcdirs ""&basedir\lib\wolfip\src"" ""&basedir\lib\wolfip\src\tftp""" -&srcdirs="&srcdirs ""&basedir\lib\wolfip\src\port\nxp_mcxe31b_emac""" +&srcdirs="&srcdirs ""&basedir\lib\wolfip\src\port\nxp_mcxe_emac""" sYmbol.SourcePATH.Set &srcdirs ENDDO From e2edfa77f7a1627bd11cb07b1722e8bec25ea841 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Wed, 25 Nov 2026 14:53:57 -0500 Subject: [PATCH 22/24] address copilot/fenrir issues --- test-app/app_mcxe31b.c | 68 +++++++++++++++++++++++++++++++++--------- 1 file changed, 54 insertions(+), 14 deletions(-) diff --git a/test-app/app_mcxe31b.c b/test-app/app_mcxe31b.c index c42903e6da..d2fe5f249b 100644 --- a/test-app/app_mcxe31b.c +++ b/test-app/app_mcxe31b.c @@ -102,10 +102,21 @@ static void delay_ms(uint32_t ms) } } +/* CORE_CLK as it is configured: hal_init() stays on FIRC when the PLL setup + * fails */ +static uint32_t core_clock_hz(void) +{ + uint32_t src = FIRC_FREQ; + + if (MC_CGM_CSS_SELSTAT(MC_CGM_MUX0_CSS) == MC_CGM_SEL_PLL_PHI0) + src = PLL_PHI0_FREQ; + return src / (MC_CGM_DC_GET_DIV(MC_CGM_MUX0_DC(MC_CGM_DIV_CORE_CLK)) + 1U); +} + static void systick_init(void) { /* Configure SysTick for 1ms tick */ - SYST_RVR = (CLOCK_SPEED / 1000) - 1; + SYST_RVR = (core_clock_hz() / 1000U) - 1U; SYST_CVR = 0; SYST_CSR = SYST_CSR_ENABLE | SYST_CSR_TICKINT | SYST_CSR_CLKSOURCE; } @@ -439,6 +450,9 @@ static void print_keystore_info(void) #define XMODEM_PAYLOAD_SIZE 128 #define XMODEM_PACKET_SIZE_CRC (3 + XMODEM_PAYLOAD_SIZE + 2) /* SOH + blk + ~blk + data + CRC16 */ #define XMODEM_TIMEOUT_MS 1000 +/* Space in the update partition below its trailer sectors */ +#define XMODEM_MAX_SIZE (WOLFBOOT_PARTITION_SIZE - \ + (WOLFBOOT_TRAILER_SECTORS * WOLFBOOT_SECTOR_SIZE)) /* CRC-16-CCITT for XMODEM-CRC mode */ static uint16_t APP_RAMFUNCTION crc16_ccitt(const uint8_t* data, int len) @@ -501,10 +515,12 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) uint8_t payload[XMODEM_PAYLOAD_SIZE]; uint8_t pkt_num = 0, pkt_num_expected = 0xFF; uint32_t t_size = 0; + uint32_t img_size; uint32_t now; uint32_t i = 0; int transfer_started = 0; int eot_expected = 0; + int dup; int ret = -1; state->dst_offset = 0; @@ -547,10 +563,6 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) led_red_on(); /* Indicate transfer complete */ ret = 0; break; - } else if (eot_expected) { - uart_tx(XNAK); - ret = -1; - break; } /* Validate SOH */ @@ -565,9 +577,14 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) if ((uint8_t)(~xpkt[2]) == pkt_num) { uint16_t recv_crc, calc_crc; + dup = 0; if (!transfer_started) { pkt_num_expected = pkt_num; transfer_started = 1; + } else if (state->dst_offset > 0U && + pkt_num == (uint8_t)(pkt_num_expected - 1U)) { + /* The last block again: the sender missed its ACK */ + dup = 1; } else if (pkt_num_expected != pkt_num) { uart_tx(XNAK); continue; @@ -585,7 +602,30 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) xpkt[XMODEM_PACKET_SIZE_CRC - 1]; calc_crc = crc16_ccitt(xpkt + 3, XMODEM_PAYLOAD_SIZE); - if (recv_crc == calc_crc) { + if (recv_crc == calc_crc && dup) { + /* Already written: only ACK it again */ + uart_tx(XACK); + } else if (recv_crc == calc_crc) { + /* A block past the end of the image, or one that would reach + * the trailer sectors of the update partition */ + if (eot_expected || + state->dst_offset + XMODEM_PAYLOAD_SIZE > XMODEM_MAX_SIZE) { + xmodem_cancel(); + ret = -1; + break; + } + /* The image size (header offset 4) must fit, checked before + * the first block is ACKed or written */ + if (state->dst_offset == 0U) { + ram_memcpy(&img_size, xpkt + 3 + 4, sizeof(img_size)); + if (img_size > XMODEM_MAX_SIZE - IMAGE_HEADER_SIZE) { + xmodem_cancel(); + ret = -1; + break; + } + t_size = img_size + IMAGE_HEADER_SIZE; + } + /* Copy payload using RAM-based memcpy */ ram_memcpy(payload, xpkt + 3, XMODEM_PAYLOAD_SIZE); @@ -606,12 +646,7 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) pkt_num_expected++; state->dst_offset += XMODEM_PAYLOAD_SIZE; - /* Get expected size from header (offset 4 = image size) */ - if (t_size == 0 && state->dst_offset >= 8) { - t_size = *(uint32_t*)(payload + 4) + IMAGE_HEADER_SIZE; - } - - if (t_size > 0 && state->dst_offset >= t_size) { + if (state->dst_offset >= t_size) { eot_expected = 1; } } else { @@ -664,8 +699,13 @@ static int cmd_update_xmodem(void) } #else (void)erase_addr; - (void)erase_ret; - hal_flash_erase(WOLFBOOT_PARTITION_UPDATE_ADDRESS, WOLFBOOT_PARTITION_SIZE); + erase_ret = hal_flash_erase(WOLFBOOT_PARTITION_UPDATE_ADDRESS, + WOLFBOOT_PARTITION_SIZE); + if (erase_ret != 0) { + printf("Erase FAILED (%d)\r\n", erase_ret); + hal_flash_lock(); + return -1; + } #endif printf("Done.\r\n"); From 795c8cc8735b9fb75c174754e1e2eaa3ffac9084 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Tue, 1 Dec 2026 01:55:30 -0500 Subject: [PATCH 23/24] mcxe31b: opt in to the unaligned memcpy FAST_MEMCPY's unaligned-source word path now also needs FAST_MEMCPY_UNALIGNED (03718e4a). Set it to keep the word copies this port was tuned with; nothing here memcpy's from peripheral registers. --- config/examples/mcxe31b.config | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/config/examples/mcxe31b.config b/config/examples/mcxe31b.config index 8849fb0a32..bc8b6c363f 100644 --- a/config/examples/mcxe31b.config +++ b/config/examples/mcxe31b.config @@ -35,9 +35,11 @@ CFLAGS_EXTRA+=-DWOLFBOOT_RAM_ECC_INIT WOLFBOOT_SECTOR_SIZE?=0x2000 # Word-at-a-time memcpy/memset in src/string.c (bootloader and test-app). The -# Cortex-M7 loads unaligned words, so memcpy copies words even when source and -# destination alignments differ. -CFLAGS_EXTRA+=-DFAST_MEMCPY +# Cortex-M7 loads unaligned words from RAM and flash, so with +# FAST_MEMCPY_UNALIGNED memcpy copies words even when source and destination +# alignments differ. Nothing on this target copies from peripheral registers +# with memcpy. +CFLAGS_EXTRA+=-DFAST_MEMCPY -DFAST_MEMCPY_UNALIGNED # The application's vector table follows the image header and is used in # place (VTOR). The table must be 1 KB aligned, or the core fetches the vectors From 3eafa2567bc8302a09f15e86a8d527819d8c1514 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Tue, 1 Dec 2026 09:36:11 -0500 Subject: [PATCH 24/24] fix xmodem eot issue --- test-app/app_mcxe31b.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test-app/app_mcxe31b.c b/test-app/app_mcxe31b.c index d2fe5f249b..bb489ac985 100644 --- a/test-app/app_mcxe31b.c +++ b/test-app/app_mcxe31b.c @@ -557,8 +557,13 @@ static int APP_RAMFUNCTION xmodem_receive_ram(xmodem_state_t *state) } } - /* Check for EOT */ + /* Check for EOT: refused until the whole image is in flash */ if (xpkt[0] == XEOT) { + if (!eot_expected) { + xmodem_cancel(); + ret = -1; + break; + } uart_tx(XACK); led_red_on(); /* Indicate transfer complete */ ret = 0;