SD / GD flash cart

The RetroHQ Lynx SD / GD flash cartridge carries a microcontroller (MCU) that fronts an SD card. This page documents the sdcard_gd_* library that talks to it — the wire protocol, the C API for listing directories, streaming files and reprogramming the cart ROM window, and the on-card file layout the RetroHQ menu loader relies on. The driver is opt-in; the design lives in design/LYNX_SDCARD_GD_API_DESIGN.md.

1. Overview

On a RetroHQ SD/GD cart, everything behind the SD card — enumerating directories, streaming files, reflashing the cart ROM, saving data — is done by exchanging bytes with the cartridge MCU through two cartridge I/O registers. The sdcard_gd_* API wraps that byte protocol so a program can drive the card without hand-rolling the FIFO handshake.

This is an opt-in subsystem: include the header and the library is auto-linked (like the audio and compress libraries), so ROMs that never touch the card pay nothing.

#include <lynx/sdcard-gd.h>

The API is specific to the RetroHQ SD/GD cart — the _gd_ infix marks the family. A second flash-cart family, if one is ever added, gets its own header and library rather than overloading these names. Call sdcard_gd_init() once before anything else.

2. Wire protocol

2.1. Registers and handshake

Communication is a byte FIFO exposed through four addresses: IODIR ($FD8A) and IODAT ($FD8B) are the Mikey I/O direction and data registers; CART0 ($FCB2) and CART1 ($FCB3) are the cartridge bank-0 and bank-1 data ports, used as the FIFO read and write sides. Bit 4 of IODAT (mask $10, the “AUX” bit) is the ready/busy flag that gates every transfer.

Lynx CPU sdcard_gd_* driver Cart MCU SD card behind it write: spin while IODAT&$10 store byte → CART1 ($FCB3) read: spin until IODAT&$10 load byte ← CART0 ($FCB2)
The AUX bit (IODAT bit 4) gates the FIFO: the write side blocks while it is set, the read side blocks until it is set.

Multi-byte arguments are little-endian (LSB first): a 16-bit value is two bytes, a 32-bit value four. Path strings are sent NUL-terminated, one byte at a time including the terminator. Initialisation writes IODIR = 0 (all input) then CART1 = $AA, the magic byte that wakes the MCU comms state machine. Because the handshake busy-waits on hardware, the calls never time out — a wedged or absent MCU will hang.

2.2. Command set

Every command writes a single command byte, then any arguments, then (for all but low-power) reads a status/result. The command bytes are a 0-based enum:

#CommandArguments written (LE)Response read
0OpenDirNUL-terminated path1 status byte
1ReadDir—1 status byte; if OK, a 22-byte SFileInfo
2OpenFileNUL-terminated path1 status byte
3GetSize—4-byte size
4Seek4-byte absolute offset1 status byte
5Read2-byte countcount data bytes, then 1 status byte
6Write2-byte count, then count data bytes1 status byte
7Close—1 status byte
8ProgramFile2-byte start block, 1-byte block size, 2-byte block count1 status byte (blocks until flash done)
9ClearBlocks2-byte start block, 2-byte block count1 status byte (blocks until erase done)
10LowPowerMode—none

A Read streams its payload first and the status byte last, so the whole buffer is always drained. ProgramFile and ClearBlocks block on the MCU until the flash operation finishes; the status read is the completion signal. For a 512-block card (A19 driven by the aux pin) the large-card bit is folded into an argument rather than a separate field: ProgramFile ORs $10 into the block-size byte and ClearBlocks ORs $8000 into the block-count word — the wrappers do this when their b512BlockCard flag is set.

3. The C API

Twelve functions, all declared in lynx/sdcard-gd.h. The data-carrying calls are __fastcall__ and so need a prototype in scope. Full per-function detail is in the function reference.

Init and power

void sdcard_gd_init (void);
void sdcard_gd_lowpower (void);

Directory listing

FRESULT __fastcall__ sdcard_gd_opendir (const char* pDir);
FRESULT __fastcall__ sdcard_gd_readdir (SFileInfo* pInfo);

Open a directory, then call sdcard_gd_readdir() repeatedly until it returns anything other than FR_OK.

File I/O (one file open at a time)

FRESULT __fastcall__ sdcard_gd_open  (const char* pFile);
FRESULT              sdcard_gd_close (void);
FRESULT __fastcall__ sdcard_gd_seek  (unsigned long nSeekPos);
unsigned long        sdcard_gd_size  (void);
FRESULT __fastcall__ sdcard_gd_read  (void* pBuffer, unsigned int nSize);
FRESULT __fastcall__ sdcard_gd_write (const void* pBuffer, unsigned int nSize);

ROM programming

FRESULT __fastcall__ sdcard_gd_program (unsigned int  nStartBlock,
                                        unsigned char nBlockSize,
                                        unsigned int  nBlockCount,
                                        unsigned char b512BlockCard);
