The NandTier SeriesPart 12 of 12

The Launcher: Loading Games from the SD Card

A pack of games on the SD card, a directory the launcher can read, and the copy into the flash cartridge slot that ends with a jump into the game.

9 min readFirmwareSD cardFlashGames
In this article
  1. What are we trying to do?
  2. The pack on the SD card
  3. Reading the directory
  4. Is it already there?
  5. Copying a game into the flash
  6. The jump
  7. And back again
  8. Conclusion

What are we trying to do?

Eight games, each 10 to 26 KiB, sit on the SD card. The CPU can only run code from memory on its bus, and the SD card is not on it: it is a device we read 512 bytes at a time (part 8). The flash, on the other hand, the CPU can run from (part 7). So the launcher's job, when you pick a game, is:

  1. read the list of games from the SD card
  2. copy the chosen game into a fixed place in the flash, the cartridge slot at 0x0010_0000
  3. jump to it
SD carddirectorySNAKEPONG…block_buf512 bytes · SRAMflash_io()boot RAM, bit-bangSPI flashlauncher · 0x0slot · 0x10_0000CMD172 × 256 B pageserase the sectors firstthen: check the CRC, and jump to 0x0010_0000
Installing a game: SD blocks into a RAM buffer, then into the flash slot through the boot ROM's flash_io().

Every piece for this already exists. This article puts them together.

The pack on the SD card

On the PC, sw/mkcarts.py packs the games into one image that is written to the card from block 8192. The first block is a directory:

fw/fw-flash/loader.clines 15–27
15// Cartridge pack on the SD card, from block NT_CART_SD_BLOCK (sw/mkcarts.py):16//17//   block 0, the directory:18//     0   "NTCART1\0"19//     8   number of games (little-endian 32-bit)20//     12  sum of the 32-bit words at 16..51121//     16  15 entries of 32 bytes:22//           0  name, 16 bytes, NUL padded23//           16 first block of the image, from the directory block24//           20 size in bytes25//           24 CRC-32 (as zlib.crc32)26//           28 load address (NT_CART_SLOT)27//   then the images, each starting on a block boundary.

A magic string, a count and a checksum, then one 32-byte entry per game: its name for the menu, where its data starts, its size, a CRC-32 to check it, and the address it was linked for. Building it is part of make games, and you can list a pack:

Terminal
$ make games$ python3 sw/mkcarts.py --list fw/games/build/carts.img

Reading the directory

