From 780820646f53945446085d47ee3b851c41f9f541 Mon Sep 17 00:00:00 2001 From: TeTeHacko Date: Wed, 2 Dec 2026 11:01:42 +0100 Subject: [PATCH] freertos: a tick count ahead of the RTC no longer adds 2^24 ticks xPortSysTickHandler catches up with diff = (RTC - tick count) & 0xFFFFFF. With the tick count even one tick ahead, diff wrapped to ~2^24 and the loop added 16,777,215 ticks: millis() jumped 16384 s (4.55 h). Seen on MeshCore repeaters (nRF52840 + BLE) as uptime, airtime and the clock jumping ahead, several times within minutes. A difference above half the counter range is now taken as 'ahead' and skipped; the RTC catches up in a tick or two. Co-Authored-By: Claude Opus 5.5 --- .../portable/CMSIS/nrf52/port_cmsis_systick.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c b/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c index 79440a95..6b3f020f 100644 --- a/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c +++ b/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c @@ -71,6 +71,19 @@ void xPortSysTickHandler( void ) TickType_t diff; diff = (systick_counter - xTaskGetTickCount()) & portNRF_RTC_MAXTICKS; + /* The tick count can end up a few ticks AHEAD of the 24-bit RTC counter + * (one way: while the scheduler is suspended every interrupt pends a + * tick, whether or not the RTC moved). The masked difference then wraps to + * nearly 2^24, and the loop below added 16,777,215 ticks at once: + * millis(), uptime and a millis-based clock jumped 16384 s (4.55 h) + * ahead, several times in a few minutes on a MeshCore repeater with + * BLE. A real backlog is never half the counter range (2.3 h of + * missed ticks), so treat that as "ahead" and let the RTC catch up. */ + if (diff > (portNRF_RTC_MAXTICKS >> 1)) + { + diff = 0; + } + /* At most 1 step if scheduler is suspended - the xTaskIncrementTick * would return the tick state from the moment when suspend function was called. */ if ((diff > 1) && (xTaskGetSchedulerState() != taskSCHEDULER_RUNNING))