# SPDX-License-Identifier: MIT """Cartridge backup devices: SRAM/FRAM, Flash 64/128 KB, EEPROM 512 B/8 KB. All rules are GBATEK's §GBA Cart Backup sections (DOC) unless tagged otherwise; the open questions are docs/undocumented-behavior.md U-CART-1 to U-CART-3. The SRAM and Flash sit on the 8-bit backup bus at 0E000000; ``offset`` here is the address within the 64 KB window (the window repeats across 0E000000-0FFFFFFF: GBATEK §Memory Mirrors, DOC; jsmolka save/sram and save/flash* "Mirror 1", "Mirror 2", TEST ROM; disputed by jsmolka's unsafe/README for a flash cart, U-MEM-2). Every device's ``save_data()`` is the chip's memory as a raw image, the battery file's whole content (docs/cartridge.md "Battery files"). """ from __future__ import annotations class NoBackup: """No backup chip: the backup bus reads FF (jsmolka save/none "No save type returns 0xFF"; TEST ROM; HYPOTHESIS that the pulled-up data lines are the cause).""" kind = "none" def read8(self, offset: int) -> int: return 0xFF def write8(self, offset: int, value: int) -> None: pass def save_data(self) -> bytes: return b"" class SRAM: """32 KB battery SRAM or FRAM, accessed identically (§GBA Cart Backup SRAM/FRAM; DOC). The 32 KB chip appears twice in the 64 KB window (GBATEK §Memory Mirrors; DOC). Erased (never written) memory reads FF (jsmolka save/sram "Uninitialized memory" expects FF; TEST ROM; HYPOTHESIS that a fresh battery-backed chip is all FF).""" kind = "sram" def __init__(self, data: bytes | None = None) -> None: self.memory = bytearray(b"\xff" * 0x8000) if data: self.memory[: min(len(data), 0x8000)] = data[:0x8000] def read8(self, offset: int) -> int: return self.memory[offset & 0x7FFF] def write8(self, offset: int, value: int) -> None: self.memory[offset & 0x7FFF] = value & 0xFF def save_data(self) -> bytes: return bytes(self.memory) # Flash chips as name: (size, manufacturer, device) (§GBA Cart Backup Flash ROM, "Device # Types"; DOC: "Identification Codes MSB=Device Type, LSB=Manufacturer"). Which chip a board # reports is a choice of cartridge, not of GBA behaviour: games are told to support them all # (same section). Defaults: Panasonic for 64 KB and Sanyo for 128 KB (HYPOTHESIS, U-CART-2). FLASH_CHIPS = { "sst": (0x10000, 0xBF, 0xD4), "macronix": (0x10000, 0xC2, 0x1C), "panasonic": (0x10000, 0x32, 0x1B), "atmel": (0x10000, 0x1F, 0x3D), "sanyo": (0x20000, 0x62, 0x13), "macronix128": (0x20000, 0xC2, 0x09), } FLASH_DEFAULT = {0x10000: "panasonic", 0x20000: "sanyo"} ATMEL_PAGE = 128 # "Erase-and-Write 128 Bytes Sector (only Atmel devices)" (DOC) class Flash: """A 64 KB or 128 KB Flash chip and its command sequences (§GBA Cart Backup Flash ROM; DOC). Erase and write complete at once (HYPOTHESIS, U-CART-2: GBATEK gives timeouts, not durations; "Average medium Write, Erase Sector, Erase Chips timings are unknown?").""" def __init__(self, size: int = 0x10000, data: bytes | None = None, chip: str | None = None): assert size in (0x10000, 0x20000) chip = chip or FLASH_DEFAULT[size] chip_size, manufacturer, device = FLASH_CHIPS[chip] if chip_size != size: raise ValueError(f"Flash chip {chip} is {chip_size // 1024} KB, not {size // 1024} KB") self.kind = "flash128" if size == 0x20000 else "flash64" self.chip = chip self.size = size self.memory = bytearray(b"\xff" * size) if data: self.memory[: min(len(data), size)] = data[:size] self.ident = (manufacturer, device) # read at E000000 and E000001 in ID mode (DOC) self.atmel = chip == "atmel" self.bank = 0 self.step = 0 # 0 idle, 1 after AA at 5555, 2 after 55 at 2AAA self.id_mode = False self.erase_armed = False # after the 80 command self.write_armed = False # after A0: the next byte write programs self.page_left = 0 # Atmel: bytes of the 128-byte page still to come after A0 self.bank_armed = False # after B0: the next write to 0000 selects the bank def read8(self, offset: int) -> int: offset &= 0xFFFF if self.id_mode and offset < 2: return self.ident[offset] return self.memory[(self.bank << 16) | offset] def write8(self, offset: int, value: int) -> None: offset &= 0xFFFF value &= 0xFF if self.page_left: # Atmel: "[E00xxxxh+00h..7Fh]=dat[00h..7Fh] (write 128 bytes)", erase-and-write, so # each byte replaces the old one (DOC). Bytes land where they are addressed # (HYPOTHESIS: GBATEK only requires the target to be a multiple of 80h). self.memory[(self.bank << 16) | offset] = value self.page_left -= 1 return if self.write_armed: # "A0 then one byte (write a byte, to erased memory)": programming can only clear # bits (HYPOTHESIS: the usual Flash cell rule; GBATEK says to write erased memory). self.write_armed = False address = (self.bank << 16) | offset self.memory[address] &= value return if self.bank_armed and offset == 0: self.bank_armed = False if self.size == 0x20000: self.bank = value & 1 # "write bank number 0..1" (DOC) return if self.step == 0 and offset == 0x5555 and value == 0xAA: self.step = 1 elif self.step == 1 and offset == 0x2AAA and value == 0x55: self.step = 2 elif self.step == 2: self.step = 0 self.command(offset, value) else: self.step = 0 if offset == 0x5555 and value == 0xF0: # "Terminate Command after Timeout (only Macronix devices)": a lone F0 at 5555 # (DOC). Accepted from every chip (HYPOTHESIS: harmless, as nothing is busy). self.erase_armed = self.write_armed = self.bank_armed = False def command(self, offset: int, value: int) -> None: if self.erase_armed: self.erase_armed = False if offset == 0x5555 and value == 0x10: # erase the chip, FF-filled (DOC) self.memory[:] = b"\xff" * self.size elif value == 0x30 and not self.atmel: # erase the 4 KB sector at E00n000 (DOC) start = (self.bank << 16) | (offset & 0xF000) self.memory[start : start + 0x1000] = b"\xff" * 0x1000 return if offset != 0x5555: return if value == 0x90: self.id_mode = True elif value == 0xF0: self.id_mode = False elif value == 0x80: self.erase_armed = True elif value == 0xA0: if self.atmel: self.page_left = ATMEL_PAGE else: self.write_armed = True elif value == 0xB0 and self.size == 0x20000: # "Bank Switching (devices bigger than 64K only)" (DOC); a 64 KB chip ignores it # (HYPOTHESIS). self.bank_armed = True def save_data(self) -> bytes: return bytes(self.memory) # "it'll take ca. 108368 clock cycles (ca. 6.5ms) until the old data is erased and new data # is programmed" (§GBA Cart Backup EEPROM; DOC, an approximate figure). EEPROM_WRITE_CYCLES = 108368 class EEPROM: """A serial EEPROM on data bit 0 of the ROM bus, 512 B (6-bit address) or 8 KB (14-bit field, low 10 bits used), 64-bit blocks (§GBA Cart Backup EEPROM; DOC). - **Requests and /CS.** The chip's pins are ROMCS, RD, WR, AD0 and A23 (GBATEK "Pin-Outs"; DOC), and "manual transfers via LDRH/STRH won't work; probably because they don't keep /CS=LOW and A23=HIGH throughout the transfer" (DOC, GBATEK's own hedged reason). The board's reading: /CS falls anew on every non-sequential cartridge access, and a write that comes with a fresh /CS starts a new request, dropping any unfinished one (HYPOTHESIS, U-CART-3). A DMA's first access is non-sequential and the rest sequential, so a DMA delivers one request; separate CPU stores never complete one. The read stream a read request prepares survives /CS rising, since it is fetched by a second DMA (DOC). - **Busy.** After a write request the chip reads 0 until programming ends (EEPROM_WRITE_CYCLES), then 1 ("keep reading ... until Bit 0 of the returned data becomes 1 (Ready)"; DOC). - **Size.** Fixed by the first DMA3 request's length (a board convention, HYPOTHESIS: docs/cartridge.md "EEPROM") unless given, or by the battery file's size. """ kind = "eeprom" def __init__(self, size: int | None = None, data: bytes | None = None) -> None: if size is None and data: if len(data) == 0x200: size = 0x200 elif len(data) == 0x2000: size = 0x2000 self.size = size self.memory = bytearray(b"\xff" * 0x2000) if data: self.memory[: min(len(data), 0x2000)] = data[:0x2000] self.bits: list[int] = [] self.reading: list[int] = [] self.busy_until = 0 def read8(self, offset: int) -> int: """The backup bus at 0E000000 has no chip on an EEPROM cartridge: it reads as with no save (NoBackup; HYPOTHESIS, the same pulled-up data lines).""" return 0xFF def write8(self, offset: int, value: int) -> None: pass def address_bits(self) -> int: return 14 if self.size == 0x2000 else 6 def write_bit(self, bit: int, fresh: bool = False, now: int = 0) -> None: """One halfword written to the chip; ``fresh`` when its access was non-sequential.""" if fresh: self.bits = [] bits = self.bits bits.append(bit & 1) if self.size is None: return n = self.address_bits() if bits[0] == 1 and len(bits) >= 2 and bits[1] == 1 and len(bits) == 2 + n + 1: # "11", the address MSB first, "0": prepare 4 ignored bits and 64 data bits (DOC). block = self.block(bits[2 : 2 + n]) data = self.memory[block * 8 : block * 8 + 8] stream = [0, 0, 0, 0] for byte in data: stream.extend((byte >> (7 - i)) & 1 for i in range(8)) self.reading = stream self.bits = [] elif bits[0] == 1 and len(bits) >= 2 and bits[1] == 0 and len(bits) == 2 + n + 64 + 1: # "10", the address, 64 data bits MSB first, "0": erase and program (DOC). block = self.block(bits[2 : 2 + n]) payload = bits[2 + n : 2 + n + 64] for i in range(8): byte = 0 for digit in payload[i * 8 : i * 8 + 8]: byte = (byte << 1) | digit self.memory[block * 8 + i] = byte self.bits = [] self.busy_until = now + EEPROM_WRITE_CYCLES def block(self, address: list[int]) -> int: value = 0 for digit in address: value = (value << 1) | digit # 8 KB: "only the lower 10 address bits are used, upper 4 bits should be zero" (DOC). return value & (0x3FF if self.size == 0x2000 else 0x3F) def fix_size_from_dma(self, units: int) -> None: """The first DMA3 request's length chooses the chip: 9 or 73 units for 512 B, 17 or 81 for 8 KB (arithmetic from GBATEK's bit counts; a board convention, HYPOTHESIS).""" if self.size is None: if units in (9, 73): self.size = 0x200 elif units in (17, 81): self.size = 0x2000 def read_bit(self, now: int = 1 << 62) -> int: if self.reading: return self.reading.pop(0) return 1 if now >= self.busy_until else 0 def save_data(self) -> bytes: return bytes(self.memory[: self.size or 0x2000])