Designing AVR bootloader with double buffering
Planning a bootloader for AVR (e.g., ATmega328P) using two firmware slots with a safe update flow: receive new firmware into a staging flash area, verify CRC, then copy page-by-page to application area while tracking progress in EEPROM to survive power loss mid-copy, ensuring the bootloader itself remains intact and avoids bricking.
On an AVR the boot loader lives in a dedicated “boot section” at the top of flash and can use the SPM instructions to erase/write application pages. If you set the BOOTRST fuse the reset vector will always go to the boot loader first, so even if the application area is corrupted the device will still come up in the boot loader.
To survive a power failure during an update you need to avoid destroying the currently‑working application until you have a complete, verified replacement. With only one application slot the usual pattern is:
- Download the new image into a scratch area (either in flash above the application or in external memory).
- Verify its CRC.
- Mark “commit pending” in EEPROM.
- Copy page‑by‑page from the scratch area into the application area. On each reset if the EEPROM flag is set the boot loader resumes copying where it left off.
- Clear the flag when done and jump to the application.
On devices with enough flash you can even dedicate a “golden” application slot and a “staging” slot to fully double‑buffer, but the resume‑on‑reset commit pattern above gives you the same protection against mid‑write power loss.
Below is a minimal boot loader in C using avr‑libc that implements this pattern. It targets an ATmega with self‑programming capability; you must link it to the boot section and set fuses appropriately.
#include <avr/io.h>
#include <avr/boot.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <avr/eeprom.h>
#include <util/delay.h>
#include <stdint.h>
#define F_CPU 16000000UL
#define BAUD 115200
#define UBRR_VALUE ((F_CPU/16/BAUD) - 1)
#define PAGE_SIZE SPM_PAGESIZE // bytes
#define APP_START 0x0000 // start of application
#define APP_MAX_SIZE (FLASHEND + 1 - BOOTLOADER_SIZE - STAGING_SIZE)
#define STAGING_START (APP_MAX_SIZE) // where to buffer new image
#define STAGING_SIZE APP_MAX_SIZE // same size as application
#define BOOTLOADER_SIZE 0x800 // e.g. 2 KiB boot section
// EEPROM flags to track state
#define EE_FLAG_ADDR 0x00
#define FLAG_NONE 0xFF
#define FLAG_DOWNLOAD_COMPLETE 0xA5
#define FLAG_COMMIT_IN_PROGRESS 0x5A
#define EE_PAGE_INDEX_ADDR 0x01 // next page to commit
static uint16_t crc16_ccitt(const uint8_t *buf, uint32_t len) {
uint16_t crc = 0xFFFF;
for (uint32_t i = 0; i < len; i++) {
crc ^= ((uint16_t)buf[i] << 8);
for (uint8_t j = 0; j < 8; j++) {
if (crc & 0x8000)
crc = (crc << 1) ^ 0x1021;
else
crc <<= 1;
}
}
return crc;
}
static void uart_init(void) {
UBRR0H = (uint8_t)(UBRR_VALUE >> 8);
UBRR0L = (uint8_t)UBRR_VALUE;
UCSR0B = _BV(RXEN0) | _BV(TXEN0);
UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);
}
static uint8_t uart_getc(void) {
while (!(UCSR0A & _BV(RXC0)));
return UDR0;
}
static void uart_putc(uint8_t c) {
while (!(UCSR0A & _BV(UDRE0)));
UDR0 = c;
}
// Write one flash page from RAM buffer to given byte address
static void flash_write_page(uint32_t address, uint8_t *data) {
uint16_t i;
// address must be word address for boot_page_fill/write
uint32_t word_addr = address & ~(PAGE_SIZE - 1);
boot_page_erase_safe(word_addr);
for (i = 0; i < PAGE_SIZE; i += 2) {
uint16_t w = data[i] | (data[i+1] << 8);
boot_page_fill_safe(word_addr + i, w);
}
boot_page_write_safe(word_addr);
boot_rww_enable_safe();
}
static void flash_read(uint32_t address, uint8_t *buf, uint16_t len) {
for (uint16_t i = 0; i < len; i++) {
buf[i] = pgm_read_byte_near(address + i);
}
}
// Receive a firmware image over UART into the staging area.
// Protocol: [4‑byte length][data...][2‑byte CRC16]
static uint32_t receive_firmware_to_staging(void) {
uint8_t hdr[4];
for (uint8_t i = 0; i < 4; i++) hdr[i] = uart_getc();
uint32_t length = ((uint32_t)hdr[0]) |
((uint32_t)hdr[1] << 8) |
((uint32_t)hdr[2] << 16) |
((uint32_t)hdr[3] << 24);
if (length > APP_MAX_SIZE) {
// invalid length
return 0;
}
uint32_t bytes_received = 0;
uint8_t pagebuf[PAGE_SIZE];
while (bytes_received < length) {
// fill one page buffer
uint16_t chunk = PAGE_SIZE;
if (length - bytes_received < PAGE_SIZE)
chunk = (uint16_t)(length - bytes_received);
for (uint16_t i = 0; i < chunk; i++) {
pagebuf[i] = uart_getc();
}
// pad remainder with 0xFF
for (uint16_t i = chunk; i < PAGE_SIZE; i++) pagebuf[i] = 0xFF;
flash_write_page(STAGING_START + bytes_received, pagebuf);
bytes_received += chunk;
}
// Read transmitted CRC16
uint8_t crc_lo = uart_getc();
uint8_t crc_hi = uart_getc();
uint16_t recv_crc = crc_lo | (crc_hi << 8);
// Compute CRC over staged image
uint32_t remaining = length;
uint32_t addr = STAGING_START;
uint16_t crc = 0xFFFF;
while (remaining) {
uint8_t buf[32];
uint16_t chunk = remaining > sizeof(buf) ? sizeof(buf) : remaining;
flash_read(addr, buf, chunk);
crc = crc16_ccitt(buf, chunk) ^ (crc ^ 0xFFFF); // reuse calc; you can inline
addr += chunk;
remaining -= chunk;
}
if (crc != recv_crc) {
uart_putc('C'); // CRC error
return 0;
}
uart_putc('O'); // OK
// mark download complete in EEPROM
eeprom_update_byte((uint8_t*)EE_FLAG_ADDR, FLAG_DOWNLOAD_COMPLETE);
eeprom_update_byte((uint8_t*)EE_PAGE_INDEX_ADDR, 0);
return length;
}
// Copy staged image into application area, resuming from page index in EEPROM.
// This is the "commit" phase; if power fails, we can resume on next reset.
static void commit_staging_to_app(uint32_t length) {
uint8_t pagebuf[PAGE_SIZE];
uint8_t start_page = eeprom_read_byte((uint8_t*)EE_PAGE_INDEX_ADDR);
uint16_t total_pages = (length + PAGE_SIZE - 1) / PAGE_SIZE;
eeprom_update_byte((uint8_t*)EE_FLAG_ADDR, FLAG_COMMIT_IN_PROGRESS);
for (uint16_t page = start_page; page < total_pages; page++) {
uint32_t addr = (uint32_t)page * PAGE_SIZE;
flash_read(STAGING_START + addr, pagebuf, PAGE_SIZE);
flash_write_page(APP_START + addr, pagebuf);
eeprom_update_byte((uint8_t*)EE_PAGE_INDEX_ADDR, page + 1);
}
eeprom_update_byte((uint8_t*)EE_FLAG_ADDR, FLAG_NONE);
}
static void jump_to_application(void) {
// make sure interrupts are disabled and vector table points to app
cli();
// Clear MCU status register if desired
// Set the watchdog to known state if needed
// Jump to 0x0000
void (*app_start)(void) = 0x0000;
app_start();
}
int main(void) __attribute__((section(".bootloader")));
int main(void) {
uart_init();
uint8_t flag = eeprom_read_byte((uint8_t*)EE_FLAG_ADDR);
// If a commit was interrupted, finish it before jumping
if (flag == FLAG_COMMIT_IN_PROGRESS || flag == FLAG_DOWNLOAD_COMPLETE) {
// For simplicity, assume caller knows length; you can store it in EEPROM too
uint32_t length = APP_MAX_SIZE; // TODO: store actual length
commit_staging_to_app(length);
}
// Simple trigger: if host sends 0x55 within timeout, enter update
uint16_t timeout = 60000;
while (timeout--) {
if (UCSR0A & _BV(RXC0)) {
uint8_t c = uart_getc();
if (c == 0x55) {
uint32_t len = receive_firmware_to_staging();
if (len > 0) {
commit_staging_to_app(len);
}
break;
}
}
_delay_ms(1);
}
// Otherwise jump to application
jump_to_application();
while (1);
}
A few points to be aware of:
- Link the boot loader to the boot section (
-Wl,--section-start=.text=0x7000 for a 2 KiB bootloader on an ATmega328P) and set the BOOTSZ/BOOTRST fuses accordingly.
- The example uses a very simple UART protocol; in a real design you’d also include a start‑of‑frame, timeouts, and perhaps an acknowledgement scheme.
- The
STAGING_START and STAGING_SIZE need to be chosen so they don’t overlap the boot loader or application. On small devices you may not have enough flash to stage a full image; on larger devices (ATmega128/256) you can dedicate the top half of the application space as the staging area.
- To survive power loss during the commit, the code records the next page to write in EEPROM. On reset it checks the flag and resumes copying. The original application remains intact until its pages are overwritten during the commit.
With this pattern, the boot loader itself is your “golden image,” and you never overwrite it. If power is lost mid‑write, the boot loader still comes up and can either resume the commit or accept a new download without bricking the device.