Skip to Content
Under the HoodEmulator InternalsZX Spectrum Next: storage

Storage: an SD Card on a Serial Bus

A Spectrum loaded its games from a cassette, at 1,000 to 2,000 bits a second, and you could make a cup of tea while it did. A Next keeps gigabytes on an SD card and loads a whole level before you have reached for the kettle. Yet the CPU still talks to that card through a single 8-bit port, one byte at a time, as if it were a humble peripheral. How does a byte get from a flash chip inside the card into your program, and why is it so fast?

I think storage is the part of the Next most programs use and fewest programmers look at. NextZXOS and esxDOS hide it behind a file API, and most of the time that is exactly right. But the day you want to stream a sample from the card, load a level while the music plays, or understand why a loader works at 3.5 MHz and fails at 28, you need to know what sits under that API. It is a surprisingly small piece of hardware, and a very clever one.

You should know three chapters first. Memory, Ports and NextRegs: How the Z80N Reaches the Machine introduces the DivMMC, the butler who maps the SD card’s operating system in when it is needed. DMA: One Bus, Two Masters explains the DMA, which can read the card for you. The Beeper: EAR, MIC and the Tape covers the cassette, which the Next keeps too.

The road ahead

We start with the bus the card hangs on, SPI, and the five devices that share it. Then come the two ports that drive it: $E7, which chooses a device, and $EB, which moves a byte, with the timing of one byte and the curious fact that every read returns the byte from the exchange before. The heart of the chapter is the conversation with an SD card: its commands, its answers, and a sector read written out by hand; if you read only one section, read that one. After that we look at streaming with the DMA, the flash chip and the Raspberry Pi, the DivMMC’s part in all this, the tape and the +3’s disks, and resets.

The facts are for core 3.02.01. Timings are in CPU clocks, and in T-states for a CPU at 3.5 MHz where a section gives them. The FPGA’s side was checked against the Next’s hardware design; the card’s side follows the SD card specification’s SPI mode.

Five devices on one bus

An SD card can talk in two ways: its own fast four-bit bus, and SPI, the Serial Peripheral Interface, a simple serial bus that almost every microcontroller speaks. The Next uses SPI. An SPI bus has a master, which runs the show, and slaves, which answer. Four wires are enough:

  • SCK, the clock, driven by the master. One bit moves in each direction per clock pulse.
  • MOSI, master out, slave in: the master’s data, one bit at a time, the most significant bit first.
  • MISO, master in, slave out: the slave’s data, at the same time, on the same clock.
  • A select line per slave, active low. Only the selected slave listens and drives MISO; the others stay quiet.

The Next’s FPGA is always the master, and I call its SPI master the telegraphist: it taps a byte out bit by bit, and while it taps, it listens to the byte coming back on the other wire. Five slaves share its bus:

SPI master$E7: select$EB: dataSCK, MOSI →← MISOSD card 0$E7 = xxxxxx10SD card 1$E7 = xxxxxx01Pi SPI 0$E7 = $FBPi SPI 1$E7 = $F7flash (cores)$E7 = $7F, locked
The SPI bus. The FPGA’s SPI master drives SCK and MOSI and reads MISO, shared by five slaves; port $E7 chooses which one is selected, and port $EB moves the bytes.
  • Two SD cards, card 0 and card 1. The FPGA has a select line for each.
  • Two SPI devices on the Raspberry Pi’s connector, once the PI Peripheral Enable register, NextReg $A0, bit 0, turns those GPIO pins into an SPI bus.
  • The FPGA’s flash chip, which holds the cores the machine starts from.

Notice the property that makes SPI so simple, and that will come back in every section: it is full duplex. Every byte the master sends brings a byte back, whether anyone wanted it or not. To read, the master sends a byte that means nothing, $FF; to write, it ignores what comes back.

Choosing a device

Port $E7, the SPI chip select, chooses the slave. You write it, and its low bits decide:

  • Low bits 10, such as $FE, select SD card 0, whatever the other six bits are.
  • Low bits 01, such as $FD, select SD card 1, likewise.
  • $FB selects the Pi’s SPI device 0, and $F7 its device 1. These need the exact value.
  • $7F selects the flash, but only in config mode, when the machine type in NextReg $03 is 0, or after a power-on until the first soft reset. At any other time it deselects everything.
  • Anything else deselects every slave.

