Files
bootloader/tsb/tsb_asm.cpp
BlackMark 3ea8957e69 tsb: asm tier reaches full oracle feature parity at 502 B
Rewrite the inline-asm tier so it matches the hand-written fixed-baud oracle's
feature set inside the 512 B boot section: watchdog-reset bail, one-wire
half-duplex (RXEN/TXEN toggled per direction, TX turnaround guard),
config-page activation timeout, the password gate (wrong byte hangs draining
the UART), emergency erase (password \0 + double-confirm wipes flash, EEPROM
and the config page), and config/flash/EEPROM read-write. Every geometry,
baud and info-block constant comes from libavr consteval; only the dense
control flow is hand-written. 502 B, byte-identical across generated and
reflect modes.

Test harness: seed the config page from TSB_CONFIG so the password and
emergency-erase paths are exercisable, and clear simavr's AVR_UART_FLAG_POLL_
SLEEP — a host-CPU-saving usleep(1)-per-idle-poll hack that models no hardware
and paces a one-wire loader (which releases TX between bytes) in real time,
distorting protocol timing.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 16:23:16 +02:00

361 lines
14 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// TinySafeBoot on libavr — tier 3: full feature parity in ≤512 B.
//
// The complete TinySafeBoot feature set — watchdog-reset bail, one-wire
// half-duplex UART, a config-page activation timeout, the password gate,
// emergency erase, and config/flash/EEPROM read-write — reimplemented for the
// 512-byte ATmega328P boot section. Matching the hand-written assembly oracle's
// size and features at once is only reachable at assembly density, so the loader
// body is one cohesive inline-asm routine. libavr still does the datasheet work:
// every geometry, baud and info-block constant below is computed by the library,
// never hand-entered, and the loader references them as assembler immediates.
//
// The wire protocol is strict request/response, which makes the one-wire
// turn-around safe: the device owns the line whenever it drives a byte and
// releases it (RX-only) whenever it waits for one.
#include <libavr/libavr.hpp>
#include <avr/boot.h> // __SPM_ENABLE and the SPM page-op bit names
#include <avr/io.h> // SFR addresses / bit numbers for the boot entry
using namespace avr::literals;
namespace spm = avr::spm;
namespace tsb {
// Boot geometry — the chip database's to know, not ours.
constexpr std::uint16_t page = spm::page_bytes; // 128
constexpr std::uint16_t boot_bytes = 512; // BOOTSZ=11
constexpr std::uint16_t app_end = spm::flash_bytes - boot_bytes - page; // config page base
constexpr std::uint16_t eeprom_end = avr::hw::db.mem.eeprom_size - 1;
// Fixed 115200 8N1; the library solves UBRR + U2X from clock and baud.
constexpr auto baud = avr::uart::detail::solve_baud(16_MHz, 115200_Bd);
static_assert(baud.u2x && baud.ubrr < 256, "asm bring-up writes UBRR0L only, with U2X0");
// Activation window: the config page's timeout byte, floored so a corrupt page
// can never lock the loader out (at least the clock rate in MHz → ~0.5 s here).
constexpr std::uint8_t act_min = 16;
// Post-activation communication timeout (~several seconds); the loader bails to
// the application if the host falls silent mid-session.
constexpr std::uint8_t comm_timeout = 200;
constexpr std::uint8_t confirm = '!';
constexpr std::uint8_t request = '?';
constexpr std::uint8_t knock = '@';
constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 19;
// The 16-byte device-info block, LPM-read on activation. A plain progmem array:
// the loader streams it straight out with LPM, so a flash_table wrapper would
// add nothing here.
// clang-format off
[[gnu::progmem]] constexpr std::uint8_t info[16] = {
'T', 'S', 'B',
build_date & 0xFF, build_date >> 8,
0xF3, // status: native-UART fixed-baud lineage
0x1E, 0x95, 0x0F, // ATmega328P signature
page / 2, // page size in words
(app_end / 2) & 0xFF, (app_end / 2) >> 8,
eeprom_end & 0xFF, eeprom_end >> 8,
0xAA, 0xAA,
};
// clang-format on
} // namespace tsb
// Reset lands here: BOOTRST vectors to the boot base, .vectors is laid first, and
// no crt runs. The whole loader is this one naked routine.
extern "C" [[gnu::naked, gnu::used, gnu::section(".vectors")]] void __boot_entry()
{
asm volatile(
// --- bring-up ------------------------------------------------------
" ldi r16, lo8(%[ramend]) \n\t"
" out %[spl], r16 \n\t"
" ldi r16, hi8(%[ramend]) \n\t"
" out %[sph], r16 \n\t"
" in r16, %[mcusr] \n\t" // watchdog reset → hand straight back
" sbrc r16, 3 \n\t" // MCUSR bit 3 = WDRF
" rjmp 9f \n\t" // 9: = appjump
" ldi r16, %[ubrr] \n\t" // fixed baud, UBRR0L only
" sts %[ubrr0l], r16 \n\t"
" ldi r16, 0x02 \n\t" // 1<<U2X0
" sts %[ucsr0a], r16 \n\t"
" clr r22 \n\t" // direction flag bit0: 0 = receiving, 1 = driving the line
// --- activation: 3×'@' inside a config-page-timed window -----------
" ldi r30, lo8(%[appto]) \n\t" // Z = config page + 2
" ldi r31, hi8(%[appto]) \n\t"
" lpm r23, Z+ \n\t" // timeout byte; Z password
" ori r23, %[actmin] \n\t" // lockout-proof floor
" clr r17 \n\t" // knock counter
"1: rcall tsb_rx \n\t"
" brcs 9f \n\t" // window elapsed → application
" cpi r16, %[knock] \n\t"
" brne 9f \n\t" // any non-'@' → application
" inc r17 \n\t"
" cpi r17, 3 \n\t"
" brne 1b \n\t"
// --- password / emergency erase (Z at config-page password) --------
" ldi r23, %[commto] \n\t" // widen the timeout for the session
"2: ser r19 \n\t" // r19=0xff → comparison enabled
"3: lpm r18, Z+ \n\t"
" and r18, r19 \n\t" // a prior mismatch (r19=0) blanks the rest
" cpi r18, 0xff \n\t"
" breq tsb_info \n\t" // 0xff terminator → password satisfied
" rcall tsb_rx \n\t"
" cpi r16, 0 \n\t"
" breq 5f \n\t" // a 0 byte requests emergency erase
" cp r16, r18 \n\t"
" breq 2b \n\t" // char matched → next, comparison re-armed
" clr r19 \n\t" // mismatch → drain forever, never erase
" rjmp 3b \n\t"
"5: cpi r19, 0 \n\t" // only offer erase if not already wrong
" breq 3b \n\t"
" rcall tsb_rcnf \n\t" // two confirmations guard the wipe
" brts 9f \n\t"
" rcall tsb_rcnf \n\t"
" brts 9f \n\t"
" rcall tsb_emerg \n\t"
" rjmp tsb_main \n\t"
// --- device info, then the command loop ----------------------------
"tsb_info: \n\t"
" ldi r30, lo8(%[info]) \n\t"
" ldi r31, hi8(%[info]) \n\t"
" ldi r20, 16 \n\t"
" rcall tsb_sendf \n\t"
"tsb_main: \n\t"
" clr r30 \n\t" // Z = 0 for the memory commands
" clr r31 \n\t"
" ldi r16, %[cfm] \n\t" // mainloop ready
" rcall tsb_tx \n\t"
" rcall tsb_rx \n\t"
" rcall tsb_disp \n\t"
" rjmp tsb_main \n\t"
"tsb_disp: \n\t"
" cpi r16, 'f' \n\t"
" breq tsb_rflash \n\t"
" cpi r16, 'F' \n\t"
" breq tsb_wflash \n\t"
" cpi r16, 'e' \n\t"
" breq tsb_reep \n\t"
" cpi r16, 'E' \n\t"
" breq tsb_weep \n\t"
" cpi r16, 'c' \n\t"
" breq tsb_rconf \n\t"
" cpi r16, 'C' \n\t"
" breq tsb_wconf \n\t"
"9: rcall tsb_spmw \n\t" // appjump: finish any SPM, hand over at 0
" jmp 0 \n\t"
// --- 'f' read application flash (host-paced) -----------------------
"tsb_rflash: \n\t"
"1: rcall tsb_rwait \n\t"
" brts 9f \n\t"
" ldi r20, %[page] \n\t"
" rcall tsb_sendf \n\t"
" cpi r30, lo8(%[appcfg]) \n\t"
" ldi r24, hi8(%[appcfg]) \n\t"
" cpc r31, r24 \n\t"
" brlo 1b \n\t"
"9: ret \n\t"
// --- 'e' read EEPROM (host-paced) ----------------------------------
"tsb_reep: \n\t"
"1: rcall tsb_rwait \n\t"
" brts 9f \n\t"
" ldi r20, %[page] \n\t"
"2: out %[earl], r30 \n\t"
" out %[earh], r31 \n\t"
" sbi %[eecr], 0 \n\t" // EERE
" in r16, %[eedr] \n\t"
" rcall tsb_tx \n\t"
" adiw r30, 1 \n\t"
" dec r20 \n\t"
" brne 2b \n\t"
" rjmp 1b \n\t"
"9: ret \n\t"
// --- 'F' write application flash -----------------------------------
"tsb_wflash: \n\t"
" rcall tsb_erapp \n\t" // erase the whole application first (leaves Z=0)
"1: rcall tsb_rcnf \n\t"
" brts 9f \n\t"
" rcall tsb_store \n\t"
" cpi r30, lo8(%[appcfg]) \n\t"
" ldi r24, hi8(%[appcfg]) \n\t"
" cpc r31, r24 \n\t"
" brlo 1b \n\t"
"9: ret \n\t"
// --- 'E' write EEPROM ----------------------------------------------
"tsb_weep: \n\t" // Z already 0 from the mainloop
"1: rcall tsb_rcnf \n\t"
" brts 9f \n\t"
" ldi r20, %[page] \n\t"
"2: rcall tsb_rx \n\t"
" rcall tsb_eewr \n\t"
" dec r20 \n\t"
" brne 2b \n\t"
" rjmp 1b \n\t"
"9: ret \n\t"
// --- 'c' read config page, 'C' write config page -------------------
"tsb_rconf: \n\t"
" ldi r30, lo8(%[appcfg]) \n\t"
" ldi r31, hi8(%[appcfg]) \n\t"
" ldi r20, %[page] \n\t"
" rjmp tsb_sendf \n\t"
"tsb_wconf: \n\t"
" rcall tsb_rcnf \n\t"
" brts 9f \n\t"
" ldi r30, lo8(%[appcfg]) \n\t"
" ldi r31, hi8(%[appcfg]) \n\t"
" rcall tsb_erpage \n\t" // erase the config page (Z unchanged)
" rcall tsb_store \n\t" // program it from the host
" rjmp tsb_rconf \n\t" // rewind Z and echo it back
"9: ret \n\t"
// --- stream one page host→flash at Z, program it (Z → next page) ----
"tsb_store: \n\t"
" ldi r20, %[words] \n\t"
"1: rcall tsb_rx \n\t"
" mov r0, r16 \n\t"
" rcall tsb_rx \n\t"
" mov r1, r16 \n\t"
" ldi r24, %[spm_fill] \n\t"
" out %[spmcsr], r24 \n\t"
" spm \n\t"
" clr r1 \n\t"
" adiw r30, 2 \n\t"
" dec r20 \n\t"
" brne 1b \n\t"
" subi r30, lo8(%[page]) \n\t" // back to the page base for PGWRT
" sbci r31, hi8(%[page]) \n\t"
" ldi r24, %[spm_wrt] \n\t"
" out %[spmcsr], r24 \n\t"
" spm \n\t"
" rcall tsb_spmw \n\t"
" subi r30, lo8(-%[page]) \n\t" // Z → next page base
" sbci r31, hi8(-%[page]) \n\t"
" ret \n\t"
// --- erase [0, config page) ----------------------------------------
"tsb_erapp: \n\t"
" clr r30 \n\t"
" clr r31 \n\t"
"1: rcall tsb_erpage \n\t"
" subi r30, lo8(-%[page]) \n\t"
" sbci r31, hi8(-%[page]) \n\t"
" cpi r30, lo8(%[appcfg]) \n\t"
" ldi r24, hi8(%[appcfg]) \n\t"
" cpc r31, r24 \n\t"
" brlo 1b \n\t"
" clr r30 \n\t" // hand callers Z=0
" clr r31 \n\t"
" ret \n\t"
// --- erase one flash page at Z (busy-wait + RWW re-enable) ----------
"tsb_erpage: \n\t"
" ldi r24, %[spm_ers] \n\t"
" out %[spmcsr], r24 \n\t"
" spm \n\t"
" rjmp tsb_spmw \n\t" // tail: wait + RWW re-enable, then ret
// --- emergency erase: application flash, EEPROM, config page -------
"tsb_emerg: \n\t"
" rcall tsb_erapp \n\t" // erases the application, leaves Z=0
" ser r16 \n\t"
"1: rcall tsb_eewr \n\t"
" cpi r30, lo8(%[eeend1]) \n\t"
" ldi r24, hi8(%[eeend1]) \n\t"
" cpc r31, r24 \n\t"
" brne 1b \n\t"
" ldi r30, lo8(%[appcfg]) \n\t"
" ldi r31, hi8(%[appcfg]) \n\t"
" rjmp tsb_erpage \n\t" // erase the config page (tail)
// --- one EEPROM byte r16 → [Z], Z++ --------------------------------
"tsb_eewr: \n\t"
"1: sbic %[eecr], 1 \n\t" // EEPE busy
" rjmp 1b \n\t"
" out %[earl], r30 \n\t"
" out %[earh], r31 \n\t"
" out %[eedr], r16 \n\t"
" sbi %[eecr], 2 \n\t" // EEMPE, then EEPE within 4 cycles
" sbi %[eecr], 1 \n\t" // EEPE
" adiw r30, 1 \n\t"
" ret \n\t"
// --- stream r20 flash bytes from Z to the host ---------------------
"tsb_sendf: \n\t"
"1: lpm r16, Z+ \n\t"
" rcall tsb_tx \n\t"
" dec r20 \n\t"
" brne 1b \n\t"
" ret \n\t"
// --- SPM busy-wait, then re-enable RWW read access -----------------
"tsb_spmw: \n\t"
"1: in r24, %[spmcsr] \n\t"
" sbrc r24, 0 \n\t"
" rjmp 1b \n\t"
" ldi r24, %[spm_rww] \n\t"
" out %[spmcsr], r24 \n\t"
" spm \n\t"
" ret \n\t"
// --- '?' then await '!' (T=1 ⇒ not confirmed) ----------------------
"tsb_rcnf: \n\t"
" ldi r16, %[req] \n\t"
" rcall tsb_tx \n\t"
"tsb_rwait: \n\t"
" rcall tsb_rx \n\t"
" clt \n\t"
" cpi r16, %[cfm] \n\t"
" breq 9f \n\t"
" set \n\t"
"9: ret \n\t"
// --- one-wire transmit r16 (drive the line + guard, wait TXC) ------
// One-wire: RX and TX share the line, so only one direction is enabled
// at a time. Waiting for TXC (whole frame out) before a caller can
// release the line is what makes the shared wiring safe.
"tsb_tx: \n\t"
" sbrc r22, 0 \n\t" // currently receiving? turn the line around
" rjmp 2f \n\t"
"1: sts %[udr0], r16 \n\t"
"3: lds r25, %[ucsr0a] \n\t" // wait for the whole frame out (TXC0)
" sbrs r25, 6 \n\t" // UCSR0A bit 6 = TXC0
" rjmp 3b \n\t"
" sts %[ucsr0a], r25 \n\t" // write 1 to clear TXC
" ret \n\t"
"2: ldi r25, 0x08 \n\t" // TXEN0 only: drive the line (receiver off)
" sts %[ucsr0b], r25 \n\t"
" clr r22 \n\t"
" ser r21 \n\t" // turn-around guard for a shorted receiver
"4: dec r21 \n\t"
" brne 4b \n\t"
" rjmp 1b \n\t"
// --- one-wire receive → r16, C set on timeout ----------------------
"tsb_rx: \n\t"
" sbrc r22, 0 \n\t" // already receiving? keep the line released
" rjmp 1f \n\t"
" ldi r25, 0x10 \n\t" // RXEN0 only: release the line and listen
" sts %[ucsr0b], r25 \n\t"
" ser r22 \n\t"
"1: mov r27, r23 \n\t" // outer countdown high = timeout byte
" clr r26 \n\t"
"2: ser r21 \n\t"
"3: lds r16, %[ucsr0a] \n\t"
" sbrc r16, 7 \n\t" // UCSR0A bit 7 = RXC0
" rjmp 4f \n\t"
" dec r21 \n\t"
" brne 3b \n\t"
" sbiw r26, 1 \n\t"
" brcc 2b \n\t"
" sec \n\t" // timed out
" ret \n\t"
"4: lds r16, %[udr0] \n\t"
" clc \n\t"
" ret \n\t"
:
: [ramend] "i"(RAMEND), [spl] "I"(_SFR_IO_ADDR(SPL)), [sph] "I"(_SFR_IO_ADDR(SPH)),
[mcusr] "I"(_SFR_IO_ADDR(MCUSR)), [ubrr] "n"(tsb::baud.ubrr), [ubrr0l] "n"(_SFR_MEM_ADDR(UBRR0L)),
[ucsr0a] "n"(_SFR_MEM_ADDR(UCSR0A)), [ucsr0b] "n"(_SFR_MEM_ADDR(UCSR0B)), [udr0] "n"(_SFR_MEM_ADDR(UDR0)),
[spmcsr] "I"(_SFR_IO_ADDR(SPMCSR)), [spm_fill] "n"(_BV(__SPM_ENABLE)),
[spm_ers] "n"(_BV(PGERS) | _BV(__SPM_ENABLE)), [spm_wrt] "n"(_BV(PGWRT) | _BV(__SPM_ENABLE)),
[spm_rww] "n"(_BV(RWWSRE) | _BV(__SPM_ENABLE)), [eecr] "I"(_SFR_IO_ADDR(EECR)),
[eedr] "I"(_SFR_IO_ADDR(EEDR)), [earl] "I"(_SFR_IO_ADDR(EEARL)), [earh] "I"(_SFR_IO_ADDR(EEARH)),
[appcfg] "i"(tsb::app_end), [appto] "i"(tsb::app_end + 2), [eeend1] "i"(tsb::eeprom_end + 1),
[info] "i"(&tsb::info[0]), [page] "n"(tsb::page), [words] "n"(tsb::page / 2), [actmin] "n"(tsb::act_min),
[commto] "n"(tsb::comm_timeout), [cfm] "n"(tsb::confirm), [req] "n"(tsb::request), [knock] "n"(tsb::knock)
: "r0", "r1", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r30", "r31",
"cc", "memory");
}