From 3953bcb9f84274317aeca1d46f457cabe7a12e5e Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Wed, 18 Nov 2026 09:33:41 -0600 Subject: [PATCH 1/2] process-node 0.3.1: RL78 boot ROM emulator (Protocol A) behind a TOOL0 strap on PA9 PA9 (the console TX, the bench's LA3) held low through reset starts an emulated R5F100LE boot ROM instead of the node: RL78 Protocol A on one wire, open-drain single-wire half duplex, 115200 to 1 Mbit/s. Every command of R01AN0815 Rev. 1.10 (reset, baud rate set, signature, erase, blank check, program, verify, checksum, security set/get/release) with the guide's frames, checksums and status codes; flash in RAM, written only when blank. The emulator's 68 KB is kept out of .bss and filled word-wise (GCC turned the loop into byte-wise memset): zeroing it at startup and filling it byte by byte took longer than a programmer holds TOOL0 after reset. The strap is sampled with the internal pull-up, so an undriven LA3 never starts it. Host-tested in tests/test_rl78emu.c. Refs embeddedci-com/benchpod-firmware#135 Co-Authored-By: Claude Opus 5.5 --- process-node-stm32/Makefile | 4 +- process-node-stm32/STM32F446RETX_FLASH.ld | 10 + process-node-stm32/main.c | 10 +- process-node-stm32/rl78emu.c | 415 ++++++++++++++++++++++ process-node-stm32/rl78emu.h | 116 ++++++ process-node-stm32/rl78emu_port.c | 130 +++++++ process-node-stm32/tests/test_rl78emu.c | 332 +++++++++++++++++ 7 files changed, 1015 insertions(+), 2 deletions(-) create mode 100644 process-node-stm32/rl78emu.c create mode 100644 process-node-stm32/rl78emu.h create mode 100644 process-node-stm32/rl78emu_port.c create mode 100644 process-node-stm32/tests/test_rl78emu.c diff --git a/process-node-stm32/Makefile b/process-node-stm32/Makefile index 0eb15cd..8b0583b 100644 --- a/process-node-stm32/Makefile +++ b/process-node-stm32/Makefile @@ -46,7 +46,7 @@ LDFLAGS := \ -specs=nano.specs \ -specs=nosys.specs -APP_SRCS := main.c analog.c env.c i2cbus.c i2ctarget.c spi2.c uart3.c bench_cmds.c mcp2515.c syscalls.c sysmem.c system_stm32f4xx.c +APP_SRCS := main.c rl78emu.c rl78emu_port.c analog.c env.c i2cbus.c i2ctarget.c spi2.c uart3.c bench_cmds.c mcp2515.c syscalls.c sysmem.c system_stm32f4xx.c HAL_SRCS := \ stm32f4xx_hal.c \ @@ -102,5 +102,7 @@ test-host: | $(BUILD_DIR) $(BUILD_DIR)/test_mcp2515_timing $(HOSTCC) -std=c11 -Wall -Wextra -Werror -I. tests/test_proc.c -o $(BUILD_DIR)/test_proc $(BUILD_DIR)/test_proc + $(HOSTCC) -std=c11 -Wall -Wextra -Werror -I. tests/test_rl78emu.c rl78emu.c -o $(BUILD_DIR)/test_rl78emu + $(BUILD_DIR)/test_rl78emu .PHONY: all clean flash test-host diff --git a/process-node-stm32/STM32F446RETX_FLASH.ld b/process-node-stm32/STM32F446RETX_FLASH.ld index 5e9745e..fdde71a 100644 --- a/process-node-stm32/STM32F446RETX_FLASH.ld +++ b/process-node-stm32/STM32F446RETX_FLASH.ld @@ -164,6 +164,16 @@ SECTIONS __bss_end__ = _ebss; } >RAM + /* Not zeroed at startup: the RL78 emulator's 68 KB flash (rl78emu_port.c fills it itself), so + the C runtime reaches main() fast enough to see the TOOL0 strap. */ + .noinit (NOLOAD) : + { + . = ALIGN(4); + *(.noinit) + *(.noinit*) + . = ALIGN(4); + } >RAM + /* User_heap_stack section, used to check that there is enough "RAM" Ram type memory left */ ._user_heap_stack : { diff --git a/process-node-stm32/main.c b/process-node-stm32/main.c index e95a513..708c287 100644 --- a/process-node-stm32/main.c +++ b/process-node-stm32/main.c @@ -26,8 +26,10 @@ * PB15 MOSI / PB14 MISO / PB12 CS (spi), USART3 PC10 TX / PC11 RX (uart3). * * Console: USART1 PA9 (TX) / PA10 (RX), 115200 8N1. Type "help". + * PA9 held low through reset starts the RL78 boot ROM emulator instead (rl78emu.h, README). */ +#include "rl78emu.h" #include "stm32f4xx_hal.h" #include "alarm.h" #include "analog.h" @@ -42,7 +44,7 @@ #include #define FW_NAME "process-node" -#define FW_VERSION "0.3.0" +#define FW_VERSION "0.3.1" #define CMD_BUF_SIZE 200 @@ -179,6 +181,12 @@ int main(void) reset_cause_capture(); HAL_Init(); SystemClock_Config(); + /* TOOL0 strap: the console TX held low through reset starts the RL78 boot ROM emulator + (rl78emu.h) instead of the node, so a Protocol A programmer can be tested on this board. */ + if (rl78emu_strap()) + { + rl78emu_main(); + } HAL_DBGMCU_EnableDBGSleepMode(); HAL_DBGMCU_EnableDBGStopMode(); diff --git a/process-node-stm32/rl78emu.c b/process-node-stm32/rl78emu.c new file mode 100644 index 0000000..3a868cd --- /dev/null +++ b/process-node-stm32/rl78emu.c @@ -0,0 +1,415 @@ +/* + * rl78emu.c - the RL78 Protocol A boot ROM emulator (see rl78emu.h). Byte-exact to R01AN0815 + * Rev. 1.10, chapters 2-4: frames, checksums, status codes, the command flows below. + * + * Reset 00H, Baud Rate Set 9AH, Silicon Signature C0H, Block Erase 22H, Block Blank Check 32H, + * Programming 40H (data frames, a double status per frame, a final internal-verify status), + * Verify 13H (the mismatch is reported in the last frame's ST2), Checksum B0H, + * Security Set A0H / Get A1H / Release A2H. + * + * Like the real part it refuses everything but Baud Rate Set first (04H), writes only to blank + * bytes (1CH otherwise, as flash cannot turn a 0 back into a 1 without an erase), and honors the + * security flags (10H). Pure C: no HAL, host-tested in tests/test_rl78emu.c. + */ +#include "rl78emu.h" + +#include +#include + +enum { P_HDR, P_LEN, P_BODY, P_SUM, P_FTR }; + +uint8_t rl78_sum(const uint8_t *p, size_t n) +{ + uint8_t s = 0; + for (size_t i = 0; i < n; i++) + s = (uint8_t)(s - p[i]); + return s; +} + +uint8_t *rl78emu_flash(rl78emu_t *e, uint32_t addr) +{ + if (addr <= RL78_CODE_END) + return &e->code[addr - RL78_CODE_START]; + if (addr >= RL78_DATA_START && addr <= RL78_DATA_END) + return &e->data[addr - RL78_DATA_START]; + return NULL; +} + +/* newlib-nano's memset goes a byte at a time: ~30 ms for the 68 KB at 16 MHz, longer than a + programmer leaves between the TOOL0 release and its first frame */ +typedef uint32_t __attribute__((may_alias)) rl78_word_t; +/* no-tree-loop-distribute-patterns: GCC turns this loop back into that memset call otherwise */ +#if defined(__GNUC__) && !defined(__clang__) +__attribute__((optimize("no-tree-loop-distribute-patterns"))) +#endif +static void fill_ff(uint8_t *p, size_t n) +{ + rl78_word_t *w = (rl78_word_t *)(void *)p; + for (size_t i = 0; i < n / 4u; i++) + w[i] = 0xFFFFFFFFu; +} + +void rl78emu_init(rl78emu_t *e, const rl78emu_port_t *port) +{ + memset(e, 0, offsetof(rl78emu_t, code)); /* the state, not the flash */ + e->port = *port; + e->baud = 115200u; + e->phase = RL78_WAIT_CMD; + fill_ff(e->code, sizeof(e->code)); + fill_ff(e->data, sizeof(e->data)); + e->sec_flg = RL78_FLG_FIXED | RL78_FLG_PROG_EN | RL78_FLG_ERASE_EN | RL78_FLG_BOOT_EN; + e->sec_bot = RL78_BOOT_BLOCKS; + e->sec_ss = 0; + e->sec_se = (uint16_t)RL78_LAST_BLOCK; +} + +void rl78emu_idle(rl78emu_t *e) +{ + e->pstate = P_HDR; +} + +/* ---- replies ---- */ + +static void send_data(rl78emu_t *e, const uint8_t *d, size_t n, bool last) +{ + uint8_t f[260]; + f[0] = RL78_STX; + f[1] = (uint8_t)n; /* 256 is sent as 00H */ + memcpy(&f[2], d, n); + f[2 + n] = rl78_sum(&f[1], n + 1); + f[3 + n] = last ? RL78_ETX : RL78_ETB; + e->port.send(e->port.ctx, f, n + 4); +} + +static void status1(rl78emu_t *e, uint8_t st) +{ + send_data(e, &st, 1, true); +} + +static void status2(rl78emu_t *e, uint8_t st1, uint8_t st2) +{ + const uint8_t d[2] = {st1, st2}; + send_data(e, d, 2, true); +} + +/* ---- the flash ---- */ + +static uint32_t addr24(const uint8_t *p) +{ + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16); +} + +static bool in_code(uint32_t a) { return a <= RL78_CODE_END; } +static bool in_data(uint32_t a) { return a >= RL78_DATA_START && a <= RL78_DATA_END; } + +/* A range of whole blocks inside one flash (code or data): start on a block start, end on a + block end, start <= end. */ +static bool range_ok(uint32_t sa, uint32_t ea) +{ + if ((sa & (RL78_BLOCK - 1u)) != 0u || (ea & (RL78_BLOCK - 1u)) != RL78_BLOCK - 1u || sa > ea) + return false; + return (in_code(sa) && in_code(ea)) || (in_data(sa) && in_data(ea)); +} + +static bool blank(rl78emu_t *e, uint32_t sa, uint32_t ea) +{ + for (uint32_t a = sa; a <= ea; a++) + if (*rl78emu_flash(e, a) != 0xFFu) + return false; + return true; +} + +static bool all_blank(rl78emu_t *e) +{ + return blank(e, RL78_CODE_START, RL78_CODE_END) && blank(e, RL78_DATA_START, RL78_DATA_END); +} + +/* Code flash blocks the security settings shield from rewriting: the boot cluster (when its + rewrite is disabled) and everything outside the flash shield window. Data flash is never + shielded. */ +static bool shielded(rl78emu_t *e, uint32_t sa, uint32_t ea) +{ + if (!in_code(sa)) + return false; + for (uint32_t b = sa / RL78_BLOCK; b <= ea / RL78_BLOCK; b++) { + if (!(e->sec_flg & RL78_FLG_BOOT_EN) && b <= e->sec_bot) + return true; + if (b < e->sec_ss || b > e->sec_se) + return true; + } + return false; +} + +/* ---- commands ---- */ + +static void cmd_baud(rl78emu_t *e, const uint8_t *info, size_t n) +{ + static const uint32_t rates[4] = {115200u, 250000u, 500000u, 1000000u}; + if (n != 2 || info[0] > 3u || info[1] < 18u) { /* D02 is volts x10: 1.8 V minimum */ + status1(e, RL78_ST_PARAM_ERR); + return; + } + const uint8_t d[3] = {RL78_ST_ACK, RL78_FREQ_MHZ, 0x00u}; /* full-speed mode */ + send_data(e, d, 3, true); /* at the old rate */ + e->baud_set = true; + e->baud = rates[info[0]]; + if (e->port.set_baud) + e->port.set_baud(e->port.ctx, e->baud); +} + +static void cmd_signature(rl78emu_t *e) +{ + static const uint8_t sig[22] = { + 0x10, 0x00, 0x06, /* DEC: RL78/G13 */ + 'R', '5', 'F', '1', '0', '0', 'L', 'E', ' ', ' ', /* DEV */ + (uint8_t)RL78_CODE_END, (uint8_t)(RL78_CODE_END >> 8), (uint8_t)(RL78_CODE_END >> 16), + (uint8_t)RL78_DATA_END, (uint8_t)(RL78_DATA_END >> 8), (uint8_t)(RL78_DATA_END >> 16), + 0x01, 0x02, 0x03, /* VER: V1.23 */ + }; + status1(e, RL78_ST_ACK); + send_data(e, sig, sizeof(sig), true); +} + +static void cmd_erase(rl78emu_t *e, const uint8_t *info, size_t n) +{ + if (n != 3) { status1(e, RL78_ST_PARAM_ERR); return; } + uint32_t sa = addr24(info); + if (!range_ok(sa, sa + RL78_BLOCK - 1u)) { status1(e, RL78_ST_PARAM_ERR); return; } + if (!(e->sec_flg & RL78_FLG_ERASE_EN) || shielded(e, sa, sa + RL78_BLOCK - 1u)) { + status1(e, RL78_ST_PROTECT); + return; + } + memset(rl78emu_flash(e, sa), 0xFF, RL78_BLOCK); + status1(e, RL78_ST_ACK); +} + +static void cmd_blank(rl78emu_t *e, const uint8_t *info, size_t n) +{ + if (n != 7 || info[6] > 1u) { status1(e, RL78_ST_PARAM_ERR); return; } + uint32_t sa = addr24(info), ea = addr24(info + 3); + if (!range_ok(sa, ea)) { status1(e, RL78_ST_PARAM_ERR); return; } + /* D01 = 01H also checks the flash option (security data): blank when nothing is disabled */ + bool ok = blank(e, sa, ea); + if (info[6] == 1u && (e->sec_flg & (RL78_FLG_PROG_EN | RL78_FLG_ERASE_EN | RL78_FLG_BOOT_EN)) != + (RL78_FLG_PROG_EN | RL78_FLG_ERASE_EN | RL78_FLG_BOOT_EN)) + ok = false; + status1(e, ok ? RL78_ST_ACK : RL78_ST_BLANK_ERR); +} + +static void cmd_range(rl78emu_t *e, uint8_t com, const uint8_t *info, size_t n) +{ + if (n != 6) { status1(e, RL78_ST_PARAM_ERR); return; } + uint32_t sa = addr24(info), ea = addr24(info + 3); + if (!range_ok(sa, ea)) { status1(e, RL78_ST_PARAM_ERR); return; } + if (com == RL78_CMD_PROGRAM && (!(e->sec_flg & RL78_FLG_PROG_EN) || shielded(e, sa, ea))) { + status1(e, RL78_ST_PROTECT); + return; + } + if (com == RL78_CMD_CHECKSUM) { + uint16_t ck = 0; + for (uint32_t a = sa; a <= ea; a++) + ck = (uint16_t)(ck - *rl78emu_flash(e, a)); + const uint8_t d[2] = {(uint8_t)ck, (uint8_t)(ck >> 8)}; + status1(e, RL78_ST_ACK); + send_data(e, d, 2, true); + return; + } + e->cur = sa; + e->end = ea; + e->mismatch = false; + e->write_failed = false; + e->phase = (com == RL78_CMD_PROGRAM) ? RL78_WAIT_PROG : RL78_WAIT_VERIFY; + status1(e, RL78_ST_ACK); +} + +/* One data frame of a Programming or Verify range. */ +static void data_frame(rl78emu_t *e, const uint8_t *d, size_t n, bool last) +{ + bool prog = (e->phase == RL78_WAIT_PROG); + uint8_t st2 = RL78_ST_ACK; + if (e->cur + n - 1u > e->end) { /* more data than the range holds */ + status2(e, RL78_ST_ACK, prog ? RL78_ST_WRITE_ERR : RL78_ST_VERIFY_ERR); + e->phase = RL78_WAIT_CMD; + return; + } + uint8_t *f = rl78emu_flash(e, e->cur); + if (prog) { + /* a frame is written whole or not at all: any non-blank byte that would change needs an + erase first */ + for (size_t i = 0; i < n; i++) + if (f[i] != 0xFFu && f[i] != d[i]) e->write_failed = true; + if (!e->write_failed) memcpy(f, d, n); + } else if (memcmp(f, d, n) != 0) { + e->mismatch = true; + } + e->cur += (uint32_t)n; + if (prog) { + st2 = e->write_failed ? RL78_ST_WRITE_ERR : RL78_ST_ACK; + } else if (last) { + /* Verify reports a mismatch (or a short range) only in the last frame's ST2 */ + st2 = (e->mismatch || e->cur != e->end + 1u) ? RL78_ST_VERIFY_ERR : RL78_ST_ACK; + } + status2(e, RL78_ST_ACK, st2); + if (prog && e->write_failed) { + e->phase = RL78_WAIT_CMD; + return; + } + if (!last) + return; + if (prog) /* the internal verify after the last frame: the whole range must have arrived */ + status1(e, e->cur == e->end + 1u ? RL78_ST_ACK : RL78_ST_BLANK_ERR); + e->phase = RL78_WAIT_CMD; +} + +static void security_frame(rl78emu_t *e, const uint8_t *d, size_t n) +{ + e->phase = RL78_WAIT_CMD; + if (n != 8) { status1(e, RL78_ST_PARAM_ERR); return; } + uint8_t flg = d[0], bot = d[1]; + uint16_t ss = (uint16_t)(d[2] | (d[3] << 8)), se = (uint16_t)(d[4] | (d[5] << 8)); + if (bot != RL78_BOOT_BLOCKS || ss > se || se > RL78_LAST_BLOCK) { + status1(e, RL78_ST_PARAM_ERR); + return; + } + /* a disabled permission can only come back through Security Release */ + const uint8_t perm = RL78_FLG_PROG_EN | RL78_FLG_ERASE_EN | RL78_FLG_BOOT_EN; + if ((flg & perm) & ~(e->sec_flg & perm)) { + status1(e, RL78_ST_PROTECT); + return; + } + e->sec_flg = (uint8_t)(RL78_FLG_FIXED | (flg & perm)); + e->sec_ss = ss; + e->sec_se = se; + status1(e, RL78_ST_ACK); +} + +static void cmd_sec_get(rl78emu_t *e) +{ + /* Get reports bit 0 as the boot area exchange flag: none on this part */ + const uint8_t d[8] = {e->sec_flg, e->sec_bot, (uint8_t)e->sec_ss, (uint8_t)(e->sec_ss >> 8), + (uint8_t)e->sec_se, (uint8_t)(e->sec_se >> 8), 0xFF, 0xFF}; + status1(e, RL78_ST_ACK); + send_data(e, d, sizeof(d), true); +} + +static void cmd_sec_release(rl78emu_t *e) +{ + if (!(e->sec_flg & RL78_FLG_ERASE_EN) || !(e->sec_flg & RL78_FLG_BOOT_EN)) { + status1(e, RL78_ST_PROTECT); + return; + } + if (!all_blank(e)) { + status1(e, RL78_ST_BLANK_ERR); + return; + } + e->sec_flg = RL78_FLG_FIXED | RL78_FLG_PROG_EN | RL78_FLG_ERASE_EN | RL78_FLG_BOOT_EN; + e->sec_ss = 0; + e->sec_se = (uint16_t)RL78_LAST_BLOCK; + status1(e, RL78_ST_ACK); +} + +static void command(rl78emu_t *e, const uint8_t *p, size_t n) +{ + uint8_t com = p[0]; + const uint8_t *info = p + 1; + size_t ni = n - 1; + if (!e->baud_set && com != RL78_CMD_BAUD) { /* Baud Rate Set must come first */ + status1(e, RL78_ST_CMD_ERR); + return; + } + switch (com) { + case RL78_CMD_BAUD: cmd_baud(e, info, ni); break; + case RL78_CMD_RESET: status1(e, RL78_ST_ACK); break; + case RL78_CMD_SIGNATURE: cmd_signature(e); break; + case RL78_CMD_ERASE: cmd_erase(e, info, ni); break; + case RL78_CMD_BLANK: cmd_blank(e, info, ni); break; + case RL78_CMD_PROGRAM: + case RL78_CMD_VERIFY: + case RL78_CMD_CHECKSUM: cmd_range(e, com, info, ni); break; + case RL78_CMD_SEC_SET: e->phase = RL78_WAIT_SEC; status1(e, RL78_ST_ACK); break; + case RL78_CMD_SEC_GET: cmd_sec_get(e); break; + case RL78_CMD_SEC_RELEASE: cmd_sec_release(e); break; + default: status1(e, RL78_ST_CMD_ERR); break; + } +} + +/* A whole frame arrived with a good checksum and footer. */ +static void frame(rl78emu_t *e, uint8_t hdr, const uint8_t *p, size_t n, uint8_t ftr) +{ + e->frames++; + if (hdr == RL78_SOH) { + if (e->phase != RL78_WAIT_CMD) { /* a command in the middle of a data phase ends it */ + e->phase = RL78_WAIT_CMD; + } + command(e, p, n); + return; + } + /* a data frame */ + switch (e->phase) { + case RL78_WAIT_PROG: + case RL78_WAIT_VERIFY: data_frame(e, p, n, ftr == RL78_ETX); break; + case RL78_WAIT_SEC: security_frame(e, p, n); break; + default: e->errors++; status1(e, RL78_ST_NACK); break; + } +} + +/* A frame failed its checksum or footer: answer in the shape the programmer waits for. */ +static void bad_frame(rl78emu_t *e, uint8_t hdr, uint8_t st) +{ + e->errors++; + if (hdr == RL78_STX && (e->phase == RL78_WAIT_PROG || e->phase == RL78_WAIT_VERIFY)) { + status2(e, st, st); + e->phase = RL78_WAIT_CMD; + return; + } + e->phase = RL78_WAIT_CMD; + status1(e, st); +} + +void rl78emu_rx(rl78emu_t *e, uint8_t b) +{ + switch (e->pstate) { + case P_HDR: + /* anything else (the 3AH/00H mode byte, line noise) is not a frame start */ + if (b == RL78_SOH || b == RL78_STX) { + e->hdr = b; + e->pstate = P_LEN; + } + break; + case P_LEN: + if (e->hdr == RL78_SOH && b == 0u) { /* a command frame has at least COM */ + e->pstate = P_HDR; + bad_frame(e, e->hdr, RL78_ST_NACK); + break; + } + e->len_byte = b; + e->want = b ? b : 256u; + e->got = 0; + e->pstate = P_BODY; + break; + case P_BODY: + e->buf[e->got++] = b; + if (e->got == e->want) + e->pstate = P_SUM; + break; + case P_SUM: + e->sum = b; + e->pstate = P_FTR; + break; + case P_FTR: { + e->pstate = P_HDR; + bool ftr_ok = (b == RL78_ETX) || (e->hdr == RL78_STX && b == RL78_ETB); + if (!ftr_ok) { + bad_frame(e, e->hdr, RL78_ST_NACK); + break; + } + uint8_t s = (uint8_t)(rl78_sum(e->buf, e->want) - e->len_byte); + if (s != e->sum) { + bad_frame(e, e->hdr, RL78_ST_SUM_ERR); + break; + } + frame(e, e->hdr, e->buf, e->want, b); + break; + } + } +} diff --git a/process-node-stm32/rl78emu.h b/process-node-stm32/rl78emu.h new file mode 100644 index 0000000..9127b4d --- /dev/null +++ b/process-node-stm32/rl78emu.h @@ -0,0 +1,116 @@ +/* + * rl78emu.h - an emulated RL78 boot ROM speaking RL78 Protocol A (Renesas R01AN0815, "RL78 + * Protocol A Serial Programming Guide"), so a programmer can be tested without an RL78. + * + * The node enters it when its console TX (PA9, the bench's LA3) is held low through reset, as + * an RL78's TOOL0 is: the line then carries the single-wire programming UART instead of the + * console. The emulated part is an R5F100LE (RL78/G13): 64 KB code flash at 000000H, 4 KB data + * flash at 0F1000H, 1 KB blocks, held in RAM (power off erases it, as a fresh part). + * + * This file is the protocol only (no HAL): bytes in through rl78emu_rx(), frames out through the + * port's send callback. main.c's port drives USART1; tests/test_rl78emu.c drives it on the host. + */ +#ifndef RL78EMU_H +#define RL78EMU_H + +#include +#include +#include + +#define RL78_SOH 0x01u +#define RL78_STX 0x02u +#define RL78_ETX 0x03u +#define RL78_ETB 0x17u + +/* Status codes (Table 1-4). */ +#define RL78_ST_CMD_ERR 0x04u +#define RL78_ST_PARAM_ERR 0x05u +#define RL78_ST_ACK 0x06u +#define RL78_ST_SUM_ERR 0x07u +#define RL78_ST_VERIFY_ERR 0x0Fu +#define RL78_ST_PROTECT 0x10u +#define RL78_ST_NACK 0x15u +#define RL78_ST_ERASE_ERR 0x1Au +#define RL78_ST_BLANK_ERR 0x1Bu /* not blank, or internal verify failed */ +#define RL78_ST_WRITE_ERR 0x1Cu + +/* Commands. */ +#define RL78_CMD_RESET 0x00u +#define RL78_CMD_VERIFY 0x13u +#define RL78_CMD_ERASE 0x22u +#define RL78_CMD_BLANK 0x32u +#define RL78_CMD_PROGRAM 0x40u +#define RL78_CMD_BAUD 0x9Au +#define RL78_CMD_SEC_SET 0xA0u +#define RL78_CMD_SEC_GET 0xA1u +#define RL78_CMD_SEC_RELEASE 0xA2u +#define RL78_CMD_CHECKSUM 0xB0u +#define RL78_CMD_SIGNATURE 0xC0u + +/* The emulated part (R5F100LE). */ +#define RL78_BLOCK 1024u +#define RL78_CODE_START 0x000000u +#define RL78_CODE_END 0x00FFFFu +#define RL78_DATA_START 0x0F1000u +#define RL78_DATA_END 0x0F1FFFu +#define RL78_CODE_SIZE (RL78_CODE_END - RL78_CODE_START + 1u) +#define RL78_DATA_SIZE (RL78_DATA_END - RL78_DATA_START + 1u) +#define RL78_LAST_BLOCK (RL78_CODE_SIZE / RL78_BLOCK - 1u) /* code flash blocks 0..63 */ +#define RL78_BOOT_BLOCKS 0x03u /* boot cluster end block (4 KB) */ +#define RL78_FREQ_MHZ 32u /* Baud Rate Set reply D01 */ + +/* Security flags (Security Set/Get FLG). Bits 7, 6, 5, 3 are fixed to 1. */ +#define RL78_FLG_FIXED 0xE8u +#define RL78_FLG_PROG_EN 0x10u +#define RL78_FLG_ERASE_EN 0x04u +#define RL78_FLG_BOOT_EN 0x02u + +typedef struct { + void (*send)(void *ctx, const uint8_t *buf, size_t len); /* one whole frame */ + void (*set_baud)(void *ctx, uint32_t baud); /* after the reply went out */ + void *ctx; +} rl78emu_port_t; + +typedef enum { RL78_WAIT_CMD, RL78_WAIT_PROG, RL78_WAIT_VERIFY, RL78_WAIT_SEC } rl78_phase_t; + +typedef struct { + rl78emu_port_t port; + /* frame parser */ + uint8_t pstate, hdr, len_byte, sum; + uint16_t want, got; + uint8_t buf[256]; + /* session */ + bool baud_set; + uint32_t baud; + rl78_phase_t phase; + uint32_t cur, end; /* PROG / VERIFY cursor and last address */ + bool mismatch; /* VERIFY: a byte differed */ + bool write_failed; /* PROG: a frame was refused */ + /* the part */ + uint8_t sec_flg, sec_bot; + uint16_t sec_ss, sec_se; + /* counters, for the console and the tests */ + uint32_t frames, errors; + /* last, word-aligned: rl78emu_init fills them 32 bits at a time */ + uint8_t code[RL78_CODE_SIZE] __attribute__((aligned(4))); + uint8_t data[RL78_DATA_SIZE] __attribute__((aligned(4))); +} rl78emu_t; + +/* Fresh part: flash erased (FFH), security all enabled, 115200 until Baud Rate Set. ~3 ms at + 16 MHz (word-wise): the port runs it while the programmer still holds TOOL0 low. */ +void rl78emu_init(rl78emu_t *e, const rl78emu_port_t *port); +/* One received byte. Frames are answered from here. */ +void rl78emu_rx(rl78emu_t *e, uint8_t byte); +/* The line went idle mid-frame (the port's timeout): drop the partial frame. */ +void rl78emu_idle(rl78emu_t *e); + +/* MCU port (rl78emu_port.c). rl78emu_strap(): PA9 (TOOL0) is held low right after reset. + rl78emu_main(): run the emulator on PA9 until the next reset; never returns. */ +bool rl78emu_strap(void); +void rl78emu_main(void); + +/* Helpers shared with the host tests. */ +uint8_t rl78_sum(const uint8_t *p, size_t n); +uint8_t *rl78emu_flash(rl78emu_t *e, uint32_t addr); /* NULL outside flash */ + +#endif diff --git a/process-node-stm32/rl78emu_port.c b/process-node-stm32/rl78emu_port.c new file mode 100644 index 0000000..3fef9d0 --- /dev/null +++ b/process-node-stm32/rl78emu_port.c @@ -0,0 +1,130 @@ +/* + * rl78emu_port.c - runs the RL78 boot ROM emulator (rl78emu.c) on the node's console pins. + * + * Entry, as on an RL78: the programmer holds TOOL0 low while it releases reset. Here TOOL0 is + * the console TX, PA9 (the bench's LA3). When main() finds PA9 low right after reset, it calls + * rl78emu_main() instead of starting the node: the emulator waits for the line to be released, + * then runs USART1 in single-wire half-duplex mode on PA9 (open drain, the programmer's pull-up + * holds it high), 115200 8N1 until Baud Rate Set, and answers Protocol A frames until the next + * reset. The watchdog is not started, so a long idle programming session is fine. + */ +#include "rl78emu.h" + +#include "dwt.h" +#include "stm32f4xx.h" +#include "stm32f4xx_hal.h" + +#define PA9 9U +#define IDLE_DROP_MS 50U /* a frame that stalls this long is dropped */ + +/* 68 KB with the emulated flash: kept out of .bss, whose zeroing at startup took ~5 ms at 16 MHz, + longer than a programmer holds TOOL0 low after reset (rl78emu_init fills it anyway) */ +__attribute__((section(".noinit"))) static rl78emu_t s_emu; +static uint32_t s_bit_ns = 8681U; + +bool rl78emu_strap(void) +{ + RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN; + (void)RCC->AHB1ENR; + GPIOA->MODER &= ~(3U << (PA9 * 2U)); /* input */ + /* The internal pull-up while sampling: an undriven LA3 floats (the pod's pull-up is on only + during a UART session), and a floating pin must not start the emulator. A programmer + holding TOOL0 low overrides it easily. */ + GPIOA->PUPDR = (GPIOA->PUPDR & ~(3U << (PA9 * 2U))) | (1U << (PA9 * 2U)); + for (volatile int i = 0; i < 200; i++) /* ~50 us to settle */ + { + } + bool low = (GPIOA->IDR & (1U << PA9)) == 0U; + GPIOA->PUPDR &= ~(3U << (PA9 * 2U)); + return low; +} + +static uint32_t brr_for(uint32_t baud) +{ + /* 16 MHz, oversampling by 16: 115200 -> 8.6875 (0x8B), 250k/500k/1M divide exactly */ + return (SystemCoreClock + baud / 2U) / baud; +} + +static void port_baud(void *ctx, uint32_t baud) +{ + (void)ctx; + USART1->CR1 &= ~USART_CR1_UE; + USART1->BRR = brr_for(baud); + USART1->CR1 |= USART_CR1_UE; + s_bit_ns = 1000000000U / baud; +} + +static void port_send(void *ctx, const uint8_t *buf, size_t len) +{ + (void)ctx; + /* The programmer sends 2 stop bits and, on a shared wire, cannot hear a reply that starts + before its own frame has ended. RXNE comes in the middle of the first stop bit, so wait + out the rest of both, plus a short turnaround, as the RL78 itself takes tens of us. */ + dwt_delay_us((s_bit_ns * 2U) / 1000U + 20U); + /* our own bytes come back on RX in half-duplex mode: keep the receiver off while sending */ + USART1->CR1 &= ~USART_CR1_RE; + for (size_t i = 0; i < len; i++) + { + while ((USART1->SR & USART_SR_TXE) == 0U) + { + } + USART1->DR = buf[i]; + } + while ((USART1->SR & USART_SR_TC) == 0U) + { + } + (void)USART1->SR; + (void)USART1->DR; + USART1->CR1 |= USART_CR1_RE; +} + +void rl78emu_main(void) +{ + dwt_init(); + /* A fresh part, set up while the programmer still holds TOOL0 low: ~5.6 ms at 16 MHz, so the + programmer must hold it at least that long after the reset (the real part needs 723 us + + tHD; tests/rl78_programmer.py holds 10 ms). */ + const rl78emu_port_t port = {port_send, port_baud, NULL}; + rl78emu_init(&s_emu, &port); + /* the programmer releases TOOL0 after the reset: wait for it */ + while ((GPIOA->IDR & (1U << PA9)) == 0U) + { + } + + RCC->APB2ENR |= RCC_APB2ENR_USART1EN; + (void)RCC->APB2ENR; + GPIOA->AFR[1] = (GPIOA->AFR[1] & ~(0xFU << ((PA9 - 8U) * 4U))) | (7U << ((PA9 - 8U) * 4U)); + GPIOA->OTYPER |= (1U << PA9); /* open drain */ + /* and the internal pull-up: the programmer's pull-up may drop out while it reopens its UART + at a new baud rate, and a floating TOOL0 decodes as noise */ + GPIOA->PUPDR = (GPIOA->PUPDR & ~(3U << (PA9 * 2U))) | (1U << (PA9 * 2U)); + GPIOA->OSPEEDR |= (3U << (PA9 * 2U)); + GPIOA->MODER = (GPIOA->MODER & ~(3U << (PA9 * 2U))) | (2U << (PA9 * 2U)); + + USART1->CR1 = 0U; + USART1->CR2 = 0U; /* 1 stop bit out; 2-stop frames are read fine */ + USART1->CR3 = USART_CR3_HDSEL; /* single wire: TX and RX on PA9 */ + USART1->BRR = brr_for(115200U); + USART1->CR1 = USART_CR1_TE | USART_CR1_RE | USART_CR1_UE; + + uint32_t last = HAL_GetTick(); + for (;;) + { + uint32_t sr = USART1->SR; + if ((sr & (USART_SR_ORE | USART_SR_FE | USART_SR_NE)) != 0U) + { + (void)USART1->DR; /* clears the error; the frame's checksum fails */ + continue; + } + if ((sr & USART_SR_RXNE) != 0U) + { + rl78emu_rx(&s_emu, (uint8_t)USART1->DR); + last = HAL_GetTick(); + } + else if (HAL_GetTick() - last > IDLE_DROP_MS) + { + rl78emu_idle(&s_emu); + last = HAL_GetTick(); + } + } +} diff --git a/process-node-stm32/tests/test_rl78emu.c b/process-node-stm32/tests/test_rl78emu.c new file mode 100644 index 0000000..c5d2731 --- /dev/null +++ b/process-node-stm32/tests/test_rl78emu.c @@ -0,0 +1,332 @@ +/* Host unit test for rl78emu.c, the RL78 Protocol A boot ROM emulator: frames, checksums and + * every command flow, byte for byte against R01AN0815 Rev. 1.10. Run: make test-host */ +#include "rl78emu.h" + +#include +#include +#include + +static int failures; +#define CHECK(c, ...) do { if (!(c)) { printf("FAIL %s:%d: ", __func__, __LINE__); \ + printf(__VA_ARGS__); printf("\n"); failures++; } } while (0) + +/* ---- the port: frames out are queued for the test to read ---- */ +static uint8_t out[4096]; +static size_t nout, rpos; +static uint32_t last_baud; +static void port_send(void *ctx, const uint8_t *b, size_t n) { (void)ctx; memcpy(out + nout, b, n); nout += n; } +static void port_baud(void *ctx, uint32_t baud) { (void)ctx; last_baud = baud; } + +static rl78emu_t E; /* 68 KB of flash: static */ + +static void fresh(void) +{ + const rl78emu_port_t p = {port_send, port_baud, NULL}; + rl78emu_init(&E, &p); + nout = rpos = 0; + last_baud = 0; +} + +static void feed(const uint8_t *b, size_t n) { for (size_t i = 0; i < n; i++) rl78emu_rx(&E, b[i]); } + +/* SOH LEN COM info SUM ETX */ +static void cmd(uint8_t com, const uint8_t *info, size_t n) +{ + uint8_t f[300]; + f[0] = RL78_SOH; f[1] = (uint8_t)(n + 1); f[2] = com; + memcpy(&f[3], info, n); + f[3 + n] = rl78_sum(&f[1], n + 2); + f[4 + n] = RL78_ETX; + feed(f, n + 5); +} + +static void data(const uint8_t *d, size_t n, int last) +{ + uint8_t f[300]; + f[0] = RL78_STX; f[1] = (uint8_t)n; + memcpy(&f[2], d, n); + f[2 + n] = rl78_sum(&f[1], n + 1); + f[3 + n] = last ? RL78_ETX : RL78_ETB; + feed(f, n + 4); +} + +/* Next frame from the emulator: its data in d, returns its length (-1 none / malformed). */ +static int next(uint8_t *d) +{ + if (rpos + 4 > nout || out[rpos] != RL78_STX) return -1; + size_t n = out[rpos + 1] ? out[rpos + 1] : 256; + if (rpos + n + 4 > nout) return -1; + memcpy(d, &out[rpos + 2], n); + uint8_t sum = out[rpos + 2 + n], ftr = out[rpos + 3 + n]; + if (sum != rl78_sum(&out[rpos + 1], n + 1) || ftr != RL78_ETX) return -1; + rpos += n + 4; + return (int)n; +} + +static int st1(void) { uint8_t d[256]; return next(d) == 1 ? d[0] : -1; } +static int st2(int *b) { uint8_t d[256]; if (next(d) != 2) return -1; *b = d[1]; return d[0]; } +static int pending(void) { return (int)(nout - rpos); } + +static void addr(uint8_t *p, uint32_t a) { p[0] = (uint8_t)a; p[1] = (uint8_t)(a >> 8); p[2] = (uint8_t)(a >> 16); } +static void range(uint8_t *p, uint32_t sa, uint32_t ea) { addr(p, sa); addr(p + 3, ea); } + +static void synced(void) +{ + fresh(); + const uint8_t mode = 0x3A; /* single-wire mode byte: no reply */ + feed(&mode, 1); + const uint8_t b[2] = {0x00, 33}; + cmd(RL78_CMD_BAUD, b, 2); + uint8_t d[256]; + (void)next(d); + cmd(RL78_CMD_RESET, NULL, 0); + (void)st1(); +} + +/* Programming of [sa, ea] with pattern(i); returns the final internal-verify status. */ +static uint8_t pat(uint32_t a, int salt) { return (uint8_t)(a * 7u + (uint32_t)salt); } +static int program(uint32_t sa, uint32_t ea, int salt, int *frame_err) +{ + uint8_t r[6]; range(r, sa, ea); + cmd(RL78_CMD_PROGRAM, r, 6); + int s = st1(); + if (s != RL78_ST_ACK) return s; + *frame_err = 0; + for (uint32_t a = sa; a <= ea; a += 256) { + uint8_t d[256]; + for (int i = 0; i < 256; i++) d[i] = pat(a + (uint32_t)i, salt); + data(d, 256, a + 256 > ea); + int b = 0, a1 = st2(&b); + if (a1 != RL78_ST_ACK || b != RL78_ST_ACK) { *frame_err = b; return -2; } + } + return st1(); +} + +static void test_checksum_examples(void) +{ + /* the PDF's worked examples: 01 01 A1 5E 03 and 02 04 FF 80 40 22 1B 03 */ + const uint8_t c[] = {0x01, 0xA1}, d[] = {0x04, 0xFF, 0x80, 0x40, 0x22}; + CHECK(rl78_sum(c, 2) == 0x5E, "command example sum %02x", rl78_sum(c, 2)); + CHECK(rl78_sum(d, 5) == 0x1B, "data example sum %02x", rl78_sum(d, 5)); +} + +static void test_baud_first(void) +{ + fresh(); + const uint8_t mode = 0x3A; + feed(&mode, 1); + CHECK(pending() == 0, "answered the mode byte"); + cmd(RL78_CMD_SIGNATURE, NULL, 0); + CHECK(st1() == RL78_ST_CMD_ERR, "a command before Baud Rate Set is not 04H"); + const uint8_t bad1[2] = {0x04, 33}, bad2[2] = {0x00, 17}; + cmd(RL78_CMD_BAUD, bad1, 2); + CHECK(st1() == RL78_ST_PARAM_ERR, "baud code 4 not refused"); + cmd(RL78_CMD_BAUD, bad2, 2); + CHECK(st1() == RL78_ST_PARAM_ERR, "1.7 V not refused"); + CHECK(last_baud == 0, "a refused Baud Rate Set changed the rate"); + const uint8_t ok[2] = {0x03, 33}; + cmd(RL78_CMD_BAUD, ok, 2); + /* the exact reply: 02 03 06 20 00 SUM 03, then the new rate */ + const uint8_t want[] = {0x02, 0x03, 0x06, 0x20, 0x00, (uint8_t)(0 - 3 - 6 - 0x20), 0x03}; + CHECK(nout - rpos == sizeof(want) && memcmp(out + rpos, want, sizeof(want)) == 0, "baud reply bytes"); + rpos = nout; + CHECK(last_baud == 1000000u, "rate %u", (unsigned)last_baud); + cmd(RL78_CMD_RESET, NULL, 0); + CHECK(st1() == RL78_ST_ACK, "reset not acked"); +} + +static void test_signature(void) +{ + synced(); + cmd(RL78_CMD_SIGNATURE, NULL, 0); + CHECK(st1() == RL78_ST_ACK, "signature status"); + uint8_t d[256]; + const uint8_t want[22] = {0x10, 0x00, 0x06, 'R', '5', 'F', '1', '0', '0', 'L', 'E', ' ', ' ', + 0xFF, 0xFF, 0x00, 0xFF, 0x1F, 0x0F, 0x01, 0x02, 0x03}; + CHECK(next(d) == 22 && memcmp(d, want, 22) == 0, "signature data"); +} + +static void test_erase_blank_program_verify(void) +{ + synced(); + uint8_t r[7], a[3]; + int fe; + /* fresh part: blank */ + range(r, 0x000000, 0x00FFFF); r[6] = 0; + cmd(RL78_CMD_BLANK, r, 7); + CHECK(st1() == RL78_ST_ACK, "fresh code flash not blank"); + /* program two blocks: 8 frames of 256, double ACK each, then the internal verify ACK */ + CHECK(program(0x000400, 0x000BFF, 1, &fe) == RL78_ST_ACK, "program"); + CHECK(*rl78emu_flash(&E, 0x000400) == pat(0x400, 1) && *rl78emu_flash(&E, 0x000BFF) == pat(0xBFF, 1) && + *rl78emu_flash(&E, 0x0003FF) == 0xFF && *rl78emu_flash(&E, 0x000C00) == 0xFF, "flash contents"); + range(r, 0x000400, 0x0007FF); r[6] = 0; + cmd(RL78_CMD_BLANK, r, 7); + CHECK(st1() == RL78_ST_BLANK_ERR, "programmed block reads blank"); + range(r, 0x000C00, 0x000FFF); + cmd(RL78_CMD_BLANK, r, 7); + CHECK(st1() == RL78_ST_ACK, "untouched block not blank"); + /* writing over programmed bytes without an erase fails (1CH) */ + CHECK(program(0x000400, 0x0007FF, 2, &fe) == -2 && fe == RL78_ST_WRITE_ERR, "overwrite allowed (%d)", fe); + /* verify: good, then one byte off (reported in the LAST frame's ST2 only) */ + for (int bad = 0; bad < 2; bad++) { + range(r, 0x000400, 0x000BFF); + cmd(RL78_CMD_VERIFY, r, 6); + CHECK(st1() == RL78_ST_ACK, "verify status"); + for (uint32_t x = 0x400; x <= 0xBFF; x += 256) { + uint8_t d[256]; + for (int i = 0; i < 256; i++) d[i] = pat(x + (uint32_t)i, 1); + if (bad && x == 0x400) d[5] ^= 1; + int last = x + 256 > 0xBFF, b = 0; + data(d, 256, last); + CHECK(st2(&b) == RL78_ST_ACK, "verify ST1"); + int want = (bad && last) ? RL78_ST_VERIFY_ERR : RL78_ST_ACK; + CHECK(b == want, "verify ST2 %02x want %02x at %x", b, want, (unsigned)x); + } + CHECK(pending() == 0, "verify sent a final status"); + } + /* checksum: 0000H minus every byte, 16 bits, low byte first */ + range(r, 0x000400, 0x0007FF); + cmd(RL78_CMD_CHECKSUM, r, 6); + uint16_t ck = 0; + for (uint32_t x = 0x400; x <= 0x7FF; x++) ck = (uint16_t)(ck - pat(x, 1)); + uint8_t d[256]; + CHECK(st1() == RL78_ST_ACK && next(d) == 2 && d[0] == (uint8_t)ck && d[1] == (uint8_t)(ck >> 8), "checksum"); + /* erase one block, then it programs again */ + addr(a, 0x000400); + cmd(RL78_CMD_ERASE, a, 3); + CHECK(st1() == RL78_ST_ACK, "erase"); + CHECK(program(0x000400, 0x0007FF, 2, &fe) == RL78_ST_ACK, "program after erase"); + /* data flash works the same way */ + CHECK(program(0x0F1000, 0x0F13FF, 3, &fe) == RL78_ST_ACK, "data flash program"); +} + +static void test_parameters(void) +{ + synced(); + uint8_t r[7], a[3]; + addr(a, 0x000401); + cmd(RL78_CMD_ERASE, a, 3); + CHECK(st1() == RL78_ST_PARAM_ERR, "misaligned erase"); + addr(a, 0x010000); + cmd(RL78_CMD_ERASE, a, 3); + CHECK(st1() == RL78_ST_PARAM_ERR, "erase past code flash"); + const uint32_t bad[][2] = { + {0x000000, 0x0003FE}, /* end not a block end */ + {0x000400, 0x0003FF}, /* start > end */ + {0x00FC00, 0x0F13FF}, /* crosses code / data flash */ + {0x00FC00, 0x0103FF}, /* past code flash */ + }; + for (size_t i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) { + range(r, bad[i][0], bad[i][1]); + cmd(RL78_CMD_PROGRAM, r, 6); + CHECK(st1() == RL78_ST_PARAM_ERR, "range %zu not refused", i); + } + range(r, 0, 0x3FF); r[6] = 2; + cmd(RL78_CMD_BLANK, r, 7); + CHECK(st1() == RL78_ST_PARAM_ERR, "blank check D01=2"); + cmd(0x55, NULL, 0); + CHECK(st1() == RL78_ST_CMD_ERR, "unknown command"); + /* a short Programming range: ETX before the end -> the internal verify fails */ + range(r, 0, 0x3FF); + cmd(RL78_CMD_PROGRAM, r, 6); + CHECK(st1() == RL78_ST_ACK, "program status"); + uint8_t d[256]; memset(d, 0x11, sizeof(d)); + int b = 0; + data(d, 256, 1); + CHECK(st2(&b) == RL78_ST_ACK && b == RL78_ST_ACK, "short frame"); + CHECK(st1() == RL78_ST_BLANK_ERR, "short range passed the internal verify"); +} + +static void test_bad_frames(void) +{ + synced(); + /* bad checksum: 07H */ + const uint8_t f1[] = {RL78_SOH, 0x01, RL78_CMD_RESET, 0x00, RL78_ETX}; + feed(f1, sizeof(f1)); + CHECK(st1() == RL78_ST_SUM_ERR, "bad sum"); + /* bad footer: 15H */ + const uint8_t f2[] = {RL78_SOH, 0x01, RL78_CMD_RESET, 0xFF, RL78_ETB}; + feed(f2, sizeof(f2)); + CHECK(st1() == RL78_ST_NACK, "bad footer"); + /* a partial frame dropped by the idle timeout, then a good one */ + const uint8_t f3[] = {RL78_SOH, 0x05, RL78_CMD_RESET}; + feed(f3, sizeof(f3)); + rl78emu_idle(&E); + cmd(RL78_CMD_RESET, NULL, 0); + CHECK(st1() == RL78_ST_ACK, "no resync after idle"); + /* a bad data frame during Programming gets the two-byte status */ + uint8_t r[6]; range(r, 0x2000, 0x23FF); + cmd(RL78_CMD_PROGRAM, r, 6); + CHECK(st1() == RL78_ST_ACK, "program status"); + uint8_t f4[260]; f4[0] = RL78_STX; f4[1] = 0; memset(&f4[2], 0x22, 256); f4[258] = 0x55; f4[259] = RL78_ETB; /* the right sum is 00H */ + feed(f4, sizeof(f4)); + int b = 0; + CHECK(st2(&b) == RL78_ST_SUM_ERR, "bad data frame sum"); +} + +static void test_security(void) +{ + synced(); + uint8_t d[256], r[7]; + int fe; + cmd(RL78_CMD_SEC_GET, NULL, 0); + CHECK(st1() == RL78_ST_ACK && next(d) == 8 && d[0] == 0xFE && d[1] == 0x03 && d[2] == 0 && d[3] == 0 && + d[4] == 63 && d[5] == 0 && d[6] == 0xFF && d[7] == 0xFF, "default security"); + /* disable programming */ + cmd(RL78_CMD_SEC_SET, NULL, 0); + CHECK(st1() == RL78_ST_ACK, "security set status"); + const uint8_t no_prog[8] = {0xEE, 0x03, 0x00, 0x00, 63, 0x00, 0xFF, 0xFF}; + data(no_prog, 8, 1); + CHECK(st1() == RL78_ST_ACK, "security set data"); + CHECK(program(0, 0x3FF, 1, &fe) == RL78_ST_PROTECT, "program while disabled"); + range(r, 0, 0xFFFF); r[6] = 1; + cmd(RL78_CMD_BLANK, r, 7); + CHECK(st1() == RL78_ST_BLANK_ERR, "flash option reads blank with a flag disabled"); + /* re-enabling needs a Security Release */ + cmd(RL78_CMD_SEC_SET, NULL, 0); + (void)st1(); + const uint8_t all[8] = {0xFE, 0x03, 0x00, 0x00, 63, 0x00, 0xFF, 0xFF}; + data(all, 8, 1); + CHECK(st1() == RL78_ST_PROTECT, "re-enabled a disabled flag"); + /* a wrong boot cluster size is a parameter error */ + cmd(RL78_CMD_SEC_SET, NULL, 0); + (void)st1(); + const uint8_t bot[8] = {0xEE, 0x07, 0x00, 0x00, 63, 0x00, 0xFF, 0xFF}; + data(bot, 8, 1); + CHECK(st1() == RL78_ST_PARAM_ERR, "BOT 07H accepted"); + /* release: refused while something is written, accepted on a blank part */ + synced(); + CHECK(program(0x1000, 0x13FF, 1, &fe) == RL78_ST_ACK, "program"); + cmd(RL78_CMD_SEC_RELEASE, NULL, 0); + CHECK(st1() == RL78_ST_BLANK_ERR, "release with data written"); + uint8_t a[3]; addr(a, 0x1000); + cmd(RL78_CMD_ERASE, a, 3); + (void)st1(); + cmd(RL78_CMD_SEC_RELEASE, NULL, 0); + CHECK(st1() == RL78_ST_ACK, "release on a blank part"); + /* a flash shield window protects the blocks outside it */ + cmd(RL78_CMD_SEC_SET, NULL, 0); + (void)st1(); + const uint8_t fsw[8] = {0xFE, 0x03, 8, 0x00, 15, 0x00, 0xFF, 0xFF}; /* blocks 8..15 */ + data(fsw, 8, 1); + CHECK(st1() == RL78_ST_ACK, "set FSW"); + CHECK(program(0x2000, 0x3FFF, 1, &fe) == RL78_ST_ACK, "program inside the window"); + CHECK(program(0x4000, 0x43FF, 1, &fe) == RL78_ST_PROTECT, "program outside the window"); + addr(a, 0x0000); + cmd(RL78_CMD_ERASE, a, 3); + CHECK(st1() == RL78_ST_PROTECT, "erase outside the window"); +} + +int main(void) +{ + test_checksum_examples(); + test_baud_first(); + test_signature(); + test_erase_blank_program_verify(); + test_parameters(); + test_bad_frames(); + test_security(); + if (failures) { printf("test_rl78emu: %d FAILED\n", failures); return 1; } + printf("test_rl78emu: all passed\n"); + return 0; +} From 284a04f1f78c3cac42fcb9ee892a750b92b0a4b9 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Wed, 18 Nov 2026 09:33:42 -0600 Subject: [PATCH 2/2] process-node: RL78 programming HIL tests against the emulator tests/rl78_programmer.py, a minimal Protocol A programmer over the pod's one-wire UART and pod-timed entry; tests/test_rl78.py (marker rl78) runs it: signature, program/verify/checksum, data flash, parameter errors, 250k/500k/1M baud, security, and a normal boot afterwards. Co-Authored-By: Claude Opus 5.5 --- process-node-stm32/README.md | 28 +++ process-node-stm32/tests/conftest.py | 1 + process-node-stm32/tests/rl78_programmer.py | 207 ++++++++++++++++++++ process-node-stm32/tests/test_rl78.py | 135 +++++++++++++ 4 files changed, 371 insertions(+) create mode 100644 process-node-stm32/tests/rl78_programmer.py create mode 100644 process-node-stm32/tests/test_rl78.py diff --git a/process-node-stm32/README.md b/process-node-stm32/README.md index 8d274b7..e6d680c 100644 --- a/process-node-stm32/README.md +++ b/process-node-stm32/README.md @@ -136,6 +136,34 @@ With 8 MHz the fastest bitrate is 500 kbit/s; 1 Mbit/s needs a 16 MHz crystal. Received frames print as `CAN rx id=0x123 ext=0 rtr=0 dlc=2 data=0102`. +## RL78 boot ROM emulator + +Holding the console TX (PA9, the bench's LA3) low through reset starts an emulated RL78 boot +ROM instead of the node, the way an RL78 enters its programming mode when TOOL0 is low at reset. +It speaks RL78 Protocol A (Renesas R01AN0815) on that one wire, so a programmer can be tested on +this board with no RL78 on the bench: + +- The part is an R5F100LE (RL78/G13): 64 KB code flash at 000000H, 4 KB data flash at 0F1000H, + 1 KB blocks. Its flash lives in RAM, so every entry starts with an erased part. +- Commands: Reset, Baud Rate Set (115200, 250000, 500000, 1000000), Silicon Signature, Block + Erase, Block Blank Check, Programming, Verify, Checksum, Security Set, Get and Release, with the + guide's frames, checksums and status codes. Like real flash, a byte is written only when blank + (an erase comes first), and the security flags are enforced. +- The line is open drain, single-wire half duplex, 1 stop bit from the emulator (a programmer sends + 2). It answers no sooner than the end of the programmer's second stop bit. +- TOOL0 has to stay low for about 6 ms after the reset release (the emulator sets up its flash in + that time). A real RL78 needs only 723 us plus tHD, so a programmer written for the real part + should hold it longer when it runs against this board. +- A normal boot is unchanged: the strap is sampled with the internal pull-up on, so an undriven + LA3 never starts the emulator. + +`tests/rl78_programmer.py` is a minimal Protocol A programmer over the BenchPod's one-wire UART +(`open_uart(half_duplex=True, entry=UartEntry(...))`, pod firmware with gateware v57), and +`tests/test_rl78.py` (marker `rl78`) runs it against the emulator: entry and signature, program, +verify and checksum, data flash, parameter errors, every baud rate, security, and a normal boot +afterwards. The protocol core (`rl78emu.c`) is also covered on the host by +`tests/test_rl78emu.c` (`make test-host`). + ## HIL tests ```bash diff --git a/process-node-stm32/tests/conftest.py b/process-node-stm32/tests/conftest.py index 5e9a518..2b996bc 100644 --- a/process-node-stm32/tests/conftest.py +++ b/process-node-stm32/tests/conftest.py @@ -59,6 +59,7 @@ "sensors_faults": "injected sensor faults", "needs_new_wiring": "skips unless BENCH_NEW_WIRING=1 (SPI2 on LA9/LA10/LA13/LA14, USART3 on LA7/LA8)", "needs_la6_resistor": "skips unless BENCH_LA6_RESISTOR=1 (1 kOhm between PA8 and LA6)", + "rl78": "RL78 Protocol A programming on LA3 against the node's RL78 boot ROM emulator", } diff --git a/process-node-stm32/tests/rl78_programmer.py b/process-node-stm32/tests/rl78_programmer.py new file mode 100644 index 0000000..d7f95a0 --- /dev/null +++ b/process-node-stm32/tests/rl78_programmer.py @@ -0,0 +1,207 @@ +"""A minimal RL78 Protocol A programmer over the BenchPod (Renesas R01AN0815): enough to drive the +node's RL78 boot ROM emulator (rl78emu.c) from the HIL tests, and an example of the pod's one-wire +UART (``half_duplex``) and pod-timed boot-mode entry (``UartEntry``). + +TOOL0 is one LA channel. The pod holds it low through the target's reset, releases it, sends the +3AH single-wire mode byte, and then talks to the boot ROM on the same wire: the programmer sends +two stop bits, the target answers with one. In half duplex the pod does not read back its own +bytes, so unlike a USB-serial programmer there is no echo to strip. +""" + +from __future__ import annotations + +import time +from typing import List, Optional, Tuple + +from embeddedci.benchpod import UartEntry + +SOH, STX, ETX, ETB = 0x01, 0x02, 0x03, 0x17 +ACK = 0x06 +BLOCK = 1024 +BAUDS = {115200: 0, 250000: 1, 500000: 2, 1000000: 3} + +# The entry, timed on the pod: TOOL0 low through a 5 ms reset, low 10 ms more (the guide's tRT is +# at least 723 us + tHD; Baud Rate Set must follow within 100 ms of the reset), released, then +# the single-wire mode byte (tTM >= 16 us after release). +ENTRY = UartEntry(reset_ms=5, tx_low=True, hold_ms=10, idle_ms=1, data=b"\x3a") + + +def checksum(data: bytes) -> int: + """0 minus every byte, low 8 bits (covers LEN through the last data byte).""" + return (-sum(data)) & 0xFF + + +class Rl78Error(Exception): + def __init__(self, what: str, status: int) -> None: + super().__init__(f"{what}: status {status:02X}H") + self.status = status + + +class Rl78Programmer: + def __init__(self, bp, tool0, timeout: float = 2.0) -> None: + self.bp = bp + self.tool0 = tool0 + self.timeout = timeout + self.uart = None + self.baud = 115200 + self._rx = b"" + + # -- link -------------------------------------------------------------------------------- + + def _open(self, baud: int, entry: Optional[UartEntry]) -> None: + self.uart = self.bp.open_uart(rx=self.tool0, half_duplex=True, baud=baud, stop_bits=2, + entry=entry, encoding="latin-1") + self.baud = baud + self._rx = b"" + + def enter(self, baud: int = 115200, volts: float = 3.3) -> Tuple[int, int]: + """Reset into the boot ROM, send the mode byte, Baud Rate Set, then Reset at the new rate. + Returns (frequency MHz, mode) from the Baud Rate Set reply.""" + self.close() + self._open(115200, ENTRY) + time.sleep(0.002) # tMB: >= 62 us after the mode byte + freq, mode = self.baud_set(baud, volts) + self.reset() + return freq, mode + + def close(self) -> None: + if self.uart is not None: + self.uart.close() + self.uart = None + + def _write(self, frame: bytes) -> None: + self.uart.write(frame.decode("latin-1")) + + def _read(self, n: int, deadline: float) -> bytes: + while len(self._rx) < n: + left = deadline - time.monotonic() + if left <= 0: + raise TimeoutError(f"RL78: timed out waiting for {n} bytes, got {self._rx.hex()}") + self._rx += self.uart.read(timeout=min(left, 0.05)).encode("latin-1") + out, self._rx = self._rx[:n], self._rx[n:] + return out + + def frame(self, timeout: Optional[float] = None) -> Tuple[bytes, bool]: + """One data frame from the target: (data, last).""" + deadline = time.monotonic() + (timeout or self.timeout) + hdr = self._read(2, deadline) + if hdr[0] != STX: + raise ValueError(f"RL78: frame starts with {hdr[0]:02X}H, not STX") + n = hdr[1] or 256 + rest = self._read(n + 2, deadline) + data, s, ftr = rest[:n], rest[n], rest[n + 1] + if s != checksum(hdr[1:2] + data): + raise ValueError("RL78: bad checksum from the target") + if ftr not in (ETX, ETB): + raise ValueError(f"RL78: frame ends with {ftr:02X}H") + return data, ftr == ETX + + def status(self, what: str, n: int = 1) -> bytes: + data, _ = self.frame() + if len(data) != n: + raise ValueError(f"{what}: {len(data)}-byte status, expected {n}") + return data + + def command(self, com: int, info: bytes = b"") -> None: + body = bytes([len(info) + 1, com]) + info + self._write(bytes([SOH]) + body + bytes([checksum(body), ETX])) + + def data_frame(self, data: bytes, last: bool) -> None: + body = bytes([len(data) & 0xFF]) + data + self._write(bytes([STX]) + body + bytes([checksum(body), ETX if last else ETB])) + + def _ack(self, what: str) -> None: + st = self.status(what)[0] + if st != ACK: + raise Rl78Error(what, st) + + # -- commands ---------------------------------------------------------------------------- + + def baud_set(self, baud: int, volts: float = 3.3) -> Tuple[int, int]: + self.command(0x9A, bytes([BAUDS[baud], int(volts * 10)])) + st = self.status("Baud Rate Set", 3) + if st[0] != ACK: + raise Rl78Error("Baud Rate Set", st[0]) + if baud != self.baud: # the reply came at the old rate: switch now + self.close() + self._open(baud, None) + return st[1], st[2] + + def reset(self) -> None: + self.command(0x00) + self._ack("Reset") + + def signature(self) -> dict: + self.command(0xC0) + self._ack("Silicon Signature") + d, _ = self.frame() + le = lambda b: b[0] | b[1] << 8 | b[2] << 16 + return {"device_code": d[0:3].hex(), "name": d[3:13].decode("ascii").rstrip(), + "code_end": le(d[13:16]), "data_end": le(d[16:19]), + "version": f"V{d[19]}.{d[20]}{d[21]}"} + + @staticmethod + def _range(sa: int, ea: int) -> bytes: + return sa.to_bytes(3, "little") + ea.to_bytes(3, "little") + + def erase(self, addr: int) -> None: + self.command(0x22, addr.to_bytes(3, "little")) + self._ack(f"Block Erase {addr:06X}H") + + def blank_check(self, sa: int, ea: int) -> bool: + self.command(0x32, self._range(sa, ea) + b"\x00") + st = self.status("Block Blank Check")[0] + if st == ACK: + return True + if st == 0x1B: + return False + raise Rl78Error("Block Blank Check", st) + + def _stream(self, what: str, data: bytes) -> List[int]: + """Send data in 256-byte frames; return each frame's ST2.""" + st2 = [] + for off in range(0, len(data), 256): + chunk = data[off:off + 256] + self.data_frame(chunk, off + 256 >= len(data)) + s1, s2 = self.status(what, 2) + if s1 != ACK: + raise Rl78Error(what, s1) + st2.append(s2) + if s2 != ACK and off + 256 < len(data): + raise Rl78Error(what, s2) + return st2 + + def program(self, sa: int, data: bytes) -> None: + ea = sa + len(data) - 1 + self.command(0x40, self._range(sa, ea)) + self._ack("Programming") + st2 = self._stream("Programming", data) + if st2[-1] != ACK: + raise Rl78Error("Programming", st2[-1]) + self._ack("Programming internal verify") + + def verify(self, sa: int, data: bytes) -> bool: + self.command(0x13, self._range(sa, sa + len(data) - 1)) + self._ack("Verify") + last = self._stream("Verify", data)[-1] + if last not in (ACK, 0x0F): + raise Rl78Error("Verify", last) + return last == ACK + + def checksum(self, sa: int, ea: int) -> int: + self.command(0xB0, self._range(sa, ea)) + self._ack("Checksum") + d, _ = self.frame() + return d[0] | d[1] << 8 + + def security_get(self) -> bytes: + self.command(0xA1) + self._ack("Security Get") + return self.frame()[0] + + def security_set(self, flg: int, bot: int, ss: int, se: int) -> None: + self.command(0xA0) + self._ack("Security Set") + self.data_frame(bytes([flg, bot]) + ss.to_bytes(2, "little") + se.to_bytes(2, "little") + + b"\xff\xff", True) + self._ack("Security Set data") diff --git a/process-node-stm32/tests/test_rl78.py b/process-node-stm32/tests/test_rl78.py new file mode 100644 index 0000000..97fbc2e --- /dev/null +++ b/process-node-stm32/tests/test_rl78.py @@ -0,0 +1,135 @@ +"""RL78 programming over TOOL0, against the node's RL78 boot ROM emulator (rl78emu.c). + +The pod holds LA3 (the node's PA9, its console TX) low through reset: the node then answers as an +RL78/G13 boot ROM (an R5F100LE, RL78 Protocol A) on that one wire, instead of booting. These tests +drive it with the minimal programmer in rl78_programmer.py: the same path a programmer for a real +RL78 takes through the pod (one-wire UART, pod-timed entry). Needs firmware 3.10.11+ on the pod +(gateware v57, capability ``uart_hd``). +""" + +from __future__ import annotations + +import os +import time + +import pytest + +from rl78_programmer import ACK, BLOCK, Rl78Error, Rl78Programmer, checksum + +pytestmark = [pytest.mark.hardware, pytest.mark.rl78] + +# After a cold power-on the NUCLEO's on-board ST-Link holds the target in reset for 2-4 s +# (measured), and a reset from the pod in that window is lost. +POWER_SETTLE_S = 5.0 + + +@pytest.fixture(scope="module") +def rl78(benchpod, wiring, node): + """The programmer on LA3. The node's console (the session-wide ``node`` fixture, which also + flashes the firmware) is closed meanwhile, as LA3 is its TX; afterwards the node is + power-cycled back into a normal boot.""" + if not benchpod.supports("uart_hd"): + pytest.skip("the pod's firmware has no one-wire UART (uart_hd, gateware v57): update it") + with node.paused(): + benchpod.power_off(wiring.efuse) + time.sleep(0.5) + benchpod.power_on(wiring.efuse) + time.sleep(POWER_SETTLE_S) + prog = Rl78Programmer(benchpod, wiring.uart_rx) + try: + yield prog + finally: + prog.close() + benchpod.power_off(wiring.efuse) + time.sleep(0.5) + benchpod.power_on(wiring.efuse) + node.uart.read_until("APP_OK", timeout=POWER_SETTLE_S + 5) + + +def test_checksum_examples(): + # R01AN0815's worked examples: 01 01 A1 5E 03 and 02 04 FF 80 40 22 1B 03 + assert checksum(bytes([0x01, 0xA1])) == 0x5E + assert checksum(bytes([0x04, 0xFF, 0x80, 0x40, 0x22])) == 0x1B + + +def test_entry_and_signature(rl78): + freq, mode = rl78.enter() + assert (freq, mode) == (32, 0) + sig = rl78.signature() + assert sig == {"device_code": "100006", "name": "R5F100LE", "code_end": 0x00FFFF, + "data_end": 0x0F1FFF, "version": "V1.23"} + + +def test_program_verify_checksum(rl78): + rl78.enter() + image = os.urandom(2 * BLOCK) + assert rl78.blank_check(0x000800, 0x000FFF) + rl78.program(0x000800, image) + assert not rl78.blank_check(0x000800, 0x000BFF) + assert rl78.verify(0x000800, image) + bad = bytearray(image) + bad[1500] ^= 0x40 + assert not rl78.verify(0x000800, bytes(bad)) + assert rl78.checksum(0x000800, 0x000FFF) == (-sum(image)) & 0xFFFF + # flash needs an erase before it is written again + with pytest.raises(Rl78Error) as err: + rl78.program(0x000800, bytes(BLOCK)) + assert err.value.status == 0x1C + rl78.erase(0x000800) + assert rl78.blank_check(0x000800, 0x000BFF) + rl78.program(0x000800, bytes(BLOCK)) + assert rl78.verify(0x000800, bytes(BLOCK)) + + +def test_data_flash(rl78): + rl78.enter() + image = os.urandom(BLOCK) + rl78.erase(0x0F1000) + rl78.program(0x0F1000, image) + assert rl78.verify(0x0F1000, image) + + +def test_parameter_errors(rl78): + rl78.enter() + with pytest.raises(Rl78Error) as err: + rl78.erase(0x000401) # not a block start + assert err.value.status == 0x05 + with pytest.raises(Rl78Error) as err: + rl78.program(0x00FC00, bytes(2 * BLOCK)) # past the end of code flash + assert err.value.status == 0x05 + + +@pytest.mark.parametrize("baud", [250000, 500000, 1000000]) +def test_baud_rates(rl78, baud): + rl78.enter(baud=baud) + assert rl78.baud == baud + image = os.urandom(4 * BLOCK) + rl78.erase(0x004000) + rl78.erase(0x004400) + rl78.erase(0x004800) + rl78.erase(0x004C00) + t0 = time.monotonic() + rl78.program(0x004000, image) + took = time.monotonic() - t0 + assert rl78.verify(0x004000, image) + print(f"{baud} baud: 4 KB programmed in {took:.2f} s") + + +def test_security(rl78): + rl78.enter() + flg = rl78.security_get() + assert flg[:6] == bytes([0xFE, 0x03, 0x00, 0x00, 63, 0x00]) + rl78.security_set(0xEE, 0x03, 0, 63) # programming disabled + with pytest.raises(Rl78Error) as err: + rl78.program(0x001000, bytes(BLOCK)) + assert err.value.status == 0x10 + + +def test_normal_boot_is_unchanged(benchpod, wiring, rl78): + """Without the strap the node boots as before (the emulator never starts by accident).""" + rl78.close() + benchpod.power_off(wiring.efuse) + time.sleep(0.5) + with benchpod.open_uart(rx=wiring.uart_rx, tx=wiring.uart_tx, baud=115200) as uart: + benchpod.power_on(wiring.efuse) + uart.expect("APP_OK", timeout=POWER_SETTLE_S + 5)