From e9ed29cf53d4534aecf895065a2e1c282724cd35 Mon Sep 17 00:00:00 2001 From: night1rider Date: Tue, 17 Nov 2026 15:48:35 -0700 Subject: [PATCH 1/3] Add AMD Versal Gen 2 (VEK385) target TARGET=versal2 runs at EL2 after BL31 as a wolfHAL board (BOARD=vek385). hal/wolfhal.c gains ext_flash_* with a partition guard. Configs and docs. --- .github/workflows/test-configs.yml | 31 ++ Makefile | 6 + arch.mk | 22 +- config/examples/versal2_vek385.config | 156 +++++++++ config/examples/versal2_vek385_linux.config | 146 ++++++++ docs/HAL.md | 7 +- docs/Targets.md | 55 +++ docs/wolfHAL.md | 45 ++- .../stm32wba55cg_nucleo/wolfHAL_board.c | 5 +- hal/boards/vek385/board.mk | 28 ++ hal/boards/vek385/wolfHAL_board.c | 315 ++++++++++++++++++ hal/boards/vek385/wolfHAL_board.h | 82 +++++ hal/versal2.h | 99 ++++++ hal/versal2.ld | 246 ++++++++++++++ hal/wolfhal.c | 204 +++++++++++- lib/wolfHAL | 2 +- src/boot_aarch64.c | 2 + src/boot_aarch64_start.S | 34 +- test-app/Makefile | 14 +- test-app/app_versal2.c | 89 +++++ 20 files changed, 1555 insertions(+), 33 deletions(-) create mode 100644 config/examples/versal2_vek385.config create mode 100644 config/examples/versal2_vek385_linux.config create mode 100644 hal/boards/vek385/board.mk create mode 100644 hal/boards/vek385/wolfHAL_board.c create mode 100644 hal/boards/vek385/wolfHAL_board.h create mode 100644 hal/versal2.h create mode 100644 hal/versal2.ld create mode 100644 test-app/app_versal2.c diff --git a/.github/workflows/test-configs.yml b/.github/workflows/test-configs.yml index 9ac4ee60f2..e30e1df2d7 100644 --- a/.github/workflows/test-configs.yml +++ b/.github/workflows/test-configs.yml @@ -1643,6 +1643,37 @@ jobs: arch: aarch64 config-file: ./config/examples/versal_vmk180.config + # Versal Gen 2 (VEK385): OSPI NOR A/B boot (TARGET=versal2) + versal2_vek385_test: + uses: ./.github/workflows/test-build.yml + with: + arch: aarch64 + config-file: ./config/examples/versal2_vek385.config + make-args: CROSS_COMPILE=aarch64-linux-gnu- + + versal2_vek385_linux_test: + uses: ./.github/workflows/test-build.yml + with: + arch: aarch64 + config-file: ./config/examples/versal2_vek385_linux.config + make-args: CROSS_COMPILE=aarch64-linux-gnu- + + # STIG flash reads only (no OSPI DMA) + versal2_vek385_stig_test: + uses: ./.github/workflows/test-build.yml + with: + arch: aarch64 + config-file: ./config/examples/versal2_vek385.config + make-args: CROSS_COMPILE=aarch64-linux-gnu- WOLFBOOT_OSPI_DMA=0 + + # Test app entered at EL1 (el2_to_el1_boot) + versal2_vek385_el1_test: + uses: ./.github/workflows/test-build.yml + with: + arch: aarch64 + config-file: ./config/examples/versal2_vek385.config + make-args: CROSS_COMPILE=aarch64-linux-gnu- BOOT_EL1=1 + versal_vmk180_highddr_test: uses: ./.github/workflows/test-build-aarch64.yml with: diff --git a/Makefile b/Makefile index d0a57b07f2..84dd65afbc 100644 --- a/Makefile +++ b/Makefile @@ -493,6 +493,12 @@ ifeq ($(TARGET),tegra234) MAIN_TARGET:=wolfboot.bin test-app/image_v1_signed.bin endif +# Versal Gen 2 runs from RAM (BL33 at 0x40000000, loaded by the PLM), so +# there is no flat flash image to assemble into a factory.bin. +ifeq ($(TARGET),versal2) + MAIN_TARGET:=wolfboot.bin test-app/image_v1_signed.bin +endif + # i.MX95 A55 is a RAM-resident BL33 loaded by SPL inside an AHAB container, so # there is no contiguous flash image to assemble into a factory.bin. ifeq ($(TARGET),imx95_a55) diff --git a/arch.mk b/arch.mk index 2c0ca84b98..23c879e966 100644 --- a/arch.mk +++ b/arch.mk @@ -249,6 +249,26 @@ ifeq ($(ARCH),AARCH64) SPI_TARGET=nxp endif + ifeq ($(TARGET),versal2) + # AMD Versal AI Edge / Prime Gen 2 (VEK385) - Cortex-A78AE + # A/B boot over OSPI (Cadence) flash. The board (devices, drivers) is a + # wolfHAL board: WOLFHAL=1 BOARD=vek385, see hal/boards/vek385. + ARCH_FLAGS=-mcpu=cortex-a78+crypto -march=armv8.2-a+crypto + CFLAGS+=$(ARCH_FLAGS) -DCORTEX_A78 + CFLAGS+=-DWOLFBOOT_DUALBOOT + ifneq ($(WOLFHAL),1) + $(error TARGET=versal2 needs WOLFHAL=1 and BOARD, e.g. BOARD=vek385) + endif + # Support detection and skip of U-Boot legacy header + CFLAGS+=-DWOLFBOOT_UBOOT_LEGACY + # The PLM owns RVBAR on Versal Gen 2, so don't write it + CFLAGS+=-DSKIP_RVBAR=1 + # aarch64-linux-gnu-gcc builds PIE by default. wolfBoot must be a + # static image at a fixed address (WOLFBOOT_ORIGIN). + CFLAGS+=-fno-pic -fno-pie + LDFLAGS+=-static -no-pie -Wl,--build-id=none + endif + ifeq ($(TARGET),tegra234) # NVIDIA Jetson Orin (Tegra234, Cortex-A78AE): bare-metal wolfBoot as the # BL33 firmware stage. The UEFI-application alternative is the aarch64_efi @@ -447,7 +467,7 @@ ifeq ($(ARCH),AARCH64) # asm (sp_arm64.c / WOLFSSL_SP_ARM64_ASM); that is enabled independently on # __aarch64__ in include/user_settings.h, so a non-FIPS cm4 build still links # sp_arm64 asm. - ifeq ($(filter zynq versal agilex5 nxp_ls1028a imx95_a55,$(TARGET)),) + ifeq ($(filter zynq versal versal2 agilex5 nxp_ls1028a imx95_a55,$(TARGET)),) NO_ARM_ASM?=1 endif diff --git a/config/examples/versal2_vek385.config b/config/examples/versal2_vek385.config new file mode 100644 index 0000000000..68cf6933da --- /dev/null +++ b/config/examples/versal2_vek385.config @@ -0,0 +1,156 @@ +# wolfBoot configuration for AMD Versal AI Edge / Prime Gen 2 (VEK385) +# Cortex-A78AE, A/B boot over OSPI (Cadence) flash. +# +# This configuration is tested in QEMU `amd-versal2-virt` (QEMU 11.1.3) +# and on a VEK385 Rev B; see the "Versal Gen 2 VEK385" section of +# docs/Targets.md. The addresses below follow AMD's OSPI layout and the +# reserved-memory map of the VEK385 DTB. +# +# Production boot flow: +# PLM -> BL31 (EL3, secure) -> wolfBoot (EL2, non-secure) -> Linux +# PLM owns 0-16 MB of DDR and TF-A 16-24 MB (BL31 runs at 0x1600000). +# wolfBoot enters at 0x40000000 (AMD default BL33 entry, per the VEK385 +# Rev B log "BL31: Non secure code at 0x40000000"). + +ARCH?=AARCH64 +TARGET?=versal2 +# Board on the wolfHAL drivers: hal/boards/vek385 (see docs/wolfHAL.md). +BOARD?=vek385 +WOLFHAL?=1 + +WOLFBOOT_VERSION?=1 + +# ECC-384 signatures with SHA-384 hashes +SIGN?=ECC384 +HASH?=SHA384 +IMAGE_HEADER_SIZE?=512 + +# Debug options +DEBUG?=1 +DEBUG_SYMBOLS=1 +DEBUG_UART=1 + +# Optional: time the boot steps (flash read, hash, signature check). +BOOT_BENCHMARK?=1 + +VTOR?=1 +CORTEX_M0?=0 +NO_ASM?=0 +ALLOW_DOWNGRADE?=0 +NVM_FLASH_WRITEONCE?=0 +V?=0 +SPMATH?=1 +RAM_CODE?=0 +DUALBANK_SWAP?=0 +PKA?=0 +WOLFTPM?=0 + +# A/B boot from the OSPI NOR flash (Micron MT35XU02GCBA, 256 MB). +# See hal/boards/vek385. +EXT_FLASH?=1 +NO_XIP=1 + +# How flash is read: 1 = CSU DMA (default, AM026 p706), 0 = STIG. +# The QEMU tests run both. +WOLFBOOT_OSPI_DMA?=1 +# The code checks `#ifdef WOLFBOOT_OSPI_DMA`, so only add the -D for DMA. +# A -DWOLFBOOT_OSPI_DMA=0 would still turn DMA on. +ifeq ($(WOLFBOOT_OSPI_DMA),1) +CFLAGS_EXTRA+=-DWOLFBOOT_OSPI_DMA=1 +endif + +# Which level the app starts at (pick one). Default: EL2, where wolfBoot +# runs. BOOT_EL1 drops only this core to EL1; BL31 starts the others at +# EL2, and Linux does not accept that mix. +#BOOT_EL1=1 +#BOOT_EL2=1 + +# ELF loading support +ELF?=1 + +# Unzip gzip FIT parts (set GZIP=0 to turn off) +GZIP?=1 + +# Load the FIT ramdisk (initramfs) and tell Linux where it is. +# A PetaLinux image.ub has one; without this it is ignored. +FIT_RAMDISK?=1 + +# Kernel load address, used instead of the FIT's own. Needed if the FIT +# has no load/entry. 0 = use the FIT's value. +#WOLFBOOT_LOAD_KERNEL_ADDRESS?=0x2001000 + +# Same for the ramdisk: 0 = use the ramdisk's own load address. +#WOLFBOOT_LOAD_RAMDISK_ADDRESS?=0x40000000 + +# Toolchain (the CI container provides aarch64-linux-gnu-) +USE_GCC=1 +CROSS_COMPILE=aarch64-linux-gnu- + +# ============================================================================ +# Boot Memory Layout +# ============================================================================ +# wolfBoot runs from DDR at 0x40000000. Load addresses stay clear of the +# reserved memory of the board DTB below them (it ends at 0x1FFFEFFF). +WOLFBOOT_ORIGIN=0x40000000 + +# Application (Linux kernel / FIT) load address: 512 MB. +WOLFBOOT_LOAD_ADDRESS?=0x20000000 + +# DTS load address in RAM: 24 MB, above PLM (0-16 MB) and TF-A (16-24 MB). +WOLFBOOT_LOAD_DTS_ADDRESS=0x1800000 + +# DTS slots in flash, after the UPDATE partition, 8 MB apart. +# Only used when the image has no built-in fdt. +WOLFBOOT_DTS_BOOT_ADDRESS=0x7600000 +WOLFBOOT_DTS_UPDATE_ADDRESS=0x7E00000 + +# ============================================================================ +# OSPI Flash Partitions +# ============================================================================ +# AMD OSPI layout (VEK385 DTB, /axi/spi@f1010000/flash@0/partitions): +# 0x0000000 Image Selector (384 KB) - DO NOT TOUCH +# 0x0060000 Image Selector Backup (384 KB) - DO NOT TOUCH +# 0x00C0000 Image Selector Scratchpad (128 KB) - DO NOT TOUCH +# 0x00E0000 Image Recovery (20 MB) - DO NOT TOUCH +# 0x14E0000 Image Recovery Scratchpad (128 KB) - DO NOT TOUCH +# 0x1500000 SystemReady-DT metadata (128 KB) - DO NOT TOUCH +# 0x1520000 SystemReady-DT metadata Backup - DO NOT TOUCH +# 0x1540000 U-Boot Variables (128 KB) - DO NOT TOUCH +# 0x1560000 U-Boot Variables Backup (128 KB) - DO NOT TOUCH +# 0x1580000 U-Boot UEFI Variables (256 KB) - DO NOT TOUCH +# 0x15C0000 Bank A Space (114 MB, ends 0x87C0000) <- wolfBoot partitions +# 0x8800000 Bank B Space (114 MB) - DO NOT TOUCH +# 0xFA40000 User Scratchpad (5.75 MB) <- wolfBoot SWAP +# +# Bank A: 0x015C0000 BOOT.BIN (8 MB kept), 0x01DC0000 BOOT (44 MB), +# 0x049C0000 UPDATE (44 MB), 0x07600000 / 0x07E00000 DTS slots. +# The driver refuses erase/program outside BOOT, UPDATE and SWAP. + +# One wolfBoot sector = one 128 KB flash sector (DCh), as on Gen 1. +# The flash has no 64 KB erase (datasheet Table 21/32, p32/p50). +WOLFBOOT_SECTOR_SIZE=0x20000 + +# Partition size: 44 MB, same as Gen 1 (fits the signed FIT) +WOLFBOOT_PARTITION_SIZE=0x2C00000 + +# BOOT partition, right after the 8 MB BOOT.BIN area +WOLFBOOT_PARTITION_BOOT_ADDRESS=0x1DC0000 + +# UPDATE partition +WOLFBOOT_PARTITION_UPDATE_ADDRESS=0x49C0000 + +# SWAP partition (one sector), in AMD's "User Scratchpad" area +WOLFBOOT_PARTITION_SWAP_ADDRESS=0xFA40000 + +# Faster reads with bigger blocks +CFLAGS_EXTRA+=-DWOLFBOOT_SHA_BLOCK_SIZE=4096 + +# Console: UART1 (0xF1930000). DEBUG_UART_NUM=0 picks UART0 (0xF1920000). +CFLAGS_EXTRA+=-DDEBUG_UART_NUM=1 + +# UART clock (UART_CLK_REF): 99999001 Hz, as the PLM sets it on the VEK385 +# (hal/boards/vek385/wolfHAL_board.h). For a board with another clock: +#CFLAGS_EXTRA+=-DUART_CLK_REF=100000000 + +# In QEMU, a small trampoline loads wolfBoot at WOLFBOOT_ORIGIN and acts +# like BL31. diff --git a/config/examples/versal2_vek385_linux.config b/config/examples/versal2_vek385_linux.config new file mode 100644 index 0000000000..22f42235b1 --- /dev/null +++ b/config/examples/versal2_vek385_linux.config @@ -0,0 +1,146 @@ +# wolfBoot configuration for AMD Versal AI Edge / Prime Gen 2 (VEK385), +# Linux boot. +# +# This is the Linux-payload variant of versal2_vek385.config. The flash +# layout, addresses, signing, OSPI driver and partition geometry are +# IDENTICAL to versal2_vek385.config (same addresses must later work on +# the board); only the payload handling differs: +# +# - the signed image in the BOOT/UPDATE partitions is a FIT +# (kernel + DTB + initramfs), built with mkimage and signed by +# tools/keytools/sign (GZIP=1: the kernel sub-image is Image.gz); +# - WOLFBOOT_LOAD_RAMDISK_ADDRESS is set so the initramfs is staged in +# a fixed, reserved-memory-safe DDR region (768 MB); +# - the kernel/DTB load addresses come from the FIT itself (the ITS +# sets load/entry), so WOLFBOOT_LOAD_KERNEL_ADDRESS stays 0 +# ("honor the FIT"). +# +# The bare-metal test-app config is versal2_vek385.config; this file is a +# separate example. See the "Versal Gen 2 VEK385" section of +# docs/Targets.md. + +ARCH?=AARCH64 +TARGET?=versal2 +# Board on the wolfHAL drivers: hal/boards/vek385 (see docs/wolfHAL.md). +BOARD?=vek385 +WOLFHAL?=1 + +WOLFBOOT_VERSION?=1 + +# ECC-384 signatures with SHA-384 hashes +SIGN?=ECC384 +HASH?=SHA384 +IMAGE_HEADER_SIZE?=512 + +# Debug options +DEBUG?=1 +DEBUG_SYMBOLS=1 +DEBUG_UART=1 + +# Optional: time the boot steps (flash read, hash, signature check). +BOOT_BENCHMARK?=1 + +VTOR?=1 +CORTEX_M0?=0 +NO_ASM?=0 +ALLOW_DOWNGRADE?=0 +NVM_FLASH_WRITEONCE?=0 +V?=0 +SPMATH?=1 +RAM_CODE?=0 +DUALBANK_SWAP?=0 +PKA?=0 +WOLFTPM?=0 + +# A/B boot from the OSPI NOR flash (Micron MT35XU02GCBA, 256 MB). +# See hal/boards/vek385. +EXT_FLASH?=1 +NO_XIP=1 + +# How flash is read: 1 = CSU DMA (default, AM026 p706), 0 = STIG. +WOLFBOOT_OSPI_DMA?=1 +# Only add the -D for DMA (see versal2_vek385.config). +ifeq ($(WOLFBOOT_OSPI_DMA),1) +CFLAGS_EXTRA+=-DWOLFBOOT_OSPI_DMA=1 +endif + +# Linux starts at EL2 with the MMU off (do_boot() in src/boot_aarch64.c); +# BL31 or the QEMU trampoline sets SCR_EL3.HCE for it. Do not use BOOT_EL1 +# on the board: BL31 starts the other cores at EL2 and Linux then stops. +BOOT_EL2=1 + +# ELF loading support +ELF?=1 + +# Unzip gzip FIT parts: the kernel (Image.gz) and the initramfs. This +# keeps the signed FIT inside the 44 MB partition. +GZIP?=1 + +# Load the FIT ramdisk (initramfs) and tell Linux where it is. +# The initramfs is the only root file system, so no root= is needed. +FIT_RAMDISK?=1 +FIT_RAMDISK_REQUIRED?=1 + +# 0 = use the FIT's kernel load address (0x24000000, 576 MB). It is clear +# of the RPU reserved memory and the FIT copy at 0x20000000. +WOLFBOOT_LOAD_KERNEL_ADDRESS?=0 + +# Ramdisk load address: 768 MB, clear of the kernel and the FIT copy. +WOLFBOOT_LOAD_RAMDISK_ADDRESS=0x30000000 + +# Toolchain (the CI container provides aarch64-linux-gnu-) +USE_GCC=1 +CROSS_COMPILE=aarch64-linux-gnu- + +# ============================================================================ +# Boot Memory Layout +# ============================================================================ +# Same as versal2_vek385.config: PLM 0-16 MB, TF-A 16-24 MB, the reserved +# memory below 512 MB ends at 0x1FFFEFFF; wolfBoot runs from DDR at +# 0x40000000. +WOLFBOOT_ORIGIN=0x40000000 + +# Where the whole signed FIT is copied: 512 MB, above the RPU memory. +WOLFBOOT_LOAD_ADDRESS?=0x20000000 + +# DTS load address in RAM: 24 MB, above PLM (0-16 MB) and TF-A (16-24 MB). +WOLFBOOT_LOAD_DTS_ADDRESS=0x1800000 + +# DTS slots in flash, after the UPDATE partition, 8 MB apart. Not used +# here, because the Linux FIT has its own DTB. +WOLFBOOT_DTS_BOOT_ADDRESS=0x7600000 +WOLFBOOT_DTS_UPDATE_ADDRESS=0x7E00000 + +# ============================================================================ +# OSPI Flash Partitions (identical to versal2_vek385.config) +# ============================================================================ +# Bank A: 0x015C0000 BOOT.BIN (8 MB kept), 0x01DC0000 BOOT (44 MB), +# 0x049C0000 UPDATE (44 MB), 0x07600000 / 0x07E00000 DTS slots. +# The driver refuses erase/program outside BOOT, UPDATE and SWAP. + +# One wolfBoot sector = one 128 KB flash sector (DCh), as on Gen 1. +WOLFBOOT_SECTOR_SIZE=0x20000 + +# Partition size: 44 MB. The signed FIT must fit. +WOLFBOOT_PARTITION_SIZE=0x2C00000 + +# BOOT partition, right after the 8 MB BOOT.BIN area +WOLFBOOT_PARTITION_BOOT_ADDRESS=0x1DC0000 + +# UPDATE partition +WOLFBOOT_PARTITION_UPDATE_ADDRESS=0x49C0000 + +# SWAP partition (one sector), in AMD's "User Scratchpad" area +WOLFBOOT_PARTITION_SWAP_ADDRESS=0xFA40000 + +# Faster reads with bigger blocks +CFLAGS_EXTRA+=-DWOLFBOOT_SHA_BLOCK_SIZE=4096 + +# Console: UART1 (0xF1930000), for both wolfBoot and Linux. +CFLAGS_EXTRA+=-DDEBUG_UART_NUM=1 + +# UART clock (UART_CLK_REF): see versal2_vek385.config. +#CFLAGS_EXTRA+=-DUART_CLK_REF=100000000 + +# In QEMU, the same trampoline as the test-app loads wolfBoot and acts +# like BL31. diff --git a/docs/HAL.md b/docs/HAL.md index 20170c840b..21ea7c7383 100644 --- a/docs/HAL.md +++ b/docs/HAL.md @@ -39,7 +39,10 @@ If the IAP interface of the flash memory of the target requires it, this functio is called before every write and erase operations to unlock write access to the flash. On some targets, this function may be empty. -`int hal_flash_write(uint32_t address, const uint8_t *data, int len)` +`int hal_flash_write(haladdr_t address, const uint8_t *data, int len)` + +`haladdr_t` is `uint32_t`, or `uintptr_t` on 64-bit targets +(`include/hal.h`). This function provides an implementation of the flash write function, using the target's IAP interface. `address` is the offset from the beginning of the @@ -57,7 +60,7 @@ If the IAP interface of the flash memory requires locking/unlocking, this functi restores the flash write protection by excluding write accesses. This function is called by the bootloader at the end of every write and erase operations. -`int hal_flash_erase(uint32_t address, int len)` +`int hal_flash_erase(haladdr_t address, int len)` Called by the bootloader to erase part of the flash memory to allow subsequent boots. Erase operations must be performed via the specific IAP interface of the target microcontroller. diff --git a/docs/Targets.md b/docs/Targets.md index e1338c0abe..c2af49e51f 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -82,6 +82,7 @@ This README describes configuration of supported targets. * [Xilinx Zynq UltraScale](#xilinx-zynq-ultrascale) * [Xilinx Zynq-7000 (ZC702)](#xilinx-zynq-7000-zc702) * [Versal Gen 1 VMK180](#versal-gen-1-vmk180) +* [Versal Gen 2 VEK385](#versal-gen-2-vek385) ## STM32F4 @@ -5011,6 +5012,60 @@ sudo fdisk -l /dev/sdX | SD1 | 1 1 1 0 | off, off, off, on | +## Versal Gen 2 VEK385 + +AMD Versal AI Edge / Prime Gen 2 (VEK385) evaluation kit, Cortex-A78AE. +`TARGET=versal2` is a wolfHAL board (`WOLFHAL=1 BOARD=vek385`, see +[wolfHAL Integration](wolfHAL.md)): the UART and OSPI flash drivers come +from `lib/wolfHAL`. Tested on a VEK385 Rev B with Vitis 2026.1. + +wolfBoot replaces U-Boot in the Versal boot flow and runs from DDR at +`0x40000000`: + +``` +PLM -> BL31 (EL3) -> wolfBoot (EL2) -> application or Linux (EL2) +``` + +It verifies the signed images in the OSPI flash and boots the one with the +higher version, from BOOT or UPDATE, in place (A/B). The application starts +at EL2; build with `BOOT_EL1=1` to start it at EL1. Linux on the board must +stay at EL2. + +### Flash layout + +Micron MT35XU02G, 256 MB, on the OSPI interface: + +| Partition | Size | Address | Description | +|-----------|--------|---------|-------------| +| BOOT.BIN | 8 MB | 0x15C0000 | boot image slot at the start of Bank A | +| BOOT | 44 MB | 0x1DC0000 | Boot partition | +| UPDATE | 44 MB | 0x49C0000 | Update partition | +| DTS boot | 1 MB | 0x7600000 | standalone DTB slot | +| DTS update| 1 MB | 0x7E00000 | standalone DTB slot | +| SWAP | 128 KB | 0xFA40000 | reserved; not used in this boot mode | + +wolfBoot only programs and erases inside BOOT, UPDATE and SWAP +(`hal/wolfhal.c`). It never writes the rest of the flash. + +### Build + +```sh +git submodule update --init +cp config/examples/versal2_vek385.config .config +make clean TARGET=versal2 +make TARGET=versal2 +``` + +This makes `wolfboot.elf` and the signed test app +`test-app/image_v1_signed.bin`. Use +`config/examples/versal2_vek385_linux.config` to boot Linux. + +### Not yet supported + +- XIP, the indirect OSPI write path and the system watchdog. +- wolfHAL timeouts: the board is built with `WHAL_CFG_NO_TIMEOUT`, so a + flash or UART that never answers makes wolfBoot hang. + ## Infineon PSoC 6 The PSoC 62 (CY8C624ABZI-S2D44) has a Cortex-M0+ and a Cortex-M4F at 100 MHz, diff --git a/docs/wolfHAL.md b/docs/wolfHAL.md index 1c26a92316..4a2dadc2d0 100644 --- a/docs/wolfHAL.md +++ b/docs/wolfHAL.md @@ -16,7 +16,7 @@ requires no changes to the core build system or HAL shim. The integration uses wolfHAL's **direct API mapping** feature. Each platform driver source provides an optional `#ifdef` block that renames its driver functions to the top-level API names. When the corresponding -`WHAL_CFG__API_MAPPING_` flag is defined, the driver file +`WHAL_CFG__DIRECT_API_MAPPING` flag is defined, the driver file itself provides the definition of the top-level API — no wrapper, no vtable indirection, no runtime null-check. Calling `whal_Flash_Write(&dev, ...)` links directly to the platform driver's implementation. @@ -35,7 +35,7 @@ The integration consists of four parts: - `wolfHAL_board.c` — device instances (clock, flash, GPIO, UART), configuration structs, and `hal_init`/`hal_prepare_boot` implementations. - `board.mk` — build variables (`ARCH_FLASH_OFFSET`, `LSCRIPT_IN`, the - `WHAL_CFG_*_API_MAPPING_*` flags, wolfHAL driver objects, `RAM_CODE` + `WHAL_CFG_*_DIRECT_API_MAPPING` flags, wolfHAL driver objects, `RAM_CODE` linker rules). 3. **Generic test application** (`test-app/app_wolfhal.c`) — demonstrates using @@ -48,7 +48,7 @@ The integration consists of four parts: ### How It Fits Together ``` -config/examples/_wolfhal_.config +config/examples/.config └─ TARGET= BOARD= WOLFHAL=1 arch.mk @@ -65,10 +65,10 @@ hal/wolfhal.c (generic — calls whal_Flash_Write, whal_Uart_Send, etc.) hal/boards// ├─ wolfHAL_board.h (includes wolfHAL driver headers, pin enums) ├─ wolfHAL_board.c (device instances, hal_init, hal_prepare_boot) - └─ board.mk (WHAL_CFG_*_API_MAPPING_*, driver objects, RAM_CODE rules) + └─ board.mk (API mapping flags, driver objects, RAM_CODE rules) ``` -The `WHAL_CFG_*_API_MAPPING_*` flags cause each wolfHAL driver source to emit +The `WHAL_CFG_*_DIRECT_API_MAPPING` flags make each wolfHAL driver source emit its functions under the top-level API name. Since only one driver source per device type is compiled, there is no conflict — and since no dispatch source (e.g., `src/flash/flash.c`) is included, there is no vtable indirection. The @@ -89,7 +89,8 @@ WOLFHAL=1 (`hal/wolfhal.c`) and includes the per-board build pieces. - `BOARD` selects the board directory under `hal/boards/`. -See `config/examples/*_wolfhal_*.config` for complete examples. +See `config/examples/stm32wba.config` and +`config/examples/versal2_vek385.config` for complete examples. ## Adding a New Board @@ -188,10 +189,9 @@ ARCH_FLASH_OFFSET=0x08000000 LSCRIPT_IN=hal/.ld # Bind wolfHAL driver sources directly to the top-level API symbols. -CFLAGS+=-DWHAL_CFG_CLOCK_API_MAPPING_ -CFLAGS+=-DWHAL_CFG_FLASH_API_MAPPING_ -CFLAGS+=-DWHAL_CFG_GPIO_API_MAPPING_ -CFLAGS+=-DWHAL_CFG_UART_API_MAPPING_ +CFLAGS+=-DWHAL_CFG__FLASH_DIRECT_API_MAPPING +CFLAGS+=-DWHAL_CFG__GPIO_DIRECT_API_MAPPING +CFLAGS+=-DWHAL_CFG__UART_DIRECT_API_MAPPING WOLFHAL_OBJS+=$(WOLFHAL_ROOT)/src/clock/_rcc.o WOLFHAL_OBJS+=$(WOLFHAL_ROOT)/src/flash/_flash.o @@ -214,7 +214,7 @@ Only one API mapping flag may be active per device type per build. ### 4. Config File -Create `config/examples/_wolfhal_.config`: +Create `config/examples/.config`: ``` TARGET= @@ -233,6 +233,29 @@ NVM_FLASH_WRITEONCE=1 Adjust partition addresses and sector sizes for your board's flash layout. Optionally add `DEBUG_UART=1` to enable UART debug output. +## External Flash and Other Board Options + +`hal/wolfhal.c` reads these optional handles and flags from the board: + +- `BOARD_EXT_FLASH_DEV` (with `EXT_FLASH=1`): a `whal_Flash` device for the + external flash. `hal/wolfhal.c` implements `ext_flash_read`, + `ext_flash_write`, `ext_flash_erase`, `ext_flash_lock` and + `ext_flash_unlock` on it. Program and erase are refused unless they fit + fully inside a BOOT, UPDATE or SWAP partition that is in the external + flash (`PART_BOOT_EXT`, `PART_UPDATE_EXT`, `PART_SWAP_EXT`), so other + data there (for example an earlier boot stage's image) is never changed. + `tools/unit-tests/unit-wolfhal-ext-flash.c` tests this code. +- `BOARD_FLASH_DEV`: leave it undefined on a board with no internal flash. + `hal_flash_write` and `hal_flash_erase` then fail, and all partitions must + be in the external flash. +- `WOLFHAL_UART_CRLF` (in `board.mk`): `uart_write` sends `'\n'` as + `"\r\n"`. + +The AMD VEK385 (`hal/boards/vek385`, `TARGET=versal2`, Cortex-A78AE) uses +all three: its OSPI flash is a wolfHAL NOR flash on a SPI memory controller, +and the target keeps its own test application (`app_versal2.c`) in place of +`app_wolfhal.c`. + ## RAM_CODE When `RAM_CODE=1` is set, wolfBoot's core flash update functions are placed in RAM diff --git a/hal/boards/stm32wba55cg_nucleo/wolfHAL_board.c b/hal/boards/stm32wba55cg_nucleo/wolfHAL_board.c index 9b152cf7f6..15dc688722 100644 --- a/hal/boards/stm32wba55cg_nucleo/wolfHAL_board.c +++ b/hal/boards/stm32wba55cg_nucleo/wolfHAL_board.c @@ -61,8 +61,9 @@ static const whal_Stm32wba_Rcc_PeriphClk g_periphClks[] = { static void set_vos_range1(void) { - whal_Reg_Update(PWR_BASE, PWR_VOSR_REG, PWR_VOSR_VOS_Msk, PWR_VOSR_VOS_Msk); - while (!(whal_Reg_Read(PWR_BASE, PWR_VOSR_REG) & PWR_VOSR_VOSRDY_Msk)) + whal_Reg32_Update(PWR_BASE, PWR_VOSR_REG, PWR_VOSR_VOS_Msk, + PWR_VOSR_VOS_Msk); + while (!(whal_Reg32_Read(PWR_BASE, PWR_VOSR_REG) & PWR_VOSR_VOSRDY_Msk)) ; } diff --git a/hal/boards/vek385/board.mk b/hal/boards/vek385/board.mk new file mode 100644 index 0000000000..0eaf527b55 --- /dev/null +++ b/hal/boards/vek385/board.mk @@ -0,0 +1,28 @@ +# AMD VEK385 (Versal AI Edge Gen 2) on the wolfHAL drivers. +# Used with TARGET=versal2 WOLFHAL=1 BOARD=vek385; arch.mk keeps the +# versal2 CPU flags, link address and linker script. + +# Bind the wolfHAL drivers directly to the top-level API symbols: +# whal_Uart_* -> PL011, whal_SpiMem_* -> Cadence OSPI, whal_Flash_* -> NOR +# flash on the OSPI controller. Only the whal_Dma dispatch is compiled: +# the Cadence driver reads through the OSPI DMA as a whal_Dma. +CFLAGS+=-DWHAL_CFG_PL011_UART_DIRECT_API_MAPPING +CFLAGS+=-DWHAL_CFG_CADENCE_OSPI_SPIMEM_DIRECT_API_MAPPING +CFLAGS+=-DWHAL_CFG_SPIMEM_NOR_FLASH_DIRECT_API_MAPPING + +# No wolfHAL timeouts for now: a bad CNTPCT_EL0 read on this board looks +# like a timeout. A device that never answers makes wolfBoot hang. +CFLAGS+=-DWHAL_CFG_NO_TIMEOUT + +# Console: send '\n' as "\r\n" (hal/wolfhal.c). +CFLAGS+=-DWOLFHAL_UART_CRLF + +WOLFHAL_OBJS+=$(WOLFHAL_ROOT)/src/reg.o +WOLFHAL_OBJS+=$(WOLFHAL_ROOT)/src/uart/pl011_uart.o +WOLFHAL_OBJS+=$(WOLFHAL_ROOT)/src/spimem/cadence_ospi_spimem.o +WOLFHAL_OBJS+=$(WOLFHAL_ROOT)/src/dma/dma.o +WOLFHAL_OBJS+=$(WOLFHAL_ROOT)/src/dma/versal2_ospi_dma.o +WOLFHAL_OBJS+=$(WOLFHAL_ROOT)/src/flash/spimem_nor_flash.o + +OBJS+=$(WOLFHAL_OBJS) +APP_OBJS+=$(WOLFHAL_OBJS) diff --git a/hal/boards/vek385/wolfHAL_board.c b/hal/boards/vek385/wolfHAL_board.c new file mode 100644 index 0000000000..552bcd3975 --- /dev/null +++ b/hal/boards/vek385/wolfHAL_board.c @@ -0,0 +1,315 @@ +/* wolfHAL_board.c + * + * AMD VEK385 board on wolfHAL: PL011 console, NOR flash on the Cadence + * OSPI (optional DMA reads), generic timer, DTS addresses. + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include +#include + +#include "hal.h" +#include "hal/versal2.h" +#include "printf.h" +#include "loader.h" +#include "aarch64_arch.h" +#include "wolfHAL_board.h" + +void hal_delay_us(uint32_t us); +uint64_t hal_get_timer_us(void); + +/* wolfHAL devices */ + +/* wolfHAL timeout tick: generic timer in us. Wraps after ~71 min; the + * timeout check handles it. */ +static uint32_t vek385_tick_us(void) +{ + return (uint32_t)hal_get_timer_us(); +} + +/* Bounds for the waits. A status wait covers the slowest erase, at most + * 1 s (datasheet Table 48); a DMA read covers a whole image. */ +#define VEK385_UART_TIMEOUT_US 1000000U +#define VEK385_OSPI_TIMEOUT_US 1000000U +#define VEK385_FLASH_TIMEOUT_US 60000000U +#define VEK385_DMA_TIMEOUT_US 60000000U + +/* Console: 8N1 at DEBUG_UART_BAUD from UART_CLK_REF. Init sets it up + * even when the PLM or BL31 already did. */ +static whal_Timeout vek385_uart_timeout = { + VEK385_UART_TIMEOUT_US, 0, vek385_tick_us +}; +whal_Uart g_wbUart = { + .base = DEBUG_UART_BASE, + .cfg = &(whal_Pl011_Uart_Cfg) { + .ibrd = WHAL_PL011_UART_IBRD(UART_CLK_REF, DEBUG_UART_BAUD), + .fbrd = WHAL_PL011_UART_FBRD(UART_CLK_REF, DEBUG_UART_BAUD), + .lcrH = WHAL_PL011_UART_LCRH_8N1_FIFO, + .timeout = &vek385_uart_timeout, + }, +}; + +#ifdef WOLFBOOT_OSPI_DMA +/* Cache upkeep for the DMA buffer. DMA writes memory behind the cache, so + * flush the buffer before the transfer and drop stale lines after it. */ +static void versal2_dcache_clean_inval(void *buf, size_t len); +static void versal2_dcache_inval(void *buf, size_t len); + +static whal_Timeout vek385_dma_timeout = { + VEK385_DMA_TIMEOUT_US, 0, vek385_tick_us +}; +static whal_Versal2_OspiDma_ChCfg versal2_dma_xfer; +static whal_Dma versal2_dma = { + .base = WHAL_VERSAL2_OSPI_BASE, + .driver = &whal_Versal2_OspiDma_Driver, + .cfg = &(whal_Versal2_OspiDma_Cfg) { + .srcRdAddr = WHAL_VERSAL2_OSPI_DMA_SRC_RD_ADDR, + .dstCtrl = WHAL_VERSAL2_OSPI_DMA_DST_CTRL, + .CacheCleanInval = versal2_dcache_clean_inval, + .CacheInval = versal2_dcache_inval, + .timeout = &vek385_dma_timeout, + .xfer = &versal2_dma_xfer, + }, +}; + +/* Point the OSPI DMA at a read buffer: the OSPI driver calls this for the + * DMA part of a read. */ +static whal_Error vek385_dma_set_read_buf(whal_Dma *dma, size_t ch, + void *buf, size_t len) +{ + whal_Versal2_OspiDma_ChCfg x = { .buf = buf, .len = len }; + + return whal_Dma_Configure(dma, ch, &x); +} + +#define VEK385_DMA (&versal2_dma) +#define VEK385_DMA_SET_BUF vek385_dma_set_read_buf +#define VEK385_DMA_MAX_LEN WHAL_VERSAL2_OSPI_DMA_MAX_LEN +/* The DMA buffer and length must be whole cache lines (no shared lines). */ +#define VEK385_DMA_ALIGN CACHE_LINE_SIZE +#else +#define VEK385_DMA NULL +#define VEK385_DMA_SET_BUF NULL +#define VEK385_DMA_MAX_LEN 0 +#define VEK385_DMA_ALIGN 0 +#endif + +/* OSPI controller, 1-bit: clock /32, CS 0, board read capture. Init turns + * off what the PLM may leave on (DTR, PHY). */ +static whal_Timeout vek385_ospi_timeout = { + VEK385_OSPI_TIMEOUT_US, 0, vek385_tick_us +}; +whal_SpiMem g_wbOspi = { + .base = WHAL_VERSAL2_OSPI_BASE, + .cfg = &(whal_CadenceOspi_SpiMem_Cfg) { + .devSize = WHAL_VERSAL2_OSPI_DEV_SIZE_VEK385, + .baudDiv = VERSAL2_OSPI_BAUD_DIV_32, + .csLines = VERSAL2_OSPI_CS_LINES, + .rdCapture = VERSAL2_OSPI_RD_CAPTURE, + .indTrigBase = WHAL_VERSAL2_OSPI_IND_TRIG_BASE, + .indTrigRange = WHAL_VERSAL2_OSPI_IND_TRIG_RANGE, + .sramPartition = WHAL_VERSAL2_OSPI_SRAM_PARTITION, + .dmaPeriphCfg = WHAL_VERSAL2_OSPI_DMA_PERIPH_CFG, + .dma = VEK385_DMA, + .dmaCh = WHAL_VERSAL2_OSPI_DMA_CH, + .dmaAlign = VEK385_DMA_ALIGN, + .dmaMaxLen = VEK385_DMA_MAX_LEN, + .SetDmaReadBuf = VEK385_DMA_SET_BUF, + .timeout = &vek385_ospi_timeout, + }, +}; + +/* MT35XU02G, 1-bit, 4-byte opcodes: read 13h, program 12h, erase DCh 128 KB + * (Table 21). Only this ID; reset and volatile 1-bit (81h), never B1h. */ +static whal_Timeout vek385_flash_timeout = { + VEK385_FLASH_TIMEOUT_US, 0, vek385_tick_us +}; +whal_Flash g_wbExtFlash = { + .cfg = &(whal_SpiMemNor_Flash_Cfg) { + .spiMemDev = &g_wbOspi, + .capacity = 0x10000000, /* 256 MB */ + .pageSz = 256, + .eraseSz = 0x20000, /* 128 KB */ + .addrBytes = 4, + .readOp = OSPI_OP_READ4, + .readDummy = 0, + .progOp = OSPI_OP_PAGE_PROGRAM4, + .eraseOp = OSPI_OP_ERASE4_128K, + .flags = WHAL_SPIMEM_NOR_FLAG_RESET, + .id = VERSAL2_FLASH_JEDEC_ID, + .errOp = WHAL_SPIMEM_NOR_MT35X_ERR_OP, + .errMask = WHAL_SPIMEM_NOR_MT35X_ERR_MASK, + .errClearOp = WHAL_SPIMEM_NOR_MT35X_ERR_CLEAR_OP, + .rstRegOp = WHAL_SPIMEM_NOR_MT35X_RST_REG_OP, + .rstRegAddrBytes = WHAL_SPIMEM_NOR_MT35X_RST_REG_ADDR_BYTES, + .rstRegAddr = WHAL_SPIMEM_NOR_MT35X_RST_REG_ADDR, + .rstRegVal = WHAL_SPIMEM_NOR_MT35X_RST_REG_VAL, + .timeout = &vek385_flash_timeout, + }, +}; + +#ifdef WOLFBOOT_OSPI_DMA +/* Flush and drop the buffer's cache lines (dc civac). The test-app has no + * flush_dcache_range(). After DMA, flushing is safe: no line is dirty. */ +static void versal2_dcache_clean_inval(void *buf, size_t len) +{ + uintptr_t addr = (uintptr_t)buf; + uintptr_t p = addr & ~(uintptr_t)(CACHE_LINE_SIZE - 1); + + for (; p < addr + len; p += CACHE_LINE_SIZE) { + __asm__ volatile("dc civac, %0" : : "r"(p) : "memory"); + } + __asm__ volatile("dsb sy" : : : "memory"); +} + +static void versal2_dcache_inval(void *buf, size_t len) +{ + versal2_dcache_clean_inval(buf, len); +} +#endif /* WOLFBOOT_OSPI_DMA */ + +/* OSPI bring-up */ +#ifdef EXT_FLASH +static int vek385_ospi_init(void) +{ + uint8_t id[3] = { 0, 0, 0 }; + int ret = 0; + +#ifdef WOLFBOOT_OSPI_DMA + /* Clear DMA status an earlier stage may have left. */ + if (whal_Dma_Init(&versal2_dma) != WHAL_SUCCESS) { + wolfBoot_printf("OSPI: DMA init failed\n"); + return -1; + } +#endif + + /* Turn on the controller. No controller reset; the NOR driver's Init + * fixes the flash mode. */ + if (whal_SpiMem_Init(&g_wbOspi) != WHAL_SUCCESS) { + wolfBoot_printf("OSPI: controller init failed\n"); + return -1; + } + + /* Check the flash ID (reset the flash and retry if needed) and clear + * old flag status error bits, so the first write can't fail on them. */ + if (whal_Flash_Init(&g_wbExtFlash) != WHAL_SUCCESS) { + ret = -1; + } + (void)whal_SpiMemNor_Flash_ReadId(&g_wbExtFlash, id); + if (ret != 0) { + wolfBoot_printf("OSPI: flash ID %02X %02X %02X is not the " + "MT35XU02G (2C 5B 1C), or no flash\n", + id[0], id[1], id[2]); + return -1; + } + wolfBoot_printf("OSPI: flash ID %02X %02X %02X (Micron MT35XU02G)\n", + id[0], id[1], id[2]); + return 0; +} +#endif /* EXT_FLASH */ + +/* Timer (ARM generic timer) */ +uint64_t hal_timer_ms(void) +{ + return (timer_get_count() * 1000ULL) / timer_get_freq(); +} + +void hal_delay_us(uint32_t us) +{ + uint64_t deadline = timer_deadline_us(us); + + while (!timer_expired(deadline)) { + } +} + +uint64_t hal_get_timer_us(void) +{ + return (timer_get_count() * 1000000ULL) / timer_get_freq(); +} + +/* HAL entry points */ + +/* Firmware must set the timer frequency (CNTFID0, AM028). If CNTFRQ_EL0 + * is 0, print a warning that TIMER_CLK_FREQ is used instead. */ +#if defined(DEBUG_UART) +static void vek385_timer_freq_warn(void) +{ + uint32_t freq; + + __asm__ volatile("mrs %0, cntfrq_el0" : "=r"(freq)); + if (freq == 0) { + wolfBoot_printf("Timer: CNTFRQ_EL0=0, assuming %lu Hz " + "(firmware must program CNTFID0)\n", + (unsigned long)TIMER_CLK_FREQ); + } +} +#endif /* DEBUG_UART */ + +void hal_init(void) +{ +#ifdef DEBUG_UART + (void)whal_Uart_Init(&g_wbUart); +#endif + +#if defined(DEBUG_UART) && defined(__WOLFBOOT) + vek385_timer_freq_warn(); + wolfBoot_printf( + "\n========================================\n" + "wolfBoot Secure Boot - AMD Versal Gen 2\n" +#ifndef WOLFBOOT_REPRODUCIBLE_BUILD + "Build: " __DATE__ " " __TIME__ "\n" +#endif + "========================================\n"); + wolfBoot_printf("Current EL: %d\n", current_el()); +#endif + +#ifdef EXT_FLASH + if (vek385_ospi_init() != 0) { + wolfBoot_printf("OSPI: init failed - no flash\n"); + wolfBoot_panic(); + } +#endif +} + +void hal_prepare_boot(void) +{ + /* uart_write() already waits for the bytes; do_boot() flushes the + * caches. */ +} + +#ifdef MMU +void* hal_get_dts_address(void) +{ +#ifdef WOLFBOOT_LOAD_DTS_ADDRESS + return (void*)WOLFBOOT_LOAD_DTS_ADDRESS; +#else + return NULL; +#endif +} + +void* hal_get_dts_update_address(void) +{ +#ifdef WOLFBOOT_DTS_UPDATE_ADDRESS + return (void*)WOLFBOOT_DTS_UPDATE_ADDRESS; +#else + return NULL; +#endif +} +#endif /* MMU */ diff --git a/hal/boards/vek385/wolfHAL_board.h b/hal/boards/vek385/wolfHAL_board.h new file mode 100644 index 0000000000..bfba43c931 --- /dev/null +++ b/hal/boards/vek385/wolfHAL_board.h @@ -0,0 +1,82 @@ +/* wolfHAL_board.h + * + * AMD VEK385 (Versal AI Edge Gen 2, Cortex-A78AE) board configuration for + * the wolfHAL drivers: PL011 console on UART1, and the Micron MT35XU02G + * OSPI flash on the Cadence OSPI controller with the Versal Gen 2 OSPI DMA + * for reads. The devices are in wolfHAL_board.c; hal/wolfhal.c uses the + * BOARD_*_DEV handles below. No internal flash: BOARD_FLASH_DEV is not + * defined, and all wolfBoot partitions are in the OSPI flash (EXT_FLASH). + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#ifndef WOLFHAL_BOARD_H +#define WOLFHAL_BOARD_H + +#include +#include +#include +#include +#include +#include +#include + +/* Console: UART1 (UG1712 "UART Interfaces"); DEBUG_UART_NUM=0 picks + * UART0. */ +#if defined(DEBUG_UART_NUM) && DEBUG_UART_NUM == 0 + #define DEBUG_UART_BASE WHAL_VERSAL2_UART0_BASE +#else + #define DEBUG_UART_BASE WHAL_VERSAL2_UART1_BASE +#endif + +/* UART clock set by the PLM: 99999001 Hz on the VEK385 (system.dtb). At + * 115200 this gives IBRD 54, FBRD 16, as the PLM leaves them. */ +#ifndef UART_CLK_REF + #define UART_CLK_REF 99999001UL +#endif + +#ifndef DEBUG_UART_BAUD + #define DEBUG_UART_BAUD 115200 +#endif + +/* OSPI flash (Micron MT35XU02GCBA, 256 MB): 4-byte address opcodes, needed + * above 16 MB (datasheet p13-14, p32-34). */ +#define OSPI_OP_READ4 0x13 /* Read, 4-byte address */ +#define OSPI_OP_PAGE_PROGRAM4 0x12 /* Page Program, 4-byte address */ +#define OSPI_OP_ERASE4_128K 0xDC /* Sector erase (128 KB) */ + +/* Flash ID 2C 5B 1C = Micron, 1.8 V, 2 Gb (datasheet Table 18), byte 0 in + * bits 7:0. Init accepts only this ID. */ +#define VERSAL2_FLASH_JEDEC_ID 0x1C5B2CUL + +/* 1-bit OSPI: clock /32 (AM028 reset value; PLM's /2 needs the PHY). Read + * capture 0x1: the reset value 0 misreads the ID on the board (probe). */ +#define VERSAL2_OSPI_BAUD_DIV_32 0xF +#define VERSAL2_OSPI_RD_CAPTURE 0x1 +#define VERSAL2_OSPI_CS_LINES 0x0 + +/* Devices (wolfHAL_board.c), used by hal/wolfhal.c */ +extern whal_Uart g_wbUart; +extern whal_SpiMem g_wbOspi; +extern whal_Flash g_wbExtFlash; + +#define BOARD_UART_DEV (&g_wbUart) +#define BOARD_EXT_FLASH_DEV (&g_wbExtFlash) + +#endif /* WOLFHAL_BOARD_H */ diff --git a/hal/versal2.h b/hal/versal2.h new file mode 100644 index 0000000000..b6d0e32cc4 --- /dev/null +++ b/hal/versal2.h @@ -0,0 +1,99 @@ +/* versal2.h + * + * AMD Versal Gen 2 (VEK385, Cortex-A78AE). Boot: PLM -> BL31 (EL3) -> + * wolfBoot (EL2) -> Linux; in QEMU a trampoline stands in for BL31. + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#ifndef _VERSAL2_H_ +#define _VERSAL2_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/* C headers only for C code; boot_aarch64_start.S also includes this. */ +#ifndef __ASSEMBLER__ +#include +#endif /* __ASSEMBLER__ */ + +/* BL31 owns EL3. wolfBoot runs at EL2; the app starts at EL2 or EL1. */ +#define EL3_SECURE 0 +#define EL2_HYPERVISOR 1 +#define EL1_NONSECURE 1 + +/* No guest hypervisor, no FPU trapping (the A78AE FPU is always on). */ +#define HYP_GUEST 0 +#define FPU_TRAP 0 + +/* Cortex-A78: erratum 855873 workaround (as on Gen 1 Versal). */ +#define CONFIG_ARM_ERRATA_855873 1 + +/* BL31 owns the interrupt controller (GIC). wolfBoot only polls, so it + * must not touch it. */ +#define SKIP_GIC_INIT 1 + +/* Default entry level for the application. */ +#if !defined(BOOT_EL1) && !defined(BOOT_EL2) + #define BOOT_EL2 1 +#endif +#if defined(BOOT_EL1) && defined(BOOT_EL2) + #error "BOOT_EL1 and BOOT_EL2 are mutually exclusive" +#endif + +/* The watchdog is not supported yet (Gen 2 uses other addresses than + * Gen 1), so a WATCHDOG build stops with an error. */ +#ifdef WATCHDOG + #error "WATCHDOG is not supported on TARGET=versal2" +#endif + +/* DDR (DTB): 2 GB at 0x0, 6 GB at 0x8_0000_0000. wolfBoot (0x40000000) + * and the app (0x20000000) are in the low 2 GB. */ +#define VERSAL2_DDR_0_BASE 0x00000000UL +#define VERSAL2_DDR_0_HIGH 0x7FFFFFFFUL +#define VERSAL2_DDR_1_BASE 0x800000000ULL +/* High 6 GB. The MMU table does not map it and wolfBoot never uses it; + * a Linux image loaded there would need a new mapping. */ +#define VERSAL2_DDR_1_HIGH 0x97FFFFFFFULL + +/* The app load address is WOLFBOOT_LOAD_ADDRESS in the config. It must be + * above the RPU areas, which end at 0x1E4E7FFF on the VEK385. */ + +#define CACHE_LINE_SIZE 64 + +/* DDR range for the MMU table (used by boot_aarch64_start.S). */ +#define XPAR_PSU_DDR_0_S_AXI_BASEADDR VERSAL2_DDR_0_BASE +#define XPAR_PSU_DDR_0_S_AXI_HIGHADDR VERSAL2_DDR_0_HIGH + +/* UART (PL011): UART0 0xF1920000, UART1 0xF1930000; the VEK385 console is + * UART1 (UG1712 "UART Interfaces"). */ +#define VERSAL2_UART0_BASE 0xF1920000UL +#define VERSAL2_UART1_BASE 0xF1930000UL + +/* The console UART, its clock and the OSPI flash settings are board + * settings: see hal/boards/vek385/wolfHAL_board.h. */ + +/* Timer frequency used only if firmware left CNTFRQ_EL0 at 0. The VEK385 + * firmware and the QEMU trampoline both set 100 MHz. */ +#ifndef TIMER_CLK_FREQ + #define TIMER_CLK_FREQ 100000000UL /* 100 MHz */ +#endif + +#endif /* _VERSAL2_H_ */ diff --git a/hal/versal2.ld b/hal/versal2.ld new file mode 100644 index 0000000000..3d9e772ef1 --- /dev/null +++ b/hal/versal2.ld @@ -0,0 +1,246 @@ +/* versal2_ddr.ld + * + * Linker script for wolfBoot on AMD Versal AI Edge / Prime Gen 2 (VEK385) + * - DDR boot, Cortex-A78AE + * + * This script is for production boot where: + * - the PLM has initialized DDR + * - BL31 runs at EL3 and hands off to EL2 + * - wolfBoot runs at EL2 from DDR at WOLFBOOT_ORIGIN (0x40000000, the + * AMD default BL33 entry address, confirmed by the VEK385 Rev B boot + * log: "BL31: Non secure code at 0x40000000"). The QEMU test loads the + * same image at the same address via an EL3 -> EL2 trampoline. + * + * Memory Map (VEK385, from the DTB): + * 0x00000000 - 0x00FFFFFF : PLM (do not use) + * 0x01000000 - 0x015FFFFF : TF-A (do not use) + * 0x01800000 : DTS load address + * 0x0C000000 - 0x1E4E7FFF : RPU reserved regions (do not use) + * 0x20000000 : application (Linux kernel) load address + * 0x40000000 - 0x401FFFFF : wolfBoot (2 MB) + * + * OSPI flash layout (MT35XU02GCBA, 256 MB): + * 0x00000000 - 0x015BFFFF : AMD Image Selector / Recovery / metadata + * 0x015C0000 - 0x087BFFFF : Bank A (114 MB) + * 0x015C0000 - 0x01DBFFFF : BOOT.BIN (8 MB reserved; AMD's + * multidomain BOOT.BIN is 5.31 MiB) + * 0x01DC0000 : wolfBoot BOOT partition (44 MB) + * 0x049C0000 : wolfBoot UPDATE partition (44 MB) + * 0x07600000 / 0x07E00000 : DTS boot / update slots + * 0x08800000 - 0x0F9FFFFF : Bank B (114 MB, AMD) + * 0x0FA40000 : user scratchpad -> wolfBoot SWAP partition + * + * Copyright (C) 2026 wolfSSL Inc. + */ + +OUTPUT_FORMAT("elf64-littleaarch64") +OUTPUT_ARCH(aarch64) +ENTRY(_vector_table) + +/* Stack and heap sizes - larger for DDR boot */ +_STACK_SIZE = DEFINED(_STACK_SIZE) ? _STACK_SIZE : 0x10000; /* 64KB stack */ +_HEAP_SIZE = DEFINED(_HEAP_SIZE) ? _HEAP_SIZE : 0x20000; /* 128KB heap */ + +_EL0_STACK_SIZE = DEFINED(_EL0_STACK_SIZE) ? _EL0_STACK_SIZE : 0x1000; +_EL1_STACK_SIZE = DEFINED(_EL1_STACK_SIZE) ? _EL1_STACK_SIZE : 0x2000; +/* Primary stack at EL2 */ +_EL2_STACK_SIZE = DEFINED(_EL2_STACK_SIZE) ? _EL2_STACK_SIZE : 0x8000; + +/* Memory region: wolfBoot at WOLFBOOT_ORIGIN with 2 MB allocated. */ +MEMORY +{ + DDR (rwx) : ORIGIN = @WOLFBOOT_ORIGIN@, LENGTH = 0x200000 +} + +/* Sections */ +SECTIONS +{ + /* Code section - must start at entry point */ + .text : { + _start_text = .; + + /* Vector table and startup code MUST be first */ + KEEP (*(.vectors)) + *(.boot) + *(.text) + *(.text.*) + *(.gnu.linkonce.t.*) + *(.plt) + *(.gnu_warning) + *(.gcc_except_table) + *(.glue_7) + *(.glue_7t) + *(.ARM.extab) + *(.gnu.linkonce.armextab.*) + + . = ALIGN(8); + _end_text = .; + } > DDR + + .init (ALIGN(64)) : { + KEEP (*(.init)) + } > DDR + + .fini (ALIGN(64)) : { + KEEP (*(.fini)) + } > DDR + + /* Read-only data */ + .rodata : { + . = ALIGN(64); + __rodata_start = .; + *(.rodata) + *(.rodata.*) + *(.gnu.linkonce.r.*) + __rodata_end = .; + } > DDR + + /* Keystore - public keys for image verification */ + .keystore : { + . = ALIGN(8); + *(.keystore) + . = ALIGN(8); + } > DDR + + /* Initialized data */ + .data : { + . = ALIGN(64); + _start_data = .; + __data_start = .; + *(.data) + *(.data.*) + *(.gnu.linkonce.d.*) + *(.jcr) + *(.got) + *(.got.plt) + _end_data = .; + __data_end = .; + } > DDR + + .got : { + *(.got) + } > DDR + + .got1 : { + *(.got1) + } > DDR + + .got2 : { + *(.got2) + } > DDR + + /* MMU tables - 4KB aligned for AArch64 */ + .mmu_tbl0 (ALIGN(4096)) : { + __mmu_tbl0_start = .; + *(.mmu_tbl0) + __mmu_tbl0_end = .; + } > DDR + + .mmu_tbl1 (ALIGN(4096)) : { + __mmu_tbl1_start = .; + *(.mmu_tbl1) + __mmu_tbl1_end = .; + } > DDR + + .mmu_tbl2 (ALIGN(4096)) : { + __mmu_tbl2_start = .; + *(.mmu_tbl2) + __mmu_tbl2_end = .; + } > DDR + + .ARM.exidx : { + __exidx_start = .; + *(.ARM.exidx*) + *(.gnu.linkonce.armexidix.*.*) + __exidx_end = .; + } > DDR + + /* Small data */ + .sdata : { + . = ALIGN(64); + __sdata_start = .; + *(.sdata) + *(.sdata.*) + *(.gnu.linkonce.s.*) + __sdata_end = .; + } > DDR + + /* RAM functions section */ + .ramcode : { + . = ALIGN(8); + _start_ramcode = .; + *(.ramcode) + *(.ramcode.*) + . = ALIGN(8); + _end_ramcode = .; + } > DDR + + /* Small BSS */ + .sbss (NOLOAD) : { + . = ALIGN(64); + __sbss_start = .; + *(.sbss) + *(.sbss.*) + *(.gnu.linkonce.sb.*) + . = ALIGN(64); + __sbss_end = .; + } > DDR + + /* Uninitialized data (BSS) */ + .bss (NOLOAD) : { + . = ALIGN(64); + __bss_start__ = .; + _start_bss = .; + *(.bss) + *(.bss.*) + *(.gnu.linkonce.b.*) + *(COMMON) + . = ALIGN(64); + __bss_end__ = .; + _end_bss = .; + } > DDR + + /* Heap */ + .heap (NOLOAD) : { + . = ALIGN(64); + _heap = .; + __heap_start = .; + . += _HEAP_SIZE; + __heap_end = .; + } > DDR + + /* Stack - EL2 is primary when booting from BL31 */ + .stack (NOLOAD) : { + . = ALIGN(64); + /* EL3 stack (not used when entering at EL2) */ + _el3_stack_end = .; + . += 0x1000; + __el3_stack = .; + + /* EL2 stack - primary execution level */ + _el2_stack_end = .; + . += _EL2_STACK_SIZE; + . = ALIGN(64); + __el2_stack = .; + + /* EL1 stack */ + _el1_stack_end = .; + . += _EL1_STACK_SIZE; + . = ALIGN(64); + __el1_stack = .; + + /* EL0 stack */ + _el0_stack_end = .; + . += _EL0_STACK_SIZE; + . = ALIGN(64); + __el0_stack = .; + } > DDR + + _end = .; +} + +/* Provide symbols for startup code */ +PROVIDE(_start_vector = _start_text); +/* Use the EL2 stack as default when entering from BL31 */ +PROVIDE(__stack = __el2_stack); +PROVIDE(_stack_base = .); diff --git a/hal/wolfhal.c b/hal/wolfhal.c index b888489526..fbcd6219be 100644 --- a/hal/wolfhal.c +++ b/hal/wolfhal.c @@ -1,10 +1,17 @@ /* wolfhal.c * * Generic wolfHAL port for wolfBoot. wolfBoot's HAL contract - * (hal_flash_*, uart_write) is satisfied here by forwarding to the - * wolfHAL API. The chip drivers behind the wolfHAL API are singletons, - * instantiated by the driver .c files from initializer macros in - * wolfHAL_board.h; this file passes the BOARD_*_DEV handles defined there. + * (hal_flash_*, ext_flash_*, uart_write) is satisfied here by forwarding to + * the wolfHAL API. The chip drivers behind the wolfHAL API are configured + * in the board directory; this file passes the BOARD_*_DEV handles defined + * in wolfHAL_board.h: + * - BOARD_FLASH_DEV: internal flash. A board without internal flash does + * not define it, and hal_flash_write/erase then fail. + * - BOARD_EXT_FLASH_DEV: external flash, with EXT_FLASH=1. Program and + * erase are refused outside the wolfBoot BOOT, UPDATE and SWAP + * partitions. + * - BOARD_UART_DEV: console, with DEBUG_UART=1. With WOLFHAL_UART_CRLF + * (set in board.mk), '\n' is sent as "\r\n". * * Copyright (C) 2026 wolfSSL Inc. * @@ -30,6 +37,7 @@ #include "wolfboot/wolfboot.h" #include "wolfHAL_board.h" +#ifdef BOARD_FLASH_DEV void RAMFUNCTION hal_flash_unlock(void) { whal_Flash_Unlock(BOARD_FLASH_DEV, 0, 0); @@ -40,19 +48,201 @@ void RAMFUNCTION hal_flash_lock(void) whal_Flash_Lock(BOARD_FLASH_DEV, 0, 0); } -int RAMFUNCTION hal_flash_write(uint32_t address, const uint8_t *data, int len) +int RAMFUNCTION hal_flash_write(haladdr_t address, const uint8_t *data, int len) { return whal_Flash_Write(BOARD_FLASH_DEV, (size_t)address, data, (size_t)len); } -int RAMFUNCTION hal_flash_erase(uint32_t address, int len) +int RAMFUNCTION hal_flash_erase(haladdr_t address, int len) { return whal_Flash_Erase(BOARD_FLASH_DEV, (size_t)address, (size_t)len); } +#else +/* No internal flash: wolfBoot's partitions are all in external flash. */ +void RAMFUNCTION hal_flash_unlock(void) +{ +} + +void RAMFUNCTION hal_flash_lock(void) +{ +} + +int RAMFUNCTION hal_flash_write(haladdr_t address, const uint8_t *data, int len) +{ + (void)address; + (void)data; + (void)len; + return -1; +} + +int RAMFUNCTION hal_flash_erase(haladdr_t address, int len) +{ + (void)address; + (void)len; + return -1; +} +#endif /* BOARD_FLASH_DEV */ + +#ifdef EXT_FLASH +/* Program and erase must fit inside BOOT, UPDATE or SWAP, where that + * partition is in the external flash. Anything else is refused. */ +#ifdef PART_SWAP_EXT +/* SWAP size is a variable so the unit tests can change it. */ +static uint32_t wolfhal_swap_size = (uint32_t)WOLFBOOT_SECTOR_SIZE; +#endif + +static int wolfhal_range_in_partition(uint32_t base, uint32_t size, + uint32_t addr, uint32_t len) +{ + uint32_t end; + + if (len == 0) { + return 0; + } + /* base + size must not wrap. */ + if (size > UINT32_MAX - base) { + return 0; + } + end = base + size; + /* [addr, addr+len) must sit inside [base, end). Check the start first + * so (end - addr) cannot go below zero. */ + if (addr < base) { + return 0; + } + if (addr > end) { + return 0; + } + if (len > end - addr) { + return 0; + } + return 1; +} + +/* 1 if a flash address fits the guard's 32 bits. A larger one would be cut + * by the casts below and could then look like it is inside a partition. */ +static int wolfhal_addr_fits(uintptr_t address) +{ + return ((uint64_t)address <= 0xFFFFFFFFULL); +} + +/* A partition counts when its PART_*_EXT flag says it is in the external + * flash. Its address may be 0. */ +static int wolfhal_ext_flash_guard_ok(uint32_t addr, uint32_t len) +{ +#ifdef PART_BOOT_EXT + if (wolfhal_range_in_partition((uint32_t)WOLFBOOT_PARTITION_BOOT_ADDRESS, + (uint32_t)WOLFBOOT_PARTITION_SIZE, + addr, len)) { + return 1; + } +#endif +#ifdef PART_UPDATE_EXT + if (wolfhal_range_in_partition( + (uint32_t)WOLFBOOT_PARTITION_UPDATE_ADDRESS, + (uint32_t)WOLFBOOT_PARTITION_UPDATE_SIZE, addr, len)) { + return 1; + } +#endif +#ifdef PART_SWAP_EXT + if (wolfhal_range_in_partition((uint32_t)WOLFBOOT_PARTITION_SWAP_ADDRESS, + wolfhal_swap_size, addr, len)) { + return 1; + } +#endif + (void)addr; + (void)len; + return 0; +} + +int ext_flash_read(uintptr_t address, uint8_t *data, int len) +{ + if (data == NULL || len <= 0) { + return 0; + } + if (whal_Flash_Read(BOARD_EXT_FLASH_DEV, (size_t)address, data, + (size_t)len) != WHAL_SUCCESS) { + return -1; + } + return len; +} + +/* Write and erase return 0 on success and -1 on error (docs/HAL.md). */ +int ext_flash_write(uintptr_t address, const uint8_t *data, int len) +{ + if (len == 0) { + return 0; + } + if (data == NULL || len < 0) { + return -1; + } + if (!wolfhal_addr_fits(address) || + wolfhal_ext_flash_guard_ok((uint32_t)address, (uint32_t)len) == 0) { + return -1; + } + if (whal_Flash_Write(BOARD_EXT_FLASH_DEV, (size_t)address, data, + (size_t)len) != WHAL_SUCCESS) { + return -1; + } + return 0; +} + +int ext_flash_erase(uintptr_t address, int len) +{ + if (len == 0) { + return 0; + } + if (len < 0) { + return -1; + } + if (!wolfhal_addr_fits(address) || + wolfhal_ext_flash_guard_ok((uint32_t)address, (uint32_t)len) == 0) { + return -1; + } + if (whal_Flash_Erase(BOARD_EXT_FLASH_DEV, (size_t)address, + (size_t)len) != WHAL_SUCCESS) { + return -1; + } + return 0; +} + +void ext_flash_lock(void) +{ + (void)whal_Flash_Lock(BOARD_EXT_FLASH_DEV, 0, 0); +} + +void ext_flash_unlock(void) +{ + (void)whal_Flash_Unlock(BOARD_EXT_FLASH_DEV, 0, 0); +} +#endif /* EXT_FLASH */ #ifdef DEBUG_UART +#ifdef WOLFHAL_UART_CRLF +/* Send len bytes, with '\n' sent as "\r\n" */ +void uart_write(const char *buf, unsigned int len) +{ + unsigned int start = 0; + unsigned int i; + + for (i = 0; i < len; i++) { + if (buf[i] == '\n') { + if (i > start) { + whal_Uart_Send(BOARD_UART_DEV, (const uint8_t *)buf + start, + (size_t)(i - start)); + } + whal_Uart_Send(BOARD_UART_DEV, (const uint8_t *)"\r\n", 2); + start = i + 1; + } + } + if (len > start) { + whal_Uart_Send(BOARD_UART_DEV, (const uint8_t *)buf + start, + (size_t)(len - start)); + } +} +#else void uart_write(const char *buf, unsigned int len) { whal_Uart_Send(BOARD_UART_DEV, (const uint8_t *)buf, (size_t)len); } -#endif +#endif /* WOLFHAL_UART_CRLF */ +#endif /* DEBUG_UART */ diff --git a/lib/wolfHAL b/lib/wolfHAL index a1cfc5cacf..f2e67eb934 160000 --- a/lib/wolfHAL +++ b/lib/wolfHAL @@ -1 +1 @@ -Subproject commit a1cfc5cacffe2397daac5de25359868b961112dc +Subproject commit f2e67eb934395a092a37a62d1b466cc26c3ceec4 diff --git a/src/boot_aarch64.c b/src/boot_aarch64.c index 3407776ab8..39d8687015 100644 --- a/src/boot_aarch64.c +++ b/src/boot_aarch64.c @@ -32,6 +32,8 @@ * compile in for the active target. */ #if defined(TARGET_versal) #include "hal/versal.h" +#elif defined(TARGET_versal2) +#include "hal/versal2.h" #elif defined(TARGET_agilex5) #include "hal/agilex5.h" #elif defined(TARGET_zynq) diff --git a/src/boot_aarch64_start.S b/src/boot_aarch64_start.S index aaa335baf9..521db305bf 100644 --- a/src/boot_aarch64_start.S +++ b/src/boot_aarch64_start.S @@ -30,6 +30,10 @@ #include "hal/versal.h" #endif +#ifdef TARGET_versal2 +#include "hal/versal2.h" +#endif + #ifdef TARGET_agilex5 #include "hal/agilex5.h" #endif @@ -65,7 +69,7 @@ /* VA region the TCR_EL{1,2,3} T0SZ values below cover. A high DDR window * must fit inside it; keep in step with those TCR literals. */ #ifndef WOLFBOOT_AARCH64_VA_LIMIT -#ifdef TARGET_versal +#if defined(TARGET_versal) || defined(TARGET_versal2) #define WOLFBOOT_AARCH64_VA_LIMIT 0x100000000000 /* 2^44, TCR 0x80843514 */ #else #define WOLFBOOT_AARCH64_VA_LIMIT 0x10000000000 /* 2^40, TCR 0x80823518 */ @@ -117,7 +121,7 @@ .set L2Table, MMUTableL2 .set vector_base, _vector_table -#if defined(TARGET_versal) +#if defined(TARGET_versal) || defined(TARGET_versal2) /* Versal: RVBAR is handled by PLM, not accessible from APU in JTAG mode */ .set counterfreq, 100000000 #elif defined(TARGET_agilex5) @@ -298,7 +302,7 @@ InitEL3: * Set up TCR_EL3 * Granual Size TG0 = 00 -> 4KB ***************************************************/ -#ifdef TARGET_versal +#if defined(TARGET_versal) || defined(TARGET_versal2) /* Versal: Physical Address Size PS = 100 -> 44bits 16TB * T0SZ = 20 -> (region size 2^(64-20) = 2^44) */ ldr x1,=0x80843514 @@ -380,7 +384,7 @@ InitEL2: * Set up TCR_EL2 * Granual Size TG0 = 00 -> 4KB ***************************************************/ -#ifdef TARGET_versal +#if defined(TARGET_versal) || defined(TARGET_versal2) /* Versal: Physical Address Size PS = 100 -> 44bits 16TB * T0SZ = 20 -> (region size 2^(64-20) = 2^44) */ ldr x1,=0x80843514 @@ -476,7 +480,7 @@ InitEL1: * Set up TCR_EL1 * Granual Size TG0 = 00 -> 4KB ***************************************************/ -#ifdef TARGET_versal +#if defined(TARGET_versal) || defined(TARGET_versal2) /* Versal: Physical Address Size PS = 100 -> 44bits 16TB * T0SZ = 20 -> (region size 2^(64-20) = 2^44) */ ldr x1,=0x485800514 @@ -761,7 +765,7 @@ MMUTableL2: .set SECT, SECT+0x200000 .endr -#ifdef TARGET_versal +#if defined(TARGET_versal) || defined(TARGET_versal2) /* Versal: LPD/PMC peripherals at 0xF0000000 - 0xF7FFFFFF (includes QSPI @ 0xF1030000) */ .rept 0x040 /* 0xF000_0000 - 0xF7FF_FFFF */ .8byte SECT + Device /* 128MB LPD peripherals (QSPI, I2C, etc) */ @@ -775,6 +779,19 @@ MMUTableL2: .endr #endif +#if defined(TARGET_versal2) +/* Versal Gen 2 (AM026 Table 31): 0xF8000000-0xFBFFFFFF is device memory; + * nothing is mapped above it. */ +.rept 0x20 /* 0xF800_0000 - 0xFBFF_FFFF */ +.8byte SECT + Device /* 64MB FPD_AXI_CMN_mem */ +.set SECT, SECT+0x200000 +.endr + +.rept 0x20 /* 0xFC00_0000 - 0xFFFF_FFFF */ +.8byte SECT + reserved /* no Table 31 entry (fault) */ +.set SECT, SECT+0x200000 +.endr +#else .rept 0x8 /* 0xF800_0000 - 0xF8FF_FFFF */ .8byte SECT + Device /* 16MB coresight */ .set SECT, SECT+0x200000 @@ -809,6 +826,7 @@ converted to 62MB */ .set SECT, SECT+0x200000 /* 0xFFE0_0000 - 0xFFFF_FFFF*/ .8byte SECT + Memory /* 2MB OCM/TCM */ +#endif /* TARGET_versal2 */ #endif /* TARGET_agilex5 */ #else /* TARGET_nxp_ls1028a */ @@ -972,7 +990,7 @@ MMUTableL2: .macro exception_return eret -#ifdef TARGET_versal +#if defined(TARGET_versal) || defined(TARGET_versal2) dsb nsh isb #endif @@ -994,7 +1012,7 @@ _vector_table: /* HW reset vector */ ldr x16, =_boot br x16 -#ifdef TARGET_versal +#if defined(TARGET_versal) || defined(TARGET_versal2) dsb nsh isb #endif diff --git a/test-app/Makefile b/test-app/Makefile index 09d31b7546..a005605f8b 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -1049,7 +1049,7 @@ ifeq ($(WOLFHAL),1) $(error BOARD=$(BOARD) has no hal/boards/$(BOARD)/board.mk) endif WOLFHAL_ROOT?=$(WOLFBOOT_ROOT)/lib/wolfHAL - CFLAGS+=-I$(WOLFHAL_ROOT) -DWHAL_CFG_NO_TIMEOUT -I$(WOLFBOOT_ROOT)/hal/boards/$(BOARD) + CFLAGS+=-I$(WOLFHAL_ROOT) -I$(WOLFBOOT_ROOT)/hal/boards/$(BOARD) DEBUG_UART=1 APP_OBJS+=board_$(BOARD).o include $(WOLFBOOT_ROOT)/hal/boards/$(BOARD)/board.mk @@ -1572,6 +1572,18 @@ ifeq ($(TARGET),versal) CFLAGS+=-DDEBUG_UART endif +ifeq ($(TARGET),versal2) + LSCRIPT_TEMPLATE:=AARCH64.ld + LDFLAGS+=-nostdlib + # DEBUG_UART lets the test-app use wolfBoot_printf and the HAL + DEBUG_UART:=1 + CFLAGS+=-DDEBUG_UART -DTESTAPP_VERSION=$(WOLFBOOT_VERSION) + # A wolfHAL board (WOLFHAL=1 BOARD=vek385). Its app is app_versal2.c, not + # the generic app_wolfhal.c: it prints the version markers the QEMU and + # board tests check, and the board has no LED GPIO. + APP_OBJS:=$(patsubst app_wolfhal.o,app_versal2.o,$(APP_OBJS)) +endif + ifeq ($(TARGET),zynq) LSCRIPT_TEMPLATE:=AARCH64.ld endif diff --git a/test-app/app_versal2.c b/test-app/app_versal2.c new file mode 100644 index 0000000000..857ce89226 --- /dev/null +++ b/test-app/app_versal2.c @@ -0,0 +1,89 @@ +/* app_versal2.c + * + * Versal Gen 2 test app: prints "TESTAPP-VERSION: N" (grepped by tests). + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include + +#include "hal.h" +#include "hal/versal2.h" +#include "aarch64_arch.h" +#include "wolfboot/wolfboot.h" +#include "printf.h" + +#ifndef TESTAPP_VERSION +#define TESTAPP_VERSION 1 +#endif + +void main(void) +{ +#ifdef WOLFBOOT_FIXED_PARTITIONS + uint32_t boot_version, update_version; + uint8_t boot_state = 0; + int have_boot_state = 0; +#endif + + hal_init(); + + wolfBoot_printf("\n\n"); + wolfBoot_printf("===========================================\n"); + wolfBoot_printf(" wolfBoot Test Application - AMD Versal Gen 2\n"); + wolfBoot_printf("===========================================\n\n"); + + wolfBoot_printf("Current EL: %d\n", current_el()); + + /* The QEMU tests look for this line. It shows which image version + * wolfBoot picked to boot. */ + wolfBoot_printf("TESTAPP-VERSION: %d\n", TESTAPP_VERSION); + +#ifdef WOLFBOOT_FIXED_PARTITIONS + /* Read the version in each partition (fixed partitions only). */ + boot_version = wolfBoot_get_image_version(PART_BOOT); + update_version = wolfBoot_get_image_version(PART_UPDATE); + + /* Print firmware versions */ + wolfBoot_printf("BOOT: Version: %d (0x%08x)\n", + boot_version, boot_version); + wolfBoot_printf("UPDATE: Version: %d (0x%08x)\n", + update_version, update_version); + + if (wolfBoot_get_partition_state(PART_BOOT, &boot_state) == 0) { + have_boot_state = 1; + } + else { + have_boot_state = 0; + } + if (have_boot_state) { + wolfBoot_printf("BOOT state: 0x%02X\n", boot_state); + } +#else + wolfBoot_printf("Boot mode: Disk-based (GPT/MBR partitions)\n"); +#endif + + wolfBoot_printf("Application running successfully!\n"); + + wolfBoot_printf("\nEntering idle loop...\n"); + + /* Idle loop */ + while (1) { + __asm__ volatile("wfi"); + } +} From 2b436207f89eb5b70fa8deb15c8b327d18caa2f7 Mon Sep 17 00:00:00 2001 From: night1rider Date: Tue, 17 Nov 2026 16:16:43 -0700 Subject: [PATCH 2/3] versal2: VEK385 board support: JTAG and OSPI boot, Linux Resets the flash out of the PLM's octal DDR mode at init. Adds the JTAG BIF and script, the Linux DTB script and FIT source, and the board docs. --- docs/Targets.md | 81 ++++++++++++++++++++++++++ hal/boards/vek385/wolfHAL_board.c | 7 ++- hal/versal2.its | 56 ++++++++++++++++++ tools/scripts/versal2/mk_board_dtb.sh | 81 ++++++++++++++++++++++++++ tools/scripts/versal2/program_jtag.tcl | 42 +++++++++++++ tools/scripts/versal2/versal2_boot.bif | 14 +++++ 6 files changed, 278 insertions(+), 3 deletions(-) create mode 100644 hal/versal2.its create mode 100755 tools/scripts/versal2/mk_board_dtb.sh create mode 100644 tools/scripts/versal2/program_jtag.tcl create mode 100644 tools/scripts/versal2/versal2_boot.bif diff --git a/docs/Targets.md b/docs/Targets.md index c2af49e51f..9b7873638f 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -5060,11 +5060,92 @@ This makes `wolfboot.elf` and the signed test app `test-app/image_v1_signed.bin`. Use `config/examples/versal2_vek385_linux.config` to boot Linux. +### Boot image + +wolfBoot runs after TF-A (BL31). Build upstream TF-A; AMD's prebuilt TF-A +starts OP-TEE first and cannot be used: + +```sh +git clone https://github.com/ARM-software/arm-trusted-firmware.git +cd arm-trusted-firmware +git checkout da5a281eeb92 +make PLAT=versal2 RESET_TO_BL31=1 CROSS_COMPILE=aarch64-linux-gnu- \ + MEM_BASE=0x1600000 MEM_SIZE=0x200000 bl31 +``` + +Get AMD's `base-design.pdi` and `cortexa78-linux.dtb` from +`github.com/Xilinx/soc-prebuilt-firmware` (branch `xlnx_rel_v2026.1`, folder +`vek385-versal_2ve_2vm`). Put them in one folder with TF-A's +`build/versal2/release/bl31/bl31.elf`, `wolfboot.elf` and +`tools/scripts/versal2/versal2_boot.bif`, name the DTB `system.dtb`, and +build the boot image there: + +```sh +bootgen -arch versal_2ve_2vm -image versal2_boot.bif -w -o boot.pdi +``` + +### Run the test app (JTAG) + +Set boot mode JTAG (SW1 = `0000`). Write the signed test app to BOOT with +AMD's `program_flash`, then load the boot image: + +```sh +program_flash -f test-app/image_v1_signed.bin -offset 0x1DC0000 \ + -pdi base-design.pdi -flash_type ospi-x8-single -verify +xsdb tools/scripts/versal2/program_jtag.tcl boot.pdi +``` + +wolfBoot and the test app print on UART1, the second FT4232 port +(interface B), at 115200 8N1. Load `boot.pdi` again after each +`program_flash`. + +To test an update, build and sign the test app as version 2 and write +`test-app/image_v2_signed.bin` to UPDATE (`-offset 0x49C0000`): + +```sh +make -C test-app clean TARGET=versal2 WOLFBOOT_VERSION=2 +make -C test-app TARGET=versal2 WOLFBOOT_VERSION=2 +tools/keytools/sign --ecc384 --sha384 test-app/image.elf \ + wolfboot_signing_private_key.der 2 +``` + +### Boot from the OSPI flash + +Write `boot.pdi` to the flash and set boot mode OSPI (SW1 = `0001`): + +```sh +program_flash -f boot.pdi -offset 0 -pdi base-design.pdi \ + -flash_type ospi-x8-single -verify +``` + +Offset 0 is for a flash without AMD's boot images. On a flash with AMD's +Image Selector, write it to the start of Bank A instead +(`-offset 0x15C0000`; not tested with AMD's Image Selector). + +### Boot Linux + +1. Build wolfBoot with `config/examples/versal2_vek385_linux.config` and + build `boot.pdi` again with the new `wolfboot.elf`. +2. Make the kernel DTB from AMD's DTB: + `tools/scripts/versal2/mk_board_dtb.sh cortexa78-linux.dtb kernel.dtb`. +3. Put `Image.gz`, `kernel.dtb` and `initramfs.cpio.gz` in the wolfBoot + directory, then build and sign the FIT: + + ```sh + mkimage -f hal/versal2.its fitImage + tools/keytools/sign --ecc384 --sha384 fitImage \ + wolfboot_signing_private_key.der 1 + ``` +4. Write `fitImage_v1_signed.bin` to BOOT (`-offset 0x1DC0000`) and boot as + above. wolfBoot boots the higher version, so the FIT needs a higher + version than an image left in UPDATE. + ### Not yet supported - XIP, the indirect OSPI write path and the system watchdog. - wolfHAL timeouts: the board is built with `WHAL_CFG_NO_TIMEOUT`, so a flash or UART that never answers makes wolfBoot hang. +- High DDR for Linux: `mk_board_dtb.sh` keeps the low 2 GB only. ## Infineon PSoC 6 diff --git a/hal/boards/vek385/wolfHAL_board.c b/hal/boards/vek385/wolfHAL_board.c index 552bcd3975..4ffa6c4149 100644 --- a/hal/boards/vek385/wolfHAL_board.c +++ b/hal/boards/vek385/wolfHAL_board.c @@ -136,8 +136,8 @@ whal_SpiMem g_wbOspi = { }, }; -/* MT35XU02G, 1-bit, 4-byte opcodes: read 13h, program 12h, erase DCh 128 KB - * (Table 21). Only this ID; reset and volatile 1-bit (81h), never B1h. */ +/* MT35XU02G, 1-bit, 4-byte opcodes (Table 21). Only this ID; resets (octal + * DDR first: the PLM leaves it there) and volatile 1-bit (81h), never B1h. */ static whal_Timeout vek385_flash_timeout = { VEK385_FLASH_TIMEOUT_US, 0, vek385_tick_us }; @@ -152,7 +152,8 @@ whal_Flash g_wbExtFlash = { .readDummy = 0, .progOp = OSPI_OP_PAGE_PROGRAM4, .eraseOp = OSPI_OP_ERASE4_128K, - .flags = WHAL_SPIMEM_NOR_FLAG_RESET, + .flags = WHAL_SPIMEM_NOR_FLAG_RESET | + WHAL_SPIMEM_NOR_FLAG_RESET_OCTAL_DTR, .id = VERSAL2_FLASH_JEDEC_ID, .errOp = WHAL_SPIMEM_NOR_MT35X_ERR_OP, .errMask = WHAL_SPIMEM_NOR_MT35X_ERR_MASK, diff --git a/hal/versal2.its b/hal/versal2.its new file mode 100644 index 0000000000..b276ff9929 --- /dev/null +++ b/hal/versal2.its @@ -0,0 +1,56 @@ +/dts-v1/; + +/* FIT for config/examples/versal2_vek385_linux.config. Image.gz, kernel.dtb + * and initramfs.cpio.gz are read from the wolfBoot directory. */ +/ { + description = "AMD Versal Gen 2 VEK385 - wolfBoot Linux"; + #address-cells = <1>; + + images { + kernel-1 { + description = "Linux Kernel"; + data = /incbin/("../Image.gz"); + type = "kernel"; + arch = "arm64"; + os = "linux"; + compression = "gzip"; + load = <0x24000000>; + entry = <0x24000000>; + hash-1 { + algo = "sha256"; + }; + }; + /* No load address: wolfBoot copies it to WOLFBOOT_LOAD_DTS_ADDRESS. */ + fdt-1 { + description = "Board DTB (tools/scripts/versal2/mk_board_dtb.sh)"; + data = /incbin/("../kernel.dtb"); + type = "flat_dt"; + arch = "arm64"; + compression = "none"; + hash-1 { + algo = "sha256"; + }; + }; + ramdisk-1 { + description = "initramfs"; + data = /incbin/("../initramfs.cpio.gz"); + type = "ramdisk"; + arch = "arm64"; + os = "linux"; + compression = "gzip"; + load = <0x30000000>; + hash-1 { + algo = "sha256"; + }; + }; + }; + configurations { + default = "conf1"; + conf1 { + description = "Linux kernel, DTB and initramfs"; + kernel = "kernel-1"; + fdt = "fdt-1"; + ramdisk = "ramdisk-1"; + }; + }; +}; diff --git a/tools/scripts/versal2/mk_board_dtb.sh b/tools/scripts/versal2/mk_board_dtb.sh new file mode 100755 index 0000000000..63d9502961 --- /dev/null +++ b/tools/scripts/versal2/mk_board_dtb.sh @@ -0,0 +1,81 @@ +#!/bin/bash +# +# mk_board_dtb.sh - Make the Linux DTB for the VEK385 board from AMD's +# VEK385 Rev B Linux DTB (cortexa78-linux.dtb in AMD's +# soc-prebuilt-firmware, the same file as the system.dtb in the board +# BIF). It goes in the Linux FIT. +# +# Changes, nothing else: +# 1. /chosen/bootargs: console on UART1 (the UART wolfBoot uses) and +# rdinit=/init (the FIT ramdisk is the root filesystem). +# 2. Memory: low DDR only (0 - 2 GB). The high DDR regions and the CMA +# pools in them are removed (high DDR is not supported yet). +# 3. reserved-memory: BL31 at 0x1600000 (2 MB, MEM_BASE/MEM_SIZE of the +# board TF-A build). AMD's DTB reserves only 0x1000000 - 0x1600000. +# 4. OSPI partitions: wolfBoot BOOT / UPDATE / SWAP, as in +# versal2_vek385_linux.config, in place of AMD's layout. +# +# Usage: +# ./mk_board_dtb.sh +# +set -euo pipefail +IN="${1:?usage: mk_board_dtb.sh }" +OUT="${2:?usage: mk_board_dtb.sh }" +OSPI=/axi/spi@f1010000 +PARTS=$OSPI/flash@0/partitions + +for t in fdtput fdtget dtc; do + command -v $t >/dev/null || { echo "$t not found"; exit 2; } +done +[ -s "$IN" ] || { echo "input DTB missing: $IN"; exit 3; } +MODEL="$(fdtget -t s "$IN" / model)" +[ "$MODEL" = "AMD Versal VEK385 revB" ] \ + || { echo "not the VEK385 Rev B DTB: $MODEL"; exit 3; } + +cp "$IN" "$OUT" + +# 1. Command line +fdtput -t s "$OUT" /chosen bootargs \ + "earlycon=pl011,mmio32,0xf1930000 console=ttyAMA1,115200 rdinit=/init" + +# 2. Low DDR only +fdtput -t x "$OUT" /memory@00000000 reg 0 0 0 80000000 +fdtput -r "$OUT" /memory@50000000000 +fdtput -r "$OUT" /memory@60000000000 +fdtput -r "$OUT" /reserved-memory/cma_reserved@800000000 +fdtput -r "$OUT" /reserved-memory/cma_reserved@50000000000 +fdtput -r "$OUT" /reserved-memory/cma_reserved@60000000000 + +# 3. BL31 +fdtput -c "$OUT" /reserved-memory/bl31@1600000 +fdtput -t x "$OUT" /reserved-memory/bl31@1600000 reg 0 1600000 0 200000 +fdtput "$OUT" /reserved-memory/bl31@1600000 no-map + +# 4. OSPI partitions +fdtput -r "$OUT" $PARTS +fdtput -c "$OUT" $PARTS +fdtput -t s "$OUT" $PARTS compatible "fixed-partitions" +fdtput -t x "$OUT" $PARTS "#address-cells" 1 +fdtput -t x "$OUT" $PARTS "#size-cells" 1 +add_part() { + fdtput -c "$OUT" "$PARTS/partition@$1" + fdtput -t x "$OUT" "$PARTS/partition@$1" reg "$1" "$2" + fdtput -t s "$OUT" "$PARTS/partition@$1" label "$3" +} +# fdtput -c puts a new node first, so add them last to first. +add_part fa40000 20000 swap +add_part 49c0000 2c00000 update +add_part 1dc0000 2c00000 boot + +# Check +dtc -I dtb -O dts -q "$OUT" > /dev/null || { echo "bad DTB"; exit 4; } +[ "$(fdtget -t x "$OUT" /memory@00000000 reg)" = "0 0 0 80000000" ] \ + || { echo "memory reg wrong"; exit 4; } +[ "$(fdtget -t x "$OUT" /reserved-memory/bl31@1600000 reg)" \ + = "0 1600000 0 200000" ] || { echo "bl31 reg wrong"; exit 4; } +[ "$(fdtget -l "$OUT" $PARTS | tr '\n' ' ')" \ + = "partition@1dc0000 partition@49c0000 partition@fa40000 " ] \ + || { echo "partitions wrong"; exit 4; } + +echo "board DTB: $OUT ($(stat -c %s "$OUT") bytes)" +echo "BOARD-DTB-OK" diff --git a/tools/scripts/versal2/program_jtag.tcl b/tools/scripts/versal2/program_jtag.tcl new file mode 100644 index 0000000000..91ba396884 --- /dev/null +++ b/tools/scripts/versal2/program_jtag.tcl @@ -0,0 +1,42 @@ +# Program a VEK385 boot PDI over JTAG (boot mode must be JTAG, SW1 = 0000). +# Usage: xsdb program_jtag.tcl +# The PDI carries TF-A and wolfBoot, so there is no separate ELF +# download. Prints PROGRAM_JTAG_OK. + +if {$argc < 1} { + puts stderr "usage: xsdb program_jtag.tcl " + exit 2 +} +set pdi [lindex $argv 0] +if {![file exists $pdi]} { + puts stderr "ERROR: file not found: $pdi" + exit 2 +} + +connect +puts "JTAG targets:" +puts [targets] + +# A running PLM rejects a full boot PDI, so re-run the BootROM first. +targets -set -nocase -filter {name =~ "*A78*#0.0"} +puts "System reset ..." +rst -system +after 3000 + +targets -set -nocase -filter {name =~ "Versal*"} +puts "Programming PDI: $pdi" +if {[catch {device program $pdi} err]} { + puts stderr "ERROR: device program failed: $err" + catch {puts stderr "PLM log:\n[plm log]"} + exit 3 +} +# Give the PLM time to load TF-A and wolfBoot. +after 3000 + +puts "JTAG targets after boot:" +puts [targets] +puts "PLM log:" +catch {puts [plm log]} +puts "PROGRAM_JTAG_OK" +disconnect +exit 0 diff --git a/tools/scripts/versal2/versal2_boot.bif b/tools/scripts/versal2/versal2_boot.bif new file mode 100644 index 0000000000..c8eadbe371 --- /dev/null +++ b/tools/scripts/versal2/versal2_boot.bif @@ -0,0 +1,14 @@ +/* VEK385 boot image: AMD's base design PDI, then the board DTB, TF-A + * BL31 (EL3) and wolfBoot (EL2). See docs/Targets.md, "Board (JTAG)". */ +the_ROM_image: +{ + image { + { type=bootimage, file=base-design.pdi } + } + image { + id = 0x1c000000, name=apu_subsystem + { type=raw, load=0x1000000, file=system.dtb } + { core=a78-0, exception_level=el-3, trustzone, file=bl31.elf } + { core=a78-0, exception_level=el-2, file=wolfboot.elf } + } +} From 5290e9c8fc6ca528504ca35a390aab1e6aefa361 Mon Sep 17 00:00:00 2001 From: night1rider Date: Tue, 17 Nov 2026 16:16:43 -0700 Subject: [PATCH 3/3] versal2: add unit tests for the wolfHAL glue Host unit tests for the ext_flash code and partition guard, uart_write and the internal flash calls of hal/wolfhal.c, on mock wolfHAL devices. --- .../workflows/test-external-library-paths.yml | 3 +- .gitignore | 7 + tools/unit-tests/Makefile | 60 +++ tools/unit-tests/unit-wolfhal-ext-flash.c | 445 ++++++++++++++++++ tools/unit-tests/unit-wolfhal-uart-flash.c | 295 ++++++++++++ 5 files changed, 809 insertions(+), 1 deletion(-) create mode 100644 tools/unit-tests/unit-wolfhal-ext-flash.c create mode 100644 tools/unit-tests/unit-wolfhal-uart-flash.c diff --git a/.github/workflows/test-external-library-paths.yml b/.github/workflows/test-external-library-paths.yml index a94ce1c0a1..a9efd6ba46 100644 --- a/.github/workflows/test-external-library-paths.yml +++ b/.github/workflows/test-external-library-paths.yml @@ -90,4 +90,5 @@ jobs: WOLFBOOT_LIB_WOLFPSA="$(realpath ../external-libs/wolfPSA)" \ WOLFBOOT_LIB_WOLFTPM="$(realpath ../external-libs/wolfTPM)" \ WOLFBOOT_LIB_WOLFHSM="$(realpath ../external-libs/wolfHSM)" \ - WOLFBOOT_LIB_WOLFCOSE="$(realpath ../external-libs/wolfCOSE)" + WOLFBOOT_LIB_WOLFCOSE="$(realpath ../external-libs/wolfCOSE)" \ + WOLFBOOT_LIB_WOLFHAL="$(realpath ../external-libs/wolfHAL)" diff --git a/.gitignore b/.gitignore index b25caae9eb..019d19fbd1 100644 --- a/.gitignore +++ b/.gitignore @@ -549,6 +549,11 @@ tools/unit-tests/unit-t2080-fman-loader tools/unit-tests/unit-ti-hercules-write tools/unit-tests/unit-versal-ext-write tools/unit-tests/unit-versal-qspi-dma +tools/unit-tests/unit-wolfhal-ext-flash +tools/unit-tests/unit-wolfhal-ext-flash-intboot +tools/unit-tests/unit-wolfhal-ext-flash-intswap +tools/unit-tests/unit-wolfhal-uart-flash +tools/unit-tests/unit-wolfhal-uart-flash-intflash tools/unit-tests/unit-xspi-tfd-index tools/unit-tests/unit-zynq-erase-loop tools/unit-tests/unit-zynq-ext-write @@ -575,6 +580,8 @@ tools/unit-tests/versal_ext_write_extract.h tools/unit-tests/versal_host.c tools/unit-tests/versal_host.h tools/unit-tests/versal_qspidev_extract.h +tools/unit-tests/wolfhal_ext_flash_extract.h +tools/unit-tests/wolfhal_uart_flash_extract.h tools/unit-tests/zynq_erase_extract.h tools/unit-tests/zynq_write_extract.h tools/unit-tests/unit-sign-header-failure diff --git a/tools/unit-tests/Makefile b/tools/unit-tests/Makefile index 24c1245162..5f091c709e 100644 --- a/tools/unit-tests/Makefile +++ b/tools/unit-tests/Makefile @@ -22,6 +22,7 @@ WOLFBOOT_LIB_WOLFPSA?=../../lib/wolfPSA WOLFBOOT_LIB_WOLFTPM?=../../lib/wolfTPM WOLFBOOT_LIB_WOLFHSM?=../../lib/wolfHSM WOLFBOOT_LIB_WOLFCOSE?=../../lib/wolfCOSE +WOLFBOOT_LIB_WOLFHAL?=../../lib/wolfHAL ifeq ($(wildcard $(WOLFBOOT_LIB_WOLFPSA)),) WOLFBOOT_LIB_WOLFPSA=../../../external-libs/wolfPSA @@ -35,6 +36,9 @@ endif ifeq ($(wildcard $(WOLFBOOT_LIB_WOLFCOSE)),) WOLFBOOT_LIB_WOLFCOSE=../../../external-libs/wolfCOSE endif +ifeq ($(wildcard $(WOLFBOOT_LIB_WOLFHAL)),) +WOLFBOOT_LIB_WOLFHAL=../../../external-libs/wolfHAL +endif # Convert to absolute paths for standalone usage WOLFBOOT_LIB_WOLFSSL:=$(abspath $(WOLFBOOT_LIB_WOLFSSL)) @@ -43,6 +47,7 @@ WOLFBOOT_LIB_WOLFPSA:=$(abspath $(WOLFBOOT_LIB_WOLFPSA)) WOLFBOOT_LIB_WOLFTPM:=$(abspath $(WOLFBOOT_LIB_WOLFTPM)) WOLFBOOT_LIB_WOLFHSM:=$(abspath $(WOLFBOOT_LIB_WOLFHSM)) WOLFBOOT_LIB_WOLFCOSE:=$(abspath $(WOLFBOOT_LIB_WOLFCOSE)) +WOLFBOOT_LIB_WOLFHAL:=$(abspath $(WOLFBOOT_LIB_WOLFHAL)) CFLAGS=-I. -I../../src -I../../include -I$(WOLFBOOT_LIB_WOLFSSL) CFLAGS+=-g -ggdb @@ -173,6 +178,11 @@ TESTS+=unit-imx95-disk TESTS+=unit-versal-ext-write TESTS+=unit-versal-wdt TESTS+=unit-versal-uart-rx +TESTS+=unit-wolfhal-ext-flash +TESTS+=unit-wolfhal-ext-flash-intboot +TESTS+=unit-wolfhal-ext-flash-intswap +TESTS+=unit-wolfhal-uart-flash +TESTS+=unit-wolfhal-uart-flash-intflash TESTS+=unit-raspi3-uart-rx TESTS+=unit-mpfs-wdt TESTS+=unit-t10xx-qe-firmware @@ -2007,6 +2017,56 @@ versal_uart_rx_extract.h: ../../hal/versal.c unit-versal-uart-rx: unit-versal-uart-rx.c versal_uart_rx_extract.h versal_host.h gcc -o $@ unit-versal-uart-rx.c -DARCH_AARCH64 -DARCH_64BIT $(CFLAGS) $(LDFLAGS) +# unit-wolfhal-ext-flash copies the ext_flash code of hal/wolfhal.c (the +# partition guard and the ext_flash_* glue) and runs it on a mock wolfHAL +# flash device. The wolfHAL drivers below it are tested in wolfHAL +# (lib/wolfHAL/tests). +wolfhal_ext_flash_extract.h: ../../hal/wolfhal.c + sed -n '/^#ifdef EXT_FLASH/,/^#endif \/\* EXT_FLASH/p' $< > $@ + test -s $@ + +unit-wolfhal-ext-flash: unit-wolfhal-ext-flash.c wolfhal_ext_flash_extract.h + gcc -o $@ unit-wolfhal-ext-flash.c \ + $(WOLFBOOT_LIB_WOLFHAL)/src/flash/flash.c \ + -I$(WOLFBOOT_LIB_WOLFHAL) $(CFLAGS) $(LDFLAGS) + +# The same test for a board with BOOT in internal flash (no PART_BOOT_EXT). +unit-wolfhal-ext-flash-intboot: unit-wolfhal-ext-flash.c \ + wolfhal_ext_flash_extract.h + gcc -o $@ unit-wolfhal-ext-flash.c \ + $(WOLFBOOT_LIB_WOLFHAL)/src/flash/flash.c \ + -I$(WOLFBOOT_LIB_WOLFHAL) -DUNIT_BOOT_INTERNAL $(CFLAGS) $(LDFLAGS) + +# The same test for a board with SWAP in internal flash (NO_SWAP_EXT=1). +unit-wolfhal-ext-flash-intswap: unit-wolfhal-ext-flash.c \ + wolfhal_ext_flash_extract.h + gcc -o $@ unit-wolfhal-ext-flash.c \ + $(WOLFBOOT_LIB_WOLFHAL)/src/flash/flash.c \ + -I$(WOLFBOOT_LIB_WOLFHAL) -DUNIT_SWAP_INTERNAL $(CFLAGS) $(LDFLAGS) + +# unit-wolfhal-uart-flash copies uart_write and the internal flash calls +# of hal/wolfhal.c and runs them on mock wolfHAL devices, as on the +# VEK385: '\n' sent as "\r\n", no internal flash. +wolfhal_uart_flash_extract.h: ../../hal/wolfhal.c + sed -n -e '/^#ifdef BOARD_FLASH_DEV/,/^#endif \/\* BOARD_FLASH_DEV/p' \ + -e '/^#ifdef DEBUG_UART/,/^#endif \/\* DEBUG_UART/p' $< > $@ + test -s $@ + +unit-wolfhal-uart-flash: unit-wolfhal-uart-flash.c \ + wolfhal_uart_flash_extract.h + gcc -o $@ unit-wolfhal-uart-flash.c \ + $(WOLFBOOT_LIB_WOLFHAL)/src/uart/uart.c \ + $(WOLFBOOT_LIB_WOLFHAL)/src/flash/flash.c \ + -I$(WOLFBOOT_LIB_WOLFHAL) $(CFLAGS) $(LDFLAGS) + +# The same test for a board with internal flash and a plain uart_write. +unit-wolfhal-uart-flash-intflash: unit-wolfhal-uart-flash.c \ + wolfhal_uart_flash_extract.h + gcc -o $@ unit-wolfhal-uart-flash.c \ + $(WOLFBOOT_LIB_WOLFHAL)/src/uart/uart.c \ + $(WOLFBOOT_LIB_WOLFHAL)/src/flash/flash.c \ + -I$(WOLFBOOT_LIB_WOLFHAL) -DUNIT_INTERNAL_FLASH $(CFLAGS) $(LDFLAGS) + # unit-raspi3-uart-rx runs the real uart_rx() from hal/raspi3.c, the # other PL011 console in the tree, against an emulated register block. # Its accessors are absolute MMIO pointers, so the function is extracted diff --git a/tools/unit-tests/unit-wolfhal-ext-flash.c b/tools/unit-tests/unit-wolfhal-ext-flash.c new file mode 100644 index 0000000000..b3b6089169 --- /dev/null +++ b/tools/unit-tests/unit-wolfhal-ext-flash.c @@ -0,0 +1,445 @@ +/* unit-wolfhal-ext-flash.c + * + * Tests the hal/wolfhal.c ext_flash code (partition guard, whal_Flash_* + * calls) on a mock flash. WOLFBOOT_SECTOR_SIZE in the env sets SWAP size. + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include +#include +#include +#include + +#include + +/* Partitions from config/examples/versal2_vek385.config. BOOT starts + * at 0x1DC0000, after the 8 MB BOOT.BIN area. */ +#define WOLFBOOT_PARTITION_BOOT_ADDRESS 0x1DC0000UL +#define WOLFBOOT_PARTITION_SIZE 0x2C00000UL +#define WOLFBOOT_SECTOR_SIZE 0x20000UL +#define TEST_UPDATE_ADDRESS 0x49C0000UL +#define TEST_SWAP_ADDRESS 0xFA40000UL + +/* UPDATE and SWAP are variables here, so a test can move UPDATE or SWAP + * and change the UPDATE size. */ +static uint32_t test_update_addr = TEST_UPDATE_ADDRESS; +static uint32_t test_update_size = WOLFBOOT_PARTITION_SIZE; +static uint32_t test_swap_addr = TEST_SWAP_ADDRESS; +#define WOLFBOOT_PARTITION_UPDATE_ADDRESS test_update_addr +#define WOLFBOOT_PARTITION_UPDATE_SIZE test_update_size +#define WOLFBOOT_PARTITION_SWAP_ADDRESS test_swap_addr + +/* All three partitions are in the external flash on the VEK385. A build + * with UNIT_BOOT_INTERNAL or UNIT_SWAP_INTERNAL has that one internal. */ +#define EXT_FLASH 1 +#define PART_UPDATE_EXT 1 +#ifndef UNIT_SWAP_INTERNAL +#define PART_SWAP_EXT 1 +#define SWAP_ALLOWED 1 +#else +#define SWAP_ALLOWED 0 +#endif +#ifndef UNIT_BOOT_INTERNAL +#define PART_BOOT_EXT 1 +#define BOOT_ALLOWED 1 +#else +#define BOOT_ALLOWED 0 +#endif + +/* BOOT.BIN area: 0x15C0000-0x1DBFFFF (8 MB). AMD's BOOT.BIN ends at + * 0x1B0FE40, so a 4 MB area would overlap it at 0x19C0000-0x1B0FE40. */ +#define BOOTBIN_RESERVATION_START 0x15C0000UL +#define BOOTBIN_OLD_OVERLAP_START 0x19C0000UL + +/* ------------------------------------------------------------------ */ +/* Mock flash device (records the whal_Flash calls) */ +/* ------------------------------------------------------------------ */ + +static int fl_reads, fl_writes, fl_erases; +static size_t fl_addr, fl_len; +static whal_Error fl_ret; + +static whal_Error MockFlashRead(whal_Flash *d, size_t addr, void *data, + size_t sz) +{ + (void)d; + (void)data; + fl_reads++; + fl_addr = addr; + fl_len = sz; + return fl_ret; +} + +static whal_Error MockFlashWrite(whal_Flash *d, size_t addr, + const void *data, size_t sz) +{ + (void)d; + (void)data; + fl_writes++; + fl_addr = addr; + fl_len = sz; + return fl_ret; +} + +static whal_Error MockFlashErase(whal_Flash *d, size_t addr, size_t sz) +{ + (void)d; + fl_erases++; + fl_addr = addr; + fl_len = sz; + return fl_ret; +} + +static const whal_FlashDriver mockFlashDriver = { + .Read = MockFlashRead, + .Write = MockFlashWrite, + .Erase = MockFlashErase, +}; + +static whal_Flash mock_flash = { 0, &mockFlashDriver, NULL }; +#define BOARD_EXT_FLASH_DEV (&mock_flash) + +/* SWAP sector size: the config value, or the WOLFBOOT_SECTOR_SIZE + * environment variable if set ("make run" sets it to 0x400). */ +static uint32_t test_sector_size(void) +{ + const char *e = getenv("WOLFBOOT_SECTOR_SIZE"); + + if (e != NULL) { + unsigned long v = strtoul(e, NULL, 0); + + if (v != 0) { + return (uint32_t)v; + } + } + return (uint32_t)WOLFBOOT_SECTOR_SIZE; +} + +/* The real ext_flash code, extracted from hal/wolfhal.c. */ +#include "wolfhal_ext_flash_extract.h" + +static int flash_calls(void) +{ + return fl_reads + fl_writes + fl_erases; +} + +/* ------------------------------------------------------------------ */ +/* Address guard */ +/* ------------------------------------------------------------------ */ + +START_TEST(test_addr_guard_accepts_partitions) +{ + ck_assert_msg(wolfhal_ext_flash_guard_ok(0x1DC0000, 0x1000) == + BOOT_ALLOWED, "BOOT start"); + ck_assert_msg(wolfhal_ext_flash_guard_ok(0x1DC0000 + 0x2C00000 - 0x1000, + 0x1000) == BOOT_ALLOWED, "BOOT tail"); + ck_assert_msg(wolfhal_ext_flash_guard_ok(0x49C0000, 0x20000) == 1, + "UPDATE 128 KB"); + ck_assert_msg(wolfhal_ext_flash_guard_ok(0x49C0000 + 0x2C00000 - 0x20000, + 0x20000) == 1, + "UPDATE last 128 KB"); + ck_assert_msg(wolfhal_ext_flash_guard_ok(0xFA40000, test_sector_size()) == + SWAP_ALLOWED, "SWAP (full sector)"); + ck_assert_msg(wolfhal_ext_flash_guard_ok(0x2000000, 0x100) == + BOOT_ALLOWED, "mid-BOOT program"); +} +END_TEST + +START_TEST(test_addr_guard_refuses_out_of_range) +{ + /* AMD Image Selector / Image Recovery / metadata. */ + ck_assert_msg(wolfhal_ext_flash_guard_ok(0x0000000, 0x1000) == 0, + "Image Selector @0"); + ck_assert_msg(wolfhal_ext_flash_guard_ok(0x0100000, 0x1000) == 0, + "recovery @0x100000"); + /* Bank A past the partitions and DTS slots, and Bank B. */ + ck_assert_msg(wolfhal_ext_flash_guard_ok(0x08000000, 0x1000) == 0, + "Bank A tail"); + ck_assert_msg(wolfhal_ext_flash_guard_ok(0x08800000, 0x1000) == 0, + "Bank B"); + /* Past the end of UPDATE, and a 128 KB block straddling it. */ + ck_assert_msg(wolfhal_ext_flash_guard_ok(0x49C0000 + 0x2C00000, + 0x1000) == 0, + "UPDATE tail overrun"); + ck_assert_msg(wolfhal_ext_flash_guard_ok(0x49C0000 + 0x2C00000 - 0x10000, + 0x20000) == 0, + "128 KB straddling UPDATE end"); + /* Past the end of SWAP (for any sector size). */ + ck_assert_msg(wolfhal_ext_flash_guard_ok(0xFA40000 + test_sector_size() + - 0x400, 0x800) == 0, + "SWAP overrun"); + ck_assert_msg(wolfhal_ext_flash_guard_ok(0x1DC0000, 0) == 0, "zero length"); +} +END_TEST + +/* Every erase and program in the 8 MB BOOT.BIN area is refused before + * the flash driver is called. */ +START_TEST(test_bootbin_reservation_refused) +{ + uint8_t buf[16]; + uint32_t addr; + + memset(buf, 0x5A, sizeof(buf)); + for (addr = BOOTBIN_RESERVATION_START; addr <= 0x1DA0000; + addr += 0x20000) { + ck_assert_msg(ext_flash_erase(addr, 0x20000) == -1, + "erase at 0x%08lX accepted", (unsigned long)addr); + ck_assert_msg(ext_flash_write(addr, buf, sizeof(buf)) == -1, + "write at 0x%08lX accepted", (unsigned long)addr); + } + ck_assert_msg(ext_flash_erase(BOOTBIN_OLD_OVERLAP_START, 0x20000) == -1, + "erase at the overlap start accepted"); + ck_assert_msg(ext_flash_write(0x1B0F000, buf, sizeof(buf)) == -1, + "write in the overlap area accepted"); + ck_assert_msg(flash_calls() == 0, "a refused request reached the flash"); +} +END_TEST + +START_TEST(test_ext_flash_refuses_outside_partitions) +{ + uint8_t buf[8] = { 0 }; + + ck_assert_int_eq(ext_flash_write(0x0, buf, sizeof(buf)), -1); + ck_assert_int_eq(ext_flash_write(0x08800000, buf, sizeof(buf)), -1); + ck_assert_int_eq(ext_flash_erase(0x49C0000 + 0x2C00000 - 0x10000, + 0x20000), -1); + ck_assert_int_eq(ext_flash_erase(0x0, 0x20000), -1); + ck_assert_msg(flash_calls() == 0, "a refused request reached the flash"); +} +END_TEST + +/* ------------------------------------------------------------------ */ +/* ext_flash_* glue */ +/* ------------------------------------------------------------------ */ + +/* An address above 4 GB must not be cut down into a partition. */ +START_TEST(test_ext_flash_refuses_above_4g) +{ +#if UINTPTR_MAX > 0xFFFFFFFFUL + uint8_t buf[16] = {0}; + uintptr_t high = (uintptr_t)0x100000000ULL + 0x49C0000UL; + + ck_assert_int_eq(ext_flash_write(high, buf, sizeof(buf)), -1); + ck_assert_int_eq(ext_flash_erase(high, 0x20000), -1); + ck_assert_msg(flash_calls() == 0, "a refused request reached the flash"); +#endif +} +END_TEST + +/* A partition that would run past 4 GB is not a valid range. */ +START_TEST(test_addr_guard_refuses_wrapping_partition) +{ + ck_assert_int_eq(wolfhal_range_in_partition(0xFFFFF000U, 0x2000U, + 0xFFFFF000U, 0x100U), 0); +} +END_TEST + +/* UPDATE or SWAP at offset 0 of the external flash is a normal layout. */ +START_TEST(test_addr_guard_partition_at_offset_zero) +{ + uint8_t buf[16] = { 0 }; + + test_update_addr = 0; + ck_assert_int_eq(wolfhal_ext_flash_guard_ok(0, 0x20000), 1); + ck_assert_int_eq(ext_flash_write(0, buf, sizeof(buf)), 0); + ck_assert_int_eq(ext_flash_erase(0, 0x20000), 0); + ck_assert_int_eq(fl_writes + fl_erases, 2); + test_update_addr = TEST_UPDATE_ADDRESS; + + test_swap_addr = 0; + ck_assert_int_eq(wolfhal_ext_flash_guard_ok(0, test_sector_size()), + SWAP_ALLOWED); + ck_assert_int_eq(wolfhal_ext_flash_guard_ok(test_sector_size(), 0x100), + 0); +} +END_TEST + +/* UPDATE ends at the UPDATE size, which can differ from the BOOT size. */ +START_TEST(test_addr_guard_uses_update_size) +{ + uint32_t end = TEST_UPDATE_ADDRESS + WOLFBOOT_PARTITION_SIZE; + + /* Smaller UPDATE: the sector after it is not UPDATE. */ + test_update_size = WOLFBOOT_PARTITION_SIZE - 0x20000; + ck_assert_int_eq(wolfhal_ext_flash_guard_ok(end - 0x40000, 0x20000), 1); + ck_assert_int_eq(wolfhal_ext_flash_guard_ok(end - 0x20000, 0x20000), 0); + /* Larger UPDATE: its last sector (the trailer) is allowed. */ + test_update_size = WOLFBOOT_PARTITION_SIZE + 0x20000; + ck_assert_int_eq(wolfhal_ext_flash_guard_ok(end, 0x20000), 1); + ck_assert_int_eq(wolfhal_ext_flash_guard_ok(end + 0x20000, 0x20000), 0); +} +END_TEST + +/* BOOT is only allowed when it is in the external flash. */ +START_TEST(test_addr_guard_boot_needs_part_boot_ext) +{ + uint8_t buf[16] = { 0 }; + + ck_assert_int_eq(wolfhal_ext_flash_guard_ok(0x1DC0000, 0x20000), + BOOT_ALLOWED); +#ifdef UNIT_BOOT_INTERNAL + ck_assert_int_eq(ext_flash_write(0x1DC0000, buf, sizeof(buf)), -1); + ck_assert_int_eq(ext_flash_erase(0x1DC0000, 0x20000), -1); + ck_assert_msg(flash_calls() == 0, "a refused request reached the flash"); +#else + ck_assert_int_eq(ext_flash_write(0x1DC0000, buf, sizeof(buf)), 0); + ck_assert_int_eq(ext_flash_erase(0x1DC0000, 0x20000), 0); +#endif +} +END_TEST + +/* SWAP is only allowed when it is in the external flash. */ +START_TEST(test_addr_guard_swap_needs_part_swap_ext) +{ + uint8_t buf[16] = { 0 }; + + ck_assert_int_eq(wolfhal_ext_flash_guard_ok(0xFA40000, 0x400), + SWAP_ALLOWED); +#ifdef UNIT_SWAP_INTERNAL + ck_assert_int_eq(ext_flash_write(0xFA40000, buf, sizeof(buf)), -1); + ck_assert_int_eq(ext_flash_erase(0xFA40000, 0x400), -1); + ck_assert_msg(flash_calls() == 0, "a refused request reached the flash"); +#else + ck_assert_int_eq(ext_flash_write(0xFA40000, buf, sizeof(buf)), 0); + ck_assert_int_eq(ext_flash_erase(0xFA40000, 0x400), 0); +#endif +} +END_TEST + +/* Lock and unlock are passed to the flash device and touch no data. The + * mock has neither, like the NOR driver, which answers "not supported". */ +START_TEST(test_ext_flash_lock_unlock) +{ + ext_flash_unlock(); + ext_flash_lock(); + ck_assert_msg(flash_calls() == 0, "lock or unlock reached the flash data"); +} +END_TEST + +START_TEST(test_ext_flash_passes_requests) +{ + uint8_t buf[300]; + + memset(buf, 0, sizeof(buf)); + /* Write and erase return 0 on success, not the length. */ + ck_assert_int_eq(ext_flash_write(0x49C0100, buf, 300), 0); + ck_assert_int_eq(fl_writes, 1); + ck_assert_uint_eq(fl_addr, 0x49C0100); + ck_assert_uint_eq(fl_len, 300); + + ck_assert_int_eq(ext_flash_erase(0x49C0000, 0x40000), 0); + ck_assert_int_eq(fl_erases, 1); + ck_assert_uint_eq(fl_addr, 0x49C0000); + ck_assert_uint_eq(fl_len, 0x40000); + + /* Reads are not guarded: any address goes to the driver. */ + ck_assert_int_eq(ext_flash_read(0x0, buf, 64), 64); + ck_assert_int_eq(fl_reads, 1); + ck_assert_uint_eq(fl_addr, 0x0); + ck_assert_uint_eq(fl_len, 64); +} +END_TEST + +START_TEST(test_ext_flash_driver_error) +{ + uint8_t buf[16] = { 0 }; + + fl_ret = WHAL_EHARDWARE; + ck_assert_int_eq(ext_flash_write(0x49C0000, buf, sizeof(buf)), -1); + ck_assert_int_eq(ext_flash_erase(0x49C0000, 0x20000), -1); + ck_assert_int_eq(ext_flash_read(0x49C0000, buf, sizeof(buf)), -1); +} +END_TEST + +START_TEST(test_ext_flash_empty_requests) +{ + uint8_t buf[4] = { 0 }; + + ck_assert_int_eq(ext_flash_write(0x49C0000, buf, 0), 0); + ck_assert_int_eq(ext_flash_erase(0x49C0000, 0), 0); + /* 0 means success now, so a write with no data is an error. */ + ck_assert_int_eq(ext_flash_write(0x49C0000, NULL, 4), -1); + ck_assert_int_eq(ext_flash_write(0x49C0000, buf, -1), -1); + ck_assert_int_eq(ext_flash_erase(0x49C0000, -1), -1); + ck_assert_int_eq(ext_flash_read(0x49C0000, buf, 0), 0); + ck_assert_int_eq(ext_flash_read(0x49C0000, NULL, 4), 0); + ck_assert_msg(flash_calls() == 0, "an empty request reached the flash"); +} +END_TEST + +/* ------------------------------------------------------------------ */ + +static void setup(void) +{ + fl_reads = 0; + fl_writes = 0; + fl_erases = 0; + fl_addr = 0; + fl_len = 0; + fl_ret = WHAL_SUCCESS; +#ifdef PART_SWAP_EXT + wolfhal_swap_size = test_sector_size(); +#endif + test_update_addr = TEST_UPDATE_ADDRESS; + test_update_size = WOLFBOOT_PARTITION_SIZE; + test_swap_addr = TEST_SWAP_ADDRESS; +} + +static void teardown(void) +{ +} + +Suite *wolfhal_ext_flash_suite(void) +{ + Suite *s = suite_create("wolfhal-ext-flash"); + TCase *tc = tcase_create("wolfhal-ext-flash"); + + tcase_add_checked_fixture(tc, setup, teardown); + tcase_add_test(tc, test_addr_guard_accepts_partitions); + tcase_add_test(tc, test_addr_guard_refuses_out_of_range); + tcase_add_test(tc, test_bootbin_reservation_refused); + tcase_add_test(tc, test_ext_flash_refuses_outside_partitions); + tcase_add_test(tc, test_ext_flash_refuses_above_4g); + tcase_add_test(tc, test_addr_guard_refuses_wrapping_partition); + tcase_add_test(tc, test_addr_guard_partition_at_offset_zero); + tcase_add_test(tc, test_addr_guard_uses_update_size); + tcase_add_test(tc, test_addr_guard_boot_needs_part_boot_ext); + tcase_add_test(tc, test_addr_guard_swap_needs_part_swap_ext); + tcase_add_test(tc, test_ext_flash_lock_unlock); + tcase_add_test(tc, test_ext_flash_passes_requests); + tcase_add_test(tc, test_ext_flash_driver_error); + tcase_add_test(tc, test_ext_flash_empty_requests); + suite_add_tcase(s, tc); + + return s; +} + +int main(void) +{ + int fails; + Suite *s = wolfhal_ext_flash_suite(); + SRunner *sr = srunner_create(s); + + srunner_run_all(sr, CK_NORMAL); + fails = srunner_ntests_failed(sr); + srunner_free(sr); + + return fails; +} diff --git a/tools/unit-tests/unit-wolfhal-uart-flash.c b/tools/unit-tests/unit-wolfhal-uart-flash.c new file mode 100644 index 0000000000..f59dba15de --- /dev/null +++ b/tools/unit-tests/unit-wolfhal-uart-flash.c @@ -0,0 +1,295 @@ +/* unit-wolfhal-uart-flash.c + * + * Tests uart_write and the internal flash calls of hal/wolfhal.c on mock + * wolfHAL devices, for a board without and with internal flash. + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include +#include +#include + +#include + +/* From hal.h and wolfboot.h, which need a target. */ +typedef uintptr_t haladdr_t; +#define RAMFUNCTION + +/* Mock UART: keeps the bytes sent and counts the sends. */ + +#define UART_LOG_SIZE 64 + +static uint8_t uart_log[UART_LOG_SIZE]; +static size_t uart_len; +static int uart_sends; + +static whal_Error MockUartSend(whal_Uart *d, const void *data, size_t sz) +{ + (void)d; + uart_sends++; + if (sz > UART_LOG_SIZE - uart_len) { + return WHAL_EINVAL; + } + memcpy(uart_log + uart_len, data, sz); + uart_len += sz; + return WHAL_SUCCESS; +} + +static const whal_UartDriver mockUartDriver = { + .Send = MockUartSend, +}; + +static whal_Uart mock_uart = { 0, &mockUartDriver, NULL }; +#define BOARD_UART_DEV (&mock_uart) +#define DEBUG_UART + +#ifdef UNIT_INTERNAL_FLASH +/* Mock internal flash: records the whal_Flash calls. */ + +static int fl_locks, fl_unlocks, fl_writes, fl_erases; +static size_t fl_addr, fl_len; +static const void *fl_data; +static whal_Error fl_ret; + +static whal_Error MockFlashLock(whal_Flash *d, size_t addr, size_t len) +{ + (void)d; + (void)addr; + (void)len; + fl_locks++; + return WHAL_SUCCESS; +} + +static whal_Error MockFlashUnlock(whal_Flash *d, size_t addr, size_t len) +{ + (void)d; + (void)addr; + (void)len; + fl_unlocks++; + return WHAL_SUCCESS; +} + +static whal_Error MockFlashWrite(whal_Flash *d, size_t addr, + const void *data, size_t sz) +{ + (void)d; + fl_writes++; + fl_addr = addr; + fl_data = data; + fl_len = sz; + return fl_ret; +} + +static whal_Error MockFlashErase(whal_Flash *d, size_t addr, size_t sz) +{ + (void)d; + fl_erases++; + fl_addr = addr; + fl_len = sz; + return fl_ret; +} + +static const whal_FlashDriver mockFlashDriver = { + .Lock = MockFlashLock, + .Unlock = MockFlashUnlock, + .Write = MockFlashWrite, + .Erase = MockFlashErase, +}; + +static whal_Flash mock_flash = { 0, &mockFlashDriver, NULL }; +#define BOARD_FLASH_DEV (&mock_flash) +#else +/* As on the VEK385: no internal flash, and '\n' is sent as "\r\n". */ +#define WOLFHAL_UART_CRLF +#endif /* UNIT_INTERNAL_FLASH */ + +/* The hal/wolfhal.c code under test, copied by the Makefile. */ +#include "wolfhal_uart_flash_extract.h" + +/* The UART got exactly these bytes, in this number of sends. */ +static void uart_expect(const char *want, int sends) +{ + size_t n = strlen(want); + + ck_assert_uint_eq(uart_len, n); + ck_assert_int_eq(memcmp(uart_log, want, n), 0); + ck_assert_int_eq(uart_sends, sends); +} + +/* Only len bytes are sent. */ +START_TEST(test_uart_write_uses_len) +{ + uart_write("abcdef", 2); + uart_expect("ab", 1); +} +END_TEST + +#ifdef WOLFHAL_UART_CRLF +START_TEST(test_uart_write_crlf_lines) +{ + uart_write("ab\ncd\n", 6); + uart_expect("ab\r\ncd\r\n", 4); +} +END_TEST + +/* A newline first, two in a row, and text after the last one. */ +START_TEST(test_uart_write_crlf_edges) +{ + uart_write("\n\nx", 3); + uart_expect("\r\n\r\nx", 3); +} +END_TEST + +/* A newline as the last of the len bytes; the rest is not sent. */ +START_TEST(test_uart_write_crlf_stops_at_len) +{ + uart_write("a\nb\n", 2); + uart_expect("a\r\n", 2); +} +END_TEST + +START_TEST(test_uart_write_crlf_no_newline) +{ + uart_write("abc", 3); + uart_expect("abc", 1); +} +END_TEST + +/* len 0 sends nothing. */ +START_TEST(test_uart_write_crlf_empty) +{ + uart_write("abc", 0); + uart_expect("", 0); +} +END_TEST +#else +/* Without WOLFHAL_UART_CRLF the bytes go out unchanged, in one send. */ +START_TEST(test_uart_write_plain) +{ + uart_write("ab\ncd\n", 6); + uart_expect("ab\ncd\n", 1); +} +END_TEST +#endif /* WOLFHAL_UART_CRLF */ + +#ifdef UNIT_INTERNAL_FLASH +START_TEST(test_hal_flash_passes_requests) +{ + uint8_t b[4] = { 1, 2, 3, 4 }; + + hal_flash_unlock(); + ck_assert_int_eq(fl_unlocks, 1); + ck_assert_int_eq(hal_flash_write(0x8001000, b, 4), 0); + ck_assert_int_eq(fl_writes, 1); + ck_assert_uint_eq(fl_addr, 0x8001000); + ck_assert_uint_eq(fl_len, 4); + ck_assert_ptr_eq(fl_data, b); + ck_assert_int_eq(hal_flash_erase(0x8002000, 0x800), 0); + ck_assert_int_eq(fl_erases, 1); + ck_assert_uint_eq(fl_addr, 0x8002000); + ck_assert_uint_eq(fl_len, 0x800); + hal_flash_lock(); + ck_assert_int_eq(fl_locks, 1); +} +END_TEST + +START_TEST(test_hal_flash_driver_error) +{ + uint8_t b[4] = { 1, 2, 3, 4 }; + + fl_ret = WHAL_EINVAL; + ck_assert_int_ne(hal_flash_write(0x8001000, b, 4), 0); + ck_assert_int_ne(hal_flash_erase(0x8002000, 0x800), 0); +} +END_TEST +#else +/* No internal flash: unlock and lock do nothing, write and erase fail. */ +START_TEST(test_hal_flash_no_internal_flash) +{ + uint8_t b[4] = { 1, 2, 3, 4 }; + + hal_flash_unlock(); + ck_assert_int_eq(hal_flash_write(0x1000, b, 4), -1); + ck_assert_int_eq(hal_flash_erase(0x1000, 0x1000), -1); + hal_flash_lock(); +} +END_TEST +#endif /* UNIT_INTERNAL_FLASH */ + +static void setup(void) +{ + memset(uart_log, 0, sizeof(uart_log)); + uart_len = 0; + uart_sends = 0; +#ifdef UNIT_INTERNAL_FLASH + fl_locks = 0; + fl_unlocks = 0; + fl_writes = 0; + fl_erases = 0; + fl_addr = 0; + fl_len = 0; + fl_data = NULL; + fl_ret = WHAL_SUCCESS; +#endif +} + +static void teardown(void) +{ +} + +Suite *wolfhal_uart_flash_suite(void) +{ + Suite *s = suite_create("wolfhal-uart-flash"); + TCase *tc = tcase_create("wolfhal-uart-flash"); + + tcase_add_checked_fixture(tc, setup, teardown); + tcase_add_test(tc, test_uart_write_uses_len); +#ifdef WOLFHAL_UART_CRLF + tcase_add_test(tc, test_uart_write_crlf_lines); + tcase_add_test(tc, test_uart_write_crlf_edges); + tcase_add_test(tc, test_uart_write_crlf_stops_at_len); + tcase_add_test(tc, test_uart_write_crlf_no_newline); + tcase_add_test(tc, test_uart_write_crlf_empty); +#else + tcase_add_test(tc, test_uart_write_plain); +#endif +#ifdef UNIT_INTERNAL_FLASH + tcase_add_test(tc, test_hal_flash_passes_requests); + tcase_add_test(tc, test_hal_flash_driver_error); +#else + tcase_add_test(tc, test_hal_flash_no_internal_flash); +#endif + suite_add_tcase(s, tc); + + return s; +} + +int main(void) +{ + int fails; + Suite *s = wolfhal_uart_flash_suite(); + SRunner *sr = srunner_create(s); + + srunner_run_all(sr, CK_NORMAL); + fails = srunner_ntests_failed(sr); + srunner_free(sr); + + return fails; +}