Skip to content

Stage 1 The skeleton

Radu Mailat edited this page Nov 3, 2026 · 1 revision

How the firmware is compiled, where everything sits in memory, how the device boots, and the three contexts the code runs in. Files: firmware/src/main.c, firmware/app.ld, firmware/src/app/main_fm1.c, firmware/src/app/plat.h, firmware/src/app/app.h, firmware/src/app/plat_fm1.c, firmware/src/dsp/dsp_hot.h, tools/build.py (skim).

By the end you should be able to draw a box for each execution context, say what it owns, and explain how a real-time audio block is measured and kept on time.

1. The big picture in one paragraph

The FM-1 has no operating system. When it powers on, the chip's ROM bootloader jumps into our code, and from then on everything is ours: memory layout, interrupts, timing. There are no threads, only a main loop and two interrupts. The audio interrupt fills a buffer every 5.8 ms by running a Mega Drive sound driver and emulating two sound chips. The timer interrupt scans the panel 10,000 times a second. The main loop runs the user interface whenever neither interrupt is busy. Nearly every design decision in FM1-TRAX follows from one fact: the audio interrupt must never be late, and it is doing a lot of work.

2. How the code is compiled: the unity build

Open firmware/src/main.c. It is almost nothing but #include lines, and several of them include .c files:

#include "fm1_sys.h"       /* the HAL: header-only */
...
#include "libc.c"
#include "lcd.c"
#include "gfx.c"
...
#include "usb.c"
#include "storage.c"
#include "ota.c"
#include "lz4.c"
#include "app/app.h"
song_t song __attribute__((section(".pool")));
#include "app/panel.c"
#include "app/plat_fm1.c"
#include "app/settings.c"
#include "app/ui.c"
#include "app/link.c"
#include "app/main_fm1.c"

