diff --git a/.github/workflows/test-configs.yml b/.github/workflows/test-configs.yml index aef24ad2d9..a61ca358ed 100644 --- a/.github/workflows/test-configs.yml +++ b/.github/workflows/test-configs.yml @@ -1911,6 +1911,19 @@ jobs: config-file: ./config/examples/sim.config make-args: WOLFTPM=1 SIM_TPM=1 + rp2040_test: + uses: ./.github/workflows/test-build.yml + with: + arch: arm + config-file: ./config/examples/rp2040.config + + rp2040_dev_aids_test: + uses: ./.github/workflows/test-build.yml + with: + arch: arm + config-file: ./config/examples/rp2040.config + make-args: RP2040_RAM_LOG=1 RP2040_BOOT_GUARD=1 RP2040_XIP_QUAD=2 BOOT_BENCHMARK=1 + rp2350_test: uses: ./.github/workflows/test-build-pico-sdk.yml with: diff --git a/.gitignore b/.gitignore index e58350d14b..76cb0ce648 100644 --- a/.gitignore +++ b/.gitignore @@ -686,6 +686,7 @@ tools/unit-tests/unit-pci-4gib tools/unit-tests/unit-pkcs11-pin-zeroize tools/unit-tests/unit-pkcs11_store-stalecache tools/unit-tests/unit-rp2350-flash-write +tools/unit-tests/unit-rp2040-flash-write tools/unit-tests/unit-samr21-erase-advance tools/unit-tests/unit-samr21-flash-protect tools/unit-tests/unit-sdhci-acmd41-timeout @@ -732,6 +733,7 @@ tools/unit-tests/p1021_erase_fn_extract.h tools/unit-tests/p1021_read_extract.h tools/unit-tests/p1021_read_fn_extract.h tools/unit-tests/rp2350_flash_write_extract.h +tools/unit-tests/rp2040_flash_write_extract.h tools/unit-tests/stm32c0_write_extract.h tools/unit-tests/stm32g4_write_extract.h tools/unit-tests/stm32h7_flash_write_extract.h diff --git a/arch.mk b/arch.mk index 9b55016bc9..c81fb00171 100644 --- a/arch.mk +++ b/arch.mk @@ -975,6 +975,26 @@ ifeq ($(ARCH),ARM) PART_SWAP_EXT=1 endif + ifeq ($(TARGET),rp2040) + CORTEX_M0=1 + CFLAGS+=-Ihal + ARCH_FLASH_OFFSET=0x10000000 + WOLFBOOT_ORIGIN=0x10000000 + RP2040_SYS_MHZ?=125 + CFLAGS+=-DRP2040_SYS_MHZ=$(RP2040_SYS_MHZ) + ifneq ($(filter-out 0,$(RP2040_XIP_QUAD)),) + CFLAGS+=-DRP2040_XIP_QUAD=$(RP2040_XIP_QUAD) + endif + ifeq ($(RP2040_RAM_LOG),1) + CFLAGS+=-DRP2040_RAM_LOG + endif + ifeq ($(RP2040_BOOT_GUARD),1) + CFLAGS+=-DRP2040_BOOT_GUARD + # wolfBoot feeds the guard from its hash and sector-copy loops. + WATCHDOG=1 + endif + endif + ifeq ($(TARGET),rp2350) CORTEX_M33=1 CFLAGS+=-Ihal diff --git a/config/examples/rp2040.config b/config/examples/rp2040.config new file mode 100644 index 0000000000..9c43dfc6e6 --- /dev/null +++ b/config/examples/rp2040.config @@ -0,0 +1,54 @@ +ARCH?=ARM +TARGET?=rp2040 +SIGN?=ECC256 +HASH?=SHA256 +DEBUG?=0 +VTOR?=1 +CORTEX_M0?=1 +NO_ASM?=0 +NO_MPU=1 +EXT_FLASH?=0 +SPI_FLASH?=0 +ALLOW_DOWNGRADE?=0 +NVM_FLASH_WRITEONCE?=0 +WOLFBOOT_VERSION?=1 +V?=0 +SPMATH?=1 +RAM_CODE?=0 +DUALBANK_SWAP?=0 +DEBUG_UART?=1 + +# Cortex-M0+ has no unaligned word access. +CFLAGS_EXTRA+=-DWOLFSSL_USE_ALIGN + +# clk_sys in MHz: 12 runs from the crystal, 63..133 from PLL_SYS. +RP2040_SYS_MHZ?=125 + +# Quad flash read at clk_sys / n (2 or 4), set up by wolfBoot at start and +# inherited by the application; 0 keeps the 03h serial read of the second +# stage. Needs a W25Q-compatible flash with its Quad Enable bit set (if it +# is clear, wolfBoot stays in serial read mode). +RP2040_XIP_QUAD?=0 + +# Console is UART0 at 115200 on GP0 (TX) / GP1 (RX). Other pins: +# CFLAGS_EXTRA+=-DRP2040_UART_TX_PIN=12 -DRP2040_UART_RX_PIN=13 + +# Development aids for a board with no debug probe or UART adapter: +# RP2040_RAM_LOG=1 also keep the console text in the SRAM4 scratch bank +# (0x20040000) for the application to read back; needs +# DEBUG_UART=1 +# RP2040_BOOT_GUARD=1 enter the boot ROM USB loader if wolfBoot hangs or +# finds nothing to boot, instead of staying there +RP2040_RAM_LOG?=0 +RP2040_BOOT_GUARD?=0 + +# 2 MB QSPI flash (Pico, W5100S-EVB-Pico), 4 KB erase sectors: +# 0x10000000 boot2 (256 bytes) + wolfBoot 64 KB +# 0x10010000 BOOT partition 960 KB +# 0x10100000 UPDATE partition 960 KB +# 0x101F0000 SWAP 4 KB +WOLFBOOT_SECTOR_SIZE?=0x1000 +WOLFBOOT_PARTITION_SIZE?=0xF0000 +WOLFBOOT_PARTITION_BOOT_ADDRESS?=0x10010000 +WOLFBOOT_PARTITION_UPDATE_ADDRESS?=0x10100000 +WOLFBOOT_PARTITION_SWAP_ADDRESS?=0x101F0000 diff --git a/docs/Targets.md b/docs/Targets.md index ebf659aa8e..b7bfd0a0c7 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -54,6 +54,7 @@ This README describes configuration of supported targets. * [Qemu x86-64 UEFI](#qemu-x86-64-uefi) * [NVIDIA Jetson Orin (aarch64_efi)](#nvidia-jetson-orin-aarch64_efi) * [NVIDIA Jetson Orin (NVIDIA Tegra234) BL33 firmware](#nvidia-jetson-orin-nvidia-tegra234-bl33-firmware) +* [Raspberry Pi Pico (rp2040)](#raspberry-pi-pico-rp2040) * [Raspberry Pi pico 2 (rp2350)](#raspberry-pi-pico-rp2350) * [RealTek RTL8735B (AmebaPro2)](#realtek-rtl8735b-amebapro2) * [Renesas RA6M4](#renesas-ra6m4) @@ -8503,6 +8504,94 @@ make test-sim-internal-flash-with-update Note: This also works on Mac OS, but `objcopy` does not exist. Install with `brew install binutils` and make using `OBJCOPY=/usr/local/Cellar//binutils/2.41/bin/objcopy make`. +## Raspberry Pi Pico rp2040 + +The RP2040 is a dual Cortex-M0+ with 264 KB of SRAM and no internal flash: code executes in place from an external QSPI NOR flash (2 MB W25Q16 on the Pico and on the WIZnet W5100S-EVB-Pico) mapped at `0x10000000`. This is a native wolfBoot target: no pico-sdk, picotool or CMake is needed. + +The RP2040 has no secure boot and no OTP key storage, and its boot ROM starts whatever is in flash. wolfBoot on this part therefore provides authenticated firmware updates with rollback; it is not a hardware root of trust, because an attacker with write access to the flash can replace wolfBoot itself. + +Hardware-validated on a W5100S-EVB-Pico: boot of a signed image, update with sector swap, rejection of a tampered update and rollback of an unconfirmed one. The UART console was not available on the test setup and is build-tested only. + +### Flash layout + +``` +0x10000000 second-stage boot (256 bytes) + wolfBoot 64 KB +0x10010000 BOOT partition 960 KB +0x10100000 UPDATE partition 960 KB +0x101F0000 SWAP 4 KB +``` + +The boot ROM loads the first 256 bytes of flash to RAM, checks their CRC-32 and runs them. `hal/rp2040.c` carries its own second stage, which puts the flash interface into `03h` serial read mode, a command every SPI NOR flash supports. wolfBoot keeps a copy of it in RAM to return to XIP mode after an erase or program, which are done with the boot ROM flash routines from a single RAM function with interrupts disabled. Interrupts are disabled only on the calling core: an application that writes flash through wolfBoot (`wolfBoot_success()`, `wolfBoot_update_trigger()`) while core 1 or a DMA channel reads flash must stop them first. wolfBoot and the test application use one core and no DMA. + +### Building + +```sh +cp config/examples/rp2040.config .config +make +``` + +Options, on the make command line or in `.config`: + +| Option | Meaning | +|---|---| +| `RP2040_SYS_MHZ` | `clk_sys`: 12 (crystal, PLL off) or 63..133, default 125 | +| `RP2040_XIP_QUAD=n` | Switch the flash to quad read at `clk_sys / n` (2 or 4) when wolfBoot starts; the application inherits it. Needs a W25Q-compatible flash with its Quad Enable bit set, otherwise wolfBoot stays in serial read mode. Default 0 (off) | +| `DEBUG_UART` | Console on UART0 at 115200, GP0 (TX) / GP1 (RX) | +| `RP2040_RAM_LOG=1` | Also keep the console text in the SRAM4 scratch bank at `0x20040000` (magic `WBLG`, length, text) for the application to read back; needs `DEBUG_UART=1` | +| `RP2040_BOOT_GUARD=1` | Arm the watchdog while wolfBoot runs; if wolfBoot hangs or finds nothing to boot, the next reset enters the boot ROM USB loader. wolfBoot feeds it from its hash and copy loops; the longest watchdog period is about 8.4 s, which a single slow signature check at `RP2040_SYS_MHZ=12` can exceed (ED25519, ECC384) | + +The last two are development aids for a board with no debug probe or UART adapter and should be left off in production. + +### Flashing + +The boot ROM USB loader takes UF2 files. Hold BOOTSEL while plugging in USB and copy the file to the `RPI-RP2` drive: + +```sh +tools/scripts/rp2040/rp2040_uf2.py uf2 factory.bin factory.uf2 +cp factory.uf2 /media/$USER/RPI-RP2/ +``` + +`factory.bin` ends with the signed image. On a board that has run wolfBoot before, pad it to the end of the layout so the UF2 also blanks the UPDATE partition, SWAP and the partition trailers; otherwise an update left pending or half-swapped from before can act on the new image: + +```sh +arm-none-eabi-objcopy -I binary -O binary --pad-to=0x1F1000 --gap-fill=0xFF factory.bin factory_full.bin +tools/scripts/rp2040/rp2040_uf2.py uf2 factory_full.bin factory.uf2 +``` + +A signed update can be placed in the UPDATE partition the same way: + +```sh +tools/keytools/sign --ecc256 --sha256 test-app/image.bin wolfboot_signing_private_key.der 2 +tools/scripts/rp2040/rp2040_uf2.py uf2 test-app/image_v2_signed.bin update.uf2 --base 0x10100000 +``` + +### Test application + +`test-app/app_rp2040.c` prints its version on the console, confirms itself with `wolfBoot_success()` when the version is 2 or higher, and takes the keys `u` (trigger the update and reset), `r` (reset) and `b` (reboot into the USB loader). + +A network firmware update example, TFTP over a W5100S Ethernet controller, is in wolfIP under `src/port/rp2040_w5100s`. + +### Verification time + +Measured with `BOOT_BENCHMARK=1` on an RP2040 at 125 MHz, 88 KB image, flash in serial read mode. SHA-256 of the image takes 146 ms (260 ms for SHA-384); with `RP2040_XIP_QUAD=2` it takes 105 ms for a 92 KB image. Size is the wolfBoot `.text` section. + +| Signature | Verify | wolfBoot size | +|---|---|---| +| RSA2048 | 44 ms | 16.3 KB | +| ML-DSA-44 | 74 ms | 21.5 KB | +| ML-DSA-65 | 112 ms | 22.2 KB | +| RSA4096 | 164 ms | 16.8 KB | +| ECC256 (default, Thumb assembly) | 170 ms | 21.6 KB | +| LMS L1-H10-W8 | 357 ms | 12.8 KB | +| ECC384 | 732 ms | 30.6 KB | +| ECC256, `NO_ASM=1` | 1128 ms | 18.7 KB | +| ED25519 | 1566 ms | 16.8 KB | + +ML-DSA needs `IMAGE_HEADER_SIZE=8192` and therefore `WOLFBOOT_SECTOR_SIZE=0x2000`, for example `make SIGN=ML_DSA ML_DSA_LEVEL=2 IMAGE_SIGNATURE_SIZE=2420 IMAGE_HEADER_SIZE=8192 WOLFBOOT_SECTOR_SIZE=0x2000`. + +An update of an 88 KB image took 21 seconds from the trigger to the new application being back on the network, most of it the sector swap and the erase of the rest of the partition. + + ## Raspberry Pi Pico rp2350 See instructions in [IDE/pico-sdk/rp2350/README.md](/IDE/pico-sdk/rp2350/README.md) diff --git a/hal/rp2040.c b/hal/rp2040.c new file mode 100644 index 0000000000..dcdd6593d0 --- /dev/null +++ b/hal/rp2040.c @@ -0,0 +1,585 @@ +/* rp2040.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* Raspberry Pi RP2040 (Pico, W5100S-EVB-Pico, ...), bare metal with no + * pico-sdk dependency. + * + * The boot ROM loads the first 256 bytes of flash (the "boot2" second + * stage, below) into RAM, checks its CRC32 and runs it. boot2 sets the SSI + * controller up for execute-in-place and jumps to the wolfBoot vector + * table that follows it at 0x10000100. + * + * Flash is erased and programmed with the boot ROM routines. They need XIP + * switched off, so the one function that calls them runs from RAM with + * interrupts masked and restores XIP with a RAM copy of boot2. + * + * The RP2040 has no secure boot and no OTP: the ROM runs whatever boot2 + * passes its checksum and always offers the USB loader. wolfBoot here + * authenticates and rolls back firmware updates; it is not a hardware + * root of trust. + */ + +#include +#include +#include +#include "hal.h" +#include "hal/rp2040.h" + +#ifndef RP2040_SYS_MHZ +#define RP2040_SYS_MHZ 125 +#endif +#if (RP2040_SYS_MHZ != 12) && ((RP2040_SYS_MHZ < 63) || (RP2040_SYS_MHZ > 133)) +#error "RP2040_SYS_MHZ must be 12 or 63..133 (PLL VCO range 750..1600 MHz)" +#endif +#define RP2040_XOSC_MHZ 12UL +#define RP2040_SYS_HZ ((uint32_t)RP2040_SYS_MHZ * 1000000UL) + +#ifndef RP2040_UART_BAUD +#define RP2040_UART_BAUD 115200UL +#endif +#ifndef RP2040_UART_TX_PIN +#define RP2040_UART_TX_PIN 0 +#endif +#ifndef RP2040_UART_RX_PIN +#define RP2040_UART_RX_PIN 1 +#endif + +/* Startup delay in units of 256 crystal cycles: about 1 ms at 12 MHz. */ +#define XOSC_STARTUP_DELAY 47UL +/* VCO = 12 MHz * RP2040_SYS_MHZ, then /6 /2. */ +#define PLL_POSTDIV1 6UL +#define PLL_POSTDIV2 2UL +#define CLOCK_WAIT_SPINS 2000000UL + +#define RP2040_RAMCODE \ + __attribute__((used, noinline, section(".ramcode"), long_call)) + +#define WATCHDOG_CTRL (RP2040_WATCHDOG_BASE + 0x00UL) +#define WATCHDOG_LOAD (RP2040_WATCHDOG_BASE + 0x04UL) +#define WATCHDOG_SCRATCH1 (RP2040_WATCHDOG_BASE + 0x10UL) +#define WATCHDOG_CTRL_ENABLE (1UL << 30) +#define WATCHDOG_CTRL_PAUSE_DBG (7UL << 24) +#define WATCHDOG_LOAD_MAX 0x00FFFFFFUL +#define PSM_WDSEL 0x40010008UL +/* Everything except the oscillators is reset by the watchdog. */ +#define PSM_WDSEL_ALL 0x0001FFFCUL +#define BOOT_GUARD_MAGIC 0x77424744UL + +/* Console text kept in the SRAM4 scratch bank, which neither wolfBoot's + * nor the test application's linker script uses, so that the application + * can read it back after the hand-off. */ +#define RAM_LOG_BASE 0x20040000UL +#define RAM_LOG_SIZE 0x1000UL +#define RAM_LOG_MAGIC 0x474C4257UL +struct ram_log { + uint32_t magic; + uint32_t len; + char text[RAM_LOG_SIZE - 2U * sizeof(uint32_t)]; +}; + +/* Boot ROM: 16-bit pointers to the function table and its lookup routine. */ +#define ROM_FUNC_TABLE_PTR 0x14UL +#define ROM_LOOKUP_PTR 0x18UL +#define ROM_CODE(a, b) ((uint32_t)(a) | ((uint32_t)(b) << 8)) + +typedef void *(*rom_lookup_fn)(uint16_t *table, uint32_t code); +typedef void (*rom_void_fn)(void); +typedef void (*rom_erase_fn)(uint32_t off, uint32_t count, + uint32_t block_size, uint8_t block_cmd); +typedef void (*rom_program_fn)(uint32_t off, const uint8_t *data, + uint32_t count); +typedef void (*rom_usb_boot_fn)(uint32_t gpio_mask, uint32_t disable_mask); + +static rom_void_fn rom_connect_internal_flash; +static rom_void_fn rom_flash_exit_xip; +static rom_erase_fn rom_flash_range_erase; +static rom_program_fn rom_flash_range_program; +static rom_void_fn rom_flash_flush_cache; +static uint32_t boot2_copy[RP2040_BOOT2_SIZE / sizeof(uint32_t)]; +static uint8_t flash_buf[RP2040_FLASH_SECTOR_SIZE]; +static int flash_ready; + +#ifdef __WOLFBOOT +/* Second-stage boot for any SPI NOR flash: XIP with the plain 03h read + * command (24-bit address, no dummy cycles), SCK = clk_sys / 4. Position + * independent, because the ROM runs it from RAM. When entered from the ROM + * (LR == 0) it starts the image at 0x10000100, otherwise it returns. + * The last word is the CRC32 the ROM checks; after changing the code + * recompute it with tools/scripts/rp2040/rp2040_uf2.py boot2-crc. + */ +__asm__( + ".section .boot2, \"ax\"\n" + ".syntax unified\n" + ".thumb\n" + ".thumb_func\n" + ".global rp2040_boot2\n" + "rp2040_boot2:\n" + " push {lr}\n" + " ldr r3, =0x18000000\n" /* XIP_SSI_BASE */ + " movs r0, #0\n" + " str r0, [r3, #0x08]\n" /* SSIENR = 0 */ + " movs r1, #4\n" + " str r1, [r3, #0x14]\n" /* BAUDR = 4 */ + " ldr r1, =0x001F0300\n" /* 32-bit frames, EEPROM-read mode */ + " str r1, [r3, #0x00]\n" /* CTRLR0 */ + " str r0, [r3, #0x04]\n" /* CTRLR1 = 0 */ + " ldr r1, =0x03000218\n" /* cmd 03h, 8-bit cmd, 24-bit addr */ + " ldr r2, =0x180000F4\n" + " str r1, [r2]\n" /* SPI_CTRLR0 */ + " movs r1, #1\n" + " str r1, [r3, #0x10]\n" /* SER = 1 */ + " str r1, [r3, #0x08]\n" /* SSIENR = 1 */ + " pop {r0}\n" + " cmp r0, #0\n" + " beq 1f\n" + " bx r0\n" + "1:\n" + " ldr r0, =0x10000100\n" + " ldr r1, =0xE000ED08\n" /* VTOR */ + " str r0, [r1]\n" + " ldr r1, [r0, #0]\n" + " ldr r2, [r0, #4]\n" + " msr msp, r1\n" + " bx r2\n" + ".ltorg\n" + ".org 252\n" + ".word 0xBD6FA940\n" + ".text\n" +); +#endif /* __WOLFBOOT */ + +static int wait_bits(uint32_t addr, uint32_t mask) +{ + uint32_t spins; + + for (spins = 0; spins < CLOCK_WAIT_SPINS; spins++) { + if ((RP2040_REG(addr) & mask) == mask) + return 1; + } + return 0; +} + +static void reset_release(uint32_t bits) +{ + RP2040_REG_CLR(RESETS_RESET) = bits; + (void)wait_bits(RESETS_RESET_DONE, bits); +} + +static void clock_init(void) +{ + RP2040_REG(XOSC_STARTUP) = XOSC_STARTUP_DELAY; + RP2040_REG(XOSC_CTRL) = XOSC_CTRL_ENABLE | XOSC_CTRL_1_15MHZ; + if (!wait_bits(XOSC_STATUS, XOSC_STATUS_STABLE)) + return; + + RP2040_REG(CLK_REF_CTRL) = CLK_REF_SRC_XOSC; + (void)wait_bits(CLK_REF_SELECTED, 1UL << CLK_REF_SRC_XOSC); + RP2040_REG_CLR(CLK_SYS_CTRL) = CLK_SYS_SRC_AUX; + (void)wait_bits(CLK_SYS_SELECTED, 1UL << 0); + +#if RP2040_SYS_MHZ != 12 + RP2040_REG_SET(RESETS_RESET) = RESETS_PLL_SYS; + reset_release(RESETS_PLL_SYS); + RP2040_REG(PLL_CS) = 1UL; + RP2040_REG(PLL_FBDIV_INT) = (uint32_t)RP2040_SYS_MHZ; + RP2040_REG_CLR(PLL_PWR) = PLL_PWR_PD | PLL_PWR_VCOPD; + if (wait_bits(PLL_CS, PLL_CS_LOCK)) { + RP2040_REG(PLL_PRIM) = (PLL_POSTDIV1 << 16) | (PLL_POSTDIV2 << 12); + RP2040_REG_CLR(PLL_PWR) = PLL_PWR_POSTDIVPD; + RP2040_REG(CLK_SYS_CTRL) = 0UL; + RP2040_REG(CLK_SYS_CTRL) = CLK_SYS_SRC_AUX; + (void)wait_bits(CLK_SYS_SELECTED, 1UL << CLK_SYS_SRC_AUX); + } +#endif + + RP2040_REG(CLK_PERI_CTRL) = 0UL; + RP2040_REG(CLK_PERI_CTRL) = CLK_PERI_ENABLE; + + /* TIMER counts the watchdog tick: clk_ref / 12 = 1 MHz. */ + RP2040_REG(WATCHDOG_TICK) = WATCHDOG_TICK_ENABLE | RP2040_XOSC_MHZ; + reset_release(RESETS_TIMER | RESETS_IO_BANK0 | RESETS_PADS_BANK0); +} + +static void *rom_func(uint32_t code) +{ + volatile uintptr_t table_ptr = ROM_FUNC_TABLE_PTR; + volatile uintptr_t lookup_ptr = ROM_LOOKUP_PTR; + uint16_t *table; + rom_lookup_fn lookup; + + table = (uint16_t *)(uintptr_t)(*(const uint16_t *)table_ptr); + lookup = (rom_lookup_fn)(uintptr_t)(*(const uint16_t *)lookup_ptr); + return lookup(table, code); +} + +void rp2040_reset_to_usb_boot(void) +{ + rom_usb_boot_fn fn = (rom_usb_boot_fn)rom_func(ROM_CODE('U', 'B')); + + if (fn != NULL) + fn(0, 0); +} + +#if defined(RP2040_BOOT_GUARD) && defined(__WOLFBOOT) +/* Development aid for a board without a debug probe. The watchdog is armed + * and a flag set in SCRATCH1; both are dropped just before the image is + * started. If wolfBoot instead hangs or panics (no bootable image), the + * watchdog resets the chip, the flag is still set, and wolfBoot hands over + * to the boot ROM USB loader so a new image can be flashed. */ +static void boot_guard_arm(void) +{ + if (RP2040_REG(WATCHDOG_SCRATCH1) == BOOT_GUARD_MAGIC) { + RP2040_REG(WATCHDOG_SCRATCH1) = 0; + rp2040_reset_to_usb_boot(); + } + RP2040_REG(WATCHDOG_SCRATCH1) = BOOT_GUARD_MAGIC; + RP2040_REG(PSM_WDSEL) = PSM_WDSEL_ALL; + RP2040_REG(WATCHDOG_LOAD) = WATCHDOG_LOAD_MAX; + RP2040_REG(WATCHDOG_CTRL) = WATCHDOG_CTRL_ENABLE | WATCHDOG_CTRL_PAUSE_DBG; +} + +static void boot_guard_disarm(void) +{ + RP2040_REG_CLR(WATCHDOG_CTRL) = WATCHDOG_CTRL_ENABLE; + RP2040_REG(WATCHDOG_SCRATCH1) = 0; +} + +void wolfBoot_watchdog_feed(void) +{ + RP2040_REG(WATCHDOG_LOAD) = WATCHDOG_LOAD_MAX; +} +#endif /* RP2040_BOOT_GUARD && __WOLFBOOT */ + +#ifdef RP2040_XIP_QUAD +/* The second-stage boot leaves the flash in single-bit 03h read mode, which + * every SPI NOR flash understands. RP2040_XIP_QUAD=n moves a W25Q-compatible + * flash to Fast Read Quad I/O (EBh) in continuous read mode at clk_sys / n: + * four data lines and no command byte per access. The application inherits + * the mode. */ +#define SSI_BASE 0x18000000UL +#define SSI_CTRLR0 (SSI_BASE + 0x00UL) +#define SSI_CTRLR1 (SSI_BASE + 0x04UL) +#define SSI_SSIENR (SSI_BASE + 0x08UL) +#define SSI_SER (SSI_BASE + 0x10UL) +#define SSI_BAUDR (SSI_BASE + 0x14UL) +#define SSI_SR (SSI_BASE + 0x28UL) +#define SSI_DR0 (SSI_BASE + 0x60UL) +#define SSI_RX_SAMPLE_DLY (SSI_BASE + 0xF0UL) +#define SSI_SPI_CTRLR0 (SSI_BASE + 0xF4UL) + +#define SSI_SR_BUSY (1UL << 0) +#define SSI_SR_TFE (1UL << 2) +#define SSI_SR_RFNE (1UL << 3) + +/* CTRLR0: frame format (21), data frame size - 1 (16), transfer mode (8) */ +#define CTRLR0_STD_8BIT (7UL << 16) +#define CTRLR0_QUAD_READ ((2UL << 21) | (31UL << 16) | (3UL << 8)) +#define CTRLR0_STD_READ ((31UL << 16) | (3UL << 8)) +/* SPI_CTRLR0: XIP command (24), wait cycles (11), instruction length (8), + * address length in nibbles (2), transfer type (0) */ +#define SPI_CTRLR0_ADDR32 (8UL << 2) +#define SPI_CTRLR0_INST8 (2UL << 8) +#define SPI_CTRLR0_WAIT4 (4UL << 11) +#define SPI_CTRLR0_CMD_STD_ADDR_QUAD 1UL +#define SPI_CTRLR0_ALL_QUAD 2UL +#define SPI_CTRLR0_CFG_MASK 0x00FFFFFFUL +/* 03h read as set up by the second-stage boot above */ +#define SPI_CTRLR0_READ_03H 0x03000218UL +#define BAUDR_READ_03H 4UL + +#define FLASH_CMD_READ_SR2 0x35UL +#define FLASH_SR2_QE 0x02UL +#define FLASH_CMD_QUAD_READ 0xEBUL +/* Mode bits after the address that keep the flash in continuous read. */ +#define FLASH_MODE_CONTINUOUS 0xA0UL + +/* Returns 0 in quad read mode. Returns -1, with the 03h mode restored, + * when the flash does not have its Quad Enable bit set; that bit is + * non-volatile and is deliberately not written here. */ +static int RP2040_RAMCODE xip_quad(uint32_t baud_div) +{ + const uint32_t quad_xip = (FLASH_MODE_CONTINUOUS << 24) | + SPI_CTRLR0_ADDR32 | SPI_CTRLR0_WAIT4 | SPI_CTRLR0_ALL_QUAD; + uint32_t primask; + uint32_t sr2; + int ret = 0; + + /* Already there, as when wolfBoot made the switch before this image. + * Running the sequence again would send a serial command to a flash + * that expects quad address bits. The XIP command field reads back as + * zero, so it is left out of the comparison. */ + if (RP2040_REG(SSI_CTRLR0) == CTRLR0_QUAD_READ && + (RP2040_REG(SSI_SPI_CTRLR0) & SPI_CTRLR0_CFG_MASK) == + (quad_xip & SPI_CTRLR0_CFG_MASK)) + return 0; + + __asm__ volatile("mrs %0, primask" : "=r"(primask)); + __asm__ volatile("cpsid i"); + + RP2040_REG(SSI_SSIENR) = 0; + RP2040_REG(SSI_SER) = 1; + RP2040_REG(SSI_BAUDR) = baud_div; + RP2040_REG(SSI_RX_SAMPLE_DLY) = 1; + RP2040_REG(SSI_CTRLR0) = CTRLR0_STD_8BIT; + RP2040_REG(SSI_SSIENR) = 1; + RP2040_REG(SSI_DR0) = FLASH_CMD_READ_SR2; + RP2040_REG(SSI_DR0) = 0; + while ((RP2040_REG(SSI_SR) & (SSI_SR_TFE | SSI_SR_BUSY)) != SSI_SR_TFE) + ; + (void)RP2040_REG(SSI_DR0); + sr2 = RP2040_REG(SSI_DR0) & 0xFFUL; + + RP2040_REG(SSI_SSIENR) = 0; + if ((sr2 & FLASH_SR2_QE) == 0UL) { + RP2040_REG(SSI_BAUDR) = BAUDR_READ_03H; + RP2040_REG(SSI_RX_SAMPLE_DLY) = 0; + RP2040_REG(SSI_CTRLR0) = CTRLR0_STD_READ; + RP2040_REG(SSI_SPI_CTRLR0) = SPI_CTRLR0_READ_03H; + ret = -1; + } + else { + /* One read with the command byte puts the flash into continuous + * read mode... */ + RP2040_REG(SSI_CTRLR0) = CTRLR0_QUAD_READ; + RP2040_REG(SSI_CTRLR1) = 0; + RP2040_REG(SSI_SPI_CTRLR0) = SPI_CTRLR0_ADDR32 | SPI_CTRLR0_INST8 | + SPI_CTRLR0_WAIT4 | SPI_CTRLR0_CMD_STD_ADDR_QUAD; + RP2040_REG(SSI_SSIENR) = 1; + RP2040_REG(SSI_DR0) = FLASH_CMD_QUAD_READ; + RP2040_REG(SSI_DR0) = FLASH_MODE_CONTINUOUS; + while ((RP2040_REG(SSI_SR) & (SSI_SR_TFE | SSI_SR_BUSY)) != + SSI_SR_TFE) + ; + while ((RP2040_REG(SSI_SR) & SSI_SR_RFNE) != 0UL) + (void)RP2040_REG(SSI_DR0); + RP2040_REG(SSI_SSIENR) = 0; + /* ...after which every XIP access is address and mode bits only. */ + RP2040_REG(SSI_SPI_CTRLR0) = quad_xip; + } + RP2040_REG(SSI_SSIENR) = 1; + + __asm__ volatile("msr primask, %0" : : "r"(primask)); + return ret; +} +#endif /* RP2040_XIP_QUAD */ + +static int flash_setup(void) +{ + if (flash_ready) + return 0; + rom_connect_internal_flash = (rom_void_fn)rom_func(ROM_CODE('I', 'F')); + rom_flash_exit_xip = (rom_void_fn)rom_func(ROM_CODE('E', 'X')); + rom_flash_range_erase = (rom_erase_fn)rom_func(ROM_CODE('R', 'E')); + rom_flash_range_program = (rom_program_fn)rom_func(ROM_CODE('R', 'P')); + rom_flash_flush_cache = (rom_void_fn)rom_func(ROM_CODE('F', 'C')); + if (rom_connect_internal_flash == NULL || rom_flash_exit_xip == NULL || + rom_flash_range_erase == NULL || + rom_flash_range_program == NULL || + rom_flash_flush_cache == NULL) + return -1; + memcpy(boot2_copy, (const void *)RP2040_XIP_BASE, sizeof(boot2_copy)); + flash_ready = 1; + return 0; +} + +/* data == NULL erases [off, off + len), otherwise programs len bytes. + * Nothing in flash may be touched between exit_xip and the boot2 call. */ +static void RP2040_RAMCODE flash_op(uint32_t off, const uint8_t *data, + uint32_t len) +{ + rom_void_fn enter_xip = (rom_void_fn)((uintptr_t)boot2_copy | 1U); + uint32_t primask; + + __asm__ volatile("mrs %0, primask" : "=r"(primask)); + __asm__ volatile("cpsid i"); + rom_connect_internal_flash(); + rom_flash_exit_xip(); + if (data == NULL) { + rom_flash_range_erase(off, len, RP2040_FLASH_BLOCK_SIZE, + RP2040_FLASH_BLOCK_ERASE); + } + else { + rom_flash_range_program(off, data, len); + } + rom_flash_flush_cache(); + enter_xip(); +#ifdef RP2040_XIP_QUAD + (void)xip_quad(RP2040_XIP_QUAD); +#endif +#if defined(RP2040_BOOT_GUARD) && defined(__WOLFBOOT) + /* A long erase must not trip the boot guard. */ + RP2040_REG(WATCHDOG_LOAD) = WATCHDOG_LOAD_MAX; +#endif + __asm__ volatile("msr primask, %0" : : "r"(primask)); +} + +int hal_flash_write(uint32_t address, const uint8_t *data, int len) +{ + uint32_t off; + uint32_t pad; + uint32_t chunk; + uint32_t total; + + if (len < 0 || address < RP2040_XIP_BASE || flash_setup() != 0) + return -1; + off = address - RP2040_XIP_BASE; + while (len > 0) { + /* The source may be in flash, so stage it in RAM first. Bytes of + * the page outside the request stay 0xFF, which programs nothing. */ + pad = off & (RP2040_FLASH_PAGE_SIZE - 1UL); + chunk = sizeof(flash_buf) - pad; + if (chunk > (uint32_t)len) + chunk = (uint32_t)len; + total = (pad + chunk + RP2040_FLASH_PAGE_SIZE - 1UL) & + ~(RP2040_FLASH_PAGE_SIZE - 1UL); + memset(flash_buf, 0xFF, total); + memcpy(flash_buf + pad, data, chunk); + flash_op(off - pad, flash_buf, total); + off += chunk; + data += chunk; + len -= (int)chunk; + } + return 0; +} + +int hal_flash_erase(uint32_t address, int len) +{ + uint32_t off; + uint32_t end; + + if (len <= 0 || address < RP2040_XIP_BASE || flash_setup() != 0) + return -1; + off = (address - RP2040_XIP_BASE) & ~(RP2040_FLASH_SECTOR_SIZE - 1UL); + end = (address - RP2040_XIP_BASE + (uint32_t)len + + RP2040_FLASH_SECTOR_SIZE - 1UL) & ~(RP2040_FLASH_SECTOR_SIZE - 1UL); + flash_op(off, NULL, end - off); + return 0; +} + +void hal_flash_unlock(void) +{ +} + +void hal_flash_lock(void) +{ +} + +#if defined(DEBUG_UART) || !defined(__WOLFBOOT) +void uart_init(void) +{ + uint32_t div; + + RP2040_REG_SET(RESETS_RESET) = RESETS_UART0; + reset_release(RESETS_UART0); + RP2040_REG_SET(PADS_BANK0_GPIO(RP2040_UART_TX_PIN)) = PADS_GPIO_IE; + RP2040_REG_CLR(PADS_BANK0_GPIO(RP2040_UART_TX_PIN)) = PADS_GPIO_OD; + RP2040_REG_SET(PADS_BANK0_GPIO(RP2040_UART_RX_PIN)) = PADS_GPIO_IE; + RP2040_REG(IO_BANK0_GPIO_CTRL(RP2040_UART_TX_PIN)) = GPIO_FUNC_UART; + RP2040_REG(IO_BANK0_GPIO_CTRL(RP2040_UART_RX_PIN)) = GPIO_FUNC_UART; + + /* Divisor in 1/128 steps, rounded to the 6-bit fraction. */ + div = (uint32_t)(((uint64_t)RP2040_SYS_HZ * 8U) / RP2040_UART_BAUD); + RP2040_REG(UART0_CR) = 0; + RP2040_REG(UART0_IBRD) = div >> 7; + RP2040_REG(UART0_FBRD) = ((div & 0x7FUL) + 1UL) >> 1; + RP2040_REG(UART0_LCR_H) = UART_LCR_H_8N1_FIFO; + RP2040_REG(UART0_CR) = UART_CR_ENABLE; +} + +void uart_write(const char *buf, unsigned int sz) +{ + unsigned int i; +#if defined(RP2040_RAM_LOG) && defined(__WOLFBOOT) + struct ram_log *log = (struct ram_log *)RAM_LOG_BASE; + + for (i = 0; i < sz && log->len < sizeof(log->text); i++) + log->text[log->len++] = buf[i]; +#endif + + for (i = 0; i < sz; i++) { + if (buf[i] == '\n') { + while ((RP2040_REG(UART0_FR) & UART_FR_TXFF) != 0UL) + ; + RP2040_REG(UART0_DR) = '\r'; + } + while ((RP2040_REG(UART0_FR) & UART_FR_TXFF) != 0UL) + ; + RP2040_REG(UART0_DR) = (uint8_t)buf[i]; + } +} +#endif /* DEBUG_UART || !__WOLFBOOT */ + +#if defined(BOOT_BENCHMARK) && defined(__WOLFBOOT) +uint64_t hal_get_timer_us(void) +{ + uint32_t hi; + uint32_t lo; + uint32_t hi2; + + hi = RP2040_REG(TIMER_TIMERAWH); + for (;;) { + lo = RP2040_REG(TIMER_TIMERAWL); + hi2 = RP2040_REG(TIMER_TIMERAWH); + if (hi == hi2) + break; + hi = hi2; + } + return ((uint64_t)hi << 32) | lo; +} +#endif /* BOOT_BENCHMARK && __WOLFBOOT */ + +void hal_init(void) +{ +#if defined(RP2040_RAM_LOG) && defined(__WOLFBOOT) + struct ram_log *log = (struct ram_log *)RAM_LOG_BASE; +#endif + + clock_init(); +#if defined(RP2040_BOOT_GUARD) && defined(__WOLFBOOT) + boot_guard_arm(); +#endif +#if defined(RP2040_RAM_LOG) && defined(__WOLFBOOT) + /* Started after the guard check, so the log of a boot that the guard + * ended is still there for whatever is loaded next. */ + log->magic = RAM_LOG_MAGIC; + log->len = 0; +#endif + (void)flash_setup(); +#if defined(RP2040_XIP_QUAD) && defined(__WOLFBOOT) + (void)xip_quad(RP2040_XIP_QUAD); +#endif +#if defined(DEBUG_UART) && defined(__WOLFBOOT) + uart_init(); + uart_write("wolfBoot Init\n", 14); +#endif +} + +void hal_prepare_boot(void) +{ +#if defined(DEBUG_UART) && defined(__WOLFBOOT) + /* Let the last bytes leave the shifter before the app resets UART0. */ + while ((RP2040_REG(UART0_FR) & (1UL << 3)) != 0UL) + ; +#endif +#if defined(RP2040_BOOT_GUARD) && defined(__WOLFBOOT) + boot_guard_disarm(); +#endif +} diff --git a/hal/rp2040.h b/hal/rp2040.h new file mode 100644 index 0000000000..52bc73aab9 --- /dev/null +++ b/hal/rp2040.h @@ -0,0 +1,126 @@ +/* rp2040.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfBoot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* Raspberry Pi RP2040: dual Cortex-M0+, no internal flash. Code executes + * in place from an external QSPI NOR flash mapped at 0x10000000. + * Reference: RP2040 datasheet. + */ + +#ifndef _RP2040_H_ +#define _RP2040_H_ + +#include + +#define RP2040_REG(addr) (*(volatile uint32_t *)(addr)) +/* Atomic set and clear aliases of every APB register. */ +#define RP2040_REG_SET(addr) RP2040_REG((addr) + 0x2000UL) +#define RP2040_REG_CLR(addr) RP2040_REG((addr) + 0x3000UL) + +#define RP2040_XIP_BASE 0x10000000UL +#define RP2040_CLOCKS_BASE 0x40008000UL +#define RP2040_RESETS_BASE 0x4000C000UL +#define RP2040_IO_BANK0_BASE 0x40014000UL +#define RP2040_PADS_BANK0_BASE 0x4001C000UL +#define RP2040_XOSC_BASE 0x40024000UL +#define RP2040_PLL_SYS_BASE 0x40028000UL +#define RP2040_UART0_BASE 0x40034000UL +#define RP2040_TIMER_BASE 0x40054000UL +#define RP2040_WATCHDOG_BASE 0x40058000UL +#define RP2040_SIO_BASE 0xD0000000UL + +/* RESETS */ +#define RESETS_RESET (RP2040_RESETS_BASE + 0x00UL) +#define RESETS_RESET_DONE (RP2040_RESETS_BASE + 0x08UL) +#define RESETS_IO_BANK0 (1UL << 5) +#define RESETS_PADS_BANK0 (1UL << 8) +#define RESETS_PLL_SYS (1UL << 12) +#define RESETS_TIMER (1UL << 21) +#define RESETS_UART0 (1UL << 22) + +/* CLOCKS */ +#define CLK_REF_CTRL (RP2040_CLOCKS_BASE + 0x30UL) +#define CLK_REF_SELECTED (RP2040_CLOCKS_BASE + 0x38UL) +#define CLK_SYS_CTRL (RP2040_CLOCKS_BASE + 0x3CUL) +#define CLK_SYS_SELECTED (RP2040_CLOCKS_BASE + 0x44UL) +#define CLK_PERI_CTRL (RP2040_CLOCKS_BASE + 0x48UL) +#define CLK_REF_SRC_XOSC 2UL +#define CLK_SYS_SRC_AUX 1UL +#define CLK_PERI_ENABLE (1UL << 11) + +/* XOSC */ +#define XOSC_CTRL (RP2040_XOSC_BASE + 0x00UL) +#define XOSC_STATUS (RP2040_XOSC_BASE + 0x04UL) +#define XOSC_STARTUP (RP2040_XOSC_BASE + 0x0CUL) +#define XOSC_CTRL_ENABLE (0xFABUL << 12) +#define XOSC_CTRL_1_15MHZ 0xAA0UL +#define XOSC_STATUS_STABLE (1UL << 31) + +/* PLL_SYS */ +#define PLL_CS (RP2040_PLL_SYS_BASE + 0x00UL) +#define PLL_PWR (RP2040_PLL_SYS_BASE + 0x04UL) +#define PLL_FBDIV_INT (RP2040_PLL_SYS_BASE + 0x08UL) +#define PLL_PRIM (RP2040_PLL_SYS_BASE + 0x0CUL) +#define PLL_CS_LOCK (1UL << 31) +#define PLL_PWR_PD (1UL << 0) +#define PLL_PWR_POSTDIVPD (1UL << 3) +#define PLL_PWR_VCOPD (1UL << 5) + +/* WATCHDOG tick generator and TIMER (1 MHz) */ +#define WATCHDOG_TICK (RP2040_WATCHDOG_BASE + 0x2CUL) +#define WATCHDOG_TICK_ENABLE (1UL << 9) +#define TIMER_TIMERAWH (RP2040_TIMER_BASE + 0x24UL) +#define TIMER_TIMERAWL (RP2040_TIMER_BASE + 0x28UL) + +/* GPIO */ +#define IO_BANK0_GPIO_CTRL(n) (RP2040_IO_BANK0_BASE + 0x04UL + (n) * 8UL) +#define PADS_BANK0_GPIO(n) (RP2040_PADS_BANK0_BASE + 0x04UL + (n) * 4UL) +#define PADS_GPIO_OD (1UL << 7) +#define PADS_GPIO_IE (1UL << 6) +#define GPIO_FUNC_UART 2UL +#define GPIO_FUNC_SIO 5UL +#define SIO_GPIO_OUT_SET (RP2040_SIO_BASE + 0x14UL) +#define SIO_GPIO_OUT_CLR (RP2040_SIO_BASE + 0x18UL) +#define SIO_GPIO_OUT_XOR (RP2040_SIO_BASE + 0x1CUL) +#define SIO_GPIO_OE_SET (RP2040_SIO_BASE + 0x24UL) + +/* UART0 (PL011) */ +#define UART0_DR (RP2040_UART0_BASE + 0x00UL) +#define UART0_FR (RP2040_UART0_BASE + 0x18UL) +#define UART0_IBRD (RP2040_UART0_BASE + 0x24UL) +#define UART0_FBRD (RP2040_UART0_BASE + 0x28UL) +#define UART0_LCR_H (RP2040_UART0_BASE + 0x2CUL) +#define UART0_CR (RP2040_UART0_BASE + 0x30UL) +#define UART_FR_RXFE (1UL << 4) +#define UART_FR_TXFF (1UL << 5) +#define UART_LCR_H_8N1_FIFO ((3UL << 5) | (1UL << 4)) +#define UART_CR_ENABLE ((1UL << 0) | (1UL << 8) | (1UL << 9)) + +/* Flash geometry (W25Q-class QSPI NOR). */ +#define RP2040_FLASH_PAGE_SIZE 0x100UL +#define RP2040_FLASH_SECTOR_SIZE 0x1000UL +#define RP2040_FLASH_BLOCK_SIZE 0x10000UL +#define RP2040_FLASH_BLOCK_ERASE 0xD8U +#define RP2040_BOOT2_SIZE 0x100UL + +/* Reboot into the boot ROM USB mass-storage loader (BOOTSEL). */ +void rp2040_reset_to_usb_boot(void); + +#endif /* _RP2040_H_ */ diff --git a/hal/rp2040.ld b/hal/rp2040.ld new file mode 100644 index 0000000000..4d77d11228 --- /dev/null +++ b/hal/rp2040.ld @@ -0,0 +1,65 @@ +MEMORY +{ + FLASH (rx) : ORIGIN = @WOLFBOOT_ORIGIN@, LENGTH = @BOOTLOADER_PARTITION_SIZE@ + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00040000 /* 256 KB main SRAM */ +} + +SECTIONS +{ + /* Checksummed second-stage boot the ROM loads; the vector table must + * follow it at +0x100. */ + .boot2 : + { + KEEP(*(.boot2)) + } > FLASH + + ASSERT(SIZEOF(.boot2) == 256, "boot2 must be exactly 256 bytes") + + .text : + { + _start_text = .; + KEEP(*(.isr_vector)) + *(.text*) + *(.rodata*) + . = ALIGN(4); + _end_text = .; + } > FLASH + + .edidx : + { + . = ALIGN(4); + *(.ARM.exidx*) + } > FLASH + + .keystore : + { + . = ALIGN(4); + KEEP(*(.keystore*)) + } > FLASH + + _stored_data = .; + .data : AT (_stored_data) + { + _start_data = .; + KEEP(*(.data*)) + . = ALIGN(4); + KEEP(*(.ramcode)) + . = ALIGN(4); + _end_data = .; + } > RAM + + .bss (NOLOAD) : + { + _start_bss = .; + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + _end_bss = .; + __bss_end__ = .; + _end = .; + } > RAM + . = ALIGN(4); +} + +END_STACK = ORIGIN(RAM) + LENGTH(RAM); diff --git a/test-app/ARM-rp2040.ld b/test-app/ARM-rp2040.ld new file mode 100644 index 0000000000..c77639468b --- /dev/null +++ b/test-app/ARM-rp2040.ld @@ -0,0 +1,53 @@ +MEMORY +{ + FLASH (rx) : ORIGIN = @WOLFBOOT_TEST_APP_ADDRESS@, LENGTH = @WOLFBOOT_TEST_APP_SIZE@ + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 256K +} + +SECTIONS +{ + .text : + { + _start_text = .; + KEEP(*(.isr_vector)) + *(.init) + *(.fini) + *(.text*) + *(.rodata*) + . = ALIGN(4); + _end_text = .; + } > FLASH + + .ARM : + { + . = ALIGN(4); + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } > FLASH + + _stored_data = .; + + .data : AT (_stored_data) + { + _start_data = .; + KEEP(*(.data*)) + . = ALIGN(4); + KEEP(*(.ramcode)) + . = ALIGN(4); + _end_data = .; + } > RAM + + .bss : + { + _start_bss = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + _end_bss = .; + _end = .; + } > RAM +} + +PROVIDE(_start_heap = _end); +PROVIDE(_end_stack = ORIGIN(RAM) + LENGTH(RAM)); diff --git a/test-app/Makefile b/test-app/Makefile index 0616529149..22940bf63d 100644 --- a/test-app/Makefile +++ b/test-app/Makefile @@ -853,6 +853,14 @@ ifeq ($(TARGET),stm32c5) CFLAGS+=-I.. endif +ifeq ($(TARGET),rp2040) + LSCRIPT_TEMPLATE=ARM-rp2040.ld + CFLAGS+=-mcpu=cortex-m0plus -ffunction-sections -fdata-sections -fno-common + LDFLAGS+=-mcpu=cortex-m0plus + LDFLAGS+=-Wl,-gc-sections -Wl,-Map=image.map + CFLAGS+=-I.. +endif + ifeq ($(TARGET),psoc_c3) LSCRIPT_TEMPLATE=ARM-psoc_c3.ld CFLAGS+=-mcpu=cortex-m33 -ffunction-sections -fdata-sections -fno-common diff --git a/test-app/app_rp2040.c b/test-app/app_rp2040.c new file mode 100644 index 0000000000..c917dfbb5e --- /dev/null +++ b/test-app/app_rp2040.c @@ -0,0 +1,132 @@ +/* app_rp2040.c + * + * Test bare-metal application for the Raspberry Pi RP2040. + * + * 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/rp2040.h" +#include "wolfboot/wolfboot.h" +#include "target.h" + +extern void uart_init(void); +extern void uart_write(const char *buf, unsigned int len); + +/* Pico and W5100S-EVB-Pico: user LED on GP25, active high. */ +#define LED_PIN 25 + +#define AIRCR (*(volatile uint32_t *)0xE000ED0CUL) +#define AIRCR_RESET 0x05FA0004UL + +static void uart_print(const char *s) +{ + unsigned int n = 0; + + while (s[n] != 0) + n++; + uart_write(s, n); +} + +static void uart_print_u32(uint32_t v) +{ + char tmp[10]; + int t = 0; + + do { + tmp[t++] = (char)('0' + (v % 10U)); + v /= 10U; + } while (v > 0U); + while (t > 0) + uart_write(&tmp[--t], 1); +} + +static int uart_getc(void) +{ + if ((RP2040_REG(UART0_FR) & UART_FR_RXFE) != 0UL) + return -1; + return (int)(RP2040_REG(UART0_DR) & 0xFFUL); +} + +static void led_init(void) +{ + RP2040_REG(SIO_GPIO_OUT_CLR) = 1UL << LED_PIN; + RP2040_REG(SIO_GPIO_OE_SET) = 1UL << LED_PIN; + RP2040_REG(IO_BANK0_GPIO_CTRL(LED_PIN)) = GPIO_FUNC_SIO; +} + +static void system_reset(void) +{ + AIRCR = AIRCR_RESET; + while (1) + ; +} + +void main(void) +{ + uint32_t version; + uint32_t half_period_us; + uint32_t last; + uint32_t now; + int c; + + hal_init(); + uart_init(); + led_init(); + + version = wolfBoot_current_firmware_version(); + uart_print("TEST APP\n"); + uart_print("App version: "); + uart_print_u32(version); + uart_print("\n"); + + /* An updated image confirms itself; left unconfirmed, wolfBoot rolls + * back to the previous one on the next reset. */ + if (version >= 2U) { + wolfBoot_success(); + uart_print("update OK -- success confirmed\n"); + half_period_us = 100000U; + } + else { + half_period_us = 500000U; + } + uart_print("keys: u = trigger update, r = reset, b = USB BOOTSEL\n"); + + last = RP2040_REG(TIMER_TIMERAWL); + while (1) { + now = RP2040_REG(TIMER_TIMERAWL); + if ((now - last) >= half_period_us) { + last = now; + RP2040_REG(SIO_GPIO_OUT_XOR) = 1UL << LED_PIN; + } + c = uart_getc(); + if (c == 'u') { + uart_print("triggering update -> reset\n"); + wolfBoot_update_trigger(); + system_reset(); + } + else if (c == 'r') { + system_reset(); + } + else if (c == 'b') { + rp2040_reset_to_usb_boot(); + } + } +} diff --git a/tools/config.mk b/tools/config.mk index ee5fa9d734..dea434be59 100644 --- a/tools/config.mk +++ b/tools/config.mk @@ -174,7 +174,8 @@ CONFIG_VARS:= ARCH TARGET SIGN HASH MCUXSDK MCUXPRESSO MCUXPRESSO_CPU MCUXPRESSO CERT_CHAIN_GEN_CA_HASH \ CERT_CHAIN_NAME_CONSTRAINTS \ ENCRYPT_CACHE \ - MPFS_DDR_BCLK_PHASE MPFS_SD_EMMC_DEMUX_ADDR MPFS_PHY_RPC156_VAL MPFS_DDR_MEMTEST MPFS_SC_PROBE + MPFS_DDR_BCLK_PHASE MPFS_SD_EMMC_DEMUX_ADDR MPFS_PHY_RPC156_VAL MPFS_DDR_MEMTEST MPFS_SC_PROBE \ + RP2040_SYS_MHZ RP2040_XIP_QUAD RP2040_RAM_LOG RP2040_BOOT_GUARD # ?= treats a defined-but-empty value as already set, so a stale # LSCRIPT_IN?= line in .config (or an exported empty env var) would skip diff --git a/tools/scripts/rp2040/rp2040_uf2.py b/tools/scripts/rp2040/rp2040_uf2.py new file mode 100755 index 0000000000..45e1019a6a --- /dev/null +++ b/tools/scripts/rp2040/rp2040_uf2.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +""" +rp2040_uf2.py - RP2040 image helper for wolfBoot (no pico-sdk or picotool). + +Convert a flat binary to a UF2 file for the BOOTSEL mass-storage loader: + + rp2040_uf2.py uf2 factory.bin factory.uf2 [--base 0x10000000] + +An image for the start of flash (the default base) must begin with a second +stage whose checksum is correct, because the boot ROM will not run it +otherwise; the conversion fails if it does not. + +Print (and check) the checksum of the 256-byte second-stage boot at the +start of a wolfBoot image. After editing the boot2 code in hal/rp2040.c put +the printed value in its final .word: + + rp2040_uf2.py boot2-crc wolfboot.bin +""" +import struct +import sys + +UF2_MAGIC_START0 = 0x0A324655 +UF2_MAGIC_START1 = 0x9E5D5157 +UF2_MAGIC_END = 0x0AB16F30 +UF2_FLAG_FAMILY = 0x00002000 +UF2_FAMILY_RP2040 = 0xE48BFF56 +UF2_PAYLOAD = 256 +BOOT2_SIZE = 256 +FLASH_BASE = 0x10000000 + + +def crc32_mpeg2(data): + """CRC-32, polynomial 0x04C11DB7, init 0xFFFFFFFF, not reflected.""" + crc = 0xFFFFFFFF + for byte in data: + crc ^= byte << 24 + for _ in range(8): + if crc & 0x80000000: + crc = ((crc << 1) ^ 0x04C11DB7) & 0xFFFFFFFF + else: + crc = (crc << 1) & 0xFFFFFFFF + return crc + + +def boot2_crc(image): + """Return (computed, stored) checksum of the boot2 at the image start.""" + if len(image) < BOOT2_SIZE: + raise SystemExit("image is shorter than boot2") + want = crc32_mpeg2(image[:BOOT2_SIZE - 4]) + have = struct.unpack(' $@ + +unit-rp2040-flash-write: unit-rp2040-flash-write.c rp2040_flash_write_extract.h + gcc -o $@ unit-rp2040-flash-write.c $(CFLAGS) $(LDFLAGS) + # unit-ecc-raw-der runs the real wolfCrypt raw-to-DER conversion and # verification (F-11024: the wolfHSM verify path in src/image.c passed # minimal field sizes with field-start pointers to @@ -3026,7 +3036,7 @@ GENERATED_SRC:=aurix_erased_extract.h elf_store_extract.h \ kontron_spi_extract.h kontron_spi_fn_extract.h \ nrf5340_protect_fn_extract.h \ keystore_api_extract.h keystore_emitted.c keystore_gen \ - rp2350_flash_write_extract.h \ + rp2350_flash_write_extract.h rp2040_flash_write_extract.h \ sdhci_host.c \ stm32c0_write_extract.h stm32g0_write_extract.h stm32g4_write_extract.h stm32l4_write_extract.h \ stm32h7s_write_extract.h stm32h7_trailer_extract.h \ diff --git a/tools/unit-tests/unit-rp2040-flash-write.c b/tools/unit-tests/unit-rp2040-flash-write.c new file mode 100644 index 0000000000..be72dae738 --- /dev/null +++ b/tools/unit-tests/unit-rp2040-flash-write.c @@ -0,0 +1,210 @@ +/* unit-rp2040-flash-write.c + * + * Unit test for the RP2040 hal_flash_write() and hal_flash_erase(). + * + * 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 + +/* From hal/rp2040.h. */ +#define RP2040_XIP_BASE 0x10000000UL +#define RP2040_FLASH_PAGE_SIZE 0x100UL +#define RP2040_FLASH_SECTOR_SIZE 0x1000UL + +#define FLASH_MEM_SZ (4 * RP2040_FLASH_SECTOR_SIZE) +static uint8_t g_flash[FLASH_MEM_SZ]; +static uint8_t flash_buf[RP2040_FLASH_SECTOR_SIZE]; + +/* Violations of the boot ROM contract: range_program wants whole pages, + * range_erase whole sectors. */ +static int g_violations; +static int g_ops; + +static int flash_setup(void) +{ + return 0; +} + +/* Stand-in for the RAM routine that calls the boot ROM. */ +static void flash_op(uint32_t off, const uint8_t *data, uint32_t len) +{ + uint32_t align = (data == NULL) ? RP2040_FLASH_SECTOR_SIZE : + RP2040_FLASH_PAGE_SIZE; + uint32_t i; + + g_ops++; + if ((off & (align - 1)) || (len & (align - 1)) || len == 0 || + off + len > FLASH_MEM_SZ) { + g_violations++; + return; + } + if (data == NULL) { + memset(g_flash + off, 0xFF, len); + return; + } + /* Flash can only clear bits: programmed = old & new. */ + for (i = 0; i < len; i++) + g_flash[off + i] &= data[i]; +} + +/* The real functions from hal/rp2040.c (extracted). */ +#include "rp2040_flash_write_extract.h" + +static void setup(void) +{ + memset(g_flash, 0xFF, FLASH_MEM_SZ); + g_violations = 0; + g_ops = 0; +} + +static void teardown(void) +{ +} + +/* The partition-state write: trailer_write() without NVM_FLASH_WRITEONCE + * is hal_flash_write(addr, &val, 1). The rest of the page must survive. */ +START_TEST(test_one_byte_trailer_write) +{ + uint8_t val = 0x7E; + uint32_t page = 3 * RP2040_FLASH_PAGE_SIZE; + uint32_t i; + + for (i = 0; i < RP2040_FLASH_PAGE_SIZE; i++) + g_flash[page + i] = (i == 100) ? 0xFF : (uint8_t)(0xA0 ^ (i & 0x0F)); + + ck_assert_int_eq(hal_flash_write(RP2040_XIP_BASE + page + 100, &val, 1), + 0); + ck_assert_int_eq(g_violations, 0); + for (i = 0; i < RP2040_FLASH_PAGE_SIZE; i++) { + uint8_t expect = (i == 100) ? val : (uint8_t)(0xA0 ^ (i & 0x0F)); + ck_assert_uint_eq(g_flash[page + i], expect); + } + ck_assert_uint_eq(g_flash[page - 1], 0xFF); + ck_assert_uint_eq(g_flash[page + RP2040_FLASH_PAGE_SIZE], 0xFF); +} +END_TEST + +/* Unaligned start and end across several pages. */ +START_TEST(test_unaligned_multi_page) +{ + uint8_t src[700]; + uint32_t off = RP2040_FLASH_PAGE_SIZE - 3; + uint32_t i; + + for (i = 0; i < sizeof(src); i++) + src[i] = (uint8_t)(i * 7 + 1); + ck_assert_int_eq(hal_flash_write(RP2040_XIP_BASE + off, src, + (int)sizeof(src)), 0); + ck_assert_int_eq(g_violations, 0); + ck_assert_int_eq(memcmp(g_flash + off, src, sizeof(src)), 0); + ck_assert_uint_eq(g_flash[off - 1], 0xFF); + ck_assert_uint_eq(g_flash[off + sizeof(src)], 0xFF); +} +END_TEST + +/* Longer than the staging buffer, so it takes more than one ROM call. */ +START_TEST(test_longer_than_staging_buffer) +{ + static uint8_t src[2 * RP2040_FLASH_SECTOR_SIZE + 300]; + uint32_t off = 100; + uint32_t i; + + for (i = 0; i < sizeof(src); i++) + src[i] = (uint8_t)(i ^ (i >> 8)); + ck_assert_int_eq(hal_flash_write(RP2040_XIP_BASE + off, src, + (int)sizeof(src)), 0); + ck_assert_int_eq(g_violations, 0); + ck_assert_int_gt(g_ops, 2); + ck_assert_int_eq(memcmp(g_flash + off, src, sizeof(src)), 0); + ck_assert_uint_eq(g_flash[off - 1], 0xFF); + ck_assert_uint_eq(g_flash[off + sizeof(src)], 0xFF); +} +END_TEST + +/* The source may itself be in flash (a sector copy during a swap): the + * data must be staged before the ROM call, not read during it. */ +START_TEST(test_source_in_flash) +{ + uint32_t i; + + for (i = 0; i < RP2040_FLASH_SECTOR_SIZE; i++) + g_flash[i] = (uint8_t)(i * 3); + ck_assert_int_eq(hal_flash_write(RP2040_XIP_BASE + + RP2040_FLASH_SECTOR_SIZE, g_flash, (int)RP2040_FLASH_SECTOR_SIZE), 0); + ck_assert_int_eq(g_violations, 0); + ck_assert_int_eq(memcmp(g_flash, g_flash + RP2040_FLASH_SECTOR_SIZE, + RP2040_FLASH_SECTOR_SIZE), 0); +} +END_TEST + +START_TEST(test_erase_rounds_to_sectors) +{ + memset(g_flash, 0x00, FLASH_MEM_SZ); + ck_assert_int_eq(hal_flash_erase(RP2040_XIP_BASE + + RP2040_FLASH_SECTOR_SIZE + 16, 32), 0); + ck_assert_int_eq(g_violations, 0); + ck_assert_uint_eq(g_flash[RP2040_FLASH_SECTOR_SIZE - 1], 0x00); + ck_assert_uint_eq(g_flash[RP2040_FLASH_SECTOR_SIZE], 0xFF); + ck_assert_uint_eq(g_flash[2 * RP2040_FLASH_SECTOR_SIZE - 1], 0xFF); + ck_assert_uint_eq(g_flash[2 * RP2040_FLASH_SECTOR_SIZE], 0x00); +} +END_TEST + +START_TEST(test_bad_arguments) +{ + uint8_t val = 0; + + ck_assert_int_eq(hal_flash_write(RP2040_XIP_BASE - 1, &val, 1), -1); + ck_assert_int_eq(hal_flash_write(RP2040_XIP_BASE, &val, -1), -1); + ck_assert_int_eq(hal_flash_erase(RP2040_XIP_BASE - 1, 16), -1); + ck_assert_int_eq(hal_flash_erase(RP2040_XIP_BASE, 0), -1); + ck_assert_int_eq(g_ops, 0); +} +END_TEST + +Suite *rp2040_flash_suite(void) +{ + Suite *s = suite_create("rp2040-flash-write"); + TCase *tc = tcase_create("hal_flash"); + + tcase_add_checked_fixture(tc, setup, teardown); + tcase_add_test(tc, test_one_byte_trailer_write); + tcase_add_test(tc, test_unaligned_multi_page); + tcase_add_test(tc, test_longer_than_staging_buffer); + tcase_add_test(tc, test_source_in_flash); + tcase_add_test(tc, test_erase_rounds_to_sectors); + tcase_add_test(tc, test_bad_arguments); + suite_add_tcase(s, tc); + return s; +} + +int main(void) +{ + int fails; + Suite *s = rp2040_flash_suite(); + SRunner *sr = srunner_create(s); + + srunner_run_all(sr, CK_NORMAL); + fails = srunner_ntests_failed(sr); + srunner_free(sr); + return fails; +}