Why are the SD cards so forgiving and the others so strict? Because SD card software from other machines writes junk into the upper bits, and the Next’s designers chose to let it work; I appreciate that kind of politeness in hardware. The selection cannot be read back, so keep your own copy if you need it. After a reset nothing is selected, and bit 3 of NextReg $83 switches both ports, $E7 and $EB, off: they then do nothing, and a read gives $FF.

One byte, sixteen clocks

Port $EB, SPI data, moves the bytes. The telegraphist runs on the CPU’s clock, and SCK is half of it, so one byte takes 16 CPU clocks, which is 16 T-states at every CPU speed: eight pulses of SCK, each two clocks long. The bus works in what SPI calls mode 0: SCK rests low, the master changes MOSI while SCK is low, and the slave’s MISO is sampled as SCK rises.

0246810121416CPU clocksSCKMOSImasterb7b6b5b4b3b2b1b0MISOslaveb7b6b5b4b3b2b1b0red ticks: a MISO bit is taken as SCK rises
One byte on the SPI bus, to scale in CPU clocks. SCK is the CPU clock halved and rests low; MOSI carries the master’s bits b7 to b0, each for two clocks; the slave’s MISO bits are taken as SCK rises. The byte that came in is what the next read of $EB returns.

Here is a real byte. The host writes $51, the first byte of the read command we meet below, to $EB; the card, which has nothing to say while a command arrives, answers with $FF:

0246810121416CPU clocksCPU clockSCKMOSIhost: $51b7 = 0b6 = 1b5 = 0b4 = 1b3 = 0b2 = 0b1 = 0b0 = 1MISOcard: $FF11111111red: each bit is taken as SCK rises, in the middle of its two clocks
The host sends $51 while the card answers $FF, to scale in CPU clocks. MOSI changes as SCK falls and holds each bit for two clocks: 0, 1, 0, 1, 0, 0, 0, 1, which is $51 read from b7 down. MISO stays high: eight 1s, $FF. Each bit is taken as SCK rises, in the middle of its two clocks.

Read the MOSI row at the red marks, left to right, and you get 0101 0001, $51, with the most significant bit first. Read the MISO row the same way and you get eight 1s. When the sixteenth clock ends, the $51 has left and the $FF has arrived, and the next read of $EB will return that $FF.

Now the rules that follow from it, and I would learn them by heart:

  • A write to $EB sends the byte you wrote. The byte that comes back is kept.
  • A read of $EB returns the byte that came back during the previous exchange, and starts a new exchange that sends $FF. So a read is always one exchange behind: you get the answer to what was sent before. This sounds awkward, but it is what makes INIR work, as the next section shows.
  • A new exchange starts only when the last one is finished, or in its very last clock. An access to $EB sooner than that is simply lost: a write sends nothing, and a read returns the old byte and starts nothing. The CPU gets no wait state to warn it.

The last rule is the one that bites, because the telegraphist counts the CPU’s own clocks. Two OUT (C),r in a row come 12 T-states apart, and 12 is less than 16: the second byte is lost, at 3.5 MHz just as at 28. Two IN r,(C) in a row lose the second exchange the same way. OTIR and INIR, at 21 T-states a byte, are fine, and so is a polling loop. My rule of thumb: never two accesses to $EB with nothing between them; send a command from a table with OTIR, and put a NOP between two lone INs.

The speed follows the CPU. SCK is 1.75 MHz at 3.5 MHz and 14 MHz at 28 MHz, so the bus can move about 219K to 1.75 MB a second; in practice the program around it decides. This is also the answer to the opening puzzle: the bytes go one at a time, but at 28 MHz the bus that carries them is some ten thousand times faster than a tape.

Talking to an SD card

The card is not part of the FPGA; it is a small computer of its own, with a controller that speaks the SD card specification. In SPI mode the conversation goes like this:

  • A command is six bytes: $40 plus the command’s number, a 32-bit argument, most significant byte first, and a CRC byte. The specification names each command after its number: CMDn is the command whose first byte is $40 + n, so CMD17 starts with $51. The CRC is checked only for the first two commands a card gets when it starts, CMD0 and CMD8 below; after that a card in SPI mode ignores it.
  • The card answers after a pause. Between zero and eight $FF bytes come first, then a one-byte response, R1. $00 means “done, no error”; bit 0, $01, means “still in the idle state”; any other bit is an error.
  • $FF is silence. Between commands the master keeps sending $FF, and the card answers $FF. A command always starts with the bits 01, so $FF can never be mistaken for one.

