Simvik

Receive an update in chunks

Write update chunks to the spare slot in order, ignore resends, refuse gaps and overruns, and check the CRC at the end. A medium embedded C problem (OTA…

medium · OTA updates and rollback · ota · flash · crc · robustness

An update arrives over a network that can lose acknowledgements, so the server sometimes resends a chunk you already have, and a buggy proxy can skip one. Write:

  • ota_begin(o, total): start an update of total bytes. Return OTA_TOO_BIG if it is 0 or does not fit in the slot, otherwise OTA_OK.
  • ota_chunk(o, offset, data, n): in this order,
  • OTA_BAD_CHUNK if n is 0 or more than CHUNK_MAX;
  • OTA_DUP if the whole chunk is already written (offset + n <= next). Acknowledge it again, but do not write it;
  • OTA_GAP if offset is not next;
  • OTA_TOO_BIG if it would go past total;
  • otherwise copy it into slot at offset, update the CRC, advance next, and return OTA_OK.
  • ota_finish(o, crc): OTA_INCOMPLETE if not all total bytes arrived, OTA_BAD_CRC if the image's CRC-32 is not crc, otherwise OTA_DONE.

Starter code

int ota_begin(ota_t *o, uint32_t total) {
  o->total = total;
  o->next = 0;
  return OTA_OK;
}

int ota_chunk(ota_t *o, uint32_t offset, const uint8_t *data, uint32_t n) {
  memcpy(&slot[offset], data, n);
  o->next = offset + n;
  return OTA_OK;
}

int ota_finish(ota_t *o, uint32_t crc) {
  (void)o; (void)crc;
  return OTA_DONE;
}

Example tests

A clean transfer, with one resent chunk

make_image(150);
begin(150);
chunk(0, 64);
chunk(64, 64);
chunk(64, 64);
chunk(128, 22);
finish(image_crc);

Expected output:

begin 150: ok
chunk 0+64: ok
chunk 64+64: ok
chunk 64+64: duplicate
chunk 128+22: ok
finish: done, slot matches

A skipped chunk, an early finish and a wrong CRC

make_image(150);
begin(150);
chunk(0, 64);
chunk(128, 22);
finish(image_crc);
chunk(64, 64);
chunk(128, 22);
finish(image_crc ^ 1u);

Expected output:

begin 150: ok
chunk 0+64: ok
chunk 128+22: gap
finish: incomplete, slot differs
chunk 64+64: ok
chunk 128+22: ok
finish: bad crc, slot matches

Learn it first

More OTA updates and rollback problems