fw_update.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. // Staged firmware update: WebUSB streams the new app image into unused upper app-region flash; a verified
  2. // meta-page commit arms it; the next boot applies it from RAM. See fw_update.h for the protocol and the
  3. // corruption-safety invariant every step here preserves.
  4. #include "fw_update.h"
  5. #include "fault_diag.h"
  6. #include <Arduino.h>
  7. #include <string.h>
  8. // nRF52840 flash map (Adafruit UF2 bootloader layout): MBR 0x0-0x1000, SoftDevice to 0x26000, app region
  9. // 0x26000-0xED000, internal LittleFS 0xED000-0xF4000, bootloader 0xF4000+, its settings page at 0xFF000.
  10. // We manage the TOP of the app region: the meta/commit page at 0xEC000 and the staged image right below it,
  11. // growing downward. Nothing outside [APP_BASE, 0xED000) is ever written except FWUP_BL_SETTINGS (see apply).
  12. #define FWUP_APP_BASE 0x26000UL
  13. #define FWUP_APP_END 0xED000UL
  14. #define FWUP_META 0xEC000UL
  15. #define FWUP_BL_SETTINGS 0xFF000UL
  16. #define FWUP_PAGE 4096UL
  17. // Image cap. Also what makes the apply copy safe from self-overlap: dst ends at most at 0x26000+0x60000 =
  18. // 0x86000, while the staged source starts at (0xEC000-size)&~0xFFF >= 0x8C000 -- disjoint by >=24 KiB.
  19. #define FWUP_MAX_IMG 0x60000UL
  20. // Capability tag, searched for BY THE PANEL inside any .uf2 it is about to flash: an image without this
  21. // exact string predates panel updates, so flashing it silently locks future updates back to UF2-DFU
  22. // drag-and-drop -- the panel warns before letting that happen. Bump the suffix only on a breaking protocol
  23. // change (the panel searches for this exact value). The asm reference below keeps it through --gc-sections.
  24. static const char FWUP_TAG[] = "OPK-FWUP-v1";
  25. #define FWUP_META_MAGIC 0x32465055UL // "UPF2"
  26. struct FwupMeta {
  27. uint32_t magic, size, crc, staged;
  28. uint32_t metaCrc; // CRC32 over the four fields above
  29. };
  30. static_assert(sizeof(FwupMeta) == 20, "FwupMeta layout");
  31. // end of the flash the RUNNING image occupies: code/rodata (__etext) plus the .data init image loaded right
  32. // after it (.data is the last flash-loaded section in the core's linker script). Staging must stay above it.
  33. extern "C" {
  34. extern uint32_t __etext[];
  35. extern uint32_t __data_start__[];
  36. extern uint32_t __data_end__[];
  37. }
  38. static uint32_t flashUsedEnd(void)
  39. {
  40. return (uint32_t)__etext +
  41. ((uint32_t)__data_end__ - (uint32_t)__data_start__);
  42. }
  43. // ---- CRC32 (IEEE, reflected, init/xorout 0xFFFFFFFF) -- must match the panel's JS implementation ----------
  44. static uint32_t crc32Step(uint32_t crc, const volatile uint8_t *p, uint32_t n)
  45. {
  46. while (n--) {
  47. crc ^= *p++;
  48. for (int k = 0; k < 8; k++)
  49. crc = (crc >> 1) ^ (0xEDB88320UL & (0UL - (crc & 1)));
  50. }
  51. return crc;
  52. }
  53. // CRC a flash range. Beats the loop-heartbeat between blocks: verifying a full-size image takes ~200 ms of
  54. // CPU, and without beats the fault_diag live-wedge reporter (>300 ms stall) would push an unsolicited status
  55. // blob into the IN pipe right when the panel is waiting for the 0x22 ack.
  56. static uint32_t crc32Flash(uint32_t addr, uint32_t len)
  57. {
  58. uint32_t crc = 0xFFFFFFFFUL;
  59. while (len) {
  60. uint32_t blk = len > 16384 ? 16384 : len;
  61. crc = crc32Step(crc, (const volatile uint8_t *)addr, blk);
  62. addr += blk;
  63. len -= blk;
  64. faultDiagBeat();
  65. }
  66. return ~crc;
  67. }
  68. // ---- NVMC helpers (flash-resident; used for staging + meta only, never on the live app region) ------------
  69. // NVMC ops halt the CPU (page erase ~85 ms) -- callers keep it to at most one erase per loop() pass so the
  70. // 8 s watchdog and the RF link only see brief hiccups.
  71. static void nvmcErasePage(uint32_t page)
  72. {
  73. NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Een;
  74. while (!NRF_NVMC->READY) {
  75. }
  76. NRF_NVMC->ERASEPAGE = page;
  77. while (!NRF_NVMC->READY) {
  78. }
  79. NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren;
  80. while (!NRF_NVMC->READY) {
  81. }
  82. }
  83. static void nvmcWriteWords(uint32_t addr, const uint32_t *w, uint32_t nWords)
  84. {
  85. NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen;
  86. while (!NRF_NVMC->READY) {
  87. }
  88. for (uint32_t i = 0; i < nWords; i++) {
  89. ((volatile uint32_t *)addr)[i] = w[i];
  90. while (!NRF_NVMC->READY) {
  91. }
  92. }
  93. NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren;
  94. while (!NRF_NVMC->READY) {
  95. }
  96. }
  97. // staged image must start with a plausible Cortex-M vector table: initial SP word-aligned in RAM (256 KiB on
  98. // the nRF52840), reset vector Thumb within the app region. Last line of defense against arming a non-app blob.
  99. static bool vectorsPlausible(uint32_t imgAddr, uint32_t size)
  100. {
  101. if (size < 8)
  102. return false;
  103. uint32_t sp = ((const volatile uint32_t *)imgAddr)[0];
  104. uint32_t rv = ((const volatile uint32_t *)imgAddr)[1];
  105. return sp >= 0x20000000UL && sp <= 0x20040000UL && (sp & 3) == 0 &&
  106. (rv & 1) && rv >= FWUP_APP_BASE && rv < FWUP_APP_END;
  107. }
  108. // ---- staging state (transfer is strictly sequential; every ack carries s_off so the panel can resync) -----
  109. static bool s_active = false;
  110. static uint32_t s_size, s_crc, s_base, s_off, s_erased;
  111. uint32_t fwupNextOff(void)
  112. {
  113. return s_off;
  114. }
  115. uint8_t fwupBegin(uint32_t size, uint32_t crc32)
  116. {
  117. s_active = false;
  118. // any BEGIN first disarms a previously staged update -- a restarted transfer must never leave a stale
  119. // commit behind (the staged bytes it points at are about to be overwritten).
  120. nvmcErasePage(FWUP_META);
  121. if (size == 0 || size > FWUP_MAX_IMG || (size & 3))
  122. return FWUP_ERR_BOUNDS;
  123. uint32_t base = (FWUP_META - size) & ~(FWUP_PAGE - 1);
  124. // keep a page of slack above the running image so staging can NEVER touch live code/rodata/.data-init
  125. if (base < flashUsedEnd() + FWUP_PAGE)
  126. return FWUP_ERR_BOUNDS;
  127. s_size = size;
  128. s_crc = crc32;
  129. s_base = base;
  130. s_off = 0;
  131. s_erased =
  132. base; // pages erased lazily, one per chunk at most (85 ms CPU stall each)
  133. s_active = true;
  134. return FWUP_OK;
  135. }
  136. uint8_t fwupChunk(uint32_t off, const uint8_t *d, uint8_t len)
  137. {
  138. if (!s_active)
  139. return FWUP_ERR_STATE;
  140. if (len == 0 || len > 128 || (len & 3) || off + len > s_size)
  141. return FWUP_ERR_BOUNDS;
  142. if (off != s_off) {
  143. // duplicate of already-written data (panel retried a chunk whose ack got lost): don't rewrite
  144. // the words (nRF52 flash allows only 2 writes per word between erases) -- just re-ack.
  145. if (off < s_off && off + len <= s_off)
  146. return FWUP_OK;
  147. return FWUP_ERR_OFFSET; // gap/desync: ack carries s_off, panel resends from there
  148. }
  149. while (s_erased < s_base + off + len) {
  150. nvmcErasePage(s_erased);
  151. s_erased += FWUP_PAGE;
  152. }
  153. uint32_t w[32]; // chunk arrives unaligned in the command buffer; NVMC wants word writes
  154. memcpy(w, d, len);
  155. nvmcWriteWords(s_base + off, w, len / 4);
  156. s_off = off + len;
  157. return FWUP_OK;
  158. }
  159. uint8_t fwupEnd(void)
  160. {
  161. if (!s_active) {
  162. // duplicate END (the panel retried because our ack got lost): if the commit it is asking about
  163. // is exactly the one already on the meta page, re-report success instead of ERR_STATE.
  164. const volatile FwupMeta *m =
  165. (const volatile FwupMeta *)FWUP_META;
  166. if (s_size && m->magic == FWUP_META_MAGIC &&
  167. m->size == s_size && m->crc == s_crc)
  168. return FWUP_OK;
  169. return FWUP_ERR_STATE;
  170. }
  171. if (s_off != s_size)
  172. return FWUP_ERR_STATE;
  173. s_active = false;
  174. // verify what actually landed in flash, not what we were sent
  175. if (crc32Flash(s_base, s_size) != s_crc)
  176. return FWUP_ERR_CRC;
  177. if (!vectorsPlausible(s_base, s_size))
  178. return FWUP_ERR_VECTOR;
  179. // COMMIT: this meta page write is the single arming action of the whole protocol
  180. FwupMeta m = { FWUP_META_MAGIC, s_size, s_crc, s_base, 0 };
  181. m.metaCrc = ~crc32Step(0xFFFFFFFFUL, (const uint8_t *)&m, 16);
  182. nvmcErasePage(FWUP_META);
  183. nvmcWriteWords(FWUP_META, (const uint32_t *)&m, 5);
  184. return FWUP_OK;
  185. }
  186. void fwupAbort(void)
  187. {
  188. s_active = false;
  189. nvmcErasePage(FWUP_META);
  190. }
  191. // ---- boot-time apply ---------------------------------------------------------------------------------------
  192. // Runs entirely from RAM (.data section => copied out of flash by the startup code) with interrupts off: it
  193. // erases and rewrites the very flash the rest of the firmware executes from, so from the first erase to the
  194. // reset it must not touch ANY flash-resident code or data -- only registers, its arguments, and the two
  195. // flash regions it copies between. No calls, no libc, volatile pointers so the compiler can't lift the loops
  196. // into memcpy/memcmp libcalls.
  197. //
  198. // Power-cut safety is in the ordering: all target pages are erased up front (the vector page first), pages
  199. // 1..N-1 are written forward, then the vector page is written BACKWARD so word 0 -- the app-validity marker
  200. // the bootloader checks -- is the final word written anywhere in the app. Interrupt the sequence at any
  201. // point and the board reads as app-less: the UF2 bootloader keeps it, drag-and-drop recovers it.
  202. #define FWUP_RAMFUNC \
  203. __attribute__((used, noinline, section(".data.opk_ramfunc")))
  204. FWUP_RAMFUNC static void ramApply(uint32_t dst, uint32_t src, uint32_t size,
  205. uint32_t metaPage, uint32_t blSettings)
  206. {
  207. volatile uint32_t *d = (volatile uint32_t *)dst;
  208. const volatile uint32_t *s = (const volatile uint32_t *)src;
  209. const uint32_t words = size / 4;
  210. const uint32_t pg0w = words < FWUP_PAGE / 4 ? words : FWUP_PAGE / 4;
  211. // 1) erase every target page; dst itself (the vector page) goes first
  212. NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Een;
  213. while (!NRF_NVMC->READY) {
  214. }
  215. for (uint32_t a = dst; a < dst + size; a += FWUP_PAGE) {
  216. NRF_WDT->RR[0] = WDT_RR_RR_Reload;
  217. NRF_NVMC->ERASEPAGE = a;
  218. while (!NRF_NVMC->READY) {
  219. }
  220. }
  221. // 2) write pages 1..N-1 forward, then the vector page backward (word 0 dead-last)
  222. NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen;
  223. while (!NRF_NVMC->READY) {
  224. }
  225. for (uint32_t w = FWUP_PAGE / 4; w < words; w++) {
  226. if ((w & 1023) == 0)
  227. NRF_WDT->RR[0] = WDT_RR_RR_Reload;
  228. d[w] = s[w];
  229. while (!NRF_NVMC->READY) {
  230. }
  231. }
  232. for (uint32_t w = pg0w; w-- > 0;) {
  233. d[w] = s[w];
  234. while (!NRF_NVMC->READY) {
  235. }
  236. }
  237. // 3) verify the copy word-for-word against the staged source
  238. NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren;
  239. while (!NRF_NVMC->READY) {
  240. }
  241. uint32_t bad = 0;
  242. for (uint32_t w = 0; w < words; w++) {
  243. if ((w & 4095) == 0)
  244. NRF_WDT->RR[0] = WDT_RR_RR_Reload;
  245. if (d[w] != s[w]) {
  246. bad = 1;
  247. break;
  248. }
  249. }
  250. NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Een;
  251. while (!NRF_NVMC->READY) {
  252. }
  253. if (bad) {
  254. // flash cell failure: make the app unambiguously invalid (bootloader keeps the board) instead
  255. // of resetting into a half-good image. Meta is erased below so this can't loop.
  256. NRF_NVMC->ERASEPAGE = dst;
  257. while (!NRF_NVMC->READY) {
  258. }
  259. } else {
  260. // 4) bootloader settings: leave the exact "valid app, CRC check disabled" state drag-and-drop
  261. // (MSC) flashing leaves. A previous adafruit-nrfutil serial-DFU flash records a real CRC16 here,
  262. // and the bootloader re-checks it EVERY boot -- stale, it would fail our new image straight into
  263. // DFU mode. Layout = SDK11 bootloader_settings_t; word 0 ([bank_0=BANK_VALID_APP][bank_0_crc=0])
  264. // is written last so an interrupted settings write falls back to the erased-settings path.
  265. NRF_WDT->RR[0] = WDT_RR_RR_Reload;
  266. NRF_NVMC->ERASEPAGE = blSettings;
  267. while (!NRF_NVMC->READY) {
  268. }
  269. NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen;
  270. while (!NRF_NVMC->READY) {
  271. }
  272. volatile uint32_t *bs = (volatile uint32_t *)blSettings;
  273. bs[6] = 0; // sd_image_start
  274. while (!NRF_NVMC->READY) {
  275. }
  276. bs[5] = 0; // app_image_size (bank_0_size is the authoritative one)
  277. while (!NRF_NVMC->READY) {
  278. }
  279. bs[4] = 0; // bl_image_size
  280. while (!NRF_NVMC->READY) {
  281. }
  282. bs[3] = 0; // sd_image_size
  283. while (!NRF_NVMC->READY) {
  284. }
  285. bs[2] = size; // bank_0_size
  286. while (!NRF_NVMC->READY) {
  287. }
  288. bs[1] = 0x000000FEUL; // bank_1 = BANK_ERASED
  289. while (!NRF_NVMC->READY) {
  290. }
  291. bs[0] = 0x00000001UL; // bank_0 = BANK_VALID_APP, bank_0_crc = 0 ("not used")
  292. while (!NRF_NVMC->READY) {
  293. }
  294. NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Een;
  295. while (!NRF_NVMC->READY) {
  296. }
  297. }
  298. // 5) disarm: erase the meta page so the (old or new) firmware boots normally from here on
  299. NRF_NVMC->ERASEPAGE = metaPage;
  300. while (!NRF_NVMC->READY) {
  301. }
  302. NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren;
  303. while (!NRF_NVMC->READY) {
  304. }
  305. // 6) reset -- raw AIRCR write; NVIC_SystemReset() is inline but keep even its helpers out of the path
  306. __asm volatile("dsb 0xF" ::: "memory");
  307. *(volatile uint32_t *)0xE000ED0CUL = (0x5FAUL << 16) | (1UL << 2);
  308. for (;;) {
  309. }
  310. }
  311. void fwupApplyIfArmed(void)
  312. {
  313. // materialize a reference to the capability tag so the linker's --gc-sections keeps it in the image
  314. __asm volatile("" ::"r"(FWUP_TAG));
  315. const volatile FwupMeta *m = (const volatile FwupMeta *)FWUP_META;
  316. if (m->magic != FWUP_META_MAGIC)
  317. return; // erased page (0xFFFFFFFF) = nothing armed: the common path, zero boot cost
  318. // snapshot, then validate EVERYTHING before touching any flash; anything off -> disarm and boot normally
  319. FwupMeta v = { m->magic, m->size, m->crc, m->staged, m->metaCrc };
  320. bool ok = v.metaCrc ==
  321. (uint32_t)~crc32Step(0xFFFFFFFFUL, (const uint8_t *)&v, 16);
  322. ok = ok && v.size && v.size <= FWUP_MAX_IMG && (v.size & 3) == 0;
  323. ok = ok && v.staged >= FWUP_APP_BASE + FWUP_MAX_IMG &&
  324. v.staged + v.size <= FWUP_META &&
  325. (v.staged & (FWUP_PAGE - 1)) == 0;
  326. ok = ok && crc32Flash(v.staged, v.size) ==
  327. v.crc; // staged bytes still intact?
  328. ok = ok && vectorsPlausible(v.staged, v.size);
  329. if (!ok) {
  330. nvmcErasePage(FWUP_META);
  331. return;
  332. }
  333. // Point of no return. Freeze the system: nothing may run from app flash once the copy starts. The WDT
  334. // is forced on first (it survives soft reset if the previous boot armed it, but not power-on), so even
  335. // a fault inside the copier resets into the safe app-less/bootloader state instead of hanging forever.
  336. __disable_irq();
  337. if (!NRF_WDT->RUNSTATUS) {
  338. NRF_WDT->CONFIG =
  339. (WDT_CONFIG_HALT_Pause << WDT_CONFIG_HALT_Pos) |
  340. (WDT_CONFIG_SLEEP_Run << WDT_CONFIG_SLEEP_Pos);
  341. NRF_WDT->CRV = 8UL * 32768UL - 1; // ~8 s, same as the app's own
  342. NRF_WDT->RREN = WDT_RREN_RR0_Msk;
  343. NRF_WDT->TASKS_START = 1;
  344. }
  345. NRF_WDT->RR[0] = WDT_RR_RR_Reload;
  346. // call through a volatile pointer: the compiler must materialize the RAM address and may not inline the
  347. // copier back into flash-resident code
  348. void (*volatile apply)(uint32_t, uint32_t, uint32_t, uint32_t,
  349. uint32_t) = ramApply;
  350. apply(FWUP_APP_BASE, v.staged, v.size, FWUP_META, FWUP_BL_SETTINGS);
  351. for (;;) {
  352. } // unreachable (ramApply resets)
  353. }