This is a unity build: everything that touches the hardware is compiled as one translation unit. Why?

  • The HAL (firmware/hal/*.h) is header-only and full of static inline functions and register macros. One unit means one copy.
  • Every function can be static, so the compiler sees the whole program and can inline and drop dead code across "files". That matters in a 580 KB app slot.
  • Order is the dependency graph. A file can use anything included above it. That's why main.c defines small helpers (fm1_ms, RING_PUBLISH, clamp) and the flash hooks (st_read, st_erase, st_prog) before including storage.c, which calls them.

Not everything is in the unity build. tools/build.py compiles the chips and the tracker as separate units:

O2_UNITS = ["dsp/opn2.c", "dsp/psg.c", "dsp/mdsnd.c", "trk/song.c", "trk/player.c",
            "trk/presets.c", "trk/presets_fm.c"]

The unity build is compiled -Os (small), these at -O2 (fast), because they run in the audio interrupt. They don't include any HAL header: they're pure C, which is also what lets the host and the browser compile them unchanged. The split between "touches hardware" and "pure logic" is the most useful structural idea in the repository.

The hooks pattern

Look at how main.c hands storage its flash access:

static int st_read(uint32_t off, void *dst, uint32_t n)   /* 256-byte IRQ-off windows: audio keeps up */
{
    uint8_t *d = dst;
    while (n) {
        uint32_t k = n > 256u ? 256u : n, f = irq_save();
        int rc = FL_FAR(fl_read_ram)(off, d, k);
        irq_restore(f);
        ...
    }
    return 0;
}
static int st_erase(uint32_t off)
{
    if (!FL_STORE_OK(off, 0x1000u))
        return -8;
    audio_silence();
    return fl_erase4k(off, &took);
}
#include "storage.c"

storage.c only declares these three functions; whoever includes it defines them. The device defines them over the real flash, host/drive_host.c defines them over a 1 MiB array. That's dependency injection without function pointers.

Notice the two device-specific details: reads happen in 256-byte windows with interrupts off (the flash can't be read through the cache while the driver talks to it, and short windows keep the audio interrupt's latency low), and an erase first clears the audio buffer (audio_silence), because a 4 KiB erase keeps interrupts off long enough that the DMA would replay a stale buffer as a buzz. FL_STORE_OK refuses any write outside the app's data area, which protects the bootloader and the stock firmware's data.

3. Memory: the linker script

firmware/app.ld decides where everything lives:

Region Address Size What
XIP 0x02000120 581,564 bytes Code and constants, executed in place from flash through a cache
RAMTEXT 0x01C00000 24 KB .ram_text: the flash driver, then .ram_hot: the sound's inner loops
RAM 0x01C08000 96 KB .data and .bss
POOL 0x01C20000 344 KB .pool: big zero-initialised buffers
NOINIT 0x01C7C000 ~15 KB survives a reset: the boot guard, debug counters

Three of these deserve attention.

.pool. The song (song_t, about 173 KB), the drawing canvases (2 × 38 KB), the chunk store's index, the LZ4 buffers and the UI's clipboard are far bigger than the 96 KB main RAM. They are declared with __attribute__((section(".pool"))) (or the OM_POOL macro from plat.h, which is empty on the host). The section is NOLOAD: the image carries nothing for it, and fm1_cstart() zeroes it.

.ram_hot. New in FM1-TRAX. Code in XIP flash runs through an instruction cache; every miss stalls the CPU while the line is fetched over SPI. For the chip emulators, which touch a lot of code and tables every sample, the misses cost more than the work. So dsp/dsp_hot.h defines:

#ifdef __PI32V2__
#define DSP_HOT __attribute__((section(".ram_hot")))
#define DSP_HOT_DATA __attribute__((section(".ram_hotd")))
#else
#define DSP_HOT
#define DSP_HOT_DATA
#endif
#define DSP_INLINE static inline __attribute__((always_inline))

and opn2_render, psg_render, md_render and the chips' ROM tables carry it. The linker places them after the flash driver in RAMTEXT ("AT > XIP": stored in flash, run from RAM), and fm1_cstart() copies them there. DSP_INLINE matters too: a helper that wasn't inlined would be an ordinary function in flash, and the hot code would call out of RAM into the cache again.

There's a catch. RAMTEXT (0x01C0…) and XIP (0x0200…) are far apart, further than a direct call instruction can reach. So code in flash calls md_render through a pointer the compiler can't fold back into a direct call:

static inline void md_render_far(md_t *m, int32_t *out, uint32_t n)
{
#ifdef __PI32V2__
    void (*volatile f)(md_t *, int32_t *, uint32_t) = md_render;
    f(m, out, n);
#else
    md_render(m, out, n);
#endif
}

The volatile on the pointer variable is the trick: the compiler must load it, so it must make an indirect call.

.noinit. Not cleared at boot, so it survives a watchdog reset. The boot guard and the debug counters (om_dbg) live there.

4. Boot, step by step

4.1 fm1_cstart(): making C work

crt0.S sets up the stacks and calls fm1_cstart() at the bottom of main_fm1.c. Read it top to bottom:

  1. fm1_wdt_arm(0x0D): the watchdog first, so a hang anywhere after this resets the device.
  2. The boot guard. bootguard is in .noinit. pending is set at every boot and cleared by the main loop after 30 s of running. If a boot finds pending still set, the last boot crashed or hung, and failed goes up. Two failures in a row → safe mode; four → the chip's own update mode. This is what makes custom firmware safe to install: a broken build can't lock the user out.
  3. Clear .bss and .pool, copy .data and .ram_text from flash. Before this, no C global has its value.
  4. Enable the hardware guards (stack, write, bus, PC) so that a stray pointer faults instead of corrupting memory silently.
  5. Call fm1_main().

4.2 fm1_main(): bringing the device up

The order is deliberate:

flash_ok = FL_FAR(fl_jedec_ram)() == 0x856014u;   /* the expected 1 MiB part, else RAM only */
lcd_init(); splash();
if (safe_mode) safe_main();                      /* never returns */
fm1_input_init(); fm1_adc_init(); panel_init(); led_pos_init();
presets_bank_init();                             /* the DAC kit */
player_init(FS);                                 /* the chips */
settings_load();
song_boot_load();                                /* the song last used, before the audio runs */
audio_init();
usb_start();
uart_midi_init();
fm1_timer5_start(isr_timer5, 4);
fm1_irq_enable_all();
ui_init();
for (;;) { ... }
  • flash_ok: if the flash chip doesn't answer with the expected ID, the store is never touched (plat_store.c checks it everywhere). Better to run without saving than to write to an unknown part.
  • The song is loaded before audio starts. song_boot_load() sets player.lock while it fills song, but at boot the audio interrupt isn't even running yet, so there's nothing to race with.
  • Interrupts are enabled last, after every structure they touch exists.

5. Interrupts: the two real-time contexts

5.1 The audio interrupt (priority 3)

The codec is fed by DMA from abuf, a ring of two halves of 256 stereo frames. When the DMA finishes one half and moves to the other, the ALNK0 interrupt fires and we refill the half it just left:

void fm1_alnk0_irq(void)
{
    uint8_t p = fm1_audio_pending();
    fm1_audio_ack_aux(p);
    if (p & FM1_AUDIO_HALF) {
        uint32_t half = fm1_audio_free_half();
        render_block(&abuf[half * HALF_WORDS]);
        fm1_audio_ack_half();
        if (fm1_audio_free_half() != half) {
            om_dbg.late++;                         /* the DMA moved on while we rendered */
            audio_xruns++;
        }
    }
}

This is double buffering. 256 frames at 44.1 kHz is 5.8 ms: that's the deadline. If rendering takes longer, the DMA wraps around into the half we're still writing, and the check after render_block catches it: the free half has changed under us. That's an xrun (buffer under-run), counted, and the UI says AUDIO TOO SLOW.

render_block() does three things around the actual work:

static void render_block(int32_t *o)
{
    uint32_t t0 = fm1_ticks(), us, budget = HALF_FRAMES * 1000000u / FS;
    om_dbg.in_audio = 1;
    ...
        for (i = 0; i < 2u * REND_FRAMES; i++)
            b[i] = 0;
        player_render(b, REND_FRAMES);
        for (i = 0; i < 2u * REND_FRAMES; i++) {   /* 16 bits of chips (clipped) to 24, times the MASTER */
            int32_t v = b[i] * g >> 4;
            b[i] = v > 8388607 ? 8388607 : v < -8388607 ? -8388607 : v;   /* never wraps */
        }
    ...
    us = (fm1_ticks() - t0) / FM1_TICKS_PER_US;
    om_dbg.cpu_q8 = (om_dbg.cpu_q8 * 15u + (us * 256u) / budget) / 16u;
    audio_cpu_pct = (om_dbg.cpu_q8 * 100u) >> 8;
    if (us * 100u / budget > audio_cpu_peak)
        audio_cpu_peak = us * 100u / budget;
    om_dbg.in_audio = 0;
}
  1. It measures itself. The time spent, as a fraction of the 5,805 µs budget, goes into an exponential moving average in Q8 fixed point (new = (old * 15 + sample) / 16), and the worst block is kept in audio_cpu_peak until the UI reads it. SETUP shows both. If you ever write real-time code, build the meter first: you can't optimise what you can't see.
  2. It scales by MASTER and clamps. player_render hands back samples already clipped to 16 bits. Multiplying by master_q12 (0..4096) and shifting right by 4 gives up to 24 bits. The clamp is the second safety net, so that no value can ever wrap around to full scale of the opposite sign (Stage 3, section 9).
  3. It flags itself as running (om_dbg.in_audio), which the timer interrupt reads.

5.2 The timer interrupt (10 kHz, priority 4)

fm1_timer5_irq() runs every 100 µs:

  • fm1_input_tick() drives one column of the key/encoder/LED matrix. The LEDs are multiplexed: a column is lit only while it is being scanned. Any irregularity in the scan rhythm shows as flicker, and an encoder read late can miss a step.
  • Every fifth tick (2 kHz) it wants to poll USB and the TRS jack.
  • It turns the CPU's tick counter into fm1_ms.

Why is it above the audio interrupt? A render takes several milliseconds. If the timer couldn't interrupt it, the matrix scan would stop for that long in every 5.8 ms block: LEDs flicker, turns get lost. X0X found this on hardware; the comment in fm1_main records it.

But nesting has a cost: USB shares its MIDI queues with code the audio ISR runs. So the timer interrupt defers the USB poll while a render is in progress:

if (sub % 5u == 0u) {
    usb_due = 1;
    if (om_dbg.in_audio)
        uac_service();      /* USB audio can't wait: one packet a millisecond */
}
if (usb_due && !om_dbg.in_audio) {
    usb_due = 0;
    usb_poll();
    uart_midi_poll();
}

USB audio (the FM-1 appears as a USB microphone carrying its own output) can't wait up to 11 ms, so its service runs nested; it touches only its own endpoint and the consumer side of its own ring, so it can't collide with usb_poll. When two contexts nest, list exactly what each touches. That list is the proof that it's safe.

6. The main loop

for (;;) {
    fm1_wdt_feed();
    usb_retry(fm1_ms);
    if (fm1_ms > 30000u && bootguard.pending) { bootguard.pending = 0; bootguard.failed = 0; }
    /* MASTER pot: smoothed, squared */
    /* battery: 20 readings a second */
    /* OCT- + OCT+ held 5 s: update mode */
    link_service();          /* songs and the library over SysEx */
    ota_service();           /* firmware update handshake */
    ...
    if (fm1_ms - last_frame >= 16u) {
        last_frame = fm1_ms;
        ui_frame();
    } else {
        ui_input_only();
    }
}

Two small things worth copying:

The MASTER pot. knob += (a * 16 - knob) / 8 is a one-pole low-pass filter on the ADC reading, kept in 1/16ths so the division doesn't throw away the small steps. Then master_q12 = (k10 * k10) >> 8 squares it: a volume knob should feel logarithmic, and a square is a cheap approximation of an audio taper.

Input runs more often than drawing. ui_frame() does input and, every 33 ms, a full redraw. Between frames, ui_input_only() still reads the panel, so a key is never missed just because the screen is busy.

7. How the contexts talk

There are four channels between the main loop and the audio interrupt. Learn them, because every bug of this kind of program is a misuse of one of them.

  1. The command ring (player_post → player_run_commands). For "do something": play, stop, a note from the keys, mute, reset. The main loop writes, the ISR reads. Stage 3 dissects it.
  2. Published state (player.playing, player.ord, player.row, player.ch[].level, player.md.scope[]). The ISR writes, the UI reads to draw. A torn or stale value only means one frame drawn slightly wrong.
  3. player.lock. For "I need the song to hold still": loading, saving, allocating a pattern. While it's set, render() runs the chips but skips commands and ticks.
  4. The song's cells, edited in place. The one place both sides touch the same data with no handshake. Stage 3 explains why that is acceptable here.

And between the timer ISR and the main loop: fm1_in (the scanned panel state) and the USB MIDI queues, each written by one side and read by the other.

8. The platform interface: plat.h

Read firmware/src/app/plat.h in full. It is the whole contract between the app and the world:

uint32_t plat_ms(void);
uint32_t plat_buttons(void);           /* held: bit B_* */
uint32_t plat_keys(void);              /* held: bit k = key k (0 = F3) */
int32_t plat_enc(int role);            /* detents since the last call */
uint32_t plat_master(void);
int plat_battery(void);
void plat_leds(uint32_t buttons, uint32_t keys);
int plat_midi_in(uint32_t *pkt);
void plat_midi_out(uint32_t pkt);
int plat_store_load(uint32_t obj, void *dst, uint32_t max);
int plat_obj_wopen(int obj); int plat_obj_write(...); int plat_obj_wclose(void);
int plat_obj_open(int obj);  int plat_obj_read(void *dst, uint32_t n);
uint32_t plat_cpu_pct(void);
...

Notice what it is not: it has no audio function. Audio isn't pulled by the app; the platform pushes it, by calling player_render() from its own clock (the ALNK0 interrupt on the device, run_ms() in the simulator, the audio worklet's demand in the browser). Whoever owns the clock calls the renderer. That inversion is what lets the simulator run faster than real time.