FRESULT __fastcall__ sdcard_gd_clear   (unsigned int  nStartBlock,
                                        unsigned int  nBlocks,
                                        unsigned char b512BlockCard);

sdcard_gd_program() writes block count blocks of block size (in 256-byte units) into the cart ROM starting at start block, sourced from the current position of the open file. sdcard_gd_clear() erases a block range with no source file.

4. Result codes and directory entries

Every status byte decodes to an FRESULT:

ValueNameMeaning
0FR_OKsuccess
1FR_DISK_ERRlow-level I/O error
2FR_NOT_READYcard / MCU not ready
3FR_NO_FILEpath not found
4FR_NOT_OPENEDoperation needs an open file/dir
5FR_NOT_ENABLEDsubsystem disabled
6FR_NO_FILESYSTEMno valid FAT filesystem

sdcard_gd_readdir() fills a packed 22-byte record (cc65 does not pad structs, so the field order and sizes are fixed by the wire format):

typedef struct {
    unsigned long   fsize;      /* file size in bytes           */
    unsigned int    fdate;      /* FAT last-modified date       */
    unsigned int    ftime;      /* FAT last-modified time       */
    unsigned char   fattrib;    /* attribute bits (AM_*)        */
    char            fname[13];  /* 8.3 name, NUL-terminated     */
} SFileInfo;

The fattrib bits are AM_RDO ($01), AM_HID ($02), AM_SYS ($04), AM_VOL ($08), AM_DIR ($10) and AM_ARC ($20); AM_MASK ($3F) masks the defined bits.

5. SD card layout

Paths are DOS-style with / separators, relative to the card root (for example "menu/prefs" or "_preview/alien.lsd"). Directory listings return upper-case 8.3 short names in fname; long names are not returned by readdir (see §5.3). The layout below is the convention used by the RetroHQ menu loader.

5.1. Recognised ROM types

ExtFormatSizing
.LNXHeadered Lynx ROM (64-byte “LYNX” header)block size from header byte 5
.LYXRaw / headerless ROM imageblock size inferred from file size
.OHomebrew BS93 object filefixed 2048-byte blocks + object loader
.COMSame header as .Osame as .O

5.2. The menu/ directory

The menu loader keeps its own state as files it reads and writes through this same API — a good worked example of sdcard_gd_read / sdcard_gd_write:

PathPurpose
menu/prefspreferences blob (one byte per option)
menu/lastrom256-byte path of the last launched ROM
menu/homebrewscratch file for the patched BS93 object loader
menu/default.pal32-byte BGR UI palette; absent ⇒ built-in colours
menu/*.palextra sample palettes; copy over default.pal to switch

5.3. Long names, previews and block sizing

Long names. An optional romlist.txt in a directory maps 8.3 names to display names, one per line as [romname.ext]Long ROM Name (name ≤ 45 chars). Only files that exist are overridden. This is a loader convention; the API itself has no notion of long names.

Previews. A game preview is 8365 bytes of Lynx sprite image data followed by a 32-byte palette. The file sits beside the ROM with the extension changed to .LSD (alien.lnx → alien.LSD); a legacy scheme keeps <base>.lsd files in a _PREVIEW/ directory at the card root.

Block sizing. For a .LNX file, read the 64-byte header; byte 5 is the block-size code (1, 2, 4 or 8 = 256/512/1024/2048 bytes). File size minus the 64-byte header, divided by the block size in bytes (rounded up), is the block count; seek past the header, then program from block 0. Header byte 60 bit 6 ($40) is the “use the cart EEPROM as a file” flag — when set, do not call sdcard_gd_lowpower() before launch, because the game keeps talking to the MCU for saves. A .LYX file has no header: pick the block size from the total file size (64K→1, 128K→2, 256K→4, 512K→8, else 4) and program the whole image from block 0.

6. Worked example

List the ROMs in the card root, then read the header of the first one:

#include <lynx/sdcard-gd.h>

SFileInfo info;
char header[64];

sdcard_gd_init();

if (sdcard_gd_opendir("/") == FR_OK) {
    while (sdcard_gd_readdir(&info) == FR_OK) {
        if (info.fattrib & AM_DIR)
            continue;                    /* skip sub-directories   */
        /* info.fname holds an 8.3 name such as "ALIEN.LNX"        */
    }
}

if (sdcard_gd_open("ALIEN.LNX") == FR_OK) {
    sdcard_gd_read(header, 64);          /* payload then status    */
    sdcard_gd_close();
}

Programming and launching a ROM is the menu loader's job; see examples/sdcard-gd/ and design/LYNX_SDCARD_GD_API_DESIGN.md §6.6 for the block-sizing and launch sequence.

7. Compatibility

The original RetroHQ menu code uses LynxSD_*-prefixed names (LynxSD_OpenFile, LynxSD_ProgramROMFromFile, and so on). The header keeps these as thin deprecated aliases so existing community code compiles unchanged; define LYNX_NO_SDCARD_GD_COMPAT before including the header to remove them. New code should use the sdcard_gd_* names.