Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ OpenShifter 0.2.0 read a zeroed page as colour 0 0 0, which turned every LED off

Stock assumes 2 KB flash pages and rewrites halfwords 0 to 0x3ff. OpenShifter preserves everything outside halfwords 0 to 99.

Every way into update mode (`24 00`, both buttons at power-up, a fault, a stall, a host that never configures the unit) writes the flag in halfword 0. If that write fails twice, OpenShifter leaves USB and blinks all LEDs red instead of resetting, because a reset would only start the application again.

## Update protocol (bootloader)

Observed on a real unit (stock to stock, flashed from Linux with `tools/openshifter_flash.py`, 2026-10-20):
Expand Down Expand Up @@ -160,6 +162,10 @@ OpenShifter adds these (stock ignores them):

`tools/openshifter_ctl.py` sends all of these.

Commands marked "saved" write the settings page in flash, and every write erases the page first. A flash page only takes so many erases, and this one also holds the bootloader flag, so OpenShifter writes a change once nothing has changed for 1 second. Up to 16 writes can follow each other; after that, one more is allowed each minute and later changes wait in memory. `24 00` writes a waiting change at once. A change that has not been written yet is lost if the shifter loses power. OpenShifter 0.5.0 and older wrote every change at once, like stock.

To change the LED colour continuously, for example to show RPM or the gear, use `24 20`. It is never saved.

Feature report ID 0x25, 16 bytes, OpenShifter 0.4.0 and newer: `25` followed by
the version string, for example `0.4.0`, padded with NULs. It is read with
GET_REPORT (feature). Browsers cannot read the iConfiguration string, so the
Expand Down
31 changes: 22 additions & 9 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ OpenShifter has been tested without hardware, in three layers. Run them all with

| Suite | Tests | What it covers |
|---|---|---|
| `tests/test_shifter.py` | 17 | the gear/sensor core built for the host with trapping UBSan, against exact float oracles; the OpenShifter settings, LEDs and buttons |
| `tests/test_emulated.py` | 20 | the real `openshifter.bin`, and the stock image, on an emulated board |
| `tests/test_ctl.py` | 9 | `openshifter_ctl.py` against the shifter core running in a thread |
| `tests/test_flasher.py` | 19 | the flasher against a simulated bootloader and a fake sysfs tree |
| `tests/test_shifter.py` | 24 | the gear/sensor core built for the host with trapping UBSan, against exact float oracles; the OpenShifter settings, LEDs and buttons; when settings are written to flash |
| `tests/test_emulated.py` | 26 | the real `openshifter.bin`, and the stock image, on an emulated board |
| `tests/test_ctl.py` | 10 | `openshifter_ctl.py` against the shifter core running in a thread |
| `tests/test_flasher.py` | 21 | the flasher against a simulated bootloader and a fake sysfs tree |

## The emulator (`tests/emu`)

Expand All @@ -19,7 +19,8 @@ OpenShifter has been tested without hardware, in three layers. Run them all with
- GPIO and bit-band
- TIM3 PWM and DMA, used for the LEDs
- USART1 DMA
- flash (FPEC, with programming rules checked on every write)
- flash (FPEC, with programming rules checked on every write), and a worn
settings page that refuses every erase and write
- the USB device peripheral and its packet memory
- the boot ROM table the stock image calls during PLL setup
- the MLX90393 at pin level (the firmware bit-bangs SPI)
Expand All @@ -36,7 +37,8 @@ and the settings page contents, byte for byte.
OpenShifter's own settings start differently from stock (logo off, a warm
colour), so these tests give both images a settings page with logo on, gamma
off, stock's yellow and full gains in halfwords 0x50 to 0x56, which stock
ignores. The remaining differences are checked explicitly, not skipped: report
ignores. Settings pages are compared after waiting long enough for
OpenShifter's delayed write (see below). The remaining differences are checked explicitly, not skipped: report
0x24 bytes 23, 24, 53 and 54 are cleared after they are checked, OpenShifter's
report descriptor (and its length in the HID descriptor) is checked against
the expected one and then replaced with stock's, and LED frames in sequential mode are compared with the handbrake LED
Expand Down Expand Up @@ -85,6 +87,15 @@ real bugs were found this way and fixed:
high/low toggle, the handbrake button in H and the handbrake LED in SEQ
- both input reports keep flowing when the host polls only every 2 ms or
misses frames (0.3.0 failed this: report 0x24 dropped to about 3 per second)
- 40 colour changes in a row cost one flash erase, made 1 s after the last
one; after 16 writes the next change waits, though the LEDs already show it
- `24 00` writes a waiting change before it resets
- with a worn settings page, `24 00` tries the flag twice, then leaves USB and
blinks red instead of resetting

