From 5afd424f348f91c730a9b202c2c7bc96c29f59c0 Mon Sep 17 00:00:00 2001 From: UD-V2G Team Date: Wed, 30 Sep 2026 15:28:02 -0400 Subject: [PATCH 1/2] Add S12XE/XS/XF flash programming (XMMC/XFTMRK routine) Vendor USBDM's HCS12-XMMC-XFTMRK-flash-program.s19 and route the paged S12X device entries to it. The routine uses the same large-code ABI as GMMC, so the driver is unchanged. Five parts gain geometry: mc9s12xep100-family, xs64, xs128, xs256 and xf512. Every existing table entry is byte-identical. - gen_devices: accept the XFTMRK routine. XMMC entries give the reset page (0xFE) as pageReset and size the window with `pages`, so the lowest page is derived from pageEnd and the page count (1024K -> C0). MMCV4 keeps using pageReset. - prepareFlash: every HCS12 flash operation now starts with a special-mode hardware reset and a reconnect, as the reference programmer does. A target running its own code acks memory access but not the PC write that starts the routine (BDM_RC_ACK_TIMEOUT), so flashing a running board failed. - XFTMRK expects FCLKDIV to be loaded already and otherwise reports an invalid divider. Port the reference Tcl initTarget/initFlash: COP off, FCLKDIV from 2x the special-mode bus clock, FPROT/EPROT unprotected. - --sim refuses XFTMRK parts; there is no S12XE flash model and the FTS one would report a meaningless pass. Tested on an MC9S12XET256 (SDID 0xC081) with a JS16 USBDM on macOS: unsecure (mass erase, then FSEC=0xFE), then program with verify of a 61 KB image across both fixed windows and four PPAGE pages. A raw-BDM readback of every window, setting PPAGE directly, matched all 61,825 bytes. After a normal reset the board runs the image: halted in the application's main loop, PPAGE=0xFB. --- README.md | 12 ++-- build.zig | 3 + src/device.zig | 14 ++++ src/device_types.zig | 4 +- src/main.zig | 69 ++++++++++++++++++- tools/gen_devices.zig | 17 ++++- .../HCS12-XMMC-XFTMRK-flash-program.s19 | 35 ++++++++++ vendor/flash-routines/README.md | 4 ++ 8 files changed, 147 insertions(+), 11 deletions(-) create mode 100644 vendor/flash-routines/HCS12-XMMC-XFTMRK-flash-program.s19 diff --git a/README.md b/README.md index a480c3d..e0e486d 100644 --- a/README.md +++ b/README.md @@ -49,16 +49,18 @@ behave as on-target. USB-only commands (`probe`/`version`/`list`) are declined. ## Flash programming Reference RAM flash-routine method: vendored routines run on the target CPU. -Geometry (`--part`) comes from a build-time table of 188 parts (vendored USBDM -device DB), which also backs `identify`. Families: HCS08/RS08, HCS12, CFV1, plus -S12G EEPROM. Destructive commands confirm unless `--force`. +Geometry (`--part`) comes from a build-time table of 193 parts (vendored USBDM +device DB), which also backs `identify`. Families: HCS08/RS08, HCS12 (classic S12, +S12G, and S12XE/XS/XF on the paged map), CFV1, plus S12G EEPROM. Destructive +commands confirm unless `--force`. HCS12 flash operations start with a +special-mode reset, so the target does not need to be halted first. ## GDB remote stub `usbdm gdb` serves the GDB remote protocol over TCP: registers, memory, single-step, `continue`/`vCont`, flash `load` (`vFlash*`), `monitor reset`/`halt`. -Hardware breakpoints on HCS08, classic-S12 HCS12, and CFV1; S12G and watchpoints -use GDB software breakpoints. +Hardware breakpoints on HCS08, classic-S12 HCS12, and CFV1; S12G, S12X and +watchpoints use GDB software breakpoints. ## Layout diff --git a/build.zig b/build.zig index 8490a23..5e659ad 100644 --- a/build.zig +++ b/build.zig @@ -90,6 +90,9 @@ pub fn build(b: *std.Build) void { exe.root_module.addAnonymousImport("flash_hcs12_gmmc", .{ .root_source_file = b.path("vendor/flash-routines/HCS12-GMMC-FTMRG-flash-program.s19"), }); + exe.root_module.addAnonymousImport("flash_hcs12_xmmc", .{ + .root_source_file = b.path("vendor/flash-routines/HCS12-XMMC-XFTMRK-flash-program.s19"), + }); exe.root_module.addAnonymousImport("flash_cfv1", .{ .root_source_file = b.path("vendor/flash-routines/ColdfireV1-default-flash-program.elf.S19"), }); diff --git a/src/device.zig b/src/device.zig index 20754ee..5fbb12f 100644 --- a/src/device.zig +++ b/src/device.zig @@ -101,6 +101,20 @@ test "generated HCS08 table: geometry and routine-blob selection" { try std.testing.expectEqual(@as(u32, 8), g240.write_align); try std.testing.expectEqual(@as(u32, 0x1400), g240.ram_start); try std.testing.expectEqual(@as(u32, 0x100), g240.eeprom.?.sector); // erase sector, not the XML phrase size + // S12XE: XMMC/XFTMRK, FTM at 0x0100, PPAGE-banked C0..FF from pages="1024K". + const xep = lookup("mc9s12xep100-family").?; + try std.testing.expectEqual(Hcs12Routine.xmmc_xftmrk, xep.hcs12_routine); + try std.testing.expectEqual(@as(u32, 0x0100), xep.flash_base); + try std.testing.expectEqual(@as(u32, 8), xep.write_align); + try std.testing.expectEqual(@as(u32, 1024), xep.page_size); + try std.testing.expectEqual(@as(u16, 0x0015), xep.paged.?.ppage_addr); + try std.testing.expectEqual(@as(u8, 0xC0), xep.paged.?.page_first); + try std.testing.expectEqual(@as(u8, 0xFF), xep.paged.?.page_last); + try std.testing.expect(xep.spanInFlash(0xFA8000, 0xFABFFF) and xep.spanInFlash(0xC000, 0xFFFF)); + // Size-derived page count, not the 0xFE reset page: XS256 is 16 pages. + try std.testing.expectEqual(@as(u8, 0xF0), lookup("mc9s12xs256").?.paged.?.page_first); + // The linear-map entry stays out: its window is not reachable by the paged routine. + try std.testing.expect(lookup("mc9s12xep-linear") == null); } test "generated device table: known parts resolve with sane geometry" { diff --git a/src/device_types.zig b/src/device_types.zig index 9c4f011..bb9de6f 100644 --- a/src/device_types.zig +++ b/src/device_types.zig @@ -6,8 +6,8 @@ const std = @import("std"); /// Flash family - selects the RAM routine + ABI (HCS08 small-code, HCS12 large-code). pub const Family = enum { hcs08, hcs12, cfv1 }; -/// HCS12 routine: classic S12 = MMCV4/FTS, S12G = GMMC/FTMRG. -pub const Hcs12Routine = enum { mmcv4_fts, gmmc_ftmrg }; +/// HCS12 routine: classic S12 = MMCV4/FTS, S12G = GMMC/FTMRG, S12XE = XMMC/XFTMRK. +pub const Hcs12Routine = enum { mmcv4_fts, gmmc_ftmrg, xmmc_xftmrk }; /// PPAGE-banked HCS12 flash. Window always 0x8000-0xBFFF; pages /// page_first..page_last map globally as (page << 16) | offset (routine sets diff --git a/src/main.zig b/src/main.zig index ed558ac..13681cf 100644 --- a/src/main.zig +++ b/src/main.zig @@ -546,6 +546,10 @@ fn runSim( sim.cpu = .{ .hcs08 = &hcs08_cpu }; }, .hcs12 => { + // No S12XE (XFTMRK) flash model: the FTS model would run the routine + // against the wrong controller and report a meaningless pass. + if (d.hcs12_routine == .xmmc_xftmrk) + fatalCode(.usage, "--sim has no S12XE (XFTMRK) flash model; '{s}' needs real hardware", .{d.name}); hcs12_cpu = if (d.hcs12_routine == .gmmc_ftmrg) lib.cpu12.Cpu.initGmmc(arena, d.flash_base) catch fatal("out of memory building the emulator", .{}) else @@ -1332,9 +1336,11 @@ const lib_device = lib.device; // Vendored HCS08 small-code routines (embedded). 0xB0 variant: RAM above 0x80. const flash_blob_80 = @embedFile("flash_hcs08_0x80"); const flash_blob_b0 = @embedFile("flash_hcs08_0xB0"); -// Vendored HCS12 large-code routines. FTS = S12 MMCV4; GMMC = S12G FTMRG. +// Vendored HCS12 large-code routines. FTS = S12 MMCV4; GMMC = S12G FTMRG; +// XMMC = S12XE XFTMRK (same large-code ABI as GMMC). const flash_blob_hcs12_fts = @embedFile("flash_hcs12_fts"); const flash_blob_hcs12_gmmc = @embedFile("flash_hcs12_gmmc"); +const flash_blob_hcs12_xmmc = @embedFile("flash_hcs12_xmmc"); // Vendored CFV1 (ColdFire V1) large-code routine (32-bit ABI, relocatable-off). const flash_blob_cfv1 = @embedFile("flash_cfv1"); @@ -1555,6 +1561,14 @@ fn prepareFlash(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: * fatal("--part '{s}' has a flash controller base 0x{x} that doesn't fit the {s} routine's 16-bit field", .{ d.name, d.flash_base, @tagName(d.family) }); } bringUp(bdm, flags) catch |err| fatal("connect failed: {s}", .{@errorName(err)}); + // HCS12: a target running its own code acks memory access but not a PC + // write (BDM_RC_ACK_TIMEOUT), so the routine cannot be started. Reset into + // special mode first, as the reference programmer does ("reset s h"): the + // CPU comes up halted in active BDM on its reset clock. Measure after this. + if (d.family == .hcs12) { + bdm.sess.reset(.special, .hardware) catch |err| fatal("special-mode reset failed: {s}", .{@errorName(err)}); + bdm.sess.connect() catch |err| fatal("connect after reset failed: {s}", .{@errorName(err)}); + } const bus_hz = flags.bus_hz orelse blk: { // sync==0: no measurement; sync==1: firmware "unknown" sentinel (syncToHz // clamps to ~4.3 GHz). Treat both as unknown, demand --bus-hz. @@ -1564,9 +1578,43 @@ fn prepareFlash(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: * out.print("{s}using measured bus clock ~{d} kHz (override with --bus-hz){s}\n", .{ st.dim, hz / 1000, st.reset }) catch {}; break :blk hz; }; + if (d.family == .hcs12 and d.hcs12_routine == .xmmc_xftmrk) initXmmcFlash(bdm, d, bus_hz); return flashPrepFor(arena, d, bus_hz); } +/// XFTMRK flash-clock divider for a bus clock in kHz, or null if no divider puts +/// the flash clock in 800..1050 kHz. Clocked from OSCCLK = 2 x the special-mode +/// bus clock (ref HCS12-XFTMRK-flash-scripts.tcl calculateFlashDivider). +fn xmmcFlashDivider(bus_khz: u32) ?u8 { + if (bus_khz < 1000) return null; + const fm: f64 = 2.0 * @as(f64, @floatFromInt(bus_khz)); + const div = @floor(fm / 1050.0 - 0.0001); + if (div < 0 or div > 0x3F) return null; + const flash_clk = fm / (div + 1.0); + if (flash_clk < 800 or flash_clk > 1050) return null; + return @intFromFloat(div); +} + +/// The XFTMRK routine expects FCLKDIV already loaded (it reports an invalid +/// divider otherwise), so do what the reference Tcl initTarget/initFlash do: +/// disable COP, load FCLKDIV, unprotect P-flash and EEPROM. +fn initXmmcFlash(bdm: *Bdm, d: lib_device.Device, bus_hz: u32) void { + const div = xmmcFlashDivider(bus_hz / 1000) orelse + fatal("no XFTMRK flash clock divider for a {d} kHz bus clock (needs 800..1050 kHz from 2x bus); check --bus-hz", .{bus_hz / 1000}); + const base: u32 = d.flash_base; + const writes = [_]struct { addr: u32, val: u8 }{ + .{ .addr = d.watchdog_addr, .val = 0x40 }, // COPCTL: COP off + .{ .addr = base + 0x00, .val = div }, // FCLKDIV + .{ .addr = base + 0x08, .val = 0xFF }, // FPROT: unprotected + .{ .addr = base + 0x09, .val = 0xFF }, // EPROT: unprotected + }; + for (writes) |w| { + if (w.addr == 0) continue; + bdm.sess.writeMem(.byte, w.addr, &.{w.val}) catch |err| + fatal("XFTMRK flash init: write 0x{x:0>4} failed: {s}", .{ w.addr, @errorName(err) }); + } +} + /// FlashPrep for a device at a known bus clock, no I/O (shared by prepareFlash + gdb). fn flashPrepFor(arena: std.mem.Allocator, d: lib_device.Device, bus_hz: u32) FlashPrep { // frequency_khz is u16 (max ~65.5 MHz); reject rather than overflow the cast. @@ -1593,6 +1641,7 @@ fn flashPrepFor(arena: std.mem.Allocator, d: lib_device.Device, bus_hz: u32) Fla const blob = switch (d.hcs12_routine) { .mmcv4_fts => flash_blob_hcs12_fts, .gmmc_ftmrg => flash_blob_hcs12_gmmc, + .xmmc_xftmrk => flash_blob_hcs12_xmmc, }; const routine = ramflash.parseLarge(arena, blob) catch |err| fatal("cannot load HCS12 flash routine: {s}", .{@errorName(err)}); @@ -2407,6 +2456,24 @@ test "e2e HCS08: program -> readback -> blank-check(not blank) -> erase -> blank try std.testing.expectEqualSlices(u8, &.{ 0xFF, 0xFF, 0xFF, 0xFF }, &back); } +test "XFTMRK flash divider matches the reference Tcl calculation" { + // 12 MHz OSCCLK board, measured in special mode: 5990 kHz -> 11 (~998 kHz). + try std.testing.expectEqual(@as(?u8, 11), xmmcFlashDivider(5990)); + try std.testing.expectEqual(@as(?u8, 11), xmmcFlashDivider(6000)); + try std.testing.expectEqual(@as(?u8, 15), xmmcFlashDivider(8000)); + try std.testing.expectEqual(@as(?u8, null), xmmcFlashDivider(999)); +} + +test "parseLarge reads the vendored XFTMRK blob (same large-code ABI as GMMC)" { + const gpa = std.testing.allocator; + const r = try ramflash.parseLarge(gpa, flash_blob_hcs12_xmmc); + defer gpa.free(r.image); + try std.testing.expectEqual(@as(u32, 0x3000), r.image_address); + try std.testing.expect(r.capabilities & ramflash.CAP_RELOCATABLE != 0); + try std.testing.expect(r.capabilities & ramflash.CAP_DATA_FIXED == 0); + try std.testing.expect(r.entry > r.image_address and r.entry < r.image_address + r.image.len); +} + test "e2e HCS12: large-code program + verify + mass-erase via the sim" { const gpa = std.testing.allocator; const d = lib_device.lookup("mc9s12c32").?; diff --git a/tools/gen_devices.zig b/tools/gen_devices.zig index 383bf47..b0aba38 100644 --- a/tools/gen_devices.zig +++ b/tools/gen_devices.zig @@ -170,6 +170,7 @@ const SUP_HCS08 = [_][]const u8{ "HCS08-default-flash-program", "HCS08-small-fla const MMCV4 = [_][]const u8{ "HCS12-MMCV4-FTS-flash-program", "HCS12-MMCV4-FTS_2-flash-program", "HCS12-MMCV4-FTS_T-flash-program" }; const GMMC = "HCS12-GMMC-FTMRG-flash-program"; const GMMC_EE = "HCS12-GMMC-FTMRG-eeprom-program"; +const XMMC = "HCS12-XMMC-XFTMRK-flash-program"; const SUP_CFV1 = [_][]const u8{ "CFV1-default-FlashProgram", "CFV1-Watchdog-FlashProgram" }; fn inList(list: []const []const u8, s: []const u8) bool { @@ -408,7 +409,7 @@ fn processFile( const supported = switch (fam) { .hcs08 => inList(&SUP_HCS08, rt), - .hcs12 => inList(&MMCV4, rt) or std.mem.eql(u8, rt, GMMC), + .hcs12 => inList(&MMCV4, rt) or std.mem.eql(u8, rt, GMMC) or std.mem.eql(u8, rt, XMMC), .cfv1 => inList(&SUP_CFV1, rt), }; if (!supported) { @@ -510,7 +511,8 @@ fn processFile( const flash_end2 = if (has_w2) merged[1].end else 0; const is_gmmc = fam == .hcs12 and std.mem.eql(u8, rt, GMMC); - const hcs12_routine: []const u8 = if (is_gmmc) "gmmc_ftmrg" else "mmcv4_fts"; + const is_xmmc = fam == .hcs12 and std.mem.eql(u8, rt, XMMC); + const hcs12_routine: []const u8 = if (is_gmmc) "gmmc_ftmrg" else if (is_xmmc) "xmmc_xftmrk" else "mmcv4_fts"; var have_paged = false; var pg_first: u64 = 0; var pg_last: u64 = 0; @@ -521,8 +523,17 @@ fn processFile( const pe = attr(b, "pageEnd"); if (pr != null and pe != null) { saw_reset = true; - const prv = parseNum(pr.?); const pev = parseNum(pe.?); + // MMCV4 entries give the lowest page as pageReset. XMMC ones give + // the reset page (0xFE) and size the window with `pages` instead: + // a byte size when >= 1024 (e.g. "1024K" -> 64 pages), else a count + // (ref DeviceXmlParser memoryRange). + const prv = if (is_xmmc) blk: { + const pg = attr(b, "pages") orelse break :blk parseNum(pr.?); + const n = parseNum(pg); + const count = if (n >= 1024) n / 0x4000 else n; + break :blk if (count >= 1 and count <= pev + 1) pev + 1 - count else parseNum(pr.?); + } else parseNum(pr.?); // paged only if pages exist below the top two fixed windows; else they cover all -> null if (prv + 2 <= pev) { have_paged = true; diff --git a/vendor/flash-routines/HCS12-XMMC-XFTMRK-flash-program.s19 b/vendor/flash-routines/HCS12-XMMC-XFTMRK-flash-program.s19 new file mode 100644 index 0000000..b818512 --- /dev/null +++ b/vendor/flash-routines/HCS12-XMMC-XFTMRK-flash-program.s19 @@ -0,0 +1,35 @@ +S06A0000433A5C555342444D5C466C6173685F50726F6772616D6D696E675F526F7574696E65735C48435331322D584D4D432D5846544D524B2D666C6173682D70726F6772616D5C62696E5C48435331322D584D4D432D5846544D524B2D666C6173682D70726F6772616DF8 +S12330003002300033E5E03E00000000000000000000000000000000000000000000000014 +S1233020000000000000000000000000000000000000000000000000EEFAFFD26B030C0059 +S12330400000B7C55B1018EC003DB7450E008034EC01C140251A86FDC1802508A601C1C040 +S1233060250686FFE701261F585849498A402012C1082513C10CC40337B7018759598A10DA +S1233080EAB06C0169003DC60205FAFFAB1B9CEEFAFF7B6E80EE800F01011DEE80ED046D9F +S12330A0820E408006C60B15FAFF8DEE82C6FF6B086B09EE800D01011B843D1B9DEEFAFF36 +S12330C04DEE041A066E81EE81C6806B00EE81E6006B800F80B0F60F802006C60815FAFF78 +S12330E0570F801006C60915FAFF4D1B833D1B9CEEFAFF1A6E80EE800F010218EE80ED042E +S12331006D82CC08306B4669426A4A15FAFFACEE800D01021B843D1B93ECFAFEF16C86EE31 +S1233120860E011004182000BDEE86EC046C8BEE86EC0A6C80EC0C6C82EE86ECE0106C8812 +S1233140EE86EC0E496C84EC818C40002416C6116B8A0F830106C60215FAFEDCEE860F0FA9 +S1233160011C2014C6066B8A0F830706C60215FAFEC6EE860F0F0706C60215FAFEBAEE8B58 +S1233180C6306B062052EE8B6902E68A6B0AE6816B0BC6016B02EC826C0AC602074BEC840A +S12331A0270D186384C6036B02EC716D886C0AEC842707186384C604072FEC842707186324 +S12331C084C605072415FAFEF2EC82C300086C82EC80C90089006C80EE84191F6D8404758D +S12331E0A5EE860D01101B8D3D6B02ED8AEC716D8A6C0A3D1B96ECFAFE146C84EE840F01A9 +S12332002059EE84EC0A6C80EC0C6C82EE84ECE0106C88EE84EC0E496C860F83012FC60284 +S123322015FAFE142027EC82EE8015FAFE14EE8819026D88AC002706C60515FAFDFAEC8287 +S1233240C300026C82EC80C90089006C80EE86191F6D860475D0EE840D01201B8A3D1BF197 +S1233260EDECFAFDA96C88EE880E010404182000B4EE88EC046CF011EE88EC0A6C80EC0C41 +S12332806C82EE88EC0E830001E3826C86CC000018E3806C84EE88ED086D8F0318516D8CEE +S12332A0CCFFFF6C8AEE88ED0E26022073EE8218A48C6E82E481A4806C80EE8F18AB866ECD +S12332C086CC000018E3846C8418A48C6E86EC8AE485A4846C84EC818C40002403C6128F2F +S12332E0C60A6B8EEEF011C6306B062027EEF0116902E68E6B0AE6816B0BC6016B02EC82A2 +S12333006C0A15FAFDB5EC8FE3826C82CC000018E3806C80EC82AC8626D3EC80AC8426CD49 +S1233320EE880D01041BF0133D1B98EEFAFCDF6E84EE840F01084CEE84EC0A6C80EC0C6CB0 +S123334082EE84EC0EC30001496C860F83012BC60215FAFCE32023EC82EE8015FAFCE304F7 +S12333608406C60615FAFCD0186386EC82C300026C82EC80C90089006C80EC8626D9EE8469 +S12333800D01081B883DEEFAFC840F00010ECD00006D08876D060430FD0220F83D1B9C1A18 +S12333A0FAFC5F6E82EE82EC0C6C80EE82ED066940EE800D00801869021A0AB75415FAFCAC +S12333C08915FAFCC815FAFFBD15FAFD2115FAFE8D15FAFF5415FAFD3E15FAFE17EE800CB1 +S11533E000801B843D14101BFAFC4C3215FAFFAD003DD0 +S105FFFE33F1D9 +S9030000FC diff --git a/vendor/flash-routines/README.md b/vendor/flash-routines/README.md index 6e7d991..7813253 100644 --- a/vendor/flash-routines/README.md +++ b/vendor/flash-routines/README.md @@ -2,3 +2,7 @@ - [Source tree @ 4f18e1b](https://github.com/podonoghue/usbdm-flash-routines/tree/4f18e1bf67138d5b23927258a31590cbda247863) - License: GPL +- `HCS12-XMMC-XFTMRK-flash-program.s19` is from the USBDM 4.12 package + ([usbdm-eclipse-makefiles-build](https://github.com/podonoghue/usbdm-eclipse-makefiles-build) + `PackageFiles/DeviceData/HCS12/`), the same place the FTS and GMMC blobs here + match byte for byte. From b85788cdc72e23605ed992559f527d1376a215cf Mon Sep 17 00:00:00 2001 From: UD-V2G Team Date: Wed, 7 Oct 2026 09:49:27 -0400 Subject: [PATCH 2/2] HCS08: flash bring-up (reset, COP, clock, FCDIV) and oscillator trim The small-code HCS08 routine assumes a halted target with a loaded flash clock divider and a COP that is not about to fire. Nothing in the tool made that true: `program` on a running part stopped on a BDM error, and on a halted one failed with FACCERR because FCDIV was never loaded. And because the page erase takes the sector holding the oscillator trim (0xFFAE/F on ICS parts), a successful program of a normal image left the part untrimmed and running ~30 % slow. Do what UsbdmFlashProgrammer does before the routine runs (hcs08.zig): - software special reset, `connect; halt` and a check that BDMACT is set. The halt is required: BDCSCR reads 0x88 right after the reset, the firmware is already running and FCDIV is locked. The software reset is the device DB's default for HCS08; on a bench SH16 a hardware special reset left FCDIV locked even with the halt (cause not established). - COP off (SOPT=0x22, the address now comes from the device table). - the ICS clock to a known speed, then FCDIV from the measured bus clock (flash clock 150..200 kHz, PRDIV8 above 12.8 MHz) and FPROT unprotected. The BDC is switched to the bus clock (CLKSW=1) so the pod's reading IS the bus; without it the pod reports the alternate clock, 2x the bus on ICS. `connect` now labels that figure "bdc clock" when CLKSW is clear. - by default, the chip's own trim bytes are copied into the image before the erase wherever the image leaves them unset. - `--trim ` re-trims (clock.zig): the BDM clock is measured at a low speed while the trim is searched (8-step binary search on TRIM, then a +/-8 sweep of the 9-bit value, 2 samples each, least-squares fit), and the trim bytes are written into the image, merging FTRIM into an NVFTRIM the image already defines. `--nvloc` overrides the location, whose default is by clock type (it lives in USBDM's DeviceData.cpp, not the device XML). Unlike the reference's stale loop-variable range test, the fitted value is range-checked. ICS variants only; ICG/MCG get the preserve behaviour. - the device table gains the clock type and register address and SOPT for HCS08 (gen_devices); no other family's rows change. - mass erase / unsecure say that the trim went with it; `unsecure` carries on past setup steps a secured part refuses. The simulator now models FCDIV (write-once, FACCERR on a command while unloaded, enforced on the --sim path) and an ICS clock, so these paths run end to end against the real routine on the CPU08 core. Tests: 200 pass. Tested on an MC9S08SH16 (ICSV2) through a JS16 pod on Linux. Programming the bench test image: bus 8.629 MHz and FCDIV 0xAB, the same values PGO leaves; the existing trim survives the sector erase. `--trim` against PGO (-trim=, same image), trim bytes TRIM/FTRIM and the firmware's resulting bus clock: 33.60 kHz 01 81 01 81 8.56/8.61 MHz (ideal 8.602) 31.25 kHz 00 99 00 99 7.983 MHz (ideal 8.000) 35.00 kHz 01 75 01 75 8.961 MHz (ideal 8.960) Mass-erased part -> `program --trim 33.6` restores 01 81 and a flash identical to the image. A first version zeroed the TRIM byte to clear FTRIM and lost the BDM at the 50 % clock swing (PGO only clears the LSB); fixed and covered by a test. Not covered: the gdb flash-load path still builds its routine without this bring-up; clock types other than ICS are not trimmed; ICSV4/V5 follow the reference's parameters but are untested. --- README.md | 28 ++++ src/clock.zig | 353 ++++++++++++++++++++++++++++++++++++++++++ src/cpu08.zig | 41 ++++- src/device.zig | 2 +- src/device_types.zig | 31 ++++ src/hcs08.zig | 299 +++++++++++++++++++++++++++++++++++ src/hexfile.zig | 94 +++++++++++ src/main.zig | 261 +++++++++++++++++++++++++++++-- src/root.zig | 2 + src/sim.zig | 31 ++++ tools/gen_devices.zig | 37 +++++ 11 files changed, 1162 insertions(+), 17 deletions(-) create mode 100644 src/clock.zig create mode 100644 src/hcs08.zig diff --git a/README.md b/README.md index e0e486d..431e1c1 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,34 @@ S12G, and S12XE/XS/XF on the paged map), CFV1, plus S12G EEPROM. Destructive commands confirm unless `--force`. HCS12 flash operations start with a special-mode reset, so the target does not need to be halted first. +### HCS08 flash bring-up and oscillator trim + +Before the routine runs, an HCS08 flash command does what `UsbdmFlashProgrammer` does: +a software special reset and halt (the device DB's default), COP off (`SOPT`), the ICS +clock set to a known speed, and `FCDIV` loaded from the *measured* bus clock (the BDC is +switched to the bus clock, `CLKSW=1`, so the pod's speed reading is the bus). `FCDIV` is +write-once per reset, which is why this has to come first. + +The oscillator trim (`NVFTRIM`/`NVTRIM`, 0xFFAE/0xFFAF on ICS parts) lives in the same +sector as the vectors, so programming a normal image erases it and the part then runs +~30 % slow. Two ways to keep it: + +- by default the chip's own trim bytes are copied into the image before the erase + (only where the image leaves them unset); +- `--trim ` re-trims: the BDM clock is measured at a low speed while the trim is + searched (binary search, then a +/-8 sweep with a least-squares fit), and the result is + written into the image. `--part` is required. The frequency is the *internal reference* + (e.g. 33.6 for an 8.6016 MHz bus on an ICSV2 part); `--nvloc ` overrides where the + two bytes go (default by clock type, from USBDM's DeviceData.cpp). + +``` +usbdm program app.s19 --part mc9s08sh16 --trim 33.6 +``` + +Trim is implemented for the ICS clock variants (tested on ICSV2, MC9S08SH16); ICG and MCG +parts get the preserve-by-default behaviour only. A mass erase (`erase`, `unsecure`) +removes the trim and says so. + ## GDB remote stub `usbdm gdb` serves the GDB remote protocol over TCP: registers, memory, diff --git a/src/clock.zig b/src/clock.zig new file mode 100644 index 0000000..cc38155 --- /dev/null +++ b/src/clock.zig @@ -0,0 +1,353 @@ +//! HCS08 internal-clock handling for flash programming: the known-good clock a +//! flash operation runs at, the flash clock divider derived from it, and the +//! oscillator trim that PGO (UsbdmFlashProgrammer -trim=) computes by measuring +//! the BDM clock. Pure logic only: the target is reached through `Probe`, so the +//! search is testable without hardware. Reference: USBDM FlashProgrammerCommon.cpp +//! (trimTargetClock/trimICS_Clock/configureTargetClock), DeviceData.cpp (defaults) +//! and HCS08-default-flash-scripts.tcl (calculateFlashDivider). + +const std = @import("std"); +const types = @import("device_types"); + +pub const ClockType = types.ClockType; + +/// ICS register values in their address order: ICSC1, ICSC2, ICSTRM, ICSSC. +pub const IcsRegs = struct { c1: u8, c2: u8, trim: u8, sc: u8 }; + +/// Register offsets from the clock base address. +pub const ics_c1: u32 = 0; +pub const ics_c2: u32 = 1; +pub const ics_trm: u32 = 2; +pub const ics_sc: u32 = 3; + +/// The clock flash operations run at: internal reference, BDIV /2, nominal trim +/// (reference clock x 512/1024). PGO's "maximum safe speed untrimmed". null for +/// clocks this module does not configure. +pub fn flashRegs(ty: ClockType) ?IcsRegs { + return switch (ty) { + .ics_v1, .ics_v2, .ics_v2x512, .ics_v3 => .{ .c1 = 0x04, .c2 = 0x40, .trim = 0x80, .sc = 0x00 }, // BDIV=/2 (2-bit) + .ics_v4, .ics_v5 => .{ .c1 = 0x04, .c2 = 0x20, .trim = 0x80, .sc = 0x00 }, // BDIV=/2 (3-bit) + else => null, + }; +} + +/// A slow clock to trim at: the BDM sync measurement is more accurate the lower +/// the clock, and the trim is a property of the reference, not of the output. +pub fn lowSpeedRegs(ty: ClockType) ?IcsRegs { + return switch (ty) { + .ics_v1, .ics_v2, .ics_v2x512, .ics_v3 => .{ .c1 = 0x04, .c2 = 0xC0, .trim = 0x80, .sc = 0x00 }, // BDIV=/8 + .ics_v4 => .{ .c1 = 0x04, .c2 = 0x60, .trim = 0x80, .sc = 0x00 }, // BDIV=/8 + .ics_v5 => .{ .c1 = 0x04, .c2 = 0x80, .trim = 0x80, .sc = 0x00 }, // BDIV=/16 + else => null, + }; +} + +/// Bus clock at the low-speed setting per Hz of reference clock, i.e. the factor +/// that turns the requested trim frequency into the BDM clock to hit. +pub fn trimMultiplier(ty: ClockType) ?u32 { + return switch (ty) { + .ics_v1, .ics_v3, .ics_v2x512 => 512 / 8 / 2, + .ics_v2 => 1024 / 8 / 2, + .ics_v4 => 512 / 8, // no /2 on the bus clock + .ics_v5 => 1024 / 16, // no /2 on the bus clock + else => null, + }; +} + +/// Default location of the non-volatile trim bytes (NVFTRIM at the address, NVTRIM +/// at address+1). Hard-coded in USBDM's DeviceData.cpp by clock type; the device +/// XML carries only the clock type and its register address. +pub fn defaultTrimNv(ty: ClockType) u32 { + return switch (ty) { + .ics_v1, .ics_v2, .ics_v2x512, .ics_v3 => 0xFFAE, + .ics_v4, .ics_v5 => 0xFF6E, + .icg => 0xFFBE, + .mcg => 0xFFAE, + else => 0, + }; +} + +/// Default (nominal) reference frequency in Hz for the clock type. +pub fn defaultTrimHz(ty: ClockType) u32 { + return switch (ty) { + .ics_v1, .ics_v2, .ics_v2x512, .ics_v3, .ics_v4, .ics_v5, .mcg => 31250, + .icg => 243000, + else => 0, + }; +} + +/// Whether `search` + `trimBytes` can trim this clock. ICS only. +pub fn canTrim(ty: ClockType) bool { + return ty.isIcs(); +} + +/// FCDIV for a bus clock in kHz (HCS08 default flash module): flash clock must be +/// 150..200 kHz, PRDIV8 (bit 6) for buses above 12.8 MHz. null if impossible. +/// Integer arithmetic exactly as the reference Tcl (calculateFlashDivider). +pub fn flashDivider(bus_khz: u32) ?u8 { + if (bus_khz < 150) return null; + var div: u32 = 0; + var f = bus_khz; + if (f > 12800) { + div = 0x40; // PRDIV8 + f /= 8; + } + div |= (f - 1) / 200; + const fclk = f / ((div & 0x3F) + 1); + if (fclk < 150 or fclk > 200) return null; + return @intCast(div); +} + +/// FCDIV is a 6-bit divider plus PRDIV8; the flash clock it yields for `bus_khz`. +pub fn flashClockKhz(bus_khz: u32, fcdiv: u8) u32 { + const f = if (fcdiv & 0x40 != 0) bus_khz / 8 else bus_khz; + return f / ((fcdiv & 0x3F) + 1); +} + +// --- trim search ----------------------------------------------------------- + +/// How `search` reaches the target. `setTrim` writes ICSTRM when `msb` is non-null and +/// ICSSC's FTRIM bit when `lsb` is non-null (each independently: zeroing the TRIM byte +/// to clear FTRIM would swing the clock 50% and lose the BDM), and verifies what it +/// wrote; `measureHz` re-syncs the BDM and returns its clock in Hz (== bus clock when +/// CLKSW=1). +pub const Probe = struct { + ctx: *anyopaque, + vtable: *const VTable, + + pub const VTable = struct { + setTrim: *const fn (ctx: *anyopaque, msb: ?u8, lsb: ?u8) anyerror!void, + measureHz: *const fn (ctx: *anyopaque) anyerror!u32, + }; + + fn setTrim(self: Probe, msb: ?u8, lsb: ?u8) anyerror!void { + return self.vtable.setTrim(self.ctx, msb, lsb); + } + fn measureHz(self: Probe) anyerror!u32 { + return self.vtable.measureHz(self.ctx); + } +}; + +pub const max_trim: i32 = 505; // largest acceptable 9-bit trim +pub const min_trim: i32 = 5; // smallest +pub const sweep_offset: i32 = 8; // linear sweep is +/- this around the binary-search result +pub const samples_per_step: u32 = 2; // measurements per trim value (9-bit) + +pub const TrimError = error{TrimOutOfRange}; + +pub const TrimResult = struct { + /// 9-bit trim: TRIM = value >> 1, FTRIM = value & 1. + value: u16, + /// BDM clock measured with the trim applied. + measured_hz: u32, + /// Measurements taken by the sweep. + samples: u32, + /// The regression's slope, Hz per trim step (negative: a larger trim is slower). + hz_per_step: f64, +}; + +/// Find the 9-bit trim that makes the BDM clock `target_hz`: an 8-step binary +/// search on the TRIM byte, then a +/-8 linear sweep of the full 9-bit value taking +/// `samples_per_step` measurements per step, then a least-squares line through all +/// of them solved for the target. Leaves the winner written to the target. +/// Larger trim = slower clock on the ICS. +pub fn search(p: Probe, target_hz: u32) anyerror!TrimResult { + // FTRIM (LSB) to zero before the byte search, as the reference does: the LSB only. + try p.setTrim(null, 0); + + var msb: u8 = 0; + var mask: u8 = 0x80; + while (mask != 0) : (mask >>= 1) { + msb |= mask; + try p.setTrim(msb, null); + const hz = try p.measureHz(); + if (hz < target_hz) msb &= ~mask; // too slow: back the trim off + msb = std.math.clamp(msb, @as(u8, @intCast(@divTrunc(min_trim, 2))), @as(u8, @intCast(@divTrunc(max_trim, 2)))); + } + + const centre: i32 = @as(i32, msb) << 1; + const hi = @min(centre + sweep_offset, max_trim); + const lo = @max(centre - sweep_offset, min_trim); + + var n: f64 = 0; + var sum_x: f64 = 0; + var sum_y: f64 = 0; + var sum_xx: f64 = 0; + var sum_xy: f64 = 0; + var samples: u32 = 0; + + // Down then up: each value is measured on both a falling and a rising approach, + // which averages out the FLL's settling direction. + var pass: u2 = 0; + while (pass < 2) : (pass += 1) { + var t: i32 = if (pass == 0) hi else lo; + while (if (pass == 0) t >= lo else t <= hi) : (t += if (pass == 0) @as(i32, -1) else 1) { + try p.setTrim(@intCast(t >> 1), @intCast(t & 1)); + var k: u32 = 0; + while (k < samples_per_step) : (k += 1) { + const hz: f64 = @floatFromInt(try p.measureHz()); + const x: f64 = @floatFromInt(t); + n += 1; + sum_x += x; + sum_y += hz; + sum_xx += x * x; + sum_xy += x * hz; + samples += 1; + } + } + } + + const denom = n * sum_xx - sum_x * sum_x; + if (denom == 0) return error.TrimOutOfRange; + const beta = (n * sum_xy - sum_x * sum_y) / denom; + const alpha = (sum_y - beta * sum_x) / n; + if (beta == 0) return error.TrimOutOfRange; + const tf = (@as(f64, @floatFromInt(target_hz)) - alpha) / beta; + // The reference tests a stale loop variable here; the intent is this. + if (!(tf > @as(f64, @floatFromInt(min_trim)) and tf < @as(f64, @floatFromInt(max_trim)))) return error.TrimOutOfRange; + + const value: u16 = @intFromFloat(@round(tf)); + try p.setTrim(@intCast(value >> 1), @intCast(value & 1)); + const measured = try p.measureHz(); + return .{ .value = value, .measured_hz = measured, .samples = samples, .hz_per_step = beta }; +} + +// --- trim bytes in flash --------------------------------------------------- + +/// The two non-volatile bytes a 9-bit trim lives in. +pub const TrimBytes = struct { + ftrim_addr: u32, + ftrim: u8, + trim_addr: u32, + trim: u8, +}; + +/// NVFTRIM carries FTRIM in bit 0 and may share its byte with other options +/// (DMX32, DRS...): `image_ftrim` is what the image already holds there. An +/// absent or erased (0xFF) byte means "nothing to merge with", so the other bits +/// are cleared, as the reference does. +pub fn trimBytes(nv: u32, value: u16, image_ftrim: ?u8) TrimBytes { + var merge: u8 = image_ftrim orelse 0; + if (merge == 0xFF) merge = 0; + return .{ + .ftrim_addr = nv, + .ftrim = (merge & ~@as(u8, 1)) | @as(u8, @intCast(value & 1)), + .trim_addr = nv + 1, + .trim = @intCast(value >> 1), + }; +} + +// --- tests ----------------------------------------------------------------- + +const testing = std.testing; + +test "flashDivider matches the reference Tcl" { + // PGO on the SH16 left FCDIV=0xAB: divider 43 for an 8629 kHz bus. + try testing.expectEqual(@as(?u8, 43), flashDivider(8629)); + try testing.expectEqual(@as(?u8, 19), flashDivider(4000)); + // Above 12.8 MHz PRDIV8 divides first. + try testing.expectEqual(@as(?u8, 0x40 | 9), flashDivider(16000)); // 2000 kHz -> 9 + try testing.expectEqual(@as(?u8, null), flashDivider(100)); // too slow + // 150..200 kHz window for every bus clock the divider accepts. + var khz: u32 = 150; + while (khz < 40000) : (khz += 7) { + const d = flashDivider(khz) orelse continue; + const fc = flashClockKhz(khz, d); + try testing.expect(fc >= 150 and fc <= 200); + } +} + +test "trimBytes merges FTRIM and keeps other bits only when the image defines them" { + const t = trimBytes(0xFFAE, 0x103, null); // 259 = TRIM 0x81, FTRIM 1 + try testing.expectEqual(@as(u8, 0x01), t.ftrim); + try testing.expectEqual(@as(u8, 0x81), t.trim); + try testing.expectEqual(@as(u32, 0xFFAF), t.trim_addr); + // erased byte: other bits cleared + try testing.expectEqual(@as(u8, 0x00), trimBytes(0xFFAE, 0x100, 0xFF).ftrim); + // image-defined byte: other bits kept, bit 0 replaced + try testing.expectEqual(@as(u8, 0x41), trimBytes(0xFFAE, 0x101, 0x40).ftrim); + try testing.expectEqual(@as(u8, 0x40), trimBytes(0xFFAE, 0x100, 0x41).ftrim); +} + +/// A linear ICS: f = f0 * (1 - 0.0019 * (trim - 256)); larger trim is slower. +const ModelProbe = struct { + msb: u8 = 0, + lsb: u8 = 0, + f0_hz: f64, + jitter: f64 = 0, // +/- fraction, deterministic + n: u32 = 0, + set_calls: u32 = 0, + + fn hzNow(self: *const ModelProbe) f64 { + const t: f64 = @floatFromInt((@as(u32, self.msb) << 1) | self.lsb); + return self.f0_hz * (1.0 - 0.0019 * (t - 256.0)); + } + fn setTrim(ctx: *anyopaque, msb: ?u8, lsb: ?u8) anyerror!void { + const s: *ModelProbe = @ptrCast(@alignCast(ctx)); + if (msb) |m| s.msb = m; + if (lsb) |l| s.lsb = l; + s.set_calls += 1; + } + fn measureHz(ctx: *anyopaque) anyerror!u32 { + const s: *ModelProbe = @ptrCast(@alignCast(ctx)); + s.n += 1; + // saw-tooth noise, mean zero + const ph: f64 = @floatFromInt(@as(i32, @intCast(s.n % 7)) - 3); + return @intFromFloat(s.hzNow() * (1.0 + s.jitter * ph / 3.0)); + } + const vtable = Probe.VTable{ .setTrim = setTrim, .measureHz = measureHz }; + fn probe(self: *ModelProbe) Probe { + return .{ .ctx = self, .vtable = &vtable }; + } +}; + +test "search finds the trim whose clock is closest to the target" { + // 1.075 MHz at nominal trim 256; ask for 1% fast -> about 5 steps lower. + var m = ModelProbe{ .f0_hz = 1_075_200 }; + const target: u32 = @intFromFloat(1_075_200 * 1.01); + const r = try search(m.probe(), target); + // exact answer: 256 - 0.01/0.0019 = 250.7 + try testing.expect(r.value == 251 or r.value == 250); + try testing.expect(r.hz_per_step < 0); + const err = @abs(@as(f64, @floatFromInt(r.measured_hz)) - @as(f64, @floatFromInt(target))) / @as(f64, @floatFromInt(target)); + try testing.expect(err < 0.0025); // within ~1 step + try testing.expectEqual(@as(u32, 34 * samples_per_step), r.samples); // 17 values x 2 passes x 2 + // the winner is left on the target + try testing.expectEqual(@as(u16, r.value), (@as(u16, m.msb) << 1) | m.lsb); +} + +test "search tolerates measurement noise bigger than one trim step" { + // +/-0.4% saw-tooth noise vs 0.19% per step: regression over ~68 points still lands within 2 steps. + var m = ModelProbe{ .f0_hz = 2_150_400, .jitter = 0.004 }; + const r = try search(m.probe(), 2_150_400); // target = nominal: ideal trim 256 + try testing.expect(r.value >= 254 and r.value <= 258); +} + +test "search never writes a TRIM byte of zero (the clock would swing 50% and lose the BDM)" { + const Guard = struct { + inner: ModelProbe, + zeroed: bool = false, + fn setTrim(ctx: *anyopaque, msb: ?u8, lsb: ?u8) anyerror!void { + const g: *@This() = @ptrCast(@alignCast(ctx)); + if (msb) |m| { + if (m < 2) g.zeroed = true; + } + return ModelProbe.setTrim(&g.inner, msb, lsb); + } + fn measureHz(ctx: *anyopaque) anyerror!u32 { + const g: *@This() = @ptrCast(@alignCast(ctx)); + return ModelProbe.measureHz(&g.inner); + } + const vt = Probe.VTable{ .setTrim = setTrim, .measureHz = measureHz }; + }; + var g = Guard{ .inner = .{ .f0_hz = 2_150_400, .msb = 0x80 } }; + _ = try search(.{ .ctx = &g, .vtable = &Guard.vt }, 2_300_000); + try testing.expect(!g.zeroed); +} + +test "search reports a target the clock cannot reach" { + var m = ModelProbe{ .f0_hz = 1_000_000 }; + try testing.expectError(error.TrimOutOfRange, search(m.probe(), 2_000_000)); // 2x too fast + var m2 = ModelProbe{ .f0_hz = 1_000_000 }; + try testing.expectError(error.TrimOutOfRange, search(m2.probe(), 500_000)); +} diff --git a/src/cpu08.zig b/src/cpu08.zig index 6aeb0c5..26481c9 100644 --- a/src/cpu08.zig +++ b/src/cpu08.zig @@ -45,6 +45,13 @@ pub const Cpu = struct { flash_hi: u32, fstat: u8 = FCBEF | FCCF, fcmd: u8 = 0, + /// FCDIV: bit 7 DIVLD is set by the first write after reset, which also sets the + /// divider; later writes are ignored until the next reset (as the silicon does). + fcdiv: u8 = 0, + /// Model the flash controller refusing commands (FACCERR) until FCDIV is loaded. + /// Off for tests that drive the routine directly; on for the --sim CLI path, where + /// forgetting to load it is exactly the bug worth catching. + require_fcdiv: bool = false, latched: bool = false, latch_addr: u16 = 0, latch_data: u8 = 0, @@ -90,7 +97,7 @@ pub const Cpu = struct { const a: u32 = addr; if (a >= self.ctrl_base and a <= self.ctrl_base + 6) { return switch (a - self.ctrl_base) { - FCDIV => 0x80, // DIVLD set + FCDIV => self.fcdiv, FSTAT => self.fstat, FCMD => self.fcmd, else => 0, @@ -115,16 +122,25 @@ pub const Cpu = struct { } fn flashRegWrite(self: *Cpu, off: u8, val: u8) void { switch (off) { + FCDIV => { + if (self.fcdiv & 0x80 == 0) self.fcdiv = (val & 0x7F) | 0x80; + }, FCMD => self.fcmd = val, FSTAT => { if (val & FACCERR != 0) self.fstat &= ~FACCERR; if (val & FPVIOL != 0) self.fstat &= ~FPVIOL; if (val & FCBEF != 0 and self.latched) self.launch(); }, - else => {}, // FCDIV/FOPT/FCNFG/FPROT: inert + else => {}, // FOPT/FCNFG/FPROT: inert } } fn launch(self: *Cpu) void { + if (self.require_fcdiv and self.fcdiv & 0x80 == 0) { + // Command with FCDIV unloaded: access error, nothing happens. + self.fstat = FCBEF | FCCF | FACCERR; + self.latched = false; + return; + } switch (self.fcmd) { CMD_BYTE_PROG, CMD_BURST_PROG => { // program only clears bits; on erased flash a store @@ -148,12 +164,27 @@ pub const Cpu = struct { self.latched = false; } - // BDM host access: direct, bypasses the controller + /// Reset the flash controller as a target reset does: FCDIV unloaded (DIVLD clear). + pub fn resetFlashRegs(self: *Cpu) void { + self.fcdiv = 0; + self.fstat = FCBEF | FCCF; + self.latched = false; + } + + // BDM host access: direct to memory, but the flash controller's registers behave + // like registers (FCDIV is write-once), not like RAM. pub fn hostWrite(self: *Cpu, addr: u16, data: []const u8) void { - for (data, 0..) |b, i| self.mem[addr + i] = b; + for (data, 0..) |b, i| { + const a: u32 = @as(u32, addr) + @as(u32, @intCast(i)); + if (a >= self.ctrl_base and a <= self.ctrl_base + 6) { + self.flashRegWrite(@intCast(a - self.ctrl_base), b); + } else { + self.mem[a] = b; + } + } } pub fn hostRead(self: *Cpu, addr: u16, out: []u8) void { - for (out, 0..) |*b, i| b.* = self.mem[addr + i]; + for (out, 0..) |*b, i| b.* = self.read(@intCast(@as(u32, addr) + @as(u32, @intCast(i)))); } fn fetch8(self: *Cpu) u8 { diff --git a/src/device.zig b/src/device.zig index 5fbb12f..a45c1a7 100644 --- a/src/device.zig +++ b/src/device.zig @@ -24,7 +24,7 @@ pub const sdid_table = gen.sdid_table; /// Family generics (not in the XML): used when no --part is named, so a /// non-HCS08 target isn't handed HCS08 geometry. pub const generics = [_]Device{ - .{ .name = "hcs08-generic", .ram_start = 0x80, .ram_end = 0x27F, .flash_start = 0x8000, .flash_end = 0xFFFF }, + .{ .name = "hcs08-generic", .ram_start = 0x80, .ram_end = 0x27F, .flash_start = 0x8000, .flash_end = 0xFFFF, .sopt_addr = 0x1802 }, .{ .name = "hcs12-generic", .family = .hcs12, .flash_base = 0x0100, .ram_start = 0x0800, .ram_end = 0x0FFF, .flash_start = 0x4000, .flash_end = 0x7FFF, .flash_start2 = 0xC000, .flash_end2 = 0xFFFF, .page_size = 512, .write_align = 2, .security_addr = 0xFF0F, .watchdog_addr = 0x003C, .hcs12_routine = .mmcv4_fts }, .{ .name = "cfv1-generic", .family = .cfv1, .flash_base = 0xFF9820, .ram_start = 0x00800000, .ram_end = 0x00801FFF, .flash_start = 0x0, .flash_end = 0x1FFFF, .page_size = 1024, .write_align = 4, .security_addr = 0x40F, .watchdog_addr = 0xFF9802 }, }; diff --git a/src/device_types.zig b/src/device_types.zig index bb9de6f..347f68f 100644 --- a/src/device_types.zig +++ b/src/device_types.zig @@ -23,6 +23,30 @@ pub const Eeprom = struct { base_global: u32, size: u32, sector: u32, align_byte /// (-> D-flash commands 0x11/0x12, not PPAGE/P-flash). pub const eeprom_linear_flag: u32 = 0x8000_0000; +/// Internal clock generator, from the device DB's ``. Decides how +/// the target clock is configured for flash programming and trimmed (clock.zig). +/// `other` = a type the DB has but nothing here supports (ICG, MCG, ...); such +/// parts still get their trim bytes preserved, just not re-trimmed. +pub const ClockType = enum { + external, + ics_v1, + ics_v2, + ics_v2x512, + ics_v3, + ics_v4, + ics_v5, + icg, + mcg, + other, + + pub fn isIcs(self: ClockType) bool { + return switch (self) { + .ics_v1, .ics_v2, .ics_v2x512, .ics_v3, .ics_v4, .ics_v5 => true, + else => false, + }; + } +}; + /// One SDID (System Device ID) match: read `sdid_addr` over BDM, and the part is /// `name` when (read & mask) == sdid. pub const SdidEntry = struct { @@ -65,6 +89,13 @@ pub const Device = struct { paged: ?Paged = null, /// EEPROM/D-flash geometry (when the routine can program it). eeprom: ?Eeprom = null, + /// Internal clock generator and the address of its first register (ICSC1 / + /// MCGC1 / ICGC1). HCS08 only; `external` = nothing to configure or trim. + clock: ClockType = .external, + clock_addr: u32 = 0, + /// SOPT1 (COP control). HCS08 flash operations write it first, as the + /// reference scripts do, since a running COP resets the part mid-erase. + sopt_addr: u32 = 0, pub fn flashLen(self: Device) u32 { if (self.paged) |p| return (@as(u32, p.page_last - p.page_first) + 1) * 0x4000; diff --git a/src/hcs08.zig b/src/hcs08.zig new file mode 100644 index 0000000..667a59c --- /dev/null +++ b/src/hcs08.zig @@ -0,0 +1,299 @@ +//! HCS08 flash bring-up, the part of UsbdmFlashProgrammer that happens before any +//! erase: reset into special mode, stop the COP, put the clock at a known speed, +//! optionally trim it, load FCDIV from the measured bus clock, and keep the +//! oscillator trim bytes alive across the sector erase that would otherwise wipe them. +//! +//! The small-code flash routine does none of this; it assumes a halted target with a +//! working flash clock divider and a COP that is not about to reset it. Reference: +//! USBDM FlashProgrammer_HCS08.cpp (programFlash, resetAndConnectTarget, +//! initialiseTargetFlash) and HCS08-default-flash-scripts.tcl. + +const std = @import("std"); +const session = @import("session.zig"); +const device = @import("device.zig"); +const clock = @import("clock.zig"); +const hexfile = @import("hexfile.zig"); + +/// BDCSCR bits (HCS08). +const BDCSCR_ENBDM: u8 = 0x80; +const BDCSCR_CLKSW: u8 = 0x08; +const BDCSCR_BDMACT: u8 = 0x40; + +/// SOPT1 value the reference scripts write: STOPE | BKGDPE, COP off. SOPT is write-once +/// after reset, so this has to be the first thing after the reset. +const SOPT_INIT: u8 = 0x22; + +/// FCDIV and FPROT offsets from the flash controller base. +const FCDIV_OFFSET: u32 = 0; +const FPROT_OFFSET: u32 = 4; +const FCDIV_DIVLD: u8 = 0x80; + +pub const Ctx = struct { + sess: *session.Session, + dev: device.Device, + sleep_ms: *const fn (u32) void, +}; + +pub const Request = struct { + /// Trim the internal reference to this frequency (Hz) and write the result into the + /// image. null = do not trim; the existing trim is preserved instead. + trim_hz: ?u32 = null, + /// Where the two trim bytes live; null = the clock type's default. + nvloc: ?u32 = null, + /// Use this bus clock (Hz) for FCDIV instead of measuring it. + bus_hz: ?u32 = null, + /// false = carry on past a failed step (mass-erasing a secured part must not be + /// stopped by a COP write the secured part refuses). The first failure is reported. + strict: bool = true, +}; + +pub const Result = struct { + bus_hz: u32, + fcdiv: u8, + trim: ?clock.TrimResult = null, + trim_bytes: ?clock.TrimBytes = null, + /// The chip's own trim bytes copied into the image so the erase does not lose them. + preserved: ?[2]u8 = null, + preserved_at: u32 = 0, + /// First non-strict failure, if any. + soft_error: ?anyerror = null, +}; + +pub const Error = error{ + NoFlashDivider, + FcdivNotLoaded, + TrimNotSupported, + BadTrimLocation, + SpeedUnknown, + ClockRegisterVerify, + NotHalted, +}; + +/// BDM options for a HCS08 flash session: the BDC runs from the bus clock (CLKSW=1) so +/// the pod's speed measurement IS the bus clock. Without that it reports the alternate +/// clock, twice the bus on the ICS parts. The reset line is left alone (the default +/// special reset is a software one and needs no RESET wire). +pub fn options(base: session.Options) session.Options { + var o = base; + o.use_alt_bdm_clock = 1; // CS_NORMAL + return o; +} + +fn writeReg(c: *Ctx, addr: u32, v: u8) anyerror!void { + // A clock-register write can change the BDM clock under the pod's feet: retry once + // after re-syncing (the reference's writeClockRegister). + c.sess.writeMem(.byte, addr, &.{v}) catch { + try c.sess.connect(); + try c.sess.writeMem(.byte, addr, &.{v}); + }; +} + +fn readByte(c: *Ctx, addr: u32) anyerror!u8 { + var b: [1]u8 = undefined; + try c.sess.readMem(.byte, addr, &b); + return b[0]; +} + +/// Re-sync and return the BDC clock in Hz (== bus clock once CLKSW=1). +pub fn measureHz(c: *Ctx) anyerror!u32 { + try c.sess.connect(); + const sync = try c.sess.getSpeedSync(); + if (sync <= 1) return error.SpeedUnknown; + return session.syncToHz(sync); +} + +/// Reset into special mode (BDM enabled, flash controller at its reset values) and halt +/// the CPU, as the reference does: a software reset (the device DB's default for HCS08), +/// then `connect; halt`. The halt is not optional: BDCSCR reads 0x88 (ENBDM|CLKSW, +/// BDMACT clear) straight after a reset on an SH16, i.e. the firmware is already running. +/// +/// Measured on a bench SH16: a *hardware* special reset left the CPU running with FCDIV +/// already loaded by the firmware (DIVLD set, writes ignored) even when followed by a +/// halt, while the software one gives a clean halted part with FCDIV unloaded. The cause +/// of the hardware case was not established. Falls back to every reset strategy the pod +/// has. +pub fn specialReset(c: *Ctx) anyerror!void { + c.sess.reset(.special, .software) catch { + try c.sess.connect(); + try c.sess.reset(.special, .all); + }; + try c.sess.connect(); + try c.sess.halt(); + const st: u8 = @truncate(try c.sess.readStatusReg()); + if (st & BDCSCR_BDMACT == 0) return error.NotHalted; +} + +fn forceNormalClock(c: *Ctx) anyerror!void { + const st: u8 = @truncate(try c.sess.readStatusReg()); + if (st & BDCSCR_CLKSW != 0) return; + try c.sess.writeControlReg((st & 0xB8) | BDCSCR_ENBDM | BDCSCR_CLKSW); + try c.sess.connect(); +} + +/// Write an ICS register set the way the reference does (trim first, re-sync after the +/// writes that can change the clock, FLL settle) and return the resulting bus clock. +pub fn configureIcs(c: *Ctx, regs: clock.IcsRegs) anyerror!u32 { + const base = c.dev.clock_addr; + try writeReg(c, base + clock.ics_trm, regs.trim); + try c.sess.connect(); + try writeReg(c, base + clock.ics_c1, regs.c1); + try writeReg(c, base + clock.ics_c2, regs.c2); + try c.sess.connect(); + try writeReg(c, base + clock.ics_sc, regs.sc); + c.sleep_ms(100); // FLL lock + try c.sess.connect(); + return measureHz(c); +} + +const IcsProbe = struct { + c: *Ctx, + + fn setTrim(ctx: *anyopaque, msb: ?u8, lsb: ?u8) anyerror!void { + const self: *IcsProbe = @ptrCast(@alignCast(ctx)); + const base = self.c.dev.clock_addr; + // Re-sync before each verify read: the write just moved the target clock, and a + // read at the old sync can come back as garbage (0x00 read back as 0x24 on the bench). + if (lsb) |l| { + try writeReg(self.c, base + clock.ics_sc, l); + try self.c.sess.connect(); + if ((try readByte(self.c, base + clock.ics_sc)) & 1 != l) return error.ClockRegisterVerify; + } + if (msb) |m| { + try writeReg(self.c, base + clock.ics_trm, m); + try self.c.sess.connect(); + if ((try readByte(self.c, base + clock.ics_trm)) != m) return error.ClockRegisterVerify; + } + } + fn measure(ctx: *anyopaque) anyerror!u32 { + const self: *IcsProbe = @ptrCast(@alignCast(ctx)); + return measureHz(self.c); + } + const vtable = clock.Probe.VTable{ .setTrim = setTrim, .measureHz = measure }; + fn probe(self: *IcsProbe) clock.Probe { + return .{ .ctx = self, .vtable = &vtable }; + } +}; + +/// The chip's trim bytes into the image, wherever the image leaves them unset: the +/// page erase that precedes programming takes the whole 512-byte sector, trim included, +/// and erased trim (0xFF) leaves the part running ~30% slow. +fn preserveTrim(gpa: std.mem.Allocator, c: *Ctx, img: *hexfile.Image, nv: u32) anyerror!?[2]u8 { + if (nv == 0) return null; + const mask: u32 = c.dev.page_size - 1; + if (!img.overlaps(nv & ~mask, (nv + 1) | mask)) return null; // that sector is not erased + var cur: [2]u8 = undefined; + c.sess.readMem(.byte, nv, &cur) catch return null; // secured part: nothing readable to keep + if (cur[0] == 0xFF and cur[1] == 0xFF) return null; // already blank + var kept = false; + for (cur, 0..) |b, i| { + const a = nv + @as(u32, @intCast(i)); + const have = img.byteAt(a); + // An image that defines the byte (non-erased) wins: that is the user's intent. + if ((have == null or have.? == 0xFF) and b != 0xFF) { + try img.setByte(gpa, a, b); + kept = true; + } + } + return if (kept) cur else null; +} + +/// Everything between "connected" and "ready to erase". `image` is modified: the trim +/// bytes are inserted (--trim) or the chip's existing ones are carried over. +pub fn prepare(gpa: std.mem.Allocator, c: *Ctx, req: Request, image: ?*hexfile.Image) anyerror!Result { + var res = Result{ .bus_hz = 0, .fcdiv = 0 }; + const ty = c.dev.clock; + + // Each step either succeeds or (non-strict) is recorded and skipped. + // A labeled-block helper keeps the strict path a plain `try`. + const soft = !req.strict; + + specialReset(c) catch |e| { + if (!soft) return e; + res.soft_error = res.soft_error orelse e; + }; + forceNormalClock(c) catch |e| { + if (!soft) return e; + res.soft_error = res.soft_error orelse e; + }; + if (c.dev.sopt_addr != 0) { + writeReg(c, c.dev.sopt_addr, SOPT_INIT) catch |e| { + if (!soft) return e; + res.soft_error = res.soft_error orelse e; + }; + } + + const nv = req.nvloc orelse clock.defaultTrimNv(ty); + + if (req.trim_hz) |hz| { + if (!clock.canTrim(ty)) return error.TrimNotSupported; + if (nv == 0 or !c.dev.inFlash(nv) or !c.dev.inFlash(nv + 1)) return error.BadTrimLocation; + _ = try configureIcs(c, clock.lowSpeedRegs(ty).?); + var p = IcsProbe{ .c = c }; + const target_hz = hz * clock.trimMultiplier(ty).?; + const r = clock.search(p.probe(), target_hz) catch |e| { + // Leave a clock the BDM can talk to, not whatever the search stopped on. + _ = configureIcs(c, clock.flashRegs(ty).?) catch {}; + return e; + }; + res.trim = r; + if (image) |img| { + const tb = clock.trimBytes(nv, r.value, img.byteAt(nv)); + try img.setByte(gpa, tb.ftrim_addr, tb.ftrim); + try img.setByte(gpa, tb.trim_addr, tb.trim); + res.trim_bytes = tb; + } + } else if (image) |img| { + if (preserveTrim(gpa, c, img, nv)) |kept| { + res.preserved = kept; + res.preserved_at = nv; + } else |e| { + if (!soft) return e; + res.soft_error = res.soft_error orelse e; + } + } + + // The programming clock and FCDIV. FCDIV is write-once per reset, so it goes last, + // after anything that moved the clock. + var bus_hz: u32 = 0; + if (clock.flashRegs(ty)) |regs| { + bus_hz = configureIcs(c, regs) catch |e| blk: { + if (!soft) return e; + res.soft_error = res.soft_error orelse e; + break :blk 0; + }; + } + if (bus_hz == 0) { + bus_hz = measureHz(c) catch |e| blk: { + if (!soft) return e; + res.soft_error = res.soft_error orelse e; + break :blk 0; + }; + } + if (req.bus_hz) |b| bus_hz = b; + res.bus_hz = bus_hz; + + const khz = (bus_hz + 500) / 1000; + const div = clock.flashDivider(khz) orelse { + if (!soft) return error.NoFlashDivider; + res.soft_error = res.soft_error orelse error.NoFlashDivider; + return res; + }; + res.fcdiv = div; + const fcdiv_addr = c.dev.flash_base + FCDIV_OFFSET; + const loaded: anyerror!void = blk: { + writeReg(c, fcdiv_addr, div) catch |e| break :blk e; + const rb = readByte(c, fcdiv_addr) catch |e| break :blk e; + if (rb != (div | FCDIV_DIVLD)) break :blk error.FcdivNotLoaded; + writeReg(c, c.dev.flash_base + FPROT_OFFSET, 0xFF) catch |e| break :blk e; // unprotect + }; + loaded catch |e| { + if (!soft) return e; + res.soft_error = res.soft_error orelse e; + }; + return res; +} + +extern "c" fn usleep(us: c_uint) c_int; +pub fn sleepMs(ms: u32) void { + _ = usleep(ms * 1000); +} diff --git a/src/hexfile.zig b/src/hexfile.zig index e1a03bd..c0ee0ba 100644 --- a/src/hexfile.zig +++ b/src/hexfile.zig @@ -37,6 +37,69 @@ pub const Image = struct { for (self.segments) |seg| n += seg.data.len; return n; } + + /// The byte the image defines at `addr`, or null if it does not cover it. + pub fn byteAt(self: Image, addr: u32) ?u8 { + for (self.segments) |seg| { + if (addr >= seg.addr and addr - seg.addr < seg.data.len) return seg.data[addr - seg.addr]; + } + return null; + } + + /// True if any segment overlaps the inclusive range [lo, hi]. + pub fn overlaps(self: Image, lo: u32, hi: u32) bool { + for (self.segments) |seg| { + if (seg.data.len == 0) continue; + const end = seg.addr + @as(u32, @intCast(seg.data.len - 1)); + if (seg.addr <= hi and end >= lo) return true; + } + return false; + } + + /// Define one byte, overwriting it if the image covers `addr`, otherwise + /// inserting it (merged with an adjacent segment so the invariant of sorted, + /// non-overlapping, non-adjacent segments holds). `gpa` must own the image. + pub fn setByte(self: *Image, gpa: Allocator, addr: u32, value: u8) Allocator.Error!void { + for (self.segments) |seg| { + if (addr >= seg.addr and addr - seg.addr < seg.data.len) { + seg.data[addr - seg.addr] = value; + return; + } + } + var list: std.ArrayList(Segment) = .empty; + errdefer list.deinit(gpa); + var inserted = false; + for (self.segments) |seg| { + if (!inserted and seg.addr > addr) { + try list.append(gpa, .{ .addr = addr, .data = try gpa.dupe(u8, &.{value}) }); + inserted = true; + } + try list.append(gpa, seg); + } + if (!inserted) try list.append(gpa, .{ .addr = addr, .data = try gpa.dupe(u8, &.{value}) }); + + // Merge neighbours that now touch. + var out: std.ArrayList(Segment) = .empty; + errdefer out.deinit(gpa); + for (list.items) |seg| { + if (out.items.len > 0) { + const prev = &out.items[out.items.len - 1]; + if (prev.addr + @as(u32, @intCast(prev.data.len)) == seg.addr) { + const joined = try gpa.alloc(u8, prev.data.len + seg.data.len); + @memcpy(joined[0..prev.data.len], prev.data); + @memcpy(joined[prev.data.len..], seg.data); + gpa.free(prev.data); + gpa.free(seg.data); + prev.data = joined; + continue; + } + } + try out.append(gpa, seg); + } + list.deinit(gpa); + gpa.free(self.segments); + self.segments = try out.toOwnedSlice(gpa); + } }; pub const ParseError = error{ @@ -593,3 +656,34 @@ test "fuzz: hexfile.parse never panics or leaks on adversarial input" { } else |_| {} } } + +test "Image.setByte inserts, merges neighbours and overwrites" { + const gpa = std.testing.allocator; + var img = try parse(gpa, "S1050010AABB85\nS1050020CCDD31\nS9030000FC\n"); + defer img.deinit(gpa); + try std.testing.expectEqual(@as(usize, 2), img.segments.len); + try std.testing.expectEqual(@as(?u8, 0xAA), img.byteAt(0x10)); + try std.testing.expectEqual(@as(?u8, null), img.byteAt(0x12)); + try std.testing.expect(img.overlaps(0x11, 0x30)); + try std.testing.expect(!img.overlaps(0x12, 0x1F)); + + try img.setByte(gpa, 0x11, 0x55); // overwrite in place + try std.testing.expectEqual(@as(?u8, 0x55), img.byteAt(0x11)); + try std.testing.expectEqual(@as(usize, 2), img.segments.len); + + try img.setByte(gpa, 0x12, 0x77); // touches the first segment: merged + try std.testing.expectEqual(@as(usize, 2), img.segments.len); + try std.testing.expectEqual(@as(usize, 3), img.segments[0].data.len); + + try img.setByte(gpa, 0x40, 0x01); // after everything: new segment + try img.setByte(gpa, 0x05, 0x02); // before everything: new first segment + try std.testing.expectEqual(@as(usize, 4), img.segments.len); + try std.testing.expectEqual(@as(u32, 0x05), img.segments[0].addr); + + try img.setByte(gpa, 0x1F, 0x00); // bridges nothing yet + try img.setByte(gpa, 0x13, 0x00); + // 0x10..0x13 contiguous, 0x1F separate, 0x20.. contiguous with 0x1F -> merged + try std.testing.expectEqual(@as(u32, 0x1F), img.segments[2].addr); + try std.testing.expectEqual(@as(usize, 3), img.segments[2].data.len); + try std.testing.expectEqual(@as(u32, 0x40), img.segments[3].addr); +} diff --git a/src/main.zig b/src/main.zig index 13681cf..31cca49 100644 --- a/src/main.zig +++ b/src/main.zig @@ -69,6 +69,9 @@ const usage_fmt = \\ -f, --force Skip confirmation for destructive actions (overwrite, erase) \\ --part Target device for flash (e.g. mc9s08jm60); --flash-base overrides \\ --bus-hz Target bus clock for flash timing (else measured) + \\ --trim HCS08 ICS parts: trim the internal reference to this frequency + \\ (e.g. 33.6) and program the result; needs --part + \\ --nvloc Where the trim bytes live (default: from the clock type, 0xFFAE) \\ --no-verify Skip the post-program verify pass \\ --sim Run against a software virtual target (no hardware needed) \\ --json Machine-readable output for list/parts/status/regs/read @@ -95,6 +98,8 @@ const Flags = struct { force: bool = false, part: ?[]const u8 = null, bus_hz: ?u32 = null, + trim_hz: ?u32 = null, + nvloc: ?u32 = null, flash_base: ?u16 = null, no_verify: bool = false, port: u16 = 1234, @@ -231,6 +236,13 @@ fn parseFlags(arena: std.mem.Allocator, args: []const [:0]const u8) !Flags { f.part = nextValue(args, &i, "--part"); } else if (eq(arg, "--bus-hz")) { f.bus_hz = parseInt(u32, nextValue(args, &i, "--bus-hz"), "bus frequency"); + } else if (eq(arg, "--trim")) { + const v = nextValue(args, &i, "--trim"); + const khz = std.fmt.parseFloat(f64, v) catch fatalCode(.usage, "invalid trim frequency: '{s}' (kHz, e.g. 33.6)", .{v}); + if (!(khz > 0 and khz < 10_000)) fatalCode(.usage, "trim frequency {s} kHz is out of range", .{v}); + f.trim_hz = @intFromFloat(@round(khz * 1000.0)); + } else if (eq(arg, "--nvloc")) { + f.nvloc = parseInt(u32, nextValue(args, &i, "--nvloc"), "trim location"); } else if (eq(arg, "--flash-base")) { f.flash_base = parseInt(u16, nextValue(args, &i, "--flash-base"), "flash base"); } else if (eq(arg, "--sim")) { @@ -871,8 +883,11 @@ fn cmdConnect(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *Io const sync = try bdm.sess.getSpeedSync(); if (sync != 0) { const hz = session.syncToHz(sync); - try out.print(" {s}bus speed{s} {s}{s}{d}.{d:0>3} MHz{s}\n", .{ - st.dim, st.reset, st.bold, st.green, hz / 1_000_000, (hz % 1_000_000) / 1000, st.reset, + // On HCS08 the pod measures the BDC clock: the bus only with CLKSW=1, otherwise the + // alternate clock (twice the bus on ICS parts). + const bus_label: []const u8 = if (flags.target == .hcs08 and ((bdm.sess.readStatusReg() catch 0x08) & 0x08 == 0)) "bdc clock" else "bus speed"; + try out.print(" {s}{s}{s} {s}{s}{d}.{d:0>3} MHz{s}\n", .{ + st.dim, bus_label, st.reset, st.bold, st.green, hz / 1_000_000, (hz % 1_000_000) / 1000, st.reset, }); } reportDetected(bdm, flags, out, st); @@ -1554,12 +1569,15 @@ const FlashPrep = struct { /// Connect, measure bus clock, parse the routine blob. Caller builds the /// driver locally (target-pointer lifetime). -fn prepareFlash(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *Io.Writer, st: tty.Style) FlashPrep { +fn prepareFlash(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *Io.Writer, st: tty.Style, image: ?*hexfile.Image, strict: bool) FlashPrep { const d = resolveDevice(flags); // HCS08/HCS12 controller base is a u16; CFV1 is u32 (sits high at 0xFF9820). if (d.family != .cfv1 and d.flash_base > 0xFFFF) { fatal("--part '{s}' has a flash controller base 0x{x} that doesn't fit the {s} routine's 16-bit field", .{ d.name, d.flash_base, @tagName(d.family) }); } + if (d.family == .hcs08 and flags.target == .hcs08) return prepareHcs08(arena, bdm, flags, d, out, st, image, strict); + if (flags.trim_hz != null or flags.nvloc != null) + fatalCode(.usage, "--trim/--nvloc are implemented for HCS08 ICS parts only (got {s})", .{flags.target.name()}); bringUp(bdm, flags) catch |err| fatal("connect failed: {s}", .{@errorName(err)}); // HCS12: a target running its own code acks memory access but not a PC // write (BDM_RC_ACK_TIMEOUT), so the routine cannot be started. Reset into @@ -1615,6 +1633,51 @@ fn initXmmcFlash(bdm: *Bdm, d: lib_device.Device, bus_hz: u32) void { } } +/// HCS08: reset, COP, clock, optional trim and FCDIV before the routine may run (see +/// hcs08.zig), then the same FlashPrep as any other part at the bus clock that was set up. +fn prepareHcs08(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, d: lib_device.Device, out: *Io.Writer, st: tty.Style, image: ?*hexfile.Image, strict: bool) FlashPrep { + _ = bdm.sess.capabilities() catch {}; + bdm.sess.setOptions(lib.hcs08.options(optionsForTarget(flags))) catch |err| fatal("connect failed: {s}", .{@errorName(err)}); + bdm.sess.setTarget(flags.target) catch |err| fatal("connect failed: {s}", .{@errorName(err)}); + bdm.sess.connectWithRetry(true) catch |err| fatal("connect failed: {s}", .{@errorName(err)}); + var ctx = lib.hcs08.Ctx{ .sess = &bdm.sess, .dev = d, .sleep_ms = lib.hcs08.sleepMs }; + const res = lib.hcs08.prepare(arena, &ctx, .{ + .trim_hz = flags.trim_hz, + .nvloc = flags.nvloc, + .bus_hz = flags.bus_hz, + .strict = strict, + }, image) catch |err| switch (err) { + error.NoFlashDivider => fatal("no flash clock divider fits this bus clock (the flash needs 150-200 kHz); pass --bus-hz if the measurement is wrong", .{}), + error.FcdivNotLoaded => fatal("FCDIV did not load: it was already written since the last reset, so the target was not reset cleanly (the firmware ran before the halt)", .{}), + error.TrimNotSupported => fatal("--trim needs an HCS08 part with an ICS clock; pass --part (this device's clock is '{s}')", .{@tagName(d.clock)}), + error.BadTrimLocation => fatal("the trim location is not in {s} flash; check --nvloc", .{d.name}), + error.TrimOutOfRange => fatal("the clock cannot be trimmed to {d:.3} kHz: the search ran off the end of the trim range", .{@as(f64, @floatFromInt(flags.trim_hz orelse 0)) / 1000.0}), + else => fatal("HCS08 flash bring-up failed: {s}", .{@errorName(err)}), + }; + + out.print("{s}special reset, COP off, bus clock {d}.{d:0>3} MHz, FCDIV 0x{x:0>2}{s}\n", .{ + st.dim, res.bus_hz / 1_000_000, (res.bus_hz % 1_000_000) / 1000, res.fcdiv | 0x80, st.reset, + }) catch {}; + if (res.trim) |t| { + const tb = res.trim_bytes.?; + out.print("{s}trimmed{s} the reference to {d:.3} kHz: trim 0x{x:0>3} (TRIM 0x{x:0>2}, FTRIM {d}), {d} measurements; trim bytes 0x{x:0>4}={x:0>2} 0x{x:0>4}={x:0>2}\n", .{ + st.green, st.reset, @as(f64, @floatFromInt(flags.trim_hz.?)) / 1000.0, + t.value, t.value >> 1, t.value & 1, + t.samples, tb.ftrim_addr, tb.ftrim, + tb.trim_addr, tb.trim, + }) catch {}; + } + if (res.preserved) |k| { + out.print("{s}kept the oscillator trim{s} {x:0>2} {x:0>2} at 0x{x:0>4} (the sector erase would have wiped it; --trim re-trims)\n", .{ + st.green, st.reset, k[0], k[1], res.preserved_at, + }) catch {}; + } + if (res.soft_error) |e| { + out.print("{s}warning:{s} HCS08 flash setup incomplete ({s}); continuing\n", .{ st.yellow, st.reset, @errorName(e) }) catch {}; + } + return flashPrepFor(arena, d, res.bus_hz); +} + /// FlashPrep for a device at a known bus clock, no I/O (shared by prepareFlash + gdb). fn flashPrepFor(arena: std.mem.Allocator, d: lib_device.Device, bus_hz: u32) FlashPrep { // frequency_khz is u16 (max ~65.5 MHz); reject rather than overflow the cast. @@ -1687,7 +1750,7 @@ fn cmdProgram(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *Io const path = flags.positionals[1]; const bytes = Io.Dir.cwd().readFileAlloc(global_io, path, arena, .limited(16 * 1024 * 1024)) catch |err| fatalCode(.io_error, "cannot read '{s}': {s}", .{ path, @errorName(err) }); - const image = hexfile.parse(arena, bytes) catch |err| + var image = hexfile.parse(arena, bytes) catch |err| fatalCode(.io_error, "cannot parse '{s}': {s}", .{ path, @errorName(err) }); const d = resolveDevice(flags); @@ -1704,7 +1767,8 @@ fn cmdProgram(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *Io if (!confirm(out, st, flags.force, "program {d} bytes to {s} flash (erases affected sectors)?", .{ image.totalBytes(), d.name })) fatal("aborted", .{}); - const prep = prepareFlash(arena, bdm, flags, out, st); + // HCS08: also inserts the trim bytes (--trim) or carries the chip's own over. + const prep = prepareFlash(arena, bdm, flags, out, st, &image, true); var rt = prep.ramTarget(&bdm.sess); var drv = prep.driver(rt.iface()); @@ -1748,7 +1812,7 @@ fn cmdEeprom(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *Io. fatal("aborted", .{}); // Flash routine/params, but EEPROM align+sector; bit-31 global addr → D-flash. - var prep = prepareFlash(arena, bdm, flags, out, st); + var prep = prepareFlash(arena, bdm, flags, out, st, null, true); prep.params.alignment = ee.align_bytes; prep.params.sector_size = @intCast(ee.sector); var rt = prep.ramTarget(&bdm.sess); @@ -1782,7 +1846,7 @@ fn cmdVerify(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *Io. const image = hexfile.parse(arena, bytes) catch |err| fatalCode(.io_error, "cannot parse '{s}': {s}", .{ path, @errorName(err) }); - const prep = prepareFlash(arena, bdm, flags, out, st); + const prep = prepareFlash(arena, bdm, flags, out, st, null, true); var rt = prep.ramTarget(&bdm.sess); var drv = prep.driver(rt.iface()); for (image.segments) |seg| { @@ -1791,6 +1855,16 @@ fn cmdVerify(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *Io. } } +/// A mass erase takes the factory/PGO oscillator trim with it: say so, and how to put one back. +fn trimLostNote(d: lib_device.Device, out: *Io.Writer, st: tty.Style) void { + if (d.family != .hcs08) return; + const nv = lib.clock.defaultTrimNv(d.clock); + if (nv == 0) return; + out.print("{s}note:{s} the oscillator trim at 0x{x:0>4} was erased; an untrimmed part runs off-frequency. Re-trim with: program --part {s} --trim \n", .{ + st.yellow, st.reset, nv, d.name, + }) catch {}; +} + fn cmdErase(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *Io.Writer, st: tty.Style) !void { requireFlashTarget(flags); const d = resolveDevice(flags); @@ -1803,7 +1877,7 @@ fn cmdErase(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *Io.W } else { if (!confirm(out, st, flags.force, "MASS ERASE all flash on {s}? this wipes the entire chip", .{d.name})) fatal("aborted", .{}); } - const prep = prepareFlash(arena, bdm, flags, out, st); + const prep = prepareFlash(arena, bdm, flags, out, st, null, true); var rt = prep.ramTarget(&bdm.sess); var drv = prep.driver(rt.iface()); if (page) |addr| { @@ -1811,16 +1885,19 @@ fn cmdErase(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *Io.W try out.print("{s}note: 0x{x:0>4} rounded down to sector base 0x{x:0>4}{s}\n", .{ st.dim, page_raw.?, addr, st.reset }); drv.eraseRange(addr, d.page_size) catch |err| mapRoutineError(drv.lastError(), err); try out.print("{s}erased sector at 0x{x:0>4}{s}\n", .{ st.green, addr, st.reset }); + const nv = lib.clock.defaultTrimNv(d.clock); + if (d.family == .hcs08 and nv != 0 and nv >= addr and nv < addr + d.page_size) trimLostNote(d, out, st); } else { drv.massErase(d.flash_start) catch |err| mapRoutineError(drv.lastError(), err); try out.print("{s}mass erased{s}\n", .{ st.green, st.reset }); + trimLostNote(d, out, st); } } fn cmdBlankCheck(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *Io.Writer, st: tty.Style) !void { requireFlashTarget(flags); const d = resolveDevice(flags); - const prep = prepareFlash(arena, bdm, flags, out, st); + const prep = prepareFlash(arena, bdm, flags, out, st, null, true); var rt = prep.ramTarget(&bdm.sess); var drv = prep.driver(rt.iface()); // 258 = up to 256 banked pages + two fixed windows. @@ -1843,7 +1920,7 @@ fn cmdUnsecure(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *I const d = resolveDevice(flags); const val = lib_device.unsecuredSecurityByte(d.family); if (!confirm(out, st, flags.force, "UNSECURE {s}? this mass-erases the entire chip", .{d.name})) fatal("aborted", .{}); - const prep = prepareFlash(arena, bdm, flags, out, st); + const prep = prepareFlash(arena, bdm, flags, out, st, null, false); var rt = prep.ramTarget(&bdm.sess); var drv = prep.driver(rt.iface()); // Mass-erase leaves the security byte 0xFF (secured); program the unsecured @@ -1853,6 +1930,7 @@ fn cmdUnsecure(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *I try out.print("{s}unsecured{s} (mass-erased, security@0x{x:0>4} = 0x{x:0>2}); power-cycle the target\n", .{ st.green, st.reset, d.security_addr, val, }); + trimLostNote(d, out, st); } /// secure: program the security byte to SECURED (SEC=0b00) - locks debug access. @@ -1861,7 +1939,7 @@ fn cmdSecure(arena: std.mem.Allocator, bdm: *Bdm, flags: *const Flags, out: *Io. const d = resolveDevice(flags); const val = lib_device.securedSecurityByte(d.family); if (!confirm(out, st, flags.force, "SECURE {s}? this LOCKS debug access (erases the security sector); recovery needs 'unsecure'", .{d.name})) fatal("aborted", .{}); - const prep = prepareFlash(arena, bdm, flags, out, st); + const prep = prepareFlash(arena, bdm, flags, out, st, null, true); var rt = prep.ramTarget(&bdm.sess); var drv = prep.driver(rt.iface()); // Erase the security byte's sector so it can be reprogrammed. @@ -3074,6 +3152,167 @@ test "e2e --sim+cpu backend: the REAL HCS08 routine programs through the sim sta try drv.blankCheck(0xE000, d.page_size); } +/// A simulated SH16 with the real CPU08 core, FCDIV enforced and an ICS clock model, plus a +/// session on it. The oscillator trim starts at 01 81 as on the bench part. +const Hcs08Rig = struct { + sim: Sim, + cpu: lib.cpu08.Cpu, + s: session.Session, + d: lib_device.Device, + + fn init(gpa: std.mem.Allocator, rig: *Hcs08Rig) !void { + rig.d = lib_device.lookup("mc9s08sh16").?; + rig.sim = Sim.init(gpa, rig.d); + rig.cpu = try lib.cpu08.Cpu.init(gpa, rig.d.flash_base, rig.d.flash_start, rig.d.flash_end); + rig.cpu.require_fcdiv = true; + rig.cpu.hostWrite(0xFFAE, &.{ 0x01, 0x81 }); + rig.sim.cpu = .{ .hcs08 = &rig.cpu }; + rig.sim.ics = .{ .base = rig.d.clock_addr }; + rig.s = session.Session.init(rig.sim.asTransport(.{})); + _ = rig.s.capabilities() catch {}; + try rig.s.setOptions(lib.hcs08.options(.{})); + try rig.s.setTarget(.hcs08); + try rig.s.connect(); + } + fn deinit(rig: *Hcs08Rig) void { + rig.cpu.deinit(); + rig.sim.deinit(); + } + fn ctx(rig: *Hcs08Rig) lib.hcs08.Ctx { + return .{ .sess = &rig.s, .dev = rig.d, .sleep_ms = noSleep }; + } + fn noSleep(_: u32) void {} +}; + +test "HCS08: the flash controller refuses commands until bring-up loads FCDIV" { + const gpa = std.testing.allocator; + var arena_inst = std.heap.ArenaAllocator.init(gpa); + defer arena_inst.deinit(); + const arena = arena_inst.allocator(); + var rig: Hcs08Rig = undefined; + try Hcs08Rig.init(gpa, &rig); + defer rig.deinit(); + + const prep = flashPrepFor(arena, rig.d, 8_600_000); + var rt = prep.ramTarget(&rig.s); + var drv = prep.driver(rt.iface()); + const data = [_]u8{ 0x11, 0x22, 0x33, 0x44 }; + + // What `usbdm program` used to do on a freshly reset HCS08: straight to the routine. + try std.testing.expectError(error.RoutineError, drv.eraseRange(0xE000, 512)); + + var ctx = rig.ctx(); + const res = try lib.hcs08.prepare(arena, &ctx, .{}, null); + try std.testing.expectEqual(@as(u8, 43), res.fcdiv); // the divider PGO chose for 8.63 MHz + try std.testing.expect(res.bus_hz > 8_000_000 and res.bus_hz < 9_000_000); + var fcdiv: [1]u8 = undefined; + try rig.s.readMem(.byte, 0x1820, &fcdiv); + try std.testing.expectEqual(@as(u8, 0x80 | 43), fcdiv[0]); + var cop: [1]u8 = undefined; + try rig.s.readMem(.byte, 0x1802, &cop); + try std.testing.expectEqual(@as(u8, 0x22), cop[0]); // COP off + + // Same session, FCDIV now loaded: the real routine erases, programs and verifies. + try drv.eraseRange(0xE000, 512); + try drv.program(0xE000, &data); + try drv.verify(0xE000, &data); +} + +test "HCS08 --trim: the search lands on the target and the bytes reach the image and the chip" { + const gpa = std.testing.allocator; + var arena_inst = std.heap.ArenaAllocator.init(gpa); + defer arena_inst.deinit(); + const arena = arena_inst.allocator(); + var rig: Hcs08Rig = undefined; + try Hcs08Rig.init(gpa, &rig); + defer rig.deinit(); + + // An image with only vectors and an NVOPT: the trim bytes are not in the file, as on a real build. + var image = try hexfile.parse(arena, "S113FFF0000102030405060708090A0B0C0D0E0F85\nS9030000FC\n"); + try std.testing.expectEqual(@as(?u8, null), image.byteAt(0xFFAE)); + + var ctx = rig.ctx(); + // Reference 33.6 kHz; the modelled part is 33.7 kHz at trim 256, 0.19 % per step, larger = slower. + const res = try lib.hcs08.prepare(arena, &ctx, .{ .trim_hz = 33_600 }, &image); + const t = res.trim.?; + const ideal = 256.0 + (33.7 - 33.6) / 33.7 / 0.0019; // 257.56 + try std.testing.expect(@abs(@as(f64, @floatFromInt(t.value)) - ideal) <= 1.0); + try std.testing.expectEqual(@as(?u8, @intCast(t.value >> 1)), image.byteAt(0xFFAF)); + try std.testing.expectEqual(@as(?u8, @intCast(t.value & 1)), image.byteAt(0xFFAE)); // erased byte: other bits cleared + // Trimmed clock at the trim-time speed: 33.6 kHz * 64 within a step. + const err = @abs(@as(f64, @floatFromInt(t.measured_hz)) - 33_600.0 * 64.0) / (33_600.0 * 64.0); + try std.testing.expect(err < 0.0025); + + // The programming clock afterwards is the known one, not the trimmed one. + var c2: [4]u8 = undefined; + try rig.s.readMem(.byte, 0x48, &c2); + try std.testing.expectEqual(@as(u8, 0x40), c2[1]); // BDIV /2 + try std.testing.expectEqual(@as(u8, 0x80), c2[2]); // nominal TRIM + + // Then the usual erase-all-then-program: the chip ends up with the new trim, not 01 81. + const prep = flashPrepFor(arena, rig.d, res.bus_hz); + var rt = prep.ramTarget(&rig.s); + var drv = prep.driver(rt.iface()); + for (image.segments) |seg| try drv.eraseRange(seg.addr, @intCast(seg.data.len)); + for (image.segments) |seg| try drv.program(seg.addr, seg.data); + var nv: [2]u8 = undefined; + try rig.s.readMem(.byte, 0xFFAE, &nv); + try std.testing.expectEqual(@as(u8, @intCast(t.value & 1)), nv[0]); + try std.testing.expectEqual(@as(u8, @intCast(t.value >> 1)), nv[1]); +} + +test "HCS08 --trim keeps other bits of an NVFTRIM the image defines" { + const gpa = std.testing.allocator; + var arena_inst = std.heap.ArenaAllocator.init(gpa); + defer arena_inst.deinit(); + const arena = arena_inst.allocator(); + var rig: Hcs08Rig = undefined; + try Hcs08Rig.init(gpa, &rig); + defer rig.deinit(); + var ctx = rig.ctx(); + // Hand-built image: 0xFFAE = 0x40 (some other option bit), nothing at 0xFFAF. + var img2 = try hexfile.parse(arena, "S104FFAE400E\nS9030000FC\n"); + _ = try lib.hcs08.prepare(arena, &ctx, .{ .trim_hz = 33_600 }, &img2); + try std.testing.expectEqual(@as(u8, 0x40), img2.byteAt(0xFFAE).? & 0xFE); // bit 6 survives +} + +test "HCS08 without --trim: the chip's own trim is carried across the sector erase" { + const gpa = std.testing.allocator; + var arena_inst = std.heap.ArenaAllocator.init(gpa); + defer arena_inst.deinit(); + const arena = arena_inst.allocator(); + var rig: Hcs08Rig = undefined; + try Hcs08Rig.init(gpa, &rig); + defer rig.deinit(); + var ctx = rig.ctx(); + + // Vector page image, no trim bytes: this is what `usbdm program` of a normal build looks like. + var image = try hexfile.parse(arena, "S113FFF0000102030405060708090A0B0C0D0E0F85\nS9030000FC\n"); + const res = try lib.hcs08.prepare(arena, &ctx, .{}, &image); + try std.testing.expectEqual(@as([2]u8, .{ 0x01, 0x81 }), res.preserved.?); + try std.testing.expectEqual(@as(?u8, 0x01), image.byteAt(0xFFAE)); + try std.testing.expectEqual(@as(?u8, 0x81), image.byteAt(0xFFAF)); + + const prep = flashPrepFor(arena, rig.d, res.bus_hz); + var rt = prep.ramTarget(&rig.s); + var drv = prep.driver(rt.iface()); + for (image.segments) |seg| try drv.eraseRange(seg.addr, @intCast(seg.data.len)); + for (image.segments) |seg| try drv.program(seg.addr, seg.data); + var nv: [2]u8 = undefined; + try rig.s.readMem(.byte, 0xFFAE, &nv); + try std.testing.expectEqual(@as([2]u8, .{ 0x01, 0x81 }), nv); + + // An image that does not touch the vector sector leaves the trim alone and adds nothing. + var other = try hexfile.parse(arena, "S105E000AABBB5\nS9030000FC\n"); + var rig2: Hcs08Rig = undefined; + try Hcs08Rig.init(gpa, &rig2); + defer rig2.deinit(); + var ctx2 = rig2.ctx(); + const res2 = try lib.hcs08.prepare(arena, &ctx2, .{}, &other); + try std.testing.expectEqual(@as(?[2]u8, null), res2.preserved); + try std.testing.expectEqual(@as(?u8, null), other.byteAt(0xFFAE)); +} + test "e2e --sim+cpu backend: single-step executes a real instruction" { const gpa = std.testing.allocator; const d = lib_device.lookup("mc9s08sh8").?; diff --git a/src/root.zig b/src/root.zig index 21b01ac..c689cc4 100644 --- a/src/root.zig +++ b/src/root.zig @@ -13,6 +13,8 @@ pub const hexfile = @import("hexfile.zig"); pub const flash = @import("flash.zig"); pub const ramflash = @import("ramflash.zig"); pub const device = @import("device.zig"); +pub const clock = @import("clock.zig"); +pub const hcs08 = @import("hcs08.zig"); pub const hwbreak = @import("hwbreak.zig"); pub const gdbstub = @import("gdbstub.zig"); pub const gdb = @import("gdb.zig"); diff --git a/src/sim.zig b/src/sim.zig index 17049f6..994baf6 100644 --- a/src/sim.zig +++ b/src/sim.zig @@ -151,7 +151,31 @@ pub const CpuBackend = union(enum) { } }; +/// A model of an ICS clock for the speed the pod reports, so the flash bring-up and trim +/// search can run in the simulator: bus = reference x FLL / BDIV / 2, the reference +/// following ICSTRM/FTRIM (a larger trim is slower) and BDIV following ICSC2[7:6]. +/// This is the BDM clock with CLKSW=1. +pub const IcsModel = struct { + base: u32, + /// FLL multiplier at DRS=0 (1024 on ICSV2, 512 on ICSV1/V3). + fll: f64 = 1024, + /// Reference at trim 256 (TRIM 0x80, FTRIM 0). + irc_hz: f64 = 33_700, + /// Fractional frequency change per trim step. + slope: f64 = -0.0019, + + pub fn busHz(self: IcsModel, sim: *Sim) f64 { + const c2 = sim.memGet(self.base + 1); + const trim: f64 = @floatFromInt((@as(u32, sim.memGet(self.base + 2)) << 1) | (sim.memGet(self.base + 3) & 1)); + const bdiv: f64 = @floatFromInt(@as(u32, 1) << @intCast(c2 >> 6)); + const irc = self.irc_hz * (1.0 + self.slope * (trim - 256.0)); + return irc * self.fll / bdiv / 2.0; + } +}; + pub const Sim = struct { + /// When set, the speed the pod reports follows the target's ICS registers. + ics: ?IcsModel = null, gpa: std.mem.Allocator, dev: device.Device, mem: std.AutoHashMap(u32, u8), @@ -387,6 +411,12 @@ pub const Sim = struct { }, .connect => self.connected = true, .target_reset, .target_halt => { + if (cmd == .target_reset) { + if (self.cpu) |c| switch (c) { + .hcs08 => |cp| cp.resetFlashRegs(), + else => {}, + }; + } self.halted = true; if (self.cpu) |c| c.setHalted(true); // keep core status in sync }, @@ -402,6 +432,7 @@ pub const Sim = struct { }, .set_speed => self.speed_sync = rd16p(p), .get_speed => { + if (self.ics) |m| self.speed_sync = @import("session.zig").hzToSync(@intFromFloat(m.busHz(self))) catch self.speed_sync; std.mem.writeInt(u16, scratch[0..2], self.speed_sync, .big); data = scratch[0..2]; }, diff --git a/tools/gen_devices.zig b/tools/gen_devices.zig index b0aba38..127441d 100644 --- a/tools/gen_devices.zig +++ b/tools/gen_devices.zig @@ -173,6 +173,21 @@ const GMMC_EE = "HCS12-GMMC-FTMRG-eeprom-program"; const XMMC = "HCS12-XMMC-XFTMRK-flash-program"; const SUP_CFV1 = [_][]const u8{ "CFV1-default-FlashProgram", "CFV1-Watchdog-FlashProgram" }; +/// Device-DB `` name -> device_types.ClockType tag. +fn clockTag(ty: []const u8) []const u8 { + const map = [_][2][]const u8{ + .{ "S08ICSV1", "ics_v1" }, .{ "S08ICSV2", "ics_v2" }, + .{ "S08ICSV2x512", "ics_v2x512" }, .{ "S08ICSV3", "ics_v3" }, + .{ "S08ICSV4", "ics_v4" }, .{ "S08ICSV5", "ics_v5" }, + .{ "S08ICGV1", "icg" }, .{ "S08ICGV2", "icg" }, + .{ "S08ICGV3", "icg" }, .{ "S08ICGV4", "icg" }, + .{ "S08MCGV1", "mcg" }, .{ "S08MCGV2", "mcg" }, + .{ "S08MCGV3", "mcg" }, .{ "External", "external" }, + }; + for (map) |m| if (std.mem.eql(u8, m[0], ty)) return m[1]; + return "other"; +} + fn inList(list: []const []const u8, s: []const u8) bool { for (list) |x| if (std.mem.eql(u8, x, s)) return true; return false; @@ -587,6 +602,26 @@ fn processFile( } } + // HCS08: clock generator + SOPT, so flash operations can reset, disable the + // COP, set a known clock and (optionally) trim it. An alias with no clock of + // its own inherits its target's. + var clock_tag: []const u8 = "external"; + var clock_addr: u64 = 0; + var sopt_addr: u64 = 0; + if (fam == .hcs08) { + const cbody = if (scanElem(d.body, 0, "clock") != null or target == null) d.body else tbody; + if (scanElem(cbody, 0, "clock")) |ce| { + if (attr(ce.attrs, "type")) |t| clock_tag = clockTag(t); + if (attr(ce.attrs, "registerAddress")) |r| clock_addr = parseNum(r); + } + sopt_addr = ctx.def.sopt; + if (elemAttr(d.body, "soptAddress", "value")) |x| { + sopt_addr = parseNum(x); + } else if (target != null) { + if (elemAttr(tbody, "soptAddress", "value")) |x| sopt_addr = parseNum(x); + } + } + var have_ee = false; var ee_base: u64 = 0; var ee_size: u64 = 0; @@ -635,6 +670,8 @@ fn processFile( try table_w.print(", .page_size = {d}, .write_align = {d}", .{ page_size, write_align }); try table_w.print(", .security_addr = 0x{X}, .watchdog_addr = 0x{X}", .{ sec, watchdog }); try table_w.print(", .hcs12_routine = .{s}", .{hcs12_routine}); + if (fam == .hcs08) + try table_w.print(", .clock = .{s}, .clock_addr = 0x{X}, .sopt_addr = 0x{X}", .{ clock_tag, clock_addr, sopt_addr }); if (have_paged) { try table_w.print(", .paged = .{{ .ppage_addr = 0x{X}, .page_first = 0x{X}, .page_last = 0x{X} }}", .{ page_addr, pg_first, pg_last }); } else {