plat_fm1.c is the device side. Two details are worth a look:

  • plat_buttons() translates the matrix's raw IDs into the panel's button names through a calibration table (panel.btn[]), so the app thinks in B_PLAY, not in matrix coordinates.
  • plat_leds() builds the whole LED picture in local arrays and then copies one byte per column. Clearing and relighting in place would let the 10 kHz scan catch the dark gap.

9. Crashes and safe mode

A hardware guard or an exception lands in fm1_fault(), which stops the audio, paints a red screen with the vector and PC in hex, waits 4 s and reboots. The crash count is in .noinit, so the next boot can say "RESTARTED AFTER A CRASH" with the PC, which is how a bug report from a user's device becomes an address you can look up in the map file.

safe_main() is what runs after two failed boots: no audio, no UI, no engine, just the LCD, the panel and USB, so an installer can reach the device. PLAY tries a normal boot again. When you write firmware others will install, write the recovery path first.

10. What to take away

  • Separate code that touches hardware from code that doesn't; compile the pure part for any target.
  • A unity build gives whole-program optimisation and a readable dependency order; inject platform hooks by declaring them in the library and defining them in the includer.
  • Know your memory map. Put big buffers in their own region, hot code in RAM, survivors in .noinit.
  • Double-buffered audio: render the half the DMA just left, and detect when you were too slow.
  • Measure the real-time path from day one: a moving average and a peak.
  • Nest interrupts only with a written list of what each touches.
  • The owner of the clock calls the renderer.
  • Watchdog, boot-loop counter, safe mode, crash screen: build the recovery before the features.

11. Exercises

  1. Draw the three contexts as boxes. For each, list the globals it writes and the globals it only reads. Which globals appear in two "writes" lists?
  2. The budget is HALF_FRAMES * 1000000u / FS. Compute it. If the moving average shows 60 % and the peak 95 %, what's the risk, and what in the code would you look at first?
  3. master_q12 and fm1_ms are both volatile and are shared between contexts with no lock. Why is that enough for them? (Think about the width of the value, the CPU, and who writes it.) Why would it not be enough for a 64-bit counter?
  4. audio_silence() zeroes the whole abuf before a flash erase. What would you hear without it, and why?
  5. Find every function marked DSP_HOT (grep -rn DSP_HOT firmware/src/dsp). Pick one helper it calls and check that it is DSP_INLINE too. What would happen on the device if it weren't?
  6. Sketch a plat.h for a project of your own (say, a drum machine on a Raspberry Pi Pico). What goes in, what stays out?

Next stage: the song, as data.


← Contents · Stage 2: The song's data model →

Clone this wiki locally