`SettingsWrites` in `test_shifter.py` checks the write timing itself with a
fake clock: the 1 s wait, the 16-write burst, one more write per minute after
that, and the clock wrapping after 49 days.

None of these tests may write flash outside the FPEC rules. The emulator records every program and erase and checks it.

Expand All @@ -95,9 +106,9 @@ None of these tests may write flash outside the FPEC rules. The emulator records
| iConfiguration | 0 (none) | string 4, "OpenShifter x.y.z" |
| GET_REPORT | returns a fixed buffer of unrelated RAM | returns the current report 1 or 0x24 |
| Control SET_REPORT | ignored if short; a 64-byte one crashes (jump to 0) | runs the command, like interrupt OUT |
| Recovery | none | High/low and Handbrake buttons held at power-up, fault, 3 s stall, host never configuring, PLL failure: all enter the vendor bootloader |
| Recovery | none | High/low and Handbrake buttons held at power-up, fault, 3 s stall, host never configuring, PLL failure: all enter the vendor bootloader. If the flag cannot be written, the unit leaves USB and blinks red |
| System clock | 216 MHz | 72 MHz; delays use stock's effective durations |
| Settings write | read-modify-write of 0x400 halfwords, assuming 2 KB pages | erase, then program only halfwords that need it; works with 1 KB or 2 KB pages; same resulting page |
| Settings write | read-modify-write of 0x400 halfwords, assuming 2 KB pages, on every change | erase, then program only halfwords that need it; works with 1 KB or 2 KB pages; same resulting page. Written once nothing has changed for 1 s, at most 16 writes in a row, then one a minute; `24 00` writes at once |
| Default LED colour | yellow (255 255 0) | 255 182 78 (warm orange), settable with `24 30` |
| LED output | colour × 2/3 | optional gamma 2.2 (`24 34 1`, off by default) and a white balance gain per channel, then × 2/3; gamma off and gains of 255 give stock's output |
| Logo LED | always lit | off unless turned on (`24 31 1`) |
Expand Down Expand Up @@ -131,6 +142,8 @@ Some timings differ by a few tens of milliseconds, all measured in the emulator:
- USB electrical and timing behaviour of the AIR32 USB block
- the AIR32 PLL at 72 MHz (the stock image only shows its 216 MHz configuration)
- the flash page size
- the delayed settings writes and the red stop after a failed flag write
have only run in the emulator
- **The vendor bootloader.** It is not in any update package, so the flasher
is tested against a simulator written from Tuner's code. Two real updates
went through it without errors; an interrupted update has not been tried. See
Expand All @@ -150,7 +163,7 @@ Some timings differ by a few tens of milliseconds, all measured in the emulator:
```sh
pip install -r requirements-dev.txt # unicorn 2.1.4
make -C firmware # builds build/openshifter.bin
make -C firmware test # all suites (about 4 minutes)
make -C firmware test # all suites (about 6 minutes)
python3 -m unittest discover -s tests -p test_flasher.py -v # just one suite
```

Expand Down
24 changes: 22 additions & 2 deletions firmware/src/flash.c
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
*/
#include "flash.h"
#include "board.h"
#include "periph.h"
#include "regs.h"
#include "usb.h"

