tsb: third size pass — restructure to the oracle's shape

The second pass concluded the 168 B tricks->asm gap was per-call ABI
cost. Most of it was structure. Rebuilt around the oracle's own shape —
argless noinline primitives over a whole-loader call-saved register
protocol (g_addr in Y, count r16, window r7, direction latch r6), a
top-down erase_below whose loop tests against zero and hands callers
g_addr = 0 for free, bounded rx everywhere (a silent host unwinds to
the app from any state, as the oracle does), and a named tsb_app entry
that --pmem-wrap-around=32k relaxes to the wrapped rjmp:

  tsb_asm    510 B in the 512 B section (oracle: 500), C++ except rx
             and the page-store loop — the two routines whose remaining
             cost is the calling convention itself (~30 asm lines, was
             ~280)
  tsb_tricks 526 B, no assembly at all (was 666)
  tsb_pure   836 B, still one readable function per command (was 842)

Every g_* update placement works around a GCC 16.1 wrong-code bug
(stores into global register variables deleted when only callees read
them — repro and rules in libavr dev/lessons.md). Also fixes two
latent hardware bugs all earlier tiers carried, masked by simavr's
zeroed register file: the crt-less entries never established
__zero_reg__ = 0, and the direction latch was read before written —
power-on registers are undefined.

All tiers full oracle feature parity, protocol tests green in both
libavr modes, .text byte-identical across modes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-20 01:00:27 +02:00
parent 2b705ad130
commit 74d8b92885
5 changed files with 659 additions and 552 deletions

View File