Some commands are application commands, named ACMDn. They are sent in two parts: first CMD55, whose only job is to say “the next command is an application command”, then the command itself, with its number n. Starting a card takes a handful of commands, which the driver sends once:

  1. CMD0, go to the idle state, resets the card. The card first gets at least 74 clocks with nothing selected; then CMD0 with its select line low makes it leave its own bus and speak SPI from then on, and it answers $01, idle.
  2. CMD8, send the interface condition, tells the card the voltage the host supplies and a check pattern. A card that understands it echoes both back, and that tells the driver it is a modern card, version 2.0 of the specification or later; an older card answers that the command is illegal.
  3. CMD55 then ACMD41, send the operating condition, starts the card’s own start-up, and its argument says that the host can handle a high-capacity card. The card answers $01 while it is still busy with its start-up, so the driver repeats the pair until the answer is $00: the card is ready.
  4. CMD58, read the OCR, reads the card’s 32-bit operating conditions register. One of its bits says whether the card is SDHC or larger, a high-capacity card. Such a card is addressed in sectors of 512 bytes, not in bytes, so sector 5 is argument 5, where an older card would need byte address 2,560.

After that, reading and writing are one command each:

hostMOSIcardMISO$51 sector CRC$FF $FF $FF … for as long as the card talks$FF …$FF0–8R1$00$FF …wait$FE512 data bytesCRC2tokeneach byte the host sends brings back the card’s byte below it
Reading one sector with CMD17, byte by byte (not to scale). The host sends the six-byte command, then $FF; the card answers R1 after a few $FF bytes, waits while it fetches the sector, sends the data token $FE, the 512 bytes and a two-byte CRC.
  • CMD17, read a single block, reads one sector. After R1 the card sends $FF while it fetches the data, then the data token $FE, the 512 bytes and a 16-bit CRC.
  • CMD24, write a block, writes one sector. After R1 the host sends $FE, the 512 bytes and a CRC; the card answers a data response byte, xxx00101 when it accepted the block, and then $00 while it is busy writing.
  • CMD18, read multiple blocks, reads sector after sector, each with its own $FE and CRC, until the host sends CMD12, stop transmission. That is how a file of many sectors streams without a command per sector.

Let’s read a sector. This routine assumes a card that is started, selected, and SDHC:

; read sector DE (high word 0) of an SDHC card to (HL) ReadSec: ld a,d ld (Cmd17+3),a ; sector bits 15-8 ld a,e ld (Cmd17+4),a ; sector bits 7-0 push hl ld hl,Cmd17 ld bc,$06eb ; 6 bytes to the SPI data port otir pop hl Resp: in a,(c) ; $FF until R1 comes cp $ff jr z,Resp or a ret nz ; R1 not 0: an error Token: in a,(c) ; $FF until the token cp $fe jr nz,Token ld b,0 inir ; bytes 0-255 inir ; bytes 256-511 in a,(c) ; CRC, high byte nop ; keep 16 T-states apart in a,(c) ; CRC, low byte ret Cmd17: .defb $51,0,0,0,0,$01 ; CMD17, sector, CRC

How it works:

  • The sector number goes into bytes 3 and 4 of the command at Cmd17, most significant byte first, as SD commands want it; bytes 1 and 2 stay 0. The table lives in RAM, so the routine can patch it.
  • OTIR sends the six bytes, 21 T-states apart, so none is lost. Each brings a byte back, $FF here, which nobody reads. The CRC byte, $01, is ignored by a card in SPI mode after CMD8.
  • Resp polls with IN. Each read returns the byte of the exchange before and starts the next, so the loop sees the card’s bytes in order, a step late, and stops at R1.
  • Token polls the same way until $FE. The read that returned $FE has already started the exchange that brings the first data byte, so the next IN, the first of INIR, returns byte 0. That is the read-behind rule doing exactly what we want.
  • The two INIRs read 512 bytes, and the two last INs the CRC, with a NOP between them so that the second one is not lost. A real driver also gives up after a while in both polling loops, and checks the CRC if it cares.