#define PAGE_HALFWORDS 1024

Expand Down Expand Up @@ -91,7 +93,24 @@ int settings_write(const uint16_t st[SH_SETTINGS_HALFWORDS])
write_active = 1;
int err = write_page();
write_active = 0;
return err;
return err ? -1 : 1;
}

/* The flag cannot be written, so a reset would only start the application
* again, and a fault would come back here and erase again. Leave the bus and
* blink red until the unit is unplugged. */
static __attribute__((noreturn)) void flash_failed(void)
{
static const uint8_t red[9] = {0, 170, 0, 0, 170, 0, 0, 170, 0};
static const uint8_t off[9];
usb_detach();
leds_init();
for (unsigned n = 0;; n++) {
while (leds_busy())
;
leds_show(n & 1 ? off : red);
delay_cycles(g_sysclk_hz / 4); /* 250 ms */
}
}

void enter_bootloader(void)
Expand All @@ -111,6 +130,7 @@ void enter_bootloader(void)
for (unsigned i = 0; i < PAGE_HALFWORDS; i++)
page[i] = *flash_hw(i);
page[SETTINGS_BOOT_FLAG] = 1;
write_page();
if (write_page() && write_page())
flash_failed();
board_reset();
}
7 changes: 4 additions & 3 deletions firmware/src/flash.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@

void settings_read(uint16_t st[SH_SETTINGS_HALFWORDS]);
/* Read-modify-write of the settings page; only the first
* SH_SETTINGS_HALFWORDS halfwords change. Returns 0 on success (or nothing
* to do), -1 on a flash error. */
* SH_SETTINGS_HALFWORDS halfwords change. Returns 0 if nothing changed (no
* erase), 1 after a good write, -1 on a flash error. */
int settings_write(const uint16_t st[SH_SETTINGS_HALFWORDS]);

/* Set the bootloader flag and reset. The vendor bootloader then stays in
* update mode (USB 10f5:7097) until a new image is written. Safe to call from
* any context, including fault handlers. */
* any context, including fault handlers. If the flag cannot be written after
* one retry, the unit leaves USB and blinks red instead of resetting. */
__attribute__((noreturn)) void enter_bootloader(void);

#endif
60 changes: 48 additions & 12 deletions firmware/src/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@
* - SysTick sees PendSV or the main loop stalled for 3 s;
* - the host reset the bus 6+ times without ever configuring the device;
* - the PLL could not be configured.
* If the bootloader flag cannot be written, the unit leaves USB and blinks
* red instead (flash.c).
*
* A settings change reaches flash 1 s after the last change, at a limited
* rate (sh_saves_* in shifter.c), because every write erases the page that
* holds the bootloader flag.
*/
#include "shifter.h"
#include "board.h"
Expand All @@ -27,7 +33,8 @@
static shifter_t sh;
static uint16_t st_loaded[SH_SETTINGS_HALFWORDS]; /* as read at boot */
static uint16_t st_pending[SH_SETTINGS_HALFWORDS]; /* snapshot for the next write */
static volatile uint8_t save_pending, boot_pending;
static sh_saves_t saves; /* touch with interrupts off */
static volatile uint8_t boot_pending;

static volatile uint8_t sensor_ready, sensor_paused, sensor_off_timer, sensor_off_ticks;
static volatile uint8_t asleep, led_dirty;
Expand Down Expand Up @@ -94,7 +101,7 @@ static void apply_actions(unsigned act)
for (unsigned i = 0; i < SH_SETTINGS_HALFWORDS; i++)
st_pending[i] = st_loaded[i];
shifter_save(&sh, st_pending);
save_pending = 1;
sh_saves_changed(&saves, g_ms);
}
if (act & SH_ACT_BOOT) {
led_dirty = 1;
Expand Down Expand Up @@ -206,6 +213,41 @@ void usb_lp_handler(void)
usb_irq_handler();
}

