sdcard.c

C source for Emulating a round-screen ESP32 board, 270 lines. Raw file

// sdcard.c - a faithful host-file-backed SD card in SPI mode.
//
// The M5Stack PaperS3 talks to a microSD over GP-SPI2 (see mmio.c). The ESP-IDF
// sdspi/sdmmc host clocks the card one BYTE at a time (msdlen=7 -> 8 bits): it
// sends a 6-byte command (0x40|cmd, 4-byte arg big-endian, CRC|1), then clocks
// 0xFF to read an R1/R3/R7 response, and for reads a 0xFE data token + a 512-byte
// block + 2 CRC bytes. We model an SDHC card (block addressing) whose blocks are
// backed by a host file (env PAPER_SD, default /tmp/paper_s3_sd.img). If that file
// does not exist we synthesise a valid, empty FAT16 volume so the card mounts.
//
// This is a byte-stream state machine: mmio.c hands us each MOSI byte and uses the
// returned MISO byte. No faked "no card" - the real init/CSD/CID/read sequence runs.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sdcard.h"

#define SD_SEC       512u
#define SD_TOTAL_SEC 65536u          // 32 MB card
#define SD_BYTES     ((uint64_t)SD_TOTAL_SEC * SD_SEC)

static FILE *img;                     // backing store
static int   present;

// ---- FAT16 image synthesis (only when the file is created fresh) ----
#define SPC   4u                      // sectors/cluster
#define RSVD  1u                      // reserved sectors (boot sector)
#define NFATS 2u
#define ROOTENT 512u
#define ROOTSEC (ROOTENT * 32u / SD_SEC)          // 32 sectors
static uint32_t fat_sectors(void) {
    uint32_t t1 = SD_TOTAL_SEC - (RSVD + ROOTSEC);
    uint32_t t2 = 256u * SPC + NFATS;             // 256 = bytes/sec / 2 (FAT16 entry)
    return (t1 + t2 - 1) / t2;
}
static void put16(uint8_t *p, uint16_t v){ p[0]=v; p[1]=v>>8; }
static void put32(uint8_t *p, uint32_t v){ p[0]=v; p[1]=v>>8; p[2]=v>>16; p[3]=v>>24; }

static void fat16_format(void) {
    uint32_t fatsz = fat_sectors();
    uint8_t sec[SD_SEC];

    // Boot sector / BPB.
    memset(sec, 0, sizeof sec);
    sec[0]=0xEB; sec[1]=0x3C; sec[2]=0x90;
    memcpy(sec+3, "MSDOS5.0", 8);
    put16(sec+0x0B, SD_SEC);          // bytes/sector
    sec[0x0D]=SPC;                    // sectors/cluster
    put16(sec+0x0E, RSVD);            // reserved sectors
    sec[0x10]=NFATS;                  // number of FATs
    put16(sec+0x11, ROOTENT);         // root dir entries
    put16(sec+0x13, 0);               // total sectors 16 (0 -> use 32-bit)
    sec[0x15]=0xF8;                   // media descriptor
    put16(sec+0x16, fatsz);           // sectors/FAT
    put16(sec+0x18, 63);              // sectors/track
    put16(sec+0x1A, 255);             // heads
    put32(sec+0x1C, 0);               // hidden sectors
    put32(sec+0x20, SD_TOTAL_SEC);    // total sectors 32
    sec[0x24]=0x80;                   // drive number
    sec[0x26]=0x29;                   // extended boot signature
    put32(sec+0x27, 0x50415045);      // volume id
    memcpy(sec+0x2B, "PAPER SD   ", 11);
    memcpy(sec+0x36, "FAT16   ", 8);
    sec[0x1FE]=0x55; sec[0x1FF]=0xAA;
    fseek(img, 0, SEEK_SET); fwrite(sec, 1, SD_SEC, img);

    // FAT tables: entry0 = media|0xFF00, entry1 = EOC. Both FAT copies.
    for (uint32_t f = 0; f < NFATS; f++) {
        memset(sec, 0, sizeof sec);
        sec[0]=0xF8; sec[1]=0xFF; sec[2]=0xFF; sec[3]=0xFF;
        fseek(img, (long)(RSVD + f*fatsz) * SD_SEC, SEEK_SET);
        fwrite(sec, 1, SD_SEC, img);
    }

    // Root directory: a volume-label entry so tools see a labelled, empty volume.
    memset(sec, 0, sizeof sec);
    memcpy(sec, "PAPER SD   ", 11);
    sec[0x0B]=0x08;                   // ATTR_VOLUME_ID
    fseek(img, (long)(RSVD + NFATS*fatsz + 0) * SD_SEC, SEEK_SET);
    fwrite(sec, 1, SD_SEC, img);
    fflush(img);
}

