From 33d4c9aa465fe90c40413c5ec1cc39221f0eac50 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Thu, 12 Nov 2026 23:43:50 -0500 Subject: [PATCH 01/12] 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 bd7e9e68e3..86af4d6fec 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7376,19 +7376,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"' ``` @@ -7399,18 +7407,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. @@ -7427,7 +7441,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 05c02f9e43..73c3d4b702 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1741,30 +1741,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 655e160371..2f7a0a277b 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) @@ -553,9 +564,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 e472092737ae154ba2fa3cbbf5eb56c9180cfbda Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 13 Nov 2026 15:01:20 -0500 Subject: [PATCH 02/12] 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 86af4d6fec..a76ff0619a 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7421,11 +7421,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 275e5948b4ed64bb01b8d59016b4b213641dfd21 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Fri, 13 Nov 2026 16:28:18 -0500 Subject: [PATCH 03/12] 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 73c3d4b702..0bae2b0c22 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1754,6 +1754,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 @@ -1787,7 +1791,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 714f8f59f883db336ea3084d5266a4d117f27c42 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Sun, 15 Nov 2026 13:32:14 -0500 Subject: [PATCH 04/12] 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 e5bd12ef34..7573901074 100644 --- a/src/string.c +++ b/src/string.c @@ -297,13 +297,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 a06dfefc73ca66b75e4678b2ec0853f20c3340c9 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Sun, 15 Nov 2026 23:33:42 -0500 Subject: [PATCH 05/12] 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 a76ff0619a..43943fae0f 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7173,7 +7173,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. | @@ -7381,6 +7383,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 fadd94e38d46fe5fac077de26efcf754310254e1 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 16 Nov 2026 00:12:53 -0500 Subject: [PATCH 06/12] 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 0bae2b0c22..a86e132c01 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1758,6 +1758,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 @@ -1793,7 +1799,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 bf7f127f709f16a0eb4626a4fa7a1987e2f9d1f2 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 16 Nov 2026 00:37:09 -0500 Subject: [PATCH 07/12] 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 8365093d5a7efc7ce61671851177897f02c96d10 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 16 Nov 2026 01:15:06 -0500 Subject: [PATCH 08/12] 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 43943fae0f..2e2c36afe6 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7396,30 +7396,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): @@ -7441,8 +7437,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 b5601d5cf052beb89eb7dec650dec5e5bb006905 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 16 Nov 2026 02:24:54 -0500 Subject: [PATCH 09/12] 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 2e2c36afe6..71072bfc9e 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7402,7 +7402,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 a86e132c01..1e9557d2d7 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1746,6 +1746,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 2f7a0a277b..7c99cf4474 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 012b0aeb54c6a9f183d0c069ed80cdca00014190 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 16 Nov 2026 12:54:19 -0500 Subject: [PATCH 10/12] 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 71072bfc9e..8cfb19361f 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7174,6 +7174,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. | @@ -7340,7 +7341,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 @@ -7437,6 +7440,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 6e1d350e013a33a909e4de955cc43001c45a3747 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 16 Nov 2026 13:40:42 -0500 Subject: [PATCH 11/12] 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 8cfb19361f..1939f114a3 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7278,8 +7278,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 7573901074..b76f8792c5 100644 --- a/src/string.c +++ b/src/string.c @@ -302,12 +302,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__) @@ -321,26 +330,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 1e9557d2d7..4a6cd92dda 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1748,23 +1748,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) @@ -1799,7 +1792,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 07f21aee022f2891f47f7b2ab409c292b178cef5 Mon Sep 17 00:00:00 2001 From: Thomas Cook Date: Mon, 16 Nov 2026 22:01:29 -0500 Subject: [PATCH 12/12] 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 1939f114a3..51dae72345 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -7446,7 +7446,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)