@@ -44,24 +44,29 @@ endif()
# its size; BOOTRST vectors a reset to its base) with -nostartfiles — a polled # its size; BOOTRST vectors a reset to its base) with -nostartfiles — a polled
# loader has no use for the crt or the vector table. The naked entry sits in # loader has no use for the crt or the vector table. The naked entry sits in
# .vectors, laid first, and runs. The boot base is FLASHEND+1 minus the section # .vectors, laid first, and runs. The boot base is FLASHEND+1 minus the section
# size; the linker section-start and the source's boot_bytes agree. # size; the linker section-start and the source's boot_bytes agree. tsb_app is
# the application's reset vector, pinned to 0 here so the loaders jump to a
# named function; --pmem-wrap-around lets relaxation turn that absolute jump
# into the wrapped rjmp AVR's modulo-flash PC actually executes.
# All three implement the full oracle feature set (see oracle/README.md): # All three implement the full oracle feature set (see oracle/README.md):
# watchdog bail, one-wire half-duplex, config-page activation timeout, password # watchdog bail, one-wire half-duplex, config-page activation timeout, password
# gate, emergency erase, config/flash/EEPROM read-write. They differ only in how, # gate, emergency erase, config/flash/EEPROM read-write. They differ only in how,
# and the size gradient is the cost of that "how" — see dev/lessons.md. # and the size gradient is the cost of that "how" — see dev/lessons.md.
# tsb_asm — dense inline asm for the loader core, libavr for every geometry/ # tsb_asm — the tricks tier's C++ with exactly two routines in asm (the
# baud/info constant and the stack bring-up: 498 B in the 512 B # bounded rx and the page-store loop — the two whose remaining
# section, beating the hand-written oracle (500 B) at its own # cost is the C ABI itself): 510 B in the 512 B section the
# feature set. The core is asm because C++ cannot reach it under # hand-written 500 B oracle occupies. Everything else, from
# 512 (the tricks tier is the proof). # bring-up to dispatch, is C++ on libavr.
# tsb_tricks — compiler trickery, no asm: the hot page pointer is walked in Y # tsb_tricks — no asm at all: the whole-loader register allocation lives in
# (adiw), flash/EEPROM paths share one runtime-flag body, every # global register variables (Y walks the page pointer), every
# single-call handler is always_inline'd into the no-prologue # helper is a tiny noinline primitive placed by the
# reset entry, pages stream straight to SPM/EEPROM, and the # global-register store rules, pages stream straight to
# bring-up is the two reset-non-default registers only. 666 B in # SPM/EEPROM, and the bring-up is the two reset-non-default
# the 1 KB section (BOOTSZ=10). # registers only. 526 B in the 1 KB section (BOOTSZ=10) — 14
# over the oracle's section, from 168 over at this tier's first
# floor.
# tsb_pure — pure idiomatic libavr, one function per command, TU-local # tsb_pure — pure idiomatic libavr, one function per command, TU-local
# (internal linkage), streaming (no SRAM page buffer): 842 B in # (internal linkage), streaming (no SRAM page buffer): 836 B in
# the 1 KB section. # the 1 KB section.
# #
# add_tsb_variant(<name> <boot-section-bytes>) # add_tsb_variant(<name> <boot-section-bytes>)
@@ -70,7 +75,8 @@ function(add_tsb_variant name bytes)
math(EXPR base_hex "${base_dec}" OUTPUT_FORMAT HEXADECIMAL) math(EXPR base_hex "${base_dec}" OUTPUT_FORMAT HEXADECIMAL)
add_executable(${name} tsb/${name}.cpp) add_executable(${name} tsb/${name}.cpp)
target_link_libraries(${name} PRIVATE libavr) target_link_libraries(${name} PRIVATE libavr)
target_link_options(${name} PRIVATE -nostartfiles -Wl,--section-start=.text=${base_hex}) target_link_options(${name} PRIVATE -nostartfiles -Wl,--section-start=.text=${base_hex}
-Wl,--defsym=tsb_app=0 -Wl,--pmem-wrap-around=32k)
add_custom_command(TARGET ${name} POST_BUILD COMMAND ${CMAKE_SIZE} $<TARGET_FILE:${name}>) add_custom_command(TARGET ${name} POST_BUILD COMMAND ${CMAKE_SIZE} $<TARGET_FILE:${name}>)
if(PROJECT_IS_TOP_LEVEL) if(PROJECT_IS_TOP_LEVEL)
add_test(NAME ${name}.size add_test(NAME ${name}.size

View File

@@ -38,9 +38,11 @@ avra -I /usr/share/avra tsb-fixedbaud.asm # after uncommenting .include "m328P
``` ```
**500 bytes with every feature** — the proof that ≤512 B and full feature parity **500 bytes with every feature** — the proof that ≤512 B and full feature parity
are simultaneously reachable. The port's `tsb_asm` tier matches this bar; `tsb_pure` are simultaneously reachable. The port's `tsb_asm` tier meets the same bar at
and `tsb_tricks` implement the same protocol at larger sizes in the 1 KB section, 510 B in the same 512 B section, written in C++ on libavr except the two
trading bytes for readability. routines whose remaining cost is the calling convention itself (the bounded rx
and the page-store loop); `tsb_tricks` needs no assembly at all at 526 B, and
`tsb_pure` stays fully idiomatic at 836 B, both in the 1 KB section.
The oracle targets 20 MHz / 33333 baud; the port targets 16 MHz / 115200 baud The oracle targets 20 MHz / 33333 baud; the port targets 16 MHz / 115200 baud
(what the simavr protocol test drives). Baud and geometry differ, code size and (what the simavr protocol test drives). Baud and geometry differ, code size and

View File

@@ -1,54 +1,73 @@
// TinySafeBoot on libavr — tier 3: full feature parity in ≤512 B. // TinySafeBoot on libavr — tier 3: full feature parity in the 512-byte boot
// section, in C++ except where the C ABI itself is the cost.
// //
// The complete TinySafeBoot feature set — watchdog-reset bail, one-wire // The complete TinySafeBoot feature set — watchdog-reset bail, one-wire
// half-duplex UART, a config-page activation timeout, the password gate, // half-duplex UART, a config-page activation timeout, the password gate,
// emergency erase, and config/flash/EEPROM read-write — reimplemented for the // emergency erase, and config/flash/EEPROM read-write — at 510 bytes in the
// 512-byte ATmega328P boot section. Matching the hand-written assembly oracle's // 512-byte BOOTSZ=11 section the hand-written oracle occupies (500 B). This tier used to be one
// size and features at once is only reachable at assembly density, so the loader // monolithic inline-asm routine; it is now the tricks tier's C++ (same
// body is one cohesive inline-asm routine. libavr still does the datasheet work: // register protocol, same structure — see tsb_tricks.cpp, including the
// every geometry, baud and info-block constant below is computed by the library, // global-register miscompile rules) with exactly two routines kept in
// never hand-entered, and the loader references them as assembler immediates. // assembly, the two whose remaining cost *is* the calling convention:
// //
// The wire protocol is strict request/response, which makes the one-wire // rx the bounded receive: C++ must re-floor the timeout window on every
// turn-around safe: the device owns the line whenever it drives a byte and // call (the global-register-store miscompile) and split it across
// releases it (RX-only) whenever it waits for one. // call-saved registers; the asm keeps the oracle's X-register nested
// countdown.
// store the page-store loop: C++ cannot hold the receive byte pair and the
// walked Z pointer across the rx calls without call-saved staging
// (push/pop + a Y→Z copy per word); the asm calls rx knowing exactly
// which registers it touches and walks Z live across the whole page.
//
// Everything else — bring-up, activation, password gate, emergency erase,
// dispatch, every SPM/EEPROM/flash primitive, every geometry/baud/info
// constant — is C++ on libavr, and the two asm routines splice into the same
// global-register protocol the C++ uses (g_addr in Y, g_cnt in r16, g_window
// in r7, g_receiving in r6), so calls cross the boundary with no marshalling.
//
// The wire protocol is strict request/response, which is what makes the shared
// line safe: the device drives it only between a received command and its
// reply, and releases it (RXEN0 only) whenever it waits.
#include <libavr/libavr.hpp> #include <libavr/libavr.hpp>
#include <avr/boot.h> // __SPM_ENABLE and the SPM page-op bit names #include <avr/io.h> // SP / RAMEND for the crt-free boot entry, SFR addresses for the asm routines
#include <avr/io.h> // SFR addresses / bit numbers for the boot entry
using namespace avr::literals; using namespace avr::literals;
namespace spm = avr::spm; namespace spm = avr::spm;
namespace ee = avr::eeprom;
namespace hw = avr::hw;
namespace tsb { namespace tsb {
namespace {
// Boot geometry — the chip database's to know, not ours. // The loader is purely polled — it never enables interrupts — so every SPM and
constexpr std::uint16_t page = spm::page_bytes; // 128 // EEPROM lock folds to nothing under this posture.
constexpr std::uint16_t boot_bytes = 512; // BOOTSZ=11 constexpr auto off = avr::irq::guard_policy::unused;
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 confirm = '!';
constexpr std::uint8_t request = '?'; constexpr std::uint8_t request = '?';
constexpr std::uint8_t knock = '@'; constexpr std::uint8_t knock = '@';
constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 19; // Boot geometry for the 512 B boot section (BOOTSZ=11); the page size and the
// flash/EEPROM extents are the chip database's to know. app_end is the config
// page (TSB's LASTPAGE), one page below the boot section.
constexpr std::uint16_t page = spm::page_bytes;
constexpr std::uint16_t boot_bytes = 512;
constexpr std::uint16_t app_end = spm::flash_bytes - boot_bytes - page;
constexpr std::uint16_t eeprom_end = avr::hw::db.mem.eeprom_size - 1;
// The 16-byte device-info block, LPM-read on activation. A plain progmem array: // Lockout-proof floor for the activation window (the oracle's F_CPU/1MHz).
// the loader streams it straight out with LPM, so a flash_table wrapper would constexpr std::uint8_t act_min = 16;
// add nothing here. // Post-activation window: the host gets seconds, not milliseconds, mid-session.
constexpr std::uint8_t comm_window = 200;
constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 20;
// Fixed 115200 8N1; the library solves UBRR + U2X from clock and baud.
constexpr auto baud = avr::uart::detail::solve_baud(16_MHz, 115200_Bd);
// The 16-byte device-info block, streamed out on activation.
// clang-format off // clang-format off
[[gnu::progmem]] constexpr std::uint8_t info[16] = { [[gnu::progmem]] constexpr std::uint8_t info[16] = {
'T', 'S', 'B', 'T', 'S', 'B',
@@ -62,296 +81,306 @@ constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 19;
}; };
// clang-format on // clang-format on
register std::uint16_t g_addr asm("r28");
register std::uint8_t g_cnt asm("r16");
register std::uint8_t g_window asm("r7");
register std::uint8_t g_receiving asm("r6");
const std::uint8_t *flash_ptr(std::uint16_t addr)
{
return reinterpret_cast<const std::uint8_t *>(addr);
}
// Bounded byte receive (asm 1 of 2): release the one-wire line on a direction
// change, poll RXC0 under the oracle's nested X-register countdown seeded from
// g_window (floored against lockout), byte or 0-on-silence in r24. Z survives
// — the property the store's word loop rides on.
[[gnu::noinline, gnu::noclone]] std::uint8_t rx()
{
std::uint8_t byte;
asm volatile(" tst %[dir] \n\t" // already receiving? keep the line released
" brne 1f \n\t"
" ldi %[b], 0x10 \n\t" // RXEN0 alone: release the line and listen
" sts %[ucsr0b], %[b] \n\t"
" ser %[b] \n\t"
" mov %[dir], %[b] \n\t"
"1: mov r27, %[to] \n\t" // outer countdown high byte = window
" ori r27, %[actmin] \n\t" // lockout-proof floor
" clr r26 \n\t"
"2: ser %[b] \n\t"
"3: lds %[b], %[ucsr0a] \n\t"
" sbrc %[b], 7 \n\t" // RXC0
" rjmp 4f \n\t"
" dec %[b] \n\t"
" brne 3b \n\t"
" sbiw r26, 1 \n\t"
" brcc 2b \n\t"
" clr %[b] \n\t" // silence → 0, which no compare accepts
" rjmp 5f \n\t"
"4: lds %[b], %[udr0] \n\t"
"5: \n\t"
: [b] "=&d"(byte), [dir] "+r"(g_receiving)
: [to] "r"(g_window), [actmin] "M"(act_min), [ucsr0a] "n"(_SFR_MEM_ADDR(UCSR0A)),
[ucsr0b] "n"(_SFR_MEM_ADDR(UCSR0B)), [udr0] "n"(_SFR_MEM_ADDR(UDR0))
: "r26", "r27", "cc");
return byte;
}
// One-wire transmit: take the line (TXEN0 alone) on a direction change with a
// turn-around guard, put the byte out, hold the line until the whole frame is
// out (TXC0, not UDRE0), W1C TXC0 by storing the sampled status back (keeps
// U2X0). Plain C++ — it compiles *smaller* than the oracle's routine.
[[gnu::noinline, gnu::noclone]] void tx(std::uint8_t byte)
{
if (g_receiving) {
g_receiving = 0;
hw::ucsr0b::write(hw::ucsr0b::txen0(1));
for (std::uint8_t guard = 46; guard; --guard)
;
}
hw::udr0::write(byte);
std::uint8_t status;
do {
status = hw::ucsr0a::read();
} while (!(status & hw::ucsr0a::txc0(1).value));
hw::ucsr0a::write(status);
}
// '?', then hand back the host's reply for the callers' one-byte compare.
[[gnu::noinline, gnu::noclone]] std::uint8_t rcnf()
{
tx(request);
return rx();
}
// One flash byte ← [g_addr++] (the advance right before ret — the
// global-register rule, see tsb_tricks.cpp).
[[gnu::noinline, gnu::noclone]] std::uint8_t sflash()
{
std::uint8_t byte = avr::flash_load(flash_ptr(g_addr));
++g_addr;
return byte;
}
// One EEPROM byte ← [g_addr++].
[[gnu::noinline, gnu::noclone]] std::uint8_t eerd()
{
std::uint8_t byte = ee::read(g_addr);
++g_addr;
return byte;
}
// One EEPROM byte → [g_addr++].
[[gnu::noinline, gnu::noclone]] void eewr(std::uint8_t byte)
{
ee::write<off>(g_addr, byte);
++g_addr;
}
// Stream g_cnt flash bytes from g_addr to the host.
[[gnu::noinline, gnu::noclone]] void sendf()
{
do {
tx(sflash());
} while (--g_cnt);
}
// Wait out a running SPM op, then re-open the RWW section — after every page
// op and before handing over, as the oracle does.
[[gnu::noinline, gnu::noclone]] void settle()
{
spm::wait();
spm::rww_enable<off>();
}
extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --defsym=tsb_app=0
[[noreturn]] void appjump()
{
settle();
tsb_app();
}
// Step g_addr one page down and erase that page (the decrement lives here —
// the global-register rule).
[[gnu::noinline, gnu::noclone]] void erase_below()
{
g_addr -= page;
spm::erase_page<off>(g_addr);
settle();
}
// Erase the whole application, top-down like the oracle: the loop bound is a
// compare with zero, and g_addr = 0 is handed back for free.
[[gnu::noinline, gnu::noclone]] void erase_application()
{
g_addr = app_end;
do {
erase_below();
} while (g_addr != 0);
}
// Stream one host page into the erased flash page at g_addr (asm 2 of 2): the
// word pair stages in r0:r1 straight from rx (whose register set is known —
// the cross-call liveness C++ cannot express), Z walks the page and PGWRT
// programs it. g_addr is left at the next page base.
[[gnu::noinline, gnu::noclone]] void store_flash()
{
asm volatile(" movw r30, r28 \n\t" // Z = page base; rx leaves Z live
" ldi r20, %[words] \n\t"
"1: rcall %x[rx] \n\t"
" mov r0, r24 \n\t" // word low byte
" rcall %x[rx] \n\t"
" mov r1, r24 \n\t" // word high byte
" ldi r24, 0x01 \n\t" // SPMEN: buffer the word at Z
" 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"
" movw %[base], r30 \n\t" // g_addr = the next page base
" subi r30, %[pagelo] \n\t" // Z back to this page's base
" sbci r31, %[pagehi] \n\t"
" ldi r24, 0x05 \n\t" // PGWRT | SPMEN: program the page
" out %[spmcsr], r24 \n\t"
" spm \n\t"
: [base] "+r"(g_addr)
: [rx] "i"(&rx), [spmcsr] "I"(_SFR_IO_ADDR(SPMCSR)), [words] "M"(page / 2), [pagelo] "M"(page & 0xff),
[pagehi] "M"(page >> 8)
: "r0", "r1", "r20", "r24", "r26", "r27", "r30", "r31", "cc", "memory");
settle();
}
[[noreturn, gnu::noinline]] void run()
{
// A watchdog reset hands straight back to the application, as the
// reference loader does, rather than re-entering the bootloader.
if (hw::mcusr::wdrf.test())
appjump();
// Lean bring-up from reset state: UCSR0C already reads 8N1, UBRR0H reads
// 0, and rx()/tx() raise RXEN0/TXEN0 on first use — only the divisor low
// byte and U2X0 need a store. The library still does the datasheet work.
static_assert(baud.u2x && baud.ubrr < 256, "lean bring-up writes UBRR0L only, with U2X0");
hw::reg<"UBRR0">::write(static_cast<std::uint8_t>(baud.ubrr));
hw::ucsr0a::write(hw::ucsr0a::u2x0(1));
// General-purpose registers are undefined at power-on (no crt zeroes them);
// the direction latch must start "not receiving" so the first rx() enables
// the receiver. The reference loader clears its shadow register for the
// same reason.
g_receiving = 0;
// Activation: 3×'@', each inside the config page's timeout window (rx
// floors it so a corrupt page cannot lock the loader out); anything else —
// including silence — hands over.
g_window = avr::flash_load(flash_ptr(app_end + 2));
for (std::uint8_t k = 3; k; --k)
if (rx() != knock)
appjump();
g_window = comm_window;
// Password gate (config page from app_end+3, 0xff-terminated; a blank
// page is no password). A wrong byte blanks the comparison and drains the
// line forever, so a wrong password can never fall through; a 0 requests
// emergency erase behind two confirms. On pass the info block goes out;
// the emergency path skips it and drops into the command loop.
g_addr = app_end + 3;
std::uint8_t mask = 0xff;
for (;;) {
std::uint8_t expected = avr::flash_load(flash_ptr(g_addr)) & mask;
++g_addr;
if (expected == 0xff) {
g_addr = reinterpret_cast<std::uint16_t>(&info[0]);
g_cnt = sizeof(info);
sendf();
break;
}
std::uint8_t got = rx();
if (got == 0) {
if (mask == 0)
continue;
if (rcnf() != confirm || rcnf() != confirm)
appjump();
erase_application(); // leaves g_addr = 0 for the EEPROM walk
do {
eewr(0xff);
} while (g_addr <= eeprom_end);
g_addr = app_end + page;
erase_below();
break;
}
if (got != expected)
mask = 0;
}
for (;;) {
tx(confirm); // Mainloop ready
g_addr = 0;
switch (rx()) {
case 'f': // read application flash, one page per host '!'
for (;;) {
if (rx() != confirm)
break;
g_cnt = page;
sendf();
if (g_addr >= app_end)
break;
}
break;
case 'F': // erase the application, then take pages behind '?'
erase_application(); // leaves g_addr = 0, the write start
while (rcnf() == confirm)
store_flash();
break;
case 'e': // read EEPROM, one page per host '!', until the host stops
for (;;) {
if (rx() != confirm)
break;
g_cnt = page;
do {
tx(eerd());
} while (--g_cnt);
}
break;
case 'E': // take EEPROM pages behind '?'
while (rcnf() == confirm) {
g_cnt = page;
do {
eewr(rx());
} while (--g_cnt);
}
break;
case 'c': // read the config page
read_config:
g_addr = app_end;
g_cnt = page;
sendf();
break;
case 'C': // replace the config page, then echo it back to verify
if (rcnf() != confirm)
break;
g_addr = app_end + page;
erase_below(); // leaves g_addr = app_end, the store target
store_flash();
goto read_config;
default: // 'q' or any other byte runs the application
appjump();
}
}
}
} // namespace
} // namespace tsb } // namespace tsb
// Reset lands here: BOOTRST vectors to the boot base, .vectors is laid first, and // Reset lands here: BOOTRST vectors to the boot section base and .vectors is
// no crt runs. The stack pointer is the one piece of bring-up that reads as // laid first, so this is the first instruction executed. No crt ran, so set
// plainly in C++ as in assembler, so it is; the dense loader body follows. // the stack pointer before anything is called.
extern "C" [[gnu::naked, gnu::used, gnu::section(".vectors")]] void __boot_entry() extern "C" [[gnu::naked, gnu::used, gnu::section(".vectors")]] void __boot_entry()
{ {
SP = RAMEND; SP = RAMEND;
asm volatile( // The one line of crt this loader needs: compiled code assumes
// --- bring-up ------------------------------------------------------ // __zero_reg__ (r1) is 0, and power-on registers are undefined.
" in r16, %[mcusr] \n\t" // watchdog reset → hand straight back asm volatile("clr __zero_reg__");
" sbrc r16, 3 \n\t" // MCUSR bit 3 = WDRF tsb::run();
" rjmp 9f \n\t" // 9: = appjump (drains SPM, jumps to 0)
" 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
// Knock counter spent: reserve r17 = config-page high byte for every
// app-flash-boundary compare below (saves reloading it at each site).
" ldi r17, hi8(%[appcfg]) \n\t"
"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"
" cpc r31, r17 \n\t" // r17 = hi8(appcfg), reserved above
" 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"
" cpc r31, r17 \n\t" // r17 = hi8(appcfg), reserved above
" 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"
" cpc r31, r17 \n\t" // r17 = hi8(appcfg), reserved above
" 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"
:
: [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");
} }

View File

@@ -45,7 +45,7 @@ constexpr std::uint16_t app_end = spm::flash_bytes - boot_bytes - page;
constexpr std::uint16_t eeprom_end = avr::hw::db.mem.eeprom_size - 1; constexpr std::uint16_t eeprom_end = avr::hw::db.mem.eeprom_size - 1;
// Firmware version stamp: YY*512 + MM*32 + DD, the encoding the host decodes. // Firmware version stamp: YY*512 + MM*32 + DD, the encoding the host decodes.
constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 19; constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 20;
// The 16-byte device-info block the host reads on activation. A flash_table // The 16-byte device-info block the host reads on activation. A flash_table
// keeps it in progmem with no .data image (there is no crt to copy one). // keeps it in progmem with no .data image (there is no crt to copy one).
@@ -129,21 +129,27 @@ void erase_page(std::uint16_t addr)
spm::wait(); spm::wait();
} }
// Erase the whole application, one page at a time (unwritten pages stay erased). // Erase the whole application, one page at a time, top-down as the reference
// loader does (unwritten pages stay erased and the host cannot observe the
// order; the loop bound becomes a compare with zero).
void erase_application() void erase_application()
{ {
for (std::uint16_t a = 0; a < app_end; a += page) for (std::uint16_t a = app_end; a != 0;) {
a -= page;
erase_page(a); erase_page(a);
}
spm::rww_enable<off>(); spm::rww_enable<off>();
} }
// Run the application: reset vector at 0x0000. Any non-command byte, a wrong // The application's reset vector; the linker pins it to 0x0000 (--defsym).
// password, or an idle programmer port lands here. extern "C" [[noreturn]] void tsb_app();
// Run the application. Any non-command byte, a wrong password, or an idle
// programmer port lands here.
[[noreturn]] void appjump() [[noreturn]] void appjump()
{ {
spm::wait(); // make sure any pending SPM finished before handing over spm::wait(); // make sure any pending SPM finished before handing over
reinterpret_cast<void (*)()>(0)(); tsb_app();
__builtin_unreachable();
} }
// 'f': stream the application flash back, one page per host '!'. Self-terminates // 'f': stream the application flash back, one page per host '!'. Self-terminates
@@ -295,5 +301,8 @@ gate password_gate()
extern "C" [[gnu::naked, gnu::used, gnu::section(".vectors")]] void __boot_entry() extern "C" [[gnu::naked, gnu::used, gnu::section(".vectors")]] void __boot_entry()
{ {
SP = RAMEND; SP = RAMEND;
// The one line of crt this loader needs: compiled code assumes
// __zero_reg__ (r1) is 0, and power-on registers are undefined.
asm volatile("clr __zero_reg__");
tsb::run(); tsb::run();
} }

View File

@@ -1,19 +1,33 @@
// TinySafeBoot on libavr — tier 2: C++ with compiler trickery. // TinySafeBoot on libavr — tier 2: C++ with compiler trickery, no assembly.
// //
// Same protocol, libavr surface and full feature set as the pure variant // The full TinySafeBoot feature set — watchdog bail, one-wire half-duplex,
// (tsb_pure.cpp) — watchdog bail, one-wire, config-page timeout, password gate, // config-page activation timeout, password gate, emergency erase, and
// emergency erase, config/flash/EEPROM read-write — but the readable // config/flash/EEPROM read-write — in pure C++, 526 bytes: 14 over the 512-byte
// one-handler-per-command shape is traded for size. Flash and EEPROM share a // boot section the hand-written oracle fits, from 168 over at this tier's first
// single code path selected by a *runtime* flag decoded from the command byte, // floor. The structure mirrors the oracle's: a handful of tiny noinline
// so the compiler cannot constant-propagate it into two clones; attributes // primitives sharing one whole-loader register allocation, expressed as global
// (noinline/noclone) pin that genuinely-shared sharing down, while every handler // register variables so no helper ever saves, spills, or reloads any of it.
// that is called only once is `always_inline`d into run() — which, being //
// [[noreturn]] and entered from the naked reset vector, pays no prologue/epilogue, // The register protocol (all call-saved, so calls preserve them by ABI):
// so their push/pop of call-saved registers vanishes. The hot page address lives // Y (r28:r29) g_addr the walked flash/EEPROM address — adiw-able
// in the Y register (call-saved and adiw-able) so it is walked, not respilled; // r16 g_cnt byte countdown of the running block — ldi-able
// pages stream straight to SPM/EEPROM with no SRAM staging; and the bring-up // r7 g_window rx timeout, roughly 30 ms units at 16 MHz
// writes only the two registers that are not already at their reset value. No // r6 g_receiving one-wire direction latch, cleared at bring-up
// inline assembly. // (power-on registers are undefined)
//
// GCC 16.1 miscompiles stores into global register variables: an update whose
// remaining uses all hide inside callees is deleted whenever a CALL follows it
// before any jump/ret (the backend's liveness walk lumps fixed registers with
// call-clobbered ones — minimal repro in libavr's
// local/scratch/probes/gcc-avr-globalreg-repro.cpp, lessons.md entry). Every
// g_* update below therefore sits where a *local* read or a jump/ret follows
// it — the helpers advance g_addr immediately before returning, and rx()
// re-floors the window on every call instead of storing the floored value
// once. The layout is load-bearing; do not "simplify" it.
//
// The wire protocol is strict request/response, which is what makes the shared
// line safe: the device drives it only between a received command and its
// reply, and releases it (RXEN0 only) whenever it waits.
#include <libavr/libavr.hpp> #include <libavr/libavr.hpp>
@@ -22,281 +36,328 @@
using namespace avr::literals; using namespace avr::literals;
namespace spm = avr::spm; namespace spm = avr::spm;
namespace ee = avr::eeprom; namespace ee = avr::eeprom;
namespace hw = avr::hw;
using dev = avr::device<{.clock = 16_MHz}>;
using serial_t = dev::uart0<{.baud = 115200_Bd, .max_baud_error = 3_pct, .half_duplex = true}>;
inline constexpr serial_t serial{};
namespace tsb { namespace tsb {
namespace {
// The loader is purely polled — it never enables interrupts — so every SPM and
// EEPROM lock folds to nothing under this posture.
constexpr auto off = avr::irq::guard_policy::unused; constexpr auto off = avr::irq::guard_policy::unused;
constexpr std::uint8_t confirm = '!'; constexpr std::uint8_t confirm = '!';
constexpr std::uint8_t request = '?'; constexpr std::uint8_t request = '?';
constexpr std::uint8_t knock = '@'; constexpr std::uint8_t knock = '@';
// Boot geometry for the 1 KB boot section (BOOTSZ=10); the page size and the
// flash/EEPROM extents are the chip database's to know. app_end is the config
// page (TSB's LASTPAGE), one page below the boot section.
constexpr std::uint16_t page = spm::page_bytes; constexpr std::uint16_t page = spm::page_bytes;
constexpr std::uint16_t boot_bytes = 1024; constexpr std::uint16_t boot_bytes = 1024;
constexpr std::uint16_t app_end = spm::flash_bytes - boot_bytes - page; constexpr std::uint16_t app_end = spm::flash_bytes - boot_bytes - page;
constexpr std::uint16_t eeprom_end = avr::hw::db.mem.eeprom_size - 1; constexpr std::uint16_t eeprom_end = avr::hw::db.mem.eeprom_size - 1;
constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 19; // Lockout-proof floor for the activation window (the oracle's F_CPU/1MHz).
constexpr std::uint8_t act_min = 16;
// Post-activation window: the host gets seconds, not milliseconds, mid-session.
constexpr std::uint8_t comm_window = 200;
constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 20;
// Fixed 115200 8N1; the library solves UBRR + U2X from clock and baud. // Fixed 115200 8N1; the library solves UBRR + U2X from clock and baud.
constexpr auto baud = avr::uart::detail::solve_baud(16_MHz, 115200_Bd); constexpr auto baud = avr::uart::detail::solve_baud(16_MHz, 115200_Bd);
// The 16-byte device-info block, streamed out on activation.
// clang-format off // clang-format off
[[gnu::progmem]] constexpr std::uint8_t info[16] = { [[gnu::progmem]] constexpr std::uint8_t info[16] = {
'T', 'S', 'B', 'T', 'S', 'B',
build_date & 0xFF, build_date >> 8, build_date & 0xFF, build_date >> 8,
0xF3, 0xF3, // status: native-UART fixed-baud lineage
0x1E, 0x95, 0x0F, 0x1E, 0x95, 0x0F, // ATmega328P signature
page / 2, page / 2, // page size in words
(app_end / 2) & 0xFF, (app_end / 2) >> 8, (app_end / 2) & 0xFF, (app_end / 2) >> 8,
eeprom_end & 0xFF, eeprom_end >> 8, eeprom_end & 0xFF, eeprom_end >> 8,
0xAA, 0xAA, 0xAA, 0xAA,
}; };
// clang-format on // clang-format on
// The hot page walk lives in call-saved global registers, TSB-style: g_addr is
// the running flash/EEPROM byte address, g_cnt the byte countdown. Being global
// they are never spilled around the rx/tx/spm calls the way a local would be —
// the library's UART and SPM helpers preserve the call-saved registers. g_addr
// takes Y (r28:r29): call-saved like any low pair, but also adiw-able and
// directly immediate-arithmetic-able, so advancing it is one instruction where a
// low pair would need a copy into a high register first.
register std::uint16_t g_addr asm("r28"); register std::uint16_t g_addr asm("r28");
register std::uint8_t g_cnt asm("r6"); register std::uint8_t g_cnt asm("r16");
register std::uint8_t g_window asm("r7");
std::uint8_t rx() register std::uint8_t g_receiving asm("r6");
{
return serial.read_blocking();
}
void tx(std::uint8_t byte)
{
serial.write(byte);
}
const std::uint8_t *flash_ptr(std::uint16_t addr) const std::uint8_t *flash_ptr(std::uint16_t addr)
{ {
return reinterpret_cast<const std::uint8_t *>(addr); return reinterpret_cast<const std::uint8_t *>(addr);
} }
// Stream g_cnt bytes to the host from flash (LPM) or EEPROM, memory chosen at // Bounded byte receive, the oracle's shape: release the one-wire line on a
// run time so the optimiser cannot split the loop into two clones. // direction change, poll RXC0 under nested countdowns, 0 on silence. The 0
[[gnu::noinline, gnu::noclone]] void send(bool flash) // then falls through every compare — not a knock, not a confirm, not a
// command — so a silent host unwinds the loader to the application from
// anywhere, and a mid-session cable pull cannot wedge it.
[[gnu::noinline, gnu::noclone]] std::uint8_t rx()
{
if (!g_receiving) {
g_receiving = 1;
hw::ucsr0b::write(hw::ucsr0b::rxen0(1)); // RXEN0 alone: release and listen
}
// act_min ORs in here, per call, not once into g_window at setup — the
// one placement the global-register-store miscompile cannot delete.
std::uint16_t outer = static_cast<std::uint16_t>(g_window | act_min) << 8;
do {
std::uint8_t fine = 0;
do {
auto status = hw::ucsr0a::read();
if (status & hw::ucsr0a::rxc0(1).value)
return hw::udr0::read();
} while (--fine);
} while (--outer);
return 0;
}
// One-wire transmit: take the line (TXEN0 alone — the receiver must be off
// while driving) on a direction change, with a turn-around guard so a shorted
// peer can switch first; then hold the line until the whole frame is out
// (TXC0, not UDRE0 — the stop bit must be on the wire before a caller may
// release the line), and W1C TXC0 by storing the sampled status back, which
// keeps U2X0.
[[gnu::noinline, gnu::noclone]] void tx(std::uint8_t byte)
{
if (g_receiving) {
g_receiving = 0;
hw::ucsr0b::write(hw::ucsr0b::txen0(1));
for (std::uint8_t guard = 46; guard; --guard)
;
}
hw::udr0::write(byte);
std::uint8_t status;
do {
status = hw::ucsr0a::read();
} while (!(status & hw::ucsr0a::txc0(1).value));
hw::ucsr0a::write(status);
}
// '?', then hand back the host's reply for the callers' one-byte compare.
[[gnu::noinline, gnu::noclone]] std::uint8_t rcnf()
{
tx(request);
return rx();
}
// One flash byte ← [g_addr++] (the advance right before ret — see header).
[[gnu::noinline, gnu::noclone]] std::uint8_t sflash()
{
std::uint8_t byte = avr::flash_load(flash_ptr(g_addr));
++g_addr;
return byte;
}
// One EEPROM byte ← [g_addr++].
[[gnu::noinline, gnu::noclone]] std::uint8_t eerd()
{
std::uint8_t byte = ee::read(g_addr);
++g_addr;
return byte;
}
// One EEPROM byte → [g_addr++].
[[gnu::noinline, gnu::noclone]] void eewr(std::uint8_t byte)
{
ee::write<off>(g_addr, byte);
++g_addr;
}
// Stream g_cnt flash bytes from g_addr to the host.
[[gnu::noinline, gnu::noclone]] void sendf()
{ {
do { do {
tx(flash ? avr::flash_load(flash_ptr(g_addr)) : ee::read(g_addr)); tx(sflash());
++g_addr;
} while (--g_cnt); } while (--g_cnt);
} }
[[gnu::noinline]] bool request_confirm() // Wait out a running SPM op, then re-open the RWW section — after every page
{ // op and before handing over, as the oracle does.
tx(request); [[gnu::noinline, gnu::noclone]] void settle()
return rx() == confirm;
}
// Stream one page straight from the host into the already-erased flash page at
// g_addr (SPM word buffer, low byte then high) or into EEPROM — no SRAM staging,
// so receive and store are one loop. The memory is a run-time flag.
// g_addr walks the page (adiw on Y) and is left at the next page base, so the
// caller advances nothing. write_page needs the base, recovered as g_addr-page.
[[gnu::noinline, gnu::noclone]] void store_page(bool flash)
{
if (flash) {
g_cnt = page / 2;
do {
std::uint8_t lo = rx();
std::uint8_t hi = rx();
spm::fill<off>(g_addr, static_cast<std::uint16_t>(lo | (hi << 8)));
g_addr += 2;
} while (--g_cnt);
spm::write_page<off>(g_addr - page);
spm::wait();
} else {
g_cnt = page;
do {
ee::write<off>(g_addr, rx());
++g_addr;
} while (--g_cnt);
}
}
[[noreturn]] void appjump()
{ {
spm::wait(); spm::wait();
reinterpret_cast<void (*)()>(0)();
__builtin_unreachable();
}
// One flash page erased and waited out. Shared, so the SPM erase command
// sequence is emitted once for the whole-app erase, the config page and the
// emergency wipe rather than three times.
[[gnu::noinline]] void erase1(std::uint16_t addr)
{
spm::erase_page<off>(addr);
spm::wait();
}
// Re-enable RWW flash reads after programming, shared for the same reason.
[[gnu::noinline]] void rww()
{
spm::rww_enable<off>(); spm::rww_enable<off>();
} }
// Erase the whole application, one page at a time. extern "C" [[noreturn]] void tsb_app(); // the application's reset vector: --defsym=tsb_app=0
[[gnu::noinline]] void erase_application()
[[noreturn]] void appjump()
{ {
g_addr = 0; settle();
do { tsb_app();
erase1(g_addr);
g_addr += page;
} while (g_addr < app_end);
rww();
} }
// 'f'/'e': stream memory back one page per host '!'. send advances g_addr, so // Step g_addr one page down and erase that page. The decrement lives in here,
// flash self-terminates at the application boundary; EEPROM runs until the host // before the erase's own use of it, not in the caller's loop where a following
// stops. // call would get it deleted (see header).
[[gnu::always_inline]] inline void read_mem(bool flash) [[gnu::noinline, gnu::noclone]] void erase_below()
{ {
g_addr = 0; g_addr -= page;
for (;;) { spm::erase_page<off>(g_addr);
if (rx() != confirm) settle();
return;
g_cnt = page;
send(flash);
if (flash && g_addr >= app_end)
return;
}
} }
// 'F'/'E': flash erases the whole application first, then both take the pages // Erase the whole application, top-down like the oracle: the loop bound is a
// the host offers behind '?'. // compare with zero, and g_addr = 0 — the value every caller wants next — is
[[gnu::always_inline]] inline void write_mem(bool flash) // handed back for free.
[[gnu::noinline, gnu::noclone]] void erase_application()
{ {
if (flash)
erase_application();
g_addr = 0;
while (request_confirm())
store_page(flash);
}
// 'C': replace the config page, then echo it back for the host to verify.
[[gnu::always_inline]] inline void write_config()
{
if (!request_confirm())
return;
g_addr = app_end; g_addr = app_end;
erase1(g_addr);
store_page(true);
rww();
g_addr = app_end;
g_cnt = page;
send(true);
}
// Emergency erase: wipe the application flash, the EEPROM and the config page.
[[gnu::always_inline]] inline void emergency_erase()
{
erase_application();
g_addr = 0;
do { do {
ee::write<off>(g_addr, 0xff); erase_below();
} while (++g_addr <= eeprom_end); } while (g_addr != 0);
erase1(app_end);
rww();
} }
// The password gate. A byte of 0 requests emergency erase; a wrong byte hangs // Stream one host page into the erased flash page at g_addr (SPM word buffer,
// the loader (still draining the line), so it can never fall through to erase. // low byte then high) — no SRAM staging, receive and program are one loop.
enum class gate : std::uint8_t { pass, emergency }; // g_addr is left at the next page base.
[[gnu::noinline, gnu::noclone]] void store_flash()
[[gnu::always_inline]] inline gate password_gate()
{ {
for (const std::uint8_t *pw = flash_ptr(app_end + 3);; ++pw) { g_cnt = page / 2;
std::uint8_t expected = avr::flash_load(pw); do {
if (expected == 0xff) std::uint16_t word = rx();
return gate::pass; word |= static_cast<std::uint16_t>(rx()) << 8;
std::uint8_t got = rx(); spm::fill<off>(g_addr, word);
if (got == 0) g_addr += 2;
return gate::emergency; } while (--g_cnt);
if (got != expected) spm::write_page<off>(g_addr - page);
for (;;) settle();
rx();
}
} }
[[noreturn]] void run() [[noreturn, gnu::noinline]] void run()
{ {
if (avr::hw::mcusr::wdrf.test()) // A watchdog reset hands straight back to the application, as the
// reference loader does, rather than re-entering the bootloader.
if (hw::mcusr::wdrf.test())
appjump(); appjump();
// Lean bring-up: at reset UCSR0C already reads 8N1 and UBRR0H reads 0, and // Lean bring-up from reset state: UCSR0C already reads 8N1, UBRR0H reads
// read()/write() enable RXEN0/TXEN0 on first use, so only the baud divisor low // 0, and rx()/tx() raise RXEN0/TXEN0 on first use only the divisor low
// byte (it fits 8 bits — see the static_assert) and U2X0 must be written. The // byte and U2X0 need a store. The library still does the datasheet work.
// library surface still does the datasheet work.
static_assert(baud.u2x && baud.ubrr < 256, "lean bring-up writes UBRR0L only, with U2X0"); static_assert(baud.u2x && baud.ubrr < 256, "lean bring-up writes UBRR0L only, with U2X0");
avr::hw::reg<"UBRR0">::write(static_cast<std::uint8_t>(baud.ubrr)); hw::reg<"UBRR0">::write(static_cast<std::uint8_t>(baud.ubrr));
avr::hw::ucsr0a::write(avr::hw::ucsr0a::u2x0(1)); hw::ucsr0a::write(hw::ucsr0a::u2x0(1));
// General-purpose registers are undefined at power-on (no crt zeroes them);
// the direction latch must start "not receiving" so the first rx() enables
// the receiver. The reference loader clears its shadow register for the
// same reason.
g_receiving = 0;
__uint24 idle = static_cast<__uint24>(avr::flash_load(flash_ptr(app_end + 2)) | 16) << 16; // Activation: 3×'@', each inside the config page's timeout window (rx
std::uint8_t knocks = 0; // floors it so a corrupt page cannot lock the loader out); anything else —
while (knocks < 3) { // including silence — hands over.
if (auto byte = serial.read()) g_window = avr::flash_load(flash_ptr(app_end + 2));
knocks = *byte == knock ? knocks + 1 : 0; for (std::uint8_t k = 3; k; --k)
else if (--idle == 0) if (rx() != knock)
appjump(); appjump();
} g_window = comm_window;
switch (password_gate()) { // Password gate (config page from app_end+3, 0xff-terminated; a blank
case gate::pass: // page is no password). A wrong byte blanks the comparison and drains the
g_addr = reinterpret_cast<std::uint16_t>(&info[0]); // line forever, so a wrong password can never fall through; a 0 requests
g_cnt = sizeof(info); // emergency erase behind two confirms. On pass the info block goes out;
send(true); // the emergency path skips it and drops into the command loop.
break; g_addr = app_end + 3;
case gate::emergency: std::uint8_t mask = 0xff;
if (!request_confirm() || !request_confirm()) for (;;) {
appjump(); std::uint8_t expected = avr::flash_load(flash_ptr(g_addr)) & mask;
emergency_erase(); ++g_addr;
break; if (expected == 0xff) {
g_addr = reinterpret_cast<std::uint16_t>(&info[0]);
g_cnt = sizeof(info);
sendf();
break;
}
std::uint8_t got = rx();
if (got == 0) {
if (mask == 0)
continue;
if (rcnf() != confirm || rcnf() != confirm)
appjump();
erase_application(); // leaves g_addr = 0 for the EEPROM walk
do {
eewr(0xff);
} while (g_addr <= eeprom_end);
g_addr = app_end + page;
erase_below();
break;
}
if (got != expected)
mask = 0;
} }
for (;;) { for (;;) {
tx(confirm); // Mainloop ready tx(confirm); // Mainloop ready
// Decode the command arithmetically so flash/write stay run-time values: g_addr = 0;
// bit 5 is the case bit (upper = write), the folded-lower letter picks the switch (rx()) {
// memory. A single unified path serves f/F/e/E. case 'f': // read application flash, one page per host '!'
std::uint8_t cmd = rx(); for (;;) {
std::uint8_t lower = cmd | 0x20; if (rx() != confirm)
bool write = (cmd & 0x20) == 0; break;
if (lower == 'f' || lower == 'e') {
bool flash = lower == 'f';
if (write)
write_mem(flash);
else
read_mem(flash);
} else if (lower == 'c') {
if (write) {
write_config();
} else {
g_addr = app_end;
g_cnt = page; g_cnt = page;
send(true); sendf();
if (g_addr >= app_end)
break;
} }
} else { break;
case 'F': // erase the application, then take pages behind '?'
erase_application(); // leaves g_addr = 0, the write start
while (rcnf() == confirm)
store_flash();
break;
case 'e': // read EEPROM, one page per host '!', until the host stops
for (;;) {
if (rx() != confirm)
break;
g_cnt = page;
do {
tx(eerd());
} while (--g_cnt);
}
break;
case 'E': // take EEPROM pages behind '?'
while (rcnf() == confirm) {
g_cnt = page;
do {
eewr(rx());
} while (--g_cnt);
}
break;
case 'c': // read the config page
read_config:
g_addr = app_end;
g_cnt = page;
sendf();
break;
case 'C': // replace the config page, then echo it back to verify
if (rcnf() != confirm)
break;
g_addr = app_end + page;
erase_below(); // leaves g_addr = app_end, the store target
store_flash();
goto read_config;
default: // 'q' or any other byte runs the application
appjump(); appjump();
} }
} }
} }
} // namespace
} // namespace tsb } // namespace tsb
// Reset lands here: BOOTRST vectors to the boot section base and .vectors is
// laid first, so this is the first instruction executed. No crt ran, so set
// the stack pointer before anything is called.
extern "C" [[gnu::naked, gnu::used, gnu::section(".vectors")]] void __boot_entry() extern "C" [[gnu::naked, gnu::used, gnu::section(".vectors")]] void __boot_entry()
{ {
SP = RAMEND; SP = RAMEND;
// The one line of crt this loader needs: compiled code assumes
// __zero_reg__ (r1) is 0, and power-on registers are undefined.
asm volatile("clr __zero_reg__");
tsb::run(); tsb::run();
} }