Files
bootloader/tsb/tsb_pure.cpp
BlackMark 57d94cf631 tsb: refactor the pure tier onto libavr sugar
The showcase tier now leans on the helpers it fed back instead of reaching under
them: the info block is an avr::flash_table (no raw [[gnu::progmem]]), a page is
filled with spm::fill(addr, span) (no hand-packed lo|hi<<8 loop), and the
WDT-reset bail reads field<"MCUSR","WDRF">::test() (no read() & {}(1).value).

Zero-overhead throughout: .text stays 740 B, byte-identical across generated and
reflect modes, protocol test green. The info block streams through the existing
address-based send_flash rather than a range-for over the flash_table — the
range-for is a distinct loop that cannot share the loader's one flash streamer,
so it would add 14 B for no functional gain.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-19 13:33:53 +02:00

268 lines
7.7 KiB
C++

// 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.
#include <libavr/libavr.hpp>
#include <avr/io.h> // SP / RAMEND for the crt-free boot entry
using namespace avr::literals;
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}>;
inline constexpr serial_t serial{};
namespace tsb {
// 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;
// The two handshake bytes, identical across every TSB host.
constexpr std::uint8_t confirm = '!';
constexpr std::uint8_t request = '?';
// 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.
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;
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.
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.
// clang-format off
inline constexpr std::array<std::uint8_t, 16> info_data = {
'T', 'S', 'B',
build_date & 0xFF, build_date >> 8,
0xF3, // status byte (native-UART fixed-baud lineage)
0x1E, 0x95, 0x0F, // ATmega328P signature
page / 2, // page size in words
(app_end / 2) & 0xFF, (app_end / 2) >> 8, // app-flash boundary, words
eeprom_end & 0xFF, eeprom_end >> 8,
0xAA, 0xAA, // ATmega processor-type marker (bytes 14 == 15)
};
// clang-format on
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.
[[gnu::section(".noinit")]] std::uint8_t buffer[page];
std::uint8_t rx()
{
for (;;)
if (auto byte = serial.read())
return *byte;
}
void tx(std::uint8_t byte)
{
serial.write(byte);
}
const std::uint8_t *flash_ptr(std::uint16_t addr)
{
return reinterpret_cast<const std::uint8_t *>(addr);
}
// Stream `count` bytes to the host, from flash (LPM) or from EEPROM.
void send_flash(std::uint16_t addr, std::uint16_t count)
{
while (count--)
tx(avr::flash_load(flash_ptr(addr++)));
}
void send_eeprom(std::uint16_t addr, std::uint16_t count)
{
while (count--)
tx(ee::read(addr++));
}
// Take one page from the host into the SRAM buffer.
void get_page()
{
for (std::uint16_t i = 0; i < page; ++i)
buffer[i] = rx();
}
// Prompt the host with '?' and report whether it answered '!'.
bool request_confirm()
{
tx(request);
return rx() == confirm;
}
// Program the SRAM buffer into one already-erased flash page (low byte then
// high, as the SPM word buffer wants).
void write_flash_page(std::uint16_t addr)
{
spm::fill<off>(addr, std::span<const std::uint8_t>{buffer, page});
spm::write_page<off>(addr);
spm::wait();
}
// Write the SRAM buffer into EEPROM byte by byte.
void write_eeprom_page(std::uint16_t addr)
{
for (std::uint16_t i = 0; i < page; ++i)
ee::write<off>(addr + i, buffer[i]);
}
// Run the application: reset vector at 0x0000. Any non-command byte, a wrong
// password, or an idle programmer port lands here.
[[noreturn]] void appjump()
{
spm::wait(); // make sure any pending SPM finished before handing over
reinterpret_cast<void (*)()>(0)();
__builtin_unreachable();
}
// 'f': stream the application flash back, one page per host '!'. Self-terminates
// at the application boundary; the host normally stops earlier with a non-'!'.
void read_flash()
{
for (std::uint16_t a = 0; a < app_end; a += page) {
if (rx() != confirm)
return;
send_flash(a, page);
}
}
// 'e': stream EEPROM back, one page per host '!', until the host stops.
void read_eeprom()
{
for (std::uint16_t a = 0;; a += page) {
if (rx() != confirm)
return;
send_eeprom(a, page);
}
}
// 'F': erase the whole application first (unwritten pages stay erased), 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();
}
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.
void write_eeprom()
{
for (std::uint16_t a = 0; request_confirm(); a += page) {
get_page();
write_eeprom_page(a);
}
}
// 'C': replace the config page, then echo it back for the host to verify.
void write_config()
{
if (!request_confirm())
return;
get_page();
spm::erase_page<off>(app_end);
spm::wait();
write_flash_page(app_end);
spm::rww_enable<off>();
send_flash(app_end, page);
}
[[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.
if (avr::hw::field<"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.
std::uint8_t knocks = 0;
std::uint32_t idle = 4000000;
while (knocks < 3) {
if (auto byte = serial.read())
knocks = *byte == '@' ? 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());
for (;;) {
tx(confirm); // Mainloop ready
switch (rx()) {
case 'f':
read_flash();
break;
case 'F':
write_flash();
break;
case 'e':
read_eeprom();
break;
case 'E':
write_eeprom();
break;
case 'c':
send_flash(app_end, page);
break;
case 'C':
write_config();
break;
default:
appjump(); // 'q' or any other byte runs the application
}
}
}
} // 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()
{
SP = RAMEND;
tsb::run();
}