From f85d8a45845f3093bbcdcacfa425be998fea8437 Mon Sep 17 00:00:00 2001 From: Cryan209 Date: Fri, 4 Sep 2026 19:48:47 +1200 Subject: [PATCH] Download a ROM's datapump into the emulated DSP A flash image does carry a separable C52 payload. Its supervisor sends one at every boot, and the call site that starts that download names every parameter needed to find it: the entry word, the source offsets, and the window segment the downloader loads into ES. Recover it from there rather than from a constant, because the 25 MHz supervisor keeps the same payload at 0x296e0 behind the same instructions, and an offset taken from one image reads the wrong bytes out of another. Teaching the bridge to receive it needs a second transfer protocol, not an extension of the first. An update payload's supervisor strobes one window on port 0x1e; a ROM's downloader alternates two, strobing 0x40..0x4e with 1 and 0x50..0x5e with 2 on port 0x18, and submits its word checksum with 4. They cannot be merged: 0x58..0x5e are the runtime mailbox under both, and also the upper transfer window under the ROM's. Nothing in a single write separates those uses, so the download's own completion does. Two things then stopped the transfer. The timer model grants timer 2's max count at the first poll of a control register, which is right for the calibrated delays both firmwares busy-wait on and wrong for the DSP transfer routines, which reuse that bit as their handshake timeout: e3aa reported a failure that never happened and the download never started. The XMF supervisor has the same collision, already handled by address. Decline the grant while the CPU is inside the transfer routines the call site locates. And e370 sets its window up through the same window and strobes as the program, so its eight 0083 words were counted as payload; drop what arrived before the entry request completes. The supervisor now transfers all 27,710 words through the modelled ports, byte-identical to the flash range, with the checksum strobe after. The C52 core does not execute them yet: nothing performs the launch to the requested entry that the DSP's own boot ROM would. Also correct S0STS's bit map against the 80C186EB manual, figure 10-14. The fields sit above a reserved bit 0, so bit 1 is CTS and bit 3 TXE, one place higher than a plain reading of the field list gives. Four firmware uses agree and none parses under the unshifted reading. Behaviour is unchanged: bit 1 keeps the edges the previous model produced, now named for what it is and marked as standing in for an unmodelled DTE handshake. Co-Authored-By: Claude Opus 5 --- courier_emu/bridge.py | 149 +++++++++++++++++++++++++++++++++++------ courier_emu/cli.py | 8 +-- courier_emu/machine.py | 33 ++++++++- courier_emu/rom.py | 136 +++++++++++++++++++++++++++++++++++++ courier_emu/timers.py | 20 +++++- courier_emu/uart.py | 73 ++++++++++++++++---- tests/test_rom.py | 49 +++++++++++++- 7 files changed, 421 insertions(+), 47 deletions(-) diff --git a/courier_emu/bridge.py b/courier_emu/bridge.py index c273041..68b97ba 100644 --- a/courier_emu/bridge.py +++ b/courier_emu/bridge.py @@ -34,6 +34,57 @@ C52_CALL_OVERLAY_WORDS = C52_CALL_OVERLAY_DESTINATION - C52_CALL_OVERLAY_SOURCE C52_CALL_OVERLAY_SIGNATURE = bytes.fromhex("4a6908e3") DSP_RUNTIME_PORTS = (0x58, 0x5A, 0x5C, 0x5E) +# A supervisor sends the C52 program through one of two transfer protocols, +# and they are not compatible enough to merge. An update payload's supervisor +# strobes eight bytes at a time from one window on port 0x1e. A flash ROM's +# downloader at e47b alternates two windows, strobing 0x40..0x4e with 1 and +# 0x50..0x5e with 2, both on port 0x18, and finishes by submitting its word +# checksum with 4. +# +# The collision that forces a profile rather than a union: 0x58..0x5e are the +# runtime mailbox registers in both protocols, but in the ROM's they are also +# the upper half of the second transfer window. Nothing in a single write +# distinguishes the two uses, so the download's own completion does - before +# the program is in, those ports are window lanes; after it, they are the +# mailbox. That is the order the hardware runs them in. +ROM_COMMAND_PORT = 0x18 +ROM_CHECKSUM_STROBE = 4 +# The value e3aa writes to 0x1c as it leaves, on both its paths. +ENTRY_REQUEST_COMPLETE = 2 + + +@dataclass(frozen=True) +class TransferProfile: + """How a supervisor moves program words into the DSP.""" + + name: str + command_port: int + # Strobe value to the base port of the window it commits. + windows: tuple[tuple[int, int], ...] + checksum_strobe: int | None + # Whether the runtime mailbox registers double as transfer window lanes. + mailbox_shares_window: bool + + @property + def first_strobe(self) -> int: + return self.windows[0][0] + + def lanes(self) -> dict[int, tuple[int, int]]: + """Map each window port to the strobe that commits it and its lane.""" + return { + base + lane * DSP_WINDOW_STRIDE: (strobe, lane) + for strobe, base in self.windows + for lane in range(8) + } + + +XMF_TRANSFER = TransferProfile( + "xmf", DSP_COMMAND_PORT, ((1, DSP_WINDOW_FIRST),), None, False +) +ROM_TRANSFER = TransferProfile( + "rom", ROM_COMMAND_PORT, ((1, 0x40), (2, 0x50)), ROM_CHECKSUM_STROBE, True +) + # The supervisor's receive table stores this tag's data word at [0x287], which # is the DAA revision `ATI7` prints and which the product ID at 0x8369d # branches on. Its three neighbours -- 0x7c, 0x7d, 0x7e -- fill [0x283]/[0x285], @@ -101,12 +152,24 @@ class CourierDspBridge: ) -> None: self.image = image self.expected_bootstrap = image.dsp_program_segments()[0][1] - # The 2.3 supervisor downloads the shorter 0xcbc0-byte resident - # bootstrap; the 2.1/2.2 supervisors transfer the full segment. - self.bootstrap_target_size = ( - 0xCBC0 if getattr(image, "supervisor_offset", 0) == 0x17BB0 - else DSP_BOOT_SIZE + # A ROM locates its payload through its own download call site, which + # an update payload has no need of; that is what tells the two + # transfer protocols apart here. + self.transfer = ( + ROM_TRANSFER if hasattr(image, "dsp_download") else XMF_TRANSFER ) + if self.transfer is ROM_TRANSFER: + # A ROM's supervisor makes one download call covering the whole + # payload, so the transfer is complete only once all of it has + # arrived. There is no shorter resident bootstrap to recognize. + self.bootstrap_target_size = len(self.expected_bootstrap) + else: + # The 2.3 supervisor downloads the shorter 0xcbc0-byte resident + # bootstrap; the 2.1/2.2 supervisors transfer the full segment. + self.bootstrap_target_size = ( + 0xCBC0 if getattr(image, "supervisor_offset", 0) == 0x17BB0 + else DSP_BOOT_SIZE + ) self.core = NativeC5x(image) self._configure_frame_interrupt() self._call_overlay = self._find_call_overlay() @@ -114,7 +177,14 @@ class CourierDspBridge: self._call_resume_pending = False self._call_resume_state: dict[str, int | bool] | None = None self.batch = batch - self.window = bytearray(b"\xff" * 8) + self._lanes = self.transfer.lanes() + self._windows = { + strobe: bytearray(b"\xff" * 8) for strobe, _ in self.transfer.windows + } + # The first window keeps the old name; the bootstrap recognition and + # the status report both read it. + self.window = self._windows[self.transfer.first_strobe] + self.checksum_submits = 0 self.bootstrap = bytearray() self.active = False self.bootstrap_match: bool | None = None @@ -657,15 +727,20 @@ class CourierDspBridge: self._queue_runtime_message(0x001D, 0x0000) self._connected_event_queued = True - @staticmethod - def handles(port: int) -> bool: - return port in (0x1C, DSP_COMMAND_PORT, *DSP_RUNTIME_PORTS) or ( - DSP_WINDOW_FIRST <= port <= DSP_WINDOW_LAST - and (port - DSP_WINDOW_FIRST) % DSP_WINDOW_STRIDE == 0 + def handles(self, port: int) -> bool: + return ( + port in (0x1C, self.transfer.command_port, *DSP_RUNTIME_PORTS) + or port in self._lanes ) def write(self, port: int, size: int, value: int, pc: int | None = None) -> None: - if port in DSP_RUNTIME_PORTS and size == 1: + if ( + port in DSP_RUNTIME_PORTS + and size == 1 + # Under the ROM's protocol these ports carry the upper transfer + # window until the program is in, and the mailbox only after. + and not (self.transfer.mailbox_shares_window and not self.active) + ): self._runtime_mode = True if port == 0x58: self._runtime_header = (self._runtime_header & 0xFF00) | (value & 0xFF) @@ -688,6 +763,18 @@ class CourierDspBridge: self._answer_runtime_request(*words) return if port == 0x1C: + if ( + self.transfer.checksum_strobe is not None + and not self.active + and size == 1 + and (value & 0xFF) == ENTRY_REQUEST_COMPLETE + ): + # A ROM's supervisor sets its transfer window up before it + # requests the entry, and that setup goes through the same + # window and strobes as the program does - eight 0083 words on + # the captured board. The entry request ends here, so whatever + # the window carried before it was configuration, not program. + self.bootstrap.clear() if self._runtime_mode: if not (value & 1): self._runtime_ready = False @@ -701,14 +788,31 @@ class CourierDspBridge: self._runtime_inbound_delivered[f"{header:04x}:{data:04x}"] += 1 self._runtime_inbound_seen = False return - if DSP_WINDOW_FIRST <= port <= DSP_WINDOW_LAST: - lane = (port - DSP_WINDOW_FIRST) // DSP_WINDOW_STRIDE - if 0 <= lane < len(self.window): - self.window[lane] = value & 0xFF + placement = self._lanes.get(port) + if placement is not None: + strobe, lane = placement + self._windows[strobe][lane] = value & 0xFF return - if port != DSP_COMMAND_PORT or size != 1 or (value & 0xFF) != 1: + if port != self.transfer.command_port or size != 1: return - if self.active and bytes(self.window) == self.expected_bootstrap[:8]: + strobe = value & 0xFF + if ( + self.transfer.checksum_strobe is not None + and strobe == self.transfer.checksum_strobe + ): + # The ROM's downloader submits its 16-bit word sum here and polls + # for acceptance. The transfer is already complete by length, so + # this is recorded rather than acted on. + self.checksum_submits += 1 + return + if strobe not in self._windows: + return + window = self._windows[strobe] + if ( + strobe == self.transfer.first_strobe + and self.active + and bytes(window) == self.expected_bootstrap[:8] + ): # The supervisor re-enters its DSP download routine for a line # operation. Recognize the program's first transfer window; port # 0x1c also carries ordinary handshakes and is not a reset signal @@ -718,7 +822,7 @@ class CourierDspBridge: self._configure_frame_interrupt() self._call_overlay_active = False self._call_resume_pending = self._v8_armed - self.bootstrap = bytearray(self.window) + self.bootstrap = bytearray(window) self.bootstrap_match = None self.active = False self._runtime_mode = False @@ -730,7 +834,7 @@ class CourierDspBridge: return if not self.active: self.transfer_commands += 1 - self.bootstrap.extend(self.window) + self.bootstrap.extend(window) if len(self.bootstrap) >= self.bootstrap_target_size: self.bootstrap_match = ( self.bootstrap[:self.bootstrap_target_size] @@ -804,7 +908,10 @@ class CourierDspBridge: if not self._runtime_mode: return (1 << (size * 8)) - 1 return int(self._runtime_ready) | (2 if self._runtime_inbound else 0) - if port == DSP_COMMAND_PORT: + if port == self.transfer.command_port: + # The downloader polls this port for the boot ROM's ready and + # acceptance bits between groups. They are synthesized, as the + # boot ROM that drives them is not available. return (1 << (size * 8)) - 1 if port in (0x5C, 0x5E) and self.active and hasattr(self.core, "io"): # The ASIC exposes the C52's 16-bit status latch as high byte at diff --git a/courier_emu/cli.py b/courier_emu/cli.py index 7b763a3..b649c4b 100644 --- a/courier_emu/cli.py +++ b/courier_emu/cli.py @@ -101,8 +101,8 @@ def daa_codec_wanted(args: argparse.Namespace, image: object) -> bool: return True if args.daa_codec: raise ValueError( - f"{Path(args.image).name} is a flash ROM, which carries no separable " - "C52 payload for the DSP bridge the codec rides on" + f"{Path(args.image).name} carries no separable C52 payload for the " + "DSP bridge the codec rides on" ) return False @@ -111,8 +111,8 @@ def _worker_command(args: argparse.Namespace) -> list[str]: image = load_image(args.image) if args.with_dsp and not hasattr(image, "dsp_program_segments"): raise ValueError( - f"{Path(args.image).name} is a flash ROM, which carries no separable " - "C52 payload for the DSP bridge to load" + f"{Path(args.image).name} carries no separable C52 payload for the " + "DSP bridge to load" ) daa_codec = daa_codec_wanted(args, image) command = [ diff --git a/courier_emu/machine.py b/courier_emu/machine.py index 64c43b3..b71d4e2 100644 --- a/courier_emu/machine.py +++ b/courier_emu/machine.py @@ -79,6 +79,10 @@ START_BIT_INSTRUCTIONS = 32_768 RX_BIT_INSTRUCTIONS = 150 # When the harness's terminal raises its handshake. Long enough after reset # that the ROM's callback chain has already sampled the line unasserted. +# How far past the later of a ROM's DSP reset and download entries those +# routines run. Both and their handshake waits sit inside the resulting span; +# e3aa..e67b in the captured board image, whose block ends at e597. +ROM_DOWNLOADER_SPAN = 0x200 DTE_READY_INSTRUCTIONS = 30_000_000 # And when it starts sending. The chain wants the handshake asserted, then a # quiet spell, then a character: [0x321] counts thirty of its own polls down @@ -309,7 +313,9 @@ class CourierMachine: self.accelerated_delays = 0 self.milestones: list[str] = [] if with_dsp and not hasattr(image, "dsp_program_segments"): - raise ValueError("the DSP bridge needs an XMF payload, not a flash ROM") + raise ValueError( + "the DSP bridge needs an image that carries a C52 payload" + ) self.dsp_bridge = ( CourierDspBridge( image, @@ -325,6 +331,20 @@ class CourierMachine: else None ) self.dsp_tx_pcm = dsp_tx_pcm + # The physical span of a ROM's DSP reset and download routines, from + # the call site that names both rather than from a constant. Inside it, + # timer 2's max-count bit is a handshake timeout rather than a delay's + # completion, so the model must not grant it - see the read hook. + download = getattr(image, "dsp_download", None) + self._rom_transfer_span = ( + ( + image.base + min(download.reset, download.downloader), + image.base + max(download.reset, download.downloader) + + ROM_DOWNLOADER_SPAN, + ) + if download is not None + else None + ) # Every address constant below belongs to the update payload's map. # A full board ROM loads at its own base and runs a different # supervisor, so those constants land on unrelated code: left enabled @@ -1617,7 +1637,16 @@ class CourierMachine: # The hook runs before the read is satisfied, so a timer register # is answered by putting the modelled value where the read will # find it. Everything else in the control block stays plain memory. - modelled = self.timers.read(address, size, self.instructions) + # Both of a ROM's DSP transfer routines escape every handshake + # wait on timer 2's max count, so the acceleration that hands that + # bit to a calibrated delay at its first poll would report a + # transfer failure instead. The XMF supervisor's download loop has + # the same collision, handled by address above. + span = self._rom_transfer_span + grant = span is None or not span[0] <= current_pc() < span[1] + modelled = self.timers.read( + address, size, self.instructions, grant=grant + ) if modelled is None and self.uart is not None: modelled = self.uart.read(address, size) if modelled is not None: diff --git a/courier_emu/rom.py b/courier_emu/rom.py index 785230c..10a61a3 100644 --- a/courier_emu/rom.py +++ b/courier_emu/rom.py @@ -3,6 +3,7 @@ from __future__ import annotations from dataclasses import dataclass from hashlib import sha256 from pathlib import Path +import re import struct from typing import Any @@ -45,6 +46,66 @@ APPLICATION_OFFSET = 0 APPLICATION_SIGNATURE = b"INT80186 Modem Functions" APPLICATION_SIGNATURE_WINDOW = 0x600 +# The DSP holds no resident program. The supervisor downloads one over the I/O +# ports at every boot, which is why a flash image carries the datapump and why +# a feature could be added to a shipped modem by replacing the image. +# +# The call site that starts that download names every parameter the extraction +# needs, so none of them is hardcoded: the 25 MHz supervisor keeps the same +# payload at a different offset behind the same instructions, and a fixed +# offset recovered from one image silently reads the wrong bytes out of another. +# +# mov ax, 8000 ; entry, as a C52 program word address +# call ; reset the part and request that entry +# mov ax, ; first source offset within the window below +# mov cx, ; one past the last +# call +# +# and, inside the downloader, the source window itself: +# +# mov ax, +# mov es, ax +# +# Two independent checks agree on the result for the captured 20.16 MHz board: +# the C52 reset code sits at the offset this derives, and the resident mailbox +# sender lands inside the startup region identified separately. +DSP_ENTRY_WORD = 0x8000 +DSP_CALL_SITE = re.compile(rb"\xb8(..)\xe8(..)\xb8(..)\xb9(..)\xe8(..)", re.S) +DSP_SOURCE_WINDOW = re.compile(rb"\xb8(..)\x8e\xc0", re.S) +# How far into the downloader to look for its own source window, and the span +# the call site and downloader both live in. Both are near calls, so caller and +# callee share one code segment. +DSP_DOWNLOADER_WINDOW = 0x120 +CODE_SEGMENT_SIZE = 0x10000 + + +@dataclass(frozen=True) +class DspDownload: + """Where a ROM keeps its C52 program, read out of the code that sends it.""" + + call_site: int + reset: int + downloader: int + source_segment: int + offset: int + length: int + entry_word: int + + @property + def end(self) -> int: + return self.offset + self.length + + def describe(self) -> dict[str, Any]: + return { + "call_site": f"{self.call_site:#07x}", + "reset": f"{self.reset:#07x}", + "downloader": f"{self.downloader:#07x}", + "source_segment": f"{self.source_segment:#06x}", + "flash_range": f"{self.offset:#07x}..{self.end:#07x}", + "words": self.length // 2, + "entry_word": f"{self.entry_word:#06x}", + } + def _address(register: int) -> int: """Decode a chip-select start or stop register into a physical address.""" @@ -142,6 +203,78 @@ class CourierRom: def base(self) -> int: return self.reset.base + @property + def dsp_download(self) -> "DspDownload | None": + """The C52 payload's location, recovered from the download call site. + + A supervisor calls the downloader from more than one place - the + captured board has three - so candidates are compared on what they say + about the payload rather than on where they were found. A disagreement + there means the byte pattern matched something that is not this call + site, and a guess between two answers would hand the DSP the wrong + program rather than fail visibly, so it raises instead. + """ + candidates: list[DspDownload] = [] + for match in DSP_CALL_SITE.finditer(self.data[:CODE_SEGMENT_SIZE]): + entry, _, start, end, _ = ( + struct.unpack(" len(self.data) or length % 2: + continue + candidates.append( + DspDownload( + match.start(), reset, target, segment, offset, length, entry + ) + ) + if not candidates: + return None + def payload(download: DspDownload) -> tuple[int, ...]: + return ( + download.source_segment, + download.offset, + download.length, + download.entry_word, + ) + + if any(payload(other) != payload(candidates[0]) for other in candidates[1:]): + raise RomFormatError( + "the DSP download call site matched with conflicting parameters; " + "refusing to choose between them" + ) + return candidates[0] + + def dsp_program_segments(self) -> tuple[tuple[int, bytes], ...]: + """Return the C52 program-memory origin and bytes the ROM downloads. + + One segment, unlike an XMF's three: a ROM's supervisor makes a single + download call, so what it sends is one contiguous run of words at the + entry it requests. Whether the rest of the datapump region reaches the + DSP by some other path is not established. + """ + download = self.dsp_download + if download is None: + raise RomFormatError( + "no DSP download call site found; this ROM's C52 payload " + "cannot be located, so it cannot be attached to a DSP" + ) + return ((download.entry_word, self.data[download.offset : download.end]),) + def at(self, physical: int, count: int) -> bytes: """Read from the ROM by physical address.""" offset = physical - self.base @@ -254,4 +387,7 @@ class CourierRom: }, "peripheral_writes": self.peripheral_writes(), "parameter_sectors": self.parameter_sectors, + "dsp_download": ( + self.dsp_download.describe() if self.dsp_download else None + ), } diff --git a/courier_emu/timers.py b/courier_emu/timers.py index a1a8760..afdf515 100644 --- a/courier_emu/timers.py +++ b/courier_emu/timers.py @@ -285,8 +285,16 @@ class TimerBlock: def _tick(self, instructions: int) -> int: return ticks_for(instructions) - def read(self, address: int, size: int, instructions: int) -> int | None: - """Return the value at a timer register, or None if it is not one.""" + def read( + self, address: int, size: int, instructions: int, *, grant: bool = True + ) -> int | None: + """Return the value at a timer register, or None if it is not one. + + `grant` declines the max-count acceleration below. The bit is a + calibrated delay's completion in most of the firmware, but the DSP + transfer routines reuse it as their handshake timeout, where granting + it at the first poll reports a failure that never happened. + """ entry = TIMER_REGISTERS.get(address) if entry is None: return None @@ -294,7 +302,13 @@ class TimerBlock: timer = self.timers[index] self.reads += 1 timer.advance(self._tick(instructions)) - if name == "control" and self.fast and self.answers_reads and not timer.control & CONTROL_MAX_COUNT: + if ( + name == "control" + and grant + and self.fast + and self.answers_reads + and not timer.control & CONTROL_MAX_COUNT + ): # Both firmwares busy-wait on MAX COUNT for their calibrated # delays. Granting the wait at the first poll is the same # acceleration the harness already applies to the delay helpers, diff --git a/courier_emu/uart.py b/courier_emu/uart.py index 7bc09b7..4e411a0 100644 --- a/courier_emu/uart.py +++ b/courier_emu/uart.py @@ -44,14 +44,34 @@ REGISTERS = (B0CMP, B0CNT, S0CON, S0STS, S0RBUF, S0TBUF) # S0CON bit 5 enables the receiver. The ROM writes 0x21 - mode 1 plus this. CONTROL_RECEIVE_ENABLE = 0x20 +# S0STS bit assignments, from Figure 10-14 of the 80C186EB user's manual +# (270830-003, page 10-16). The figure's fields sit above a reserved bit 0, so +# every name is one place higher than a plain reading of the field list gives: +# CTS 1, OE 2, TXE 3, FE 4, TI 5, RI 6, RB8/PE 7, DBRK0 8, DBRK1 9. +# +# Four firmware uses corroborate that offset, and none of them parses under the +# unshifted reading: the pre-transmit spin at 0x81603 waits on mask 8 (TXE, not +# FE); 0x9f03e skips a receive when mask 0x10 is set (FE, not TI); 0x8181e and +# 0x81892 test mask 0x300 (DBRK0/DBRK1, i.e. BREAK from the DTE); and the +# transmit ISR's second-byte write at 0x819f1 gates on mask 2. +# +# CTS is the complement of the CTS pin, which the DTE drives with RTS. It is +# not cleared by reading the register. +CLEAR_TO_SEND = 0x02 +# TXE, set when SxTBUF and the shift register are both empty. The transmit +# routine at 0x81613 spins on it before every byte it writes to S0TBUF, and +# the ISR uses it to decide whether a second byte can follow immediately. +# Nothing here queues a byte behind another, so the transmitter is always +# ready. Accessing S0STS does not clear TXE. +TRANSMIT_READY = 0x08 +# RI, set when a character has been placed in S0RBUF. This board's receive is +# interrupt driven off the vector below and no firmware path polls RI, which +# is why an earlier revision of this module could label bit 1 as receive-ready +# without a run detecting the error. +RECEIVE_READY = 0x40 + # The part's fixed serial interrupt types, confirmed against the live board's # vector table rather than assumed. -# S0STS bit 1, receive data available. -RECEIVE_READY = 0x02 -# S0STS bit 3, transmit buffer empty. The transmit routine at 0x81613 spins on -# it before every byte it writes to S0TBUF. Nothing here queues a byte behind -# another, so the transmitter is always ready. -TRANSMIT_READY = 0x08 RECEIVE_VECTOR = 0x14 TRANSMIT_VECTOR = 0x15 @@ -71,6 +91,17 @@ class EbSerial: # A character on the wire, not yet handed to the firmware. holding: bool = False receive_ready: bool = False + # The CTS pin's asserted state, which a real DTE drives with RTS. + # + # Nothing here models the host side of the Plug and Play handshake, so + # this is raised with each delivered character and consumed by the status + # read, reproducing exactly the edge timing that the pre-correction model + # produced from this bit. That keeps the [0x31f] chain advancing, but it + # is a stand-in: the real sequence is the DTE dropping DTR on port 0x14 + # bit 0 and asserting RTS 30 to 50 ticks later, and until the terminal + # model drives those two lines the chain is reached by the right bit for + # the wrong reason. On the part, reading the register does not clear CTS. + clear_to_send: bool = False @property def receive_enabled(self) -> bool: @@ -79,17 +110,28 @@ class EbSerial: def read(self, address: int, size: int) -> int | None: """The value a read of `address` should find, or None if not ours.""" if address == S0STS: - # Bit 1 is receive-data-available: the callback chain at [0x31f] - # requires it clear while it waits for the DTE handshake and set - # once a character has landed, which is what carries it to the - # node that posts the startup banner's event. The error bits are - # not modelled - see the module docstring. + # The callback chain at [0x31f] is the Plug and Play external COM + # device enumeration: it wants DTR dropped and then CTS asserted, + # and posts event 0x0e, which emits the PnP identifier string. An + # earlier revision reached the same node by treating bit 1 as + # receive-data-available, because asserting it does advance the + # chain - as CTS, not as data. Bit 1 is driven from the modelled + # DTE's handshake instead. The error bits are not modelled - see + # the module docstring. ready = self.receive_ready - # The status word is read to clear, which is why the firmware - # reads it at sites that discard the value: those reads are the + # RI and TI are read to clear, which is why the firmware reads the + # register at sites that discard the value: those reads are the # acknowledge. Taking the byte out of S0RBUF does not clear it. + # CTS and TXE are not cleared by the read. self.receive_ready = False - return TRANSMIT_READY | (RECEIVE_READY if ready else 0) + cts, self.clear_to_send = self.clear_to_send, False + # RI is deliberately not asserted. This board's receive is + # interrupt driven off RECEIVE_VECTOR and no firmware path polls + # RI, so leaving it clear keeps the model's observable behaviour + # identical to the revision that had the bit map wrong, rather + # than introducing an untested status bit alongside the fix. + del ready + return TRANSMIT_READY | (CLEAR_TO_SEND if cts else 0) if address == S0RBUF: return self.receive_holding if address == S0CON: @@ -151,6 +193,8 @@ class EbSerial: """Place a byte in the receive buffer and request its interrupt.""" self.receive_holding = byte & 0xFF self.receive_ready = True + # Stand-in for the DTE's RTS; see the field's comment. + self.clear_to_send = True self.received += 1 self._request(RECEIVE_VECTOR) @@ -159,6 +203,7 @@ class EbSerial: "control": f"{self.control:#06x}", "baud_compare": f"{self.baud_compare:#06x}", "receive_enabled": self.receive_enabled, + "clear_to_send": self.clear_to_send, "received": self.received, "transmitted": self.transmitted, } diff --git a/tests/test_rom.py b/tests/test_rom.py index 2fb78b7..8891262 100644 --- a/tests/test_rom.py +++ b/tests/test_rom.py @@ -113,11 +113,54 @@ class RomBootTests(unittest.TestCase): machine.run(6_000_000) self.assertGreaterEqual(nvram.reads, 1) - def test_the_dsp_bridge_is_refused_for_a_rom(self) -> None: + def test_a_rom_yields_the_c52_payload_its_supervisor_downloads(self) -> None: + """A ROM does carry a separable payload; it just is not laid out. + + This replaces a test that asserted the bridge is refused for a ROM. + That was true only while the payload's location was unknown: the + download call site names it, so the extraction is derived rather than + assumed, and the values below are the ones the call site yields for + this image. + """ from courier_emu.machine import CourierMachine - with self.assertRaises(ValueError): - CourierMachine(CourierRom.load(IMAGE), with_dsp=True) + rom = CourierRom.load(IMAGE) + download = rom.dsp_download + self.assertIsNotNone(download) + self.assertEqual(download.entry_word, 0x8000) + self.assertEqual(download.source_segment, 0xA908) + self.assertEqual((download.offset, download.end), (0x29080, 0x368FC)) + self.assertEqual(download.length // 2, 27710) + + (origin, segment), = rom.dsp_program_segments() + self.assertEqual(origin, 0x8000) + self.assertEqual(segment, rom.data[0x29080:0x368FC]) + # The C52 reset code the load base was pinned against. + self.assertEqual(segment[:6], bytes.fromhex("00bc57aeffff")) + + machine = CourierMachine(rom, with_dsp=True) + self.assertIsNotNone(machine.dsp_bridge) + + def test_the_supervisor_downloads_the_payload_through_the_bridge(self) -> None: + """The ROM's own download reaches the DSP, byte for byte. + + Every word travels through the modelled ports: e3aa's reset and entry + request, then e47b alternating its two windows on port 0x18. Nothing + here hands the payload to the bridge directly. + """ + from courier_emu.machine import CourierMachine + + rom = CourierRom.load(IMAGE) + machine = CourierMachine(rom, with_dsp=True) + machine.run(20_000_000) + bridge = machine.dsp_bridge + self.assertTrue(bridge.active) + self.assertEqual(bridge.bootstraps, 1) + self.assertIs(bridge.bootstrap_match, True) + # 27,710 words in eight-byte groups, and the checksum strobe after. + self.assertEqual(bridge.checksum_submits, 1) + received = bytes(bridge.bootstrap[:bridge.bootstrap_target_size]) + self.assertEqual(received, rom.data[0x29080:0x368FC]) class RomFormatTests(unittest.TestCase):