fw/fw-flash/loader.clines 88–106
88int loader_read_dir(struct cart *carts, int max)89{90    static const char magic[8] = "NTCART1";91    uint8_t r7[2];92 93    if (sd_init(r7))94        return LOADER_NO_CARD;95    if (sd_read_block(NT_CART_SD_BLOCK, block_buf))96        return LOADER_READ_ERROR;97    for (int i = 0; i < 8; i++)98        if (block_buf[i] != (uint8_t)magic[i])99            return LOADER_NO_PACK;100 101    uint32_t sum = 0;102    for (int i = 16; i < SD_BLOCK_SIZE; i += 4)103        sum += get32(&block_buf[i]);104    uint32_t n = get32(&block_buf[8]);105    if (sum != get32(&block_buf[12]) || n > NT_CART_MAX)106        return LOADER_NO_PACK;

Start the card (part 8), read the directory block, and check it: the magic string first, then the checksum over the entries, which catches a card holding something else or a half-written pack.

fw/fw-flash/loader.clines 108–123
108    int count = 0;109    for (uint32_t i = 0; i < n && count < max; i++) {110        const uint8_t *e = &block_buf[16 + i * 32];111        struct cart *c = &carts[count];112        if (get32(&e[28]) != NT_CART_SLOT)113            continue;                       // built for another place: skip114        for (int k = 0; k < 16; k++)115            c->name[k] = e[k];116        c->name[16] = 0;117        c->block = get32(&e[16]);118        c->size  = get32(&e[20]);119        c->crc   = get32(&e[24]);120        count++;121    }122    return count;123}

Then each entry is copied into a struct cart. An entry linked for some other address is skipped: a game only runs where it was linked, so a pack built for another layout cannot crash the machine.

Is it already there?

Writing flash is slow and wears it out, so the launcher first checks whether the slot already holds this game, by computing the CRC of what is there and comparing it with the directory's:

fw/fw-flash/loader.clines 184–188
184int loader_installed(const struct cart *c)185{186    return c->size && c->size <= NT_CART_SLOT_SIZE &&187           crc32(SLOT_MEMORY, c->size) == c->crc;188}

SLOT_MEMORY is the slot read through XIP, so this is a plain memory read of the flash, through the cache. Play the same game twice and the second start is instant.

Copying a game into the flash

fw/fw-flash/loader.clines 197–200
197uint32_t slot    = loader_flash_base() + NT_CART_SLOT;198uint32_t sectors = (c->size + SECTOR - 1) / SECTOR;199uint32_t blocks  = (c->size + SD_BLOCK_SIZE - 1) / SD_BLOCK_SIZE;200uint32_t total   = sectors + blocks;

The slot is erased in 4 KiB sectors, and filled from 512-byte SD blocks. total counts both kinds of work for a progress bar on the screen.

fw/fw-flash/loader.clines 202–206
202for (uint32_t s = 0; s < sectors; s++) {203    flash_erase_sector(slot + s * SECTOR);204    if (progress)205        progress(s + 1, total);206}

Erase first: every sector of the slot that the game will use goes back to all ones (part 7).

fw/fw-flash/loader.clines 207–216
207for (uint32_t b = 0; b < blocks; b++) {208    if (sd_read_block(NT_CART_SD_BLOCK + c->block + b, block_buf))209        return LOADER_READ_ERROR;210    uint32_t addr = slot + b * SD_BLOCK_SIZE;211    flash_program_page(addr, block_buf);212    flash_program_page(addr + PAGE, block_buf + PAGE);213    if (progress)214        progress(sectors + b + 1, total);215}216return loader_installed(c) ? 0 : LOADER_VERIFY_ERROR;

Then for each SD block: read it, and program it as two 256-byte flash pages (a flash page is 256 bytes, an SD block 512). Finally the CRC is checked again, now over what was really written.

flash_program_page skips pages that are all FF, since an erased page already holds that:

fw/fw-flash/loader.clines 168–182
168static void flash_program_page(uint32_t addr, const uint8_t *data)169{170    int blank = 1;171    for (int i = 0; i < PAGE; i++)172        blank &= data[i] == 0xFF;173    if (blank)                              // erased already174        return;175    page_cmd[0] = FLASH_PP;176    page_cmd[1] = addr >> 16;177    page_cmd[2] = addr >> 8;178    page_cmd[3] = addr;179    for (int i = 0; i < PAGE; i++)180        page_cmd[4 + i] = data[i];181    nt_flash_io(page_cmd, 4 + PAGE, 1);     // overwrites page_cmd182}

Every one of these calls goes through nt_flash_io, the boot ROM function at 0x8000_0054. While it runs, XIP is off, so the launcher's own code in the flash cannot be fetched; that is exactly why the bit-banging has to live in the boot RAM.

The jump

fw/fw-flash/loader.clines 220–226
220void loader_start(int index)221{222    PPU_REG(PPU_CTRL) = 0;                  // the game sets the screen up223    nt_handoff_set(NT_HANDOFF_PLAY, index);224    ((void (*)(void))NT_CART_SLOT)();225    __builtin_unreachable();226}

Three lines. Turn the picture off (the game sets up its own). Leave a note for the game in the last 16 bytes of the SRAM, the handoff: which game it is. Then call the slot address as a function, exactly the way the boot ROM called the launcher in part 6.

The game's own startup code (the same start.S as the launcher's) copies its .data, clears its .bss, sets sp and gp, and calls main. From the game's point of view it has the whole machine.

And back again

When you press Q, the game ends with cart_exit():

fw/sdk/cart.clines 28–39
28void cart_exit(uint32_t slowest_frame)29{30    PPU_REG(PPU_CTRL) = PPU_CTRL_TERM;31    cart_print("\nGame over. Slowest frame: ");32    cart_print_dec(slowest_frame);33    cart_print(" of 419580 cycles\n");34 35    // the launcher starts again and opens its game menu on this game36    nt_handoff_set(NT_HANDOFF_RETURN, NT_HANDOFF->arg);37    ((void (*)(void))NT_FLASH_BASE)();38    __builtin_unreachable();39}

It switches the screen to the text terminal, prints the slowest frame it measured (how close it came to using up a whole frame), leaves a handoff that says "return", and jumps to address 0: the launcher's start. The launcher sees the handoff and opens the game menu on the game you just left:

fw/fw-flash/main.clines 206–211
206// back from a game: straight to the game menu, on that game207if (nt_handoff_cmd() == NT_HANDOFF_RETURN) {208    int sel = NT_HANDOFF->arg;209    NT_HANDOFF->magic = 0;210    arcade(sel);211}

The whole round trip, boot ROM to launcher to game and back, is function calls through addresses and a 16-byte message in RAM. No operating system, no loader in hardware.

InteractiveThe real firmware traced in the emulator, from power-on through the menu, the SD reads and the flash writes, into a game.

Conclusion

That completes the machine: a CPU we wrote, on a bus we wrote, booting a ROM we wrote, which starts a launcher that reads an SD card and writes a flash to run a game, all of it shown on HDMI by a video pipeline we wrote. Every line of it is in the repository, and every piece has been in one of these twelve articles.

Where to go from here? Change something. Add a register to the PPU, write a ninth game, make the CPU pipelined. The extra credit article shows how the project's tests catch you when you break something, which makes all of that much less scary.