Complete batch 20261016-C-embedded-2: 45 verified GLM/Pi samples, independent regrades and archives; preserve difficulty misses and Salty blockage.
97 lines
2.5 KiB
C
97 lines
2.5 KiB
C
#include "update.h"
|
|
#include <string.h>
|
|
|
|
void update_init(Update *update, Flash *flash)
|
|
{
|
|
memset(update, 0, sizeof(*update));
|
|
update->flash = flash;
|
|
}
|
|
|
|
int update_begin(Update *update, uint32_t total, uint32_t expected_crc)
|
|
{
|
|
if (total == 0 || total > UPDATE_MAX) {
|
|
return -1;
|
|
}
|
|
Flash *flash = update->flash;
|
|
flash_poweron(flash);
|
|
update_init(update, flash);
|
|
for (uint32_t offset = FLASH_PROTECTED_LOW;
|
|
offset < FLASH_PROTECTED_HIGH; offset += FLASH_PAGE) {
|
|
int result = flash_erase(flash, offset, FLASH_PAGE);
|
|
if (result != 0) {
|
|
return result;
|
|
}
|
|
}
|
|
update->total = total;
|
|
update->expected_crc = expected_crc;
|
|
int result = journal_header(update);
|
|
if (result != 0) {
|
|
update_init(update, flash);
|
|
return result;
|
|
}
|
|
update->open = 1;
|
|
return 0;
|
|
}
|
|
|
|
static int compare_previous(Update *update, uint32_t offset,
|
|
const uint8_t *bytes, size_t count)
|
|
{
|
|
uint32_t cell = UPDATE_DATA + (offset / UPDATE_CHUNK) * UPDATE_CELL;
|
|
uint8_t old[UPDATE_CHUNK];
|
|
int result = flash_read(update->flash, cell, old, count);
|
|
if (result != 0) {
|
|
return result;
|
|
}
|
|
return memcmp(old, bytes, count) == 0 ? 0 : -2;
|
|
}
|
|
|
|
int update_write(Update *update, uint32_t offset, const uint8_t *bytes,
|
|
size_t count)
|
|
{
|
|
if (!update->open || update->finished || offset >= update->total ||
|
|
offset % UPDATE_CHUNK != 0 || offset > update->next) {
|
|
return -2;
|
|
}
|
|
size_t expected = update->total - offset;
|
|
if (expected > UPDATE_CHUNK) {
|
|
expected = UPDATE_CHUNK;
|
|
}
|
|
if (count > expected || count == 0) {
|
|
return -2;
|
|
}
|
|
if (offset < update->next) {
|
|
return compare_previous(update, offset, bytes, count);
|
|
}
|
|
int result = journal_append(update, offset, bytes, count);
|
|
if (result != 0) {
|
|
return result;
|
|
}
|
|
update->next += (uint32_t)count;
|
|
return 0;
|
|
}
|
|
|
|
int update_finish(Update *update)
|
|
{
|
|
if (!update->open || update->next != update->total) {
|
|
return -2;
|
|
}
|
|
uint8_t bytes[UPDATE_MAX];
|
|
int result = journal_payload(update, bytes);
|
|
if (result != 0) {
|
|
return result;
|
|
}
|
|
if (util_crc32(bytes, update->total) != update->expected_crc) {
|
|
return -1;
|
|
}
|
|
if (update->finished) {
|
|
return 0;
|
|
}
|
|
uint8_t marker = 0;
|
|
result = flash_program(update->flash, UPDATE_HEADER + 31, &marker, 1);
|
|
if (result != 0) {
|
|
return result;
|
|
}
|
|
update->finished = 1;
|
|
return 0;
|
|
}
|