static void sd_open(void) {
    static int tried;
    if (tried) return; tried = 1;
    const char *path = getenv("PAPER_SD"); if (!path) path = "/tmp/paper_s3_sd.img";
    img = fopen(path, "r+b");
    if (!img) {                        // create + format a fresh card
        img = fopen(path, "w+b");
        if (!img) { fprintf(stderr, "[sdcard] cannot open %s\n", path); return; }
        // grow to full size (sparse), then lay down FAT16.
        fseek(img, (long)SD_BYTES - 1, SEEK_SET); fputc(0, img); fflush(img);
        fat16_format();
        fprintf(stderr, "[sdcard] created + FAT16-formatted %s (%u MB)\n", path,
                (unsigned)(SD_BYTES >> 20));
    } else {
        fprintf(stderr, "[sdcard] mounted host image %s\n", path);
    }
    present = 1;
}

static void rd_block(uint32_t lba, uint8_t *dst) {
    memset(dst, 0, SD_SEC);
    if (img && (uint64_t)lba * SD_SEC < SD_BYTES) {
        fseek(img, (long)lba * SD_SEC, SEEK_SET);
        if (fread(dst, 1, SD_SEC, img) == 0) { /* zero-filled */ }
    }
}
static void wr_block(uint32_t lba, const uint8_t *src) {
    if (img && (uint64_t)lba * SD_SEC < SD_BYTES) {
        fseek(img, (long)lba * SD_SEC, SEEK_SET);
        fwrite(src, 1, SD_SEC, img); fflush(img);
    }
}

// ---- SD SPI byte-stream state machine ----
static uint8_t cmd[6];
static int     cmd_idx = -1;          // -1 = not currently receiving a command
static uint8_t out[1 + 8 + 2 + SD_SEC + 2 + 8];  // response FIFO (R + token + block + crc)
static int     out_head, out_tail;

// write-block reception state (CMD24 / CMD25)
static int      wr_wait_token, wr_recv, wr_crc, wr_multi;
static uint32_t wr_lba;
static uint8_t  wr_buf[SD_SEC];
static int      wr_pos;

static void push(uint8_t b){ out[out_tail++ % sizeof out] = b; }
static void push_n(uint8_t b, int n){ while(n--) push(b); }

static uint32_t arg(void){ return (cmd[1]<<24)|(cmd[2]<<16)|(cmd[3]<<8)|cmd[4]; }

// Data-block CRC matching the sdspi host's check. The host compares a little-endian read
// of the 2 wire bytes against sdspi_crc16() which, because the ESP-ROM crc16_be inverts
// its input and output, reduces to bswap16(crc16_msb(init=0, poly 0x1021, data)). So emit
// the plain MSB-first CRC16/XMODEM (init 0, no XOR), high byte first.
static void push_block_crc(const uint8_t *d, int n) {
    uint16_t c = 0;
    for (int i = 0; i < n; i++) { c ^= (uint16_t)d[i] << 8;
        for (int b = 0; b < 8; b++) c = (c & 0x8000) ? (uint16_t)((c << 1) ^ 0x1021) : (uint16_t)(c << 1); }
    push(c >> 8); push(c & 0xff);
}

