tsb: pure and tricks tiers reach full oracle feature parity

Both tiers gain the features the asm tier already carries — one-wire
half-duplex (via libavr's new .half_duplex), the config-page activation
timeout, and emergency erase (password \0 + double-confirm wipes flash,
EEPROM and the config page) — on top of the watchdog bail, password gate and
config/flash/EEPROM read-write they already had. pure stays idiomatic
(flash_table info block, one function per command) at 950 B; tricks keeps its
compiler trickery (call-saved global-register page walk, unified runtime-flag
paths pinned noinline/noclone, streaming stores, arithmetic command decode)
at 808 B. Both byte-identical across generated and reflect modes; the size
gradient across the three tiers is now 502 / 808 / 950 B.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-19 16:47:21 +02:00
parent 3ea8957e69
commit 3a0d3790ee
2 changed files with 180 additions and 116 deletions

View File

@@ -1,17 +1,14 @@
// TinySafeBoot on libavr — tier 1: pure, idiomatic C++.
//
// A ≤512-byte serial flash bootloader for the ATmega328P boot section,
// reimplementing the TinySafeBoot wire protocol (native-UART fixed-baud
// lineage) on libavr. This variant is written for clarity: well-factored
// functions, no compiler-specific size hacks, no inline assembly. The only
// attribute is the one the task inherently needs — the naked reset entry that
// stands in for the absent C runtime; the flash-resident info block is a libavr
// flash_table.
//
// The structure follows the hand-written reference: one SRAM page buffer that
// every page transfer shares, separate flash/EEPROM leaf routines (so nothing
// is duplicated by constant propagation), and the polled `unused` interrupt
// posture so every SPM/EEPROM lock folds away.
// A serial flash bootloader for the ATmega328P boot section, reimplementing the
// TinySafeBoot native-UART fixed-baud protocol on libavr with the full feature
// set of the hand-written oracle: a watchdog-reset bail, one-wire half-duplex,
// a config-page activation timeout, the password gate, emergency erase, and
// config/flash/EEPROM read-write. This variant is written for clarity —
// well-factored functions, no compiler-specific size hacks, no inline assembly.
// The one-wire wiring, the flash-resident info block and every SPM/EEPROM lock
// are libavr's to handle; the only attribute is the naked reset entry that
// stands in for the absent C runtime.
#include <libavr/libavr.hpp>
@@ -22,7 +19,8 @@ namespace spm = avr::spm;
namespace ee = avr::eeprom;
using dev = avr::device<{.clock = 16_MHz}>;
using serial_t = dev::uart0<{.baud = 115200_Bd, .max_baud_error = 3_pct}>;
// One-wire: RX and TX share the line, exactly as the native-UART TSB expects.
using serial_t = dev::uart0<{.baud = 115200_Bd, .max_baud_error = 3_pct, .half_duplex = true}>;
inline constexpr serial_t serial{};
namespace tsb {
@@ -31,15 +29,15 @@ namespace tsb {
// EEPROM lock folds to nothing under this posture.
constexpr auto off = avr::irq::guard_policy::unused;
// The two handshake bytes, identical across every TSB host.
// The handshake bytes, identical across every TSB host.
constexpr std::uint8_t confirm = '!';
constexpr std::uint8_t request = '?';
constexpr std::uint8_t knock = '@';
// Boot geometry for the ATmega328P 512-byte boot section (BOOTSZ=11). The page
// size, flash and EEPROM extents are the chip database's to know. app_end is
// both the first byte the loader protects and the config page (the LASTPAGE
// holding app-jump vector, timeout and password), one page below the boot
// section.
// 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 (the LASTPAGE holding the app-jump vector, activation timeout and
// password), one page below the boot section.
constexpr std::uint16_t page = spm::page_bytes;
constexpr std::uint16_t boot_bytes = 1024;
constexpr std::uint16_t app_end = spm::flash_bytes - boot_bytes - page;
@@ -49,8 +47,7 @@ constexpr std::uint16_t eeprom_end = avr::hw::db.mem.eeprom_size - 1;
constexpr std::uint16_t build_date = 26 * 512 + 7 * 32 + 19;
// 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) and
// reads it back through LPM.
// keeps it in progmem with no .data image (there is no crt to copy one).
// clang-format off
inline constexpr std::array<std::uint8_t, 16> info_data = {
'T', 'S', 'B',
@@ -66,15 +63,14 @@ inline constexpr std::array<std::uint8_t, 16> info_data = {
using info = avr::flash_table<info_data>;
// One page staged in SRAM. Scratch that is always filled before it is read, so
// it lives in .noinit — no startup clear (there is no crt to run one) and no
// bytes in .text, which is the only thing the boot-section budget counts.
// it lives in .noinit — no startup clear (there is no crt) and no .text bytes.
[[gnu::section(".noinit")]] std::uint8_t buffer[page];
// Blocking byte read/write over the one-wire line: read() releases the line to
// the receiver, write() takes it and holds it until the frame is out.
std::uint8_t rx()
{
for (;;)
if (auto byte = serial.read())
return *byte;
return serial.read_blocking();
}
void tx(std::uint8_t byte)
@@ -130,6 +126,16 @@ void write_eeprom_page(std::uint16_t addr)
ee::write<off>(addr + i, buffer[i]);
}
// Erase the whole application, one page at a time (unwritten pages stay erased).
void erase_application()
{
for (std::uint16_t a = 0; a < app_end; a += page) {
spm::erase_page<off>(a);
spm::wait();
}
spm::rww_enable<off>();
}
// Run the application: reset vector at 0x0000. Any non-command byte, a wrong
// password, or an idle programmer port lands here.
[[noreturn]] void appjump()
@@ -160,19 +166,15 @@ void read_eeprom()
}
}
// 'F': erase the whole application first (unwritten pages stay erased), then
// take pages the host offers behind '?'.
// 'F': erase the whole application first, then take pages the host offers
// behind '?'.
void write_flash()
{
for (std::uint16_t a = 0; a < app_end; a += page) {
spm::erase_page<off>(a);
spm::wait();
}
erase_application();
for (std::uint16_t a = 0; request_confirm(); a += page) {
get_page();
write_flash_page(a);
}
spm::rww_enable<off>();
}
// 'E': take pages the host offers behind '?' into EEPROM.
@@ -197,36 +199,71 @@ void write_config()
send_flash(app_end, page);
}
// Emergency erase: wipe the application flash, the EEPROM and the config page.
// Reachable only from the password gate (a wrong byte can never reach it), so a
// blank config still leaves the loader recoverable.
void emergency_erase()
{
erase_application();
for (std::uint16_t a = 0; a <= eeprom_end; ++a)
ee::write<off>(a, 0xff);
spm::erase_page<off>(app_end);
spm::wait();
spm::rww_enable<off>();
}
// The password gate. The config page holds the password at app_end+3,
// terminated by 0xff (a blank page means no password). A byte of 0 requests
// emergency erase; a wrong byte hangs the loader, still draining the line, so a
// wrong password can never fall through to the erase.
enum class gate : std::uint8_t { pass, emergency };
gate password_gate()
{
for (const std::uint8_t *pw = flash_ptr(app_end + 3);; ++pw) {
std::uint8_t expected = avr::flash_load(pw);
if (expected == 0xff)
return gate::pass;
std::uint8_t got = rx();
if (got == 0)
return gate::emergency;
if (got != expected)
for (;;)
rx();
}
}
[[noreturn]] void run()
{
// A bootloader may be entered by a watchdog reset; the reference loader
// hands straight back to the application in that case rather than run.
// A watchdog reset hands straight back to the application, as the reference
// loader does, rather than re-entering the bootloader.
if (avr::hw::mcusr::wdrf.test())
appjump();
avr::init<serial_t>();
// Activation: the host knocks three '@'. With no programmer attached the
// port stays idle, so a bounded wait boots the application instead of
// hanging forever.
// Activation: the host knocks three '@' inside a window whose length is the
// config page's timeout byte (floored so a corrupt page can never lock the
// loader out). An idle port times out and boots the application.
std::uint32_t idle = static_cast<std::uint32_t>(avr::flash_load(flash_ptr(app_end + 2)) | 16) << 16;
std::uint8_t knocks = 0;
std::uint32_t idle = 4000000;
while (knocks < 3) {
if (auto byte = serial.read())
knocks = *byte == '@' ? knocks + 1 : 0;
knocks = *byte == knock ? knocks + 1 : 0;
else if (--idle == 0)
appjump();
}
// Password gate: the config page holds it at app_end+3, terminated by 0xff.
// A blank page (0xff there) means no password. A wrong byte hangs the loader
// silently, as TSB does.
for (const std::uint8_t *pw = flash_ptr(app_end + 3); avr::flash_load(pw) != 0xff; ++pw)
if (rx() != avr::flash_load(pw))
for (;;) {
}
send_flash(reinterpret_cast<std::uint16_t>(info::storage.data()), info::size());
switch (password_gate()) {
case gate::pass:
send_flash(reinterpret_cast<std::uint16_t>(info::storage.data()), info::size());
break;
case gate::emergency:
if (!request_confirm() || !request_confirm())
appjump();
emergency_erase();
break;
}
for (;;) {
tx(confirm); // Mainloop ready