The read-behind rule is easier to see than to describe, so here is the whole conversation, exchange by exchange. The listing reads sector 5 from a card that answers R1 after one $FF and sends its token after two more; the CPU’s instructions are on top, then the two wires, and at the bottom what each IN gets:

OTIR: CMD17, sector 5, CRCResp: polls for R1exchangeinstructionMOSI: hostMISO: cardthe IN returns1OUT$51$FF–2OUT$00$FF–3OUT$00$FF–4OUT$00$FF–5OUT$05$FF–6OUT$01$FF–7IN$FF$FF$FF8IN$FF$00$FF9IN$FF$FF$00Token: polls for $FEINIR × 2: 512 bytesthe CRCexchangeinstructionMOSI: hostMISO: cardthe IN returns10IN$FF$FF$FFfrom 911IN$FF$FE$FF12IN$FFD0$FE13IN$FFD1D014IN$FFD2D1……524IN$FFC1D511525IN$FFC2C1526IN$FF$FFC2D0 … D511: the sector’s bytes; C1, C2: its CRC; every IN sends $FF and returns the byte before
The listing’s sector read, one column per exchange. The host’s bytes go out on MOSI; the card’s come back on MISO; each IN returns the card’s byte of the exchange before, as the arrows show. R1 arrives in exchange 8 and is read in 9; the token arrives in 11 and is read in 12; INIR then reads data byte n in exchange 13 + n.
  • Exchanges 1–6 are the command: $51 (CMD17), the sector number $00 $00 $00 $05, and the CRC byte. The card sends $FF all the while, and no instruction reads it: an OUT only sends.
  • Exchanges 7–9 are Resp. Each IN sends $FF. The card sends R1, $00, in exchange 8, but the IN of exchange 8 returns what came in during exchange 7, $FF. Only exchange 9’s IN returns the $00, and the loop ends.
  • Exchanges 10–12 are Token. The card sends $FE in exchange 11, exchange 12’s IN returns it, and that same exchange has already brought in the first data byte, D0.
  • From exchange 13 INIR reads one data byte per exchange, each one an exchange late: D0 in 13, D511 in 524. The two last INs, 525 and 526, return the CRC.

Notice that the conversation is one exchange longer than the bytes it carries: the last IN sends a $FF that brings back a byte nobody reads. That is the price of reading behind, and the reason the data comes out in the right order at all.

Streaming with the DMA

The DMA can do the INIR part for you, and the SD card’s port is the one I/O port the DMA treats with special care: the telegraphist holds the DMA with wait states until the byte under way has finished. So a DMA transfer from port $EB, fixed, to memory, incrementing, never reads too early and never loses a byte, at any CPU speed. Each of its reads returns the byte before and starts the next exchange, just as the CPU’s do, so the DMA starts after the data token, as INIR did.

That makes a lovely pattern for loading while a game runs: the CPU sends the command and waits for the token, then hands the 512 bytes to the DMA in burst mode, or in continuous mode for the fastest load. The DMA chapter has the details of both modes.

The flash and the Pi

The flash chip holds the FPGA’s cores. The board loads the FPGA from it when the power comes on, before any Z80 code runs. The Next’s programs reach it only to update a core, which is why $E7 selects it only in config mode or straight after a power-on: an ordinary program cannot select it by accident and talk to the chip that the machine starts from. I like that lock. It is the one place where a stray OUT could turn a computer into a brick.

The Raspberry Pi’s connector carries an SPI bus too, once NextReg $A0 bit 0 gives it the GPIO pins, with two selects, $FB and $F7. The Next is the master there as well, so a Pi, or any SPI device on that connector, is a slave the program talks to exactly as it talks to the card.

The butler’s part

The SPI master moves bytes; it knows nothing of files. Files are the DivMMC’s business, the butler of the memory chapter, and his tools are mostly memory. His 8K ROM holds the start of the SD card’s operating system, and he has 128K of RAM, sixteen banks of 8K, for the rest of its code, its buffers and its tables. Port $E3, the DivMMC control port, sets him up:

  • Bit 7, CONMEM, maps the DivMMC in by hand: its ROM at $0000, read-only, and a RAM bank at $2000.
  • Bits 3–0 choose that bank, 0 to 15.
  • Bit 6, MAPRAM, replaces the ROM with RAM bank 3: the operating system runs from RAM, and bank 3 becomes read-only, at $0000 and also at $2000 if bits 3–0 select it there. MAPRAM can only be set: writing 0 leaves it on, as on the original DivMMC. On the Next, a reset or a 1 written to NextReg $09 bit 3 clears it.
  • Reading $E3 gives bits 7, 6 and 3–0, with bits 5 and 4 reading 0.