static void queue_read_block(uint32_t lba) {
    uint8_t blk[SD_SEC];
    rd_block(lba, blk);
    push(0x00);                       // R1 ready
    push_n(0xFF, 2);                   // Ncr gap
    push(0xFE);                        // start-block token
    for (uint32_t i = 0; i < SD_SEC; i++) push(blk[i]);
    push_block_crc(blk, SD_SEC);       // valid CRC16 (CMD59 enables data CRC)
}

static int app_cmd;   // set after CMD55: the next command is an ACMD

static void exec_command(void) {
    int c = cmd[0] & 0x3F;
    uint32_t a = arg();
    int acmd = app_cmd; app_cmd = 0;    // was this preceded by CMD55?
    static int dbg = -1; if (dbg < 0) dbg = getenv("SDDBG") ? 1 : 0;
    if (dbg) fprintf(stderr, "[sd] %sCMD%d arg=%08x (%02x %02x %02x %02x %02x %02x)\n",
                     acmd?"A":"", c, a, cmd[0],cmd[1],cmd[2],cmd[3],cmd[4],cmd[5]);
    push(0xFF);   // Ncr dead-time byte: the card responds >=1 clock after the command, so
                  // R1 lands at the driver's cmd->r1 (offset 7 = after the 6 cmd + 1 ncr byte)
    if (acmd && c == 13) {                                   // ACMD13 SD_STATUS: R1 + 64-byte block
        uint8_t st[64]; memset(st, 0, sizeof st); st[8] = 0x01;   // speed class 1
        push(0x00); push_n(0xFF,1); push(0xFE);
        for (int i=0;i<64;i++) push(st[i]);
        push_block_crc(st, 64); return;
    }
    switch (c) {
    case 5: case 52: break;                                 // SDIO (CMD5/CMD52): non-SDIO card ignores -> MISO stays 0xFF
    case 0:  push(0x01); break;                              // GO_IDLE_STATE -> idle
    case 8:  push(0x01); push(0x00); push(0x00); push(0x01); push(0xAA); break; // SEND_IF_COND (R7 echo)
    case 55: app_cmd = 1; push(0x01); break;                 // APP_CMD -> next is an ACMD
    case 41: push(0x00); break;                              // ACMD41 -> ready (init complete)
    case 58: push(0x00); push(0xC0); push(0xFF); push(0x80); push(0x00); break; // READ_OCR (R3: CCS=1, ready)
    case 16: push(0x00); break;                              // SET_BLOCKLEN (512) -> ok
    case 59: push(0x00); break;                              // CRC_ON_OFF -> ok
    case 9:  {                                               // SEND_CSD (CSD v2, 32 MB)
        uint8_t csd[16] = {0x40,0x0E,0x00,0x32,0x5B,0x59,0x00,0x00,
                           0x0F,0x00,0x7F,0x80,0x0A,0x40,0x00,0x01};
        // C_SIZE for ~32MB SDHC: capacity = (C_SIZE+1)*512KB. 32MB -> C_SIZE=63.
        csd[7]=0x00; csd[8]=0x00; csd[9]=0x3F;               // C_SIZE = 63 (bits [69:48])
        push(0x00); push_n(0xFF,1); push(0xFE);
        for (int i=0;i<16;i++) push(csd[i]);
        push_block_crc(csd, 16); break;
    }
    case 51: {                                               // ACMD51 SEND_SCR (8-byte data block)
        uint8_t scr[8] = {0x02,0x35,0x80,0x03,0x00,0x00,0x00,0x00};
        push(0x00); push_n(0xFF,1); push(0xFE);
        for (int i=0;i<8;i++) push(scr[i]);
        push_block_crc(scr, 8); break;
    }
    case 10: {                                               // SEND_CID
        uint8_t cid[16] = {0x1B,'P','S','P','A','P','R',0x10,
                           0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01};
        push(0x00); push_n(0xFF,1); push(0xFE);
        for (int i=0;i<16;i++) push(cid[i]);
        push_block_crc(cid, 16); break;
    }
    case 17: queue_read_block(a); break;                     // READ_SINGLE_BLOCK
    case 18: queue_read_block(a); break;                     // READ_MULTIPLE (host stops via CMD12)
    case 12: push(0x00); push(0x00); break;                  // STOP_TRANSMISSION
    case 24:                                                 // WRITE_BLOCK
        push(0x00); wr_wait_token = 1; wr_multi = 0; wr_lba = a; break;
    case 25:                                                 // WRITE_MULTIPLE_BLOCK
        push(0x00); wr_wait_token = 1; wr_multi = 1; wr_lba = a; break;
    case 13: push(0x00); push(0x00); break;                  // SEND_STATUS (R2)
    default: push(0x00); break;                              // accept unknown as ready
    }
}