/* ---- settings writes ------------------------------------------------------ */

static void spent(void)
{
irq_disable();
sh_saves_spent(&saves);
irq_enable();
}

/* Writes the settings when sh_saves_take() allows it. Returns 1 while a
* change is still waiting. */
static int save_settings(void)
{
uint16_t st[SH_SETTINGS_HALFWORDS];
irq_disable();
int due = sh_saves_take(&saves, g_ms, boot_pending);
if (due)
for (unsigned i = 0; i < SH_SETTINGS_HALFWORDS; i++)
st[i] = st_pending[i];
irq_enable();

if (due) {
int r = settings_write(st);
if (r)
spent();
if (r < 0 && settings_write(st)) /* one retry */
spent();
}

irq_disable();
int waiting = saves.pending;
irq_enable();
return waiting;
}

/* ---- startup -------------------------------------------------------------- */

static int buttons_held_at_power_up(void)
Expand All @@ -220,6 +262,8 @@ static int buttons_held_at_power_up(void)

int main(void)
{
sh_saves_init(&saves);

/* Exception priorities: SysTick 0 (highest), USB 1, PendSV 3. */
SCB_SHPR3 = (PRIO_PENDSV << 4 << 16) | (0u << 24);

Expand Down Expand Up @@ -259,17 +303,9 @@ int main(void)
else
uart_enable();

if (save_pending) {
uint16_t st[SH_SETTINGS_HALFWORDS];
irq_disable();
for (unsigned i = 0; i < SH_SETTINGS_HALFWORDS; i++)
st[i] = st_pending[i];
save_pending = 0;
irq_enable();
settings_write(st);
}
int waiting = save_settings();

if (boot_pending && !save_pending) {
if (boot_pending && !waiting) {
/* "24 00": show yellow, then hand over to the bootloader. */
uint32_t t0 = g_ms;
while ((led_dirty || leds_busy()) && g_ms - t0 < 200)
Expand Down
38 changes: 38 additions & 0 deletions firmware/src/shifter.c
Original file line number Diff line number Diff line change
Expand Up @@ -1007,3 +1007,41 @@ void shifter_led_grb(const shifter_t *s, int asleep, uint8_t out[9])
if (s->options & SH_OPT_LOGO)
led_put(s, out, SH_LED_LOGO, r, g, b);
}

/* ---- settings writes ---------------------------------------------------- */

void sh_saves_init(sh_saves_t *v)
{
v->changed_ms = 0;
v->refill_ms = 0;
v->pending = 0;
v->allowance = SH_SAVE_BURST;
}

void sh_saves_changed(sh_saves_t *v, uint32_t now_ms)
{
v->pending = 1;
v->changed_ms = now_ms;
}

int sh_saves_take(sh_saves_t *v, uint32_t now_ms, int urgent)
{
while (v->allowance < SH_SAVE_BURST && now_ms - v->refill_ms >= SH_SAVE_REFILL_MS) {
v->allowance++;
v->refill_ms += SH_SAVE_REFILL_MS;
}
if (v->allowance >= SH_SAVE_BURST)
v->refill_ms = now_ms;
if (!v->pending)
return 0;
if (!urgent && (now_ms - v->changed_ms < SH_SAVE_QUIET_MS || !v->allowance))
return 0;
v->pending = 0;
return 1;
}

void sh_saves_spent(sh_saves_t *v)
{
if (v->allowance)
v->allowance--;
}
24 changes: 24 additions & 0 deletions firmware/src/shifter.h
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,30 @@ void shifter_uart_packet(const shifter_t *s, uint8_t out[16]);
* asleep. */
void shifter_led_grb(const shifter_t *s, int asleep, uint8_t out[9]);

/* When to write the settings. Every write erases the settings page, which
* also holds the bootloader flag, and a flash page only takes so many
* erases. A change is written once nothing has changed for
* SH_SAVE_QUIET_MS. Up to SH_SAVE_BURST writes can follow each other;
* after that, one more is allowed every SH_SAVE_REFILL_MS. */
#define SH_SAVE_QUIET_MS 1000u
#define SH_SAVE_BURST 16u
#define SH_SAVE_REFILL_MS 60000u

typedef struct {
uint32_t changed_ms; /* time of the last change */
uint32_t refill_ms; /* time the allowance last grew, or was full */
uint8_t pending; /* a change is waiting to be written */
uint8_t allowance; /* writes left before the limit applies */
} sh_saves_t;

void sh_saves_init(sh_saves_t *v);
void sh_saves_changed(sh_saves_t *v, uint32_t now_ms);
/* 1 if the waiting change should be written now, and clears it. `urgent`
* (update mode was asked for) skips both the wait and the limit. */
int sh_saves_take(sh_saves_t *v, uint32_t now_ms, int urgent);
/* Call after each write that erased the page. */
void sh_saves_spent(sh_saves_t *v);

/* Exposed for tests. */
uint32_t sh_isqrt(uint32_t v);
void sh_sincos_q30(uint32_t angle, int32_t *sin_q30, int32_t *cos_q30);
Expand Down
6 changes: 6 additions & 0 deletions firmware/src/usb.c
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,12 @@ void usb_reconnect(void)
delay_ms(STOCK_MS(200));
}

void usb_detach(void)
{
USB_AIR_DPPU = 0;
USB_CNTR = CNTR_FRES | CNTR_PDWN;
}

void usb_init(void)
{
RCC_APB1ENR |= APB1_USB;
Expand Down
2 changes: 2 additions & 0 deletions firmware/src/usb.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ extern volatile uint16_t usb_reset_count;

/* Drop off the bus, wait, come back. Blocking. */
void usb_reconnect(void);
/* Drop off the bus and stay off. */
void usb_detach(void);
void usb_init(void);
void usb_irq_handler(void);

Expand Down
9 changes: 9 additions & 0 deletions tests/emu/stm32emu.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,7 @@ def __init__(self, image, settings=None, *, mips=24, slice_us=20, page_size=2048
self.flash_keys = 0
self.flash_events = []
self.flash_violations = []
self.flash_worn = False # True: the settings page refuses every erase and program
self.sensor = Sensor()
self.buttons = {'PA4': False, 'PA5': False, 'PB10': False}
self.usb = UsbDevice(self)
Expand Down Expand Up @@ -632,6 +633,11 @@ def flash_bytes(self, addr, n):
def _flash_write_hook(self, uc, access, addr, size, value, ud):
cr = self.regs[0x40022010]
old = struct.unpack('<H', uc.mem_read(addr & ~1, 2))[0]
if self.flash_worn and addr >= SETTINGS_ADDR:
self.flash_events.append(('program-failed', addr, value))
self.regs[0x4002200C] |= 0x04
self._undo = (addr & ~1, old)
return
ok = (cr & 1) and not (cr & 0x80) and size == 2 and not addr & 1 and (old == 0xFFFF or value == 0)
if addr < SETTINGS_ADDR:
ok = False
Expand Down Expand Up @@ -667,6 +673,9 @@ def _flash_ctrl_write(self, a, v):
if page < SETTINGS_ADDR or page >= FLASH_BASE + FLASH_SIZE:
self.flash_violations.append(('erase', hex(page)))
self.regs[0x4002200C] |= 0x10
elif self.flash_worn:
self.flash_events.append(('erase-failed', page))
self.regs[0x4002200C] |= 0x10
else:
self.uc.mem_write(page, b'\xff' * self.page_size)
self.flash_events.append(('erase', page))
Expand Down
2 changes: 2 additions & 0 deletions tests/native/shim.c
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,5 @@ void t_match(const shifter_t *s, int i, int *x, int *y, int *r)
}

int t_settings_valid(const shifter_t *s) { return s->settings_valid; }

unsigned t_saves_sizeof(void) { return sizeof(sh_saves_t); }
Loading