The butler’s other way in is the automap at his entry points, and the one that matters for files is $0008, the address RST $08 calls. But the Next has several ROMs, and each of them has its own code at $0008, so which RST $08 reaches the butler? With the entry-point settings after a reset, NextReg $B8 to $BA, $0008 maps the DivMMC only when the 48K BASIC ROM is at $0000: ROM 3 on a +3 or Next machine type, ROM 1 on a 128K one. In the 128K editor’s ROM, the +3DOS ROM or RAM, RST $08 simply runs whatever is at $0008 there, and the butler does not come. The mapping is also delayed: the 48K ROM’s own opcode at $0008 is fetched first, and the DivMMC’s code takes over from the next fetch.

So “calling the operating system” means something precise: a program with the 48K BASIC ROM paged in executes RST $08 followed by a byte that names the function, and the code that answers is the one in the butler’s memory. That is esxDOS on a machine set up with it, or, on NextZXOS, the part of NextZXOS that is loaded into the DivMMC and offers the same esxDOS calls. That code drives $E7 and $EB, and it leaves on a RETN. The memory chapter’s DivMMC section tells that story in full: what “the 48K BASIC ROM is at $0000” means exactly, how NextRegs $B8 to $BB move the entry points, and the master switch, NextReg $0A bit 4. So the whole stack is short: your program calls RST $08 from the 48K ROM, the butler’s code turns the call into SD commands, and the telegraphist turns the commands into bits.

Tape and disks

The Next keeps the Spectrum’s tape: the EAR input and MIC output of port $FE, which the beeper chapter describes, so a real cassette still loads. And the butler can stand in for the cassette: four of his entry points sit inside the 48K ROM’s tape routines, so a LOAD "" can be served from a tape image on the SD card instead.

The +3’s floppy disk is a different case. The Next has no disk controller at all. What it has is an I/O trap: with bit 0 of the I/O Traps register, NextReg $D8, set, an access to the +3’s disk ports $2FFD and $3FFD raises a Multiface NMI, and the handler can do what the disk controller would have done, from a disk image on the card. The interrupts chapter lists the trap among the NMI’s sources.

Resets

A reset, hard or soft, deselects every SPI device, so $E7 behaves as if $FF had been written. The telegraphist itself is not reset: a byte under way finishes, and the next one waits for a program. It clears port $E3, MAPRAM included, so the DivMMC is mapped out with RAM bank 0 selected. An SD card, being outside the FPGA, is not reset at all: it keeps whatever state it was in, and its driver starts it again with CMD0, as on every power-on.

What to take home

Under the file API sits an SPI bus with the FPGA as its master, the telegraphist, and five slaves: two SD cards, two SPI devices on the Pi’s connector, and the flash with the cores. Port $E7 chooses one: low bits 10 card 0, 01 card 1, $FB and $F7 the Pi, $7F the flash only in config mode or after a power-on, and anything else none.

Port $EB moves a byte in 16 CPU clocks, 16 T-states at any speed, SCK being the CPU clock halved. A write sends its byte; a read returns the byte of the exchange before and sends $FF; an access during a byte is lost, so two OUTs or two INs in a row, 12 T-states apart, lose the second. The DMA gets wait states instead, so it can stream from the card at any speed.

The card speaks the SD specification’s SPI mode: six-byte commands, an R1 response after some $FFs, CMD0, CMD8, ACMD41 and CMD58 to start, CMD17 and CMD18 to read and CMD24 to write, with $FE before each block of 512 bytes. Files are the DivMMC’s job: his ROM and 128K of RAM, port $E3 with CONMEM, the bank and the sticky MAPRAM, and his entry points, RST $08 first. Tape still works and can come from the card; the +3’s disks are emulated by software through an I/O trap. A small bus, a polite select port and a careful butler: that is all it takes to put a filing cabinet behind a single port.

Last updated on