uint8_t sdcard_spi_byte(uint8_t mosi) {
    sd_open();
    if (!present) return 0xFF;
    static int dbg2 = -1; if (dbg2 < 0) dbg2 = getenv("SDDBG") ? 1 : 0;
    static int nn; if (dbg2 && mosi != 0xFF && nn < 80) { nn++; fprintf(stderr, "[sd-mosi] %02x\n", mosi); }

    // Receiving a data block for CMD24/CMD25?
    if (wr_recv) {
        wr_buf[wr_pos++] = mosi;
        if (wr_pos >= (int)SD_SEC) {   // block complete -> commit, then absorb the 2 CRC bytes
            wr_recv = 0; wr_pos = 0; wr_crc = 2;
            wr_block(wr_lba, wr_buf);
            if (wr_multi) wr_lba++;    // CMD25: next block goes to the following LBA
        }
        return 0xFF;                    // card holds MISO high while clocking in the data
    }
    if (wr_crc > 0) {                   // the 2 CRC bytes: return 0xFF, then emit the data response
        if (--wr_crc == 0) {
            // The host's CRC-response transaction reads the data-response token as its 3rd
            // byte (rx[2]); we've returned 0xFF for the two CRC bytes, so the NEXT clocked
            // byte must be the token. Queue: token (0x05 = accepted) then busy(0)->ready(FF).
            push(0x05); push_n(0x00, 2); push(0xFF);
            if (wr_multi) wr_wait_token = 1;   // CMD25: card is ready for the next block/stop token
        }
        return 0xFF;
    }
    if (wr_wait_token) {              // waiting for the start (0xFE/0xFC) or stop (0xFD) token
        // The command's R1 (+Ncr) is clocked out in the SAME transaction that sent the
        // command; let those queued bytes drain FIRST, else we'd swallow R1 (returning
        // 0xFF) and the host's shift_cmd_response would never find it.
        if (out_head != out_tail) return out[out_head++ % sizeof out];
        if (mosi == 0xFE || mosi == 0xFC) { wr_wait_token = 0; wr_recv = 1; wr_pos = 0; }
        else if (mosi == 0xFD) { wr_wait_token = 0; wr_multi = 0; push_n(0x00, 2); push(0xFF); } // stop tran -> busy->ready
        return 0xFF;
    }

    // Command reception: a real SD command (byte with bits[7:6]==01) is always preceded
    // by at least one idle 0xFF byte — requiring that avoids false-starting on stray
    // init/garbage bytes (e.g. 0x74) that also happen to have bits[7:6]==01.
    static uint8_t prev = 0xFF;
    if (cmd_idx < 0 && (mosi & 0xC0) == 0x40 && prev == 0xFF && out_head == out_tail) {
        cmd_idx = 0;
    }
    prev = mosi;
    if (cmd_idx >= 0) {
        cmd[cmd_idx++] = mosi;
        if (cmd_idx == 6) { cmd_idx = -1; exec_command(); }
        return 0xFF;                  // card holds MISO high while receiving a command
    }

    // Otherwise stream queued response/data bytes (host clocks 0xFF).
    if (out_head != out_tail) return out[out_head++ % sizeof out];
    return 0xFF;                       // idle
}

int sdcard_present(void) { return present; }