fw_update.